Programs & Examples On #Http response codes

403 Forbidden vs 401 Unauthorized HTTP responses

These are the meanings:

401: User not (correctly) authenticated, the resource/page require authentication

403: User authenticated, but his role or permissions does not allow to access requested resource, for instance user is not an administrator and requested page is for administrators

What is "406-Not Acceptable Response" in HTTP?

"Sometimes" this can mean that the server had an internal error, and wanted to respond with an error message (ex: 500 with JSON payload) but since the request headers didn't say it accepted JSON, it returns a 406 instead. Go figure. (in this case: spring boot webapp).

In which case, your operation did fail. But the failure message was obscured by another.

PHP: How to send HTTP response code?

since PHP 5.4 you can use http_response_code() for get and set header status code.

here an example:

<?php

// Get the current response code and set a new one
var_dump(http_response_code(404));

// Get the new response code
var_dump(http_response_code());
?>

here is the document of this function in php.net:

http_response_code

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

Add it as a reference.

References > Add Reference > Browse for your DLL.

You will then need to add a using statement to the top of your code.

How to print pandas DataFrame without index

Anyone working on Jupyter Notebook to print DataFrame without index column, this worked for me:

display(table.hide_index())

Are vectors passed to functions by value or by reference in C++

If I had to guess, I'd say that you're from a Java background. This is C++, and things are passed by value unless you specify otherwise using the &-operator (note that this operator is also used as the 'address-of' operator, but in a different context). This is all well documented, but I'll re-iterate anyway:

void foo(vector<int> bar); // by value
void foo(vector<int> &bar); // by reference (non-const, so modifiable inside foo)
void foo(vector<int> const &bar); // by const-reference

You can also choose to pass a pointer to a vector (void foo(vector<int> *bar)), but unless you know what you're doing and you feel that this is really is the way to go, don't do this.

Also, vectors are not the same as arrays! Internally, the vector keeps track of an array of which it handles the memory management for you, but so do many other STL containers. You can't pass a vector to a function expecting a pointer or array or vice versa (you can get access to (pointer to) the underlying array and use this though). Vectors are classes offering a lot of functionality through its member-functions, whereas pointers and arrays are built-in types. Also, vectors are dynamically allocated (which means that the size may be determined and changed at runtime) whereas the C-style arrays are statically allocated (its size is constant and must be known at compile-time), limiting their use.

I suggest you read some more about C++ in general (specifically array decay), and then have a look at the following program which illustrates the difference between arrays and pointers:

void foo1(int *arr) { cout << sizeof(arr) << '\n'; }
void foo2(int arr[]) { cout << sizeof(arr) << '\n'; }
void foo3(int arr[10]) { cout << sizeof(arr) << '\n'; }
void foo4(int (&arr)[10]) { cout << sizeof(arr) << '\n'; }

int main()
{
    int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    foo1(arr);
    foo2(arr);
    foo3(arr);
    foo4(arr);
}

How to set Java classpath in Linux?

Can you provide some more details like which linux you are using? Are you loged in as root? On linux you have to run export CLASSPATH = %path%;LOG4J_HOME/og4j-1.2.16.jar If you want it permanent then you can add above lines in ~/.bashrc file.

Send multiple checkbox data to PHP via jQuery ajax()

    $.post("test.php", { 'choices[]': ["Jon", "Susan"] });

So I would just iterate over the checked boxes and build the array. Something like.

       var data = { 'user_ids[]' : []};
        $(":checked").each(function() {
       data['user_ids[]'].push($(this).val());
       });
        $.post("ajax.php", data);

Is there a way to select sibling nodes?

The following function will return an array containing all the siblings of the given element.

function getSiblings(elem) {
    return [...elem.parentNode.children].filter(item => item !== elem);
}

Just pass the selected element into the getSiblings() function as it's only parameter.

How to change the background colour's opacity in CSS

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

For instance,

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

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

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

You can have a look at this WORKING EXAMPLE.

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

The HTML

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

The CSS:

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

Hope this helps Now.

Remove by _id in MongoDB console

Solution and Example:

1- C:\MongoDB\Server\3.2\bin>mongo (do not issue command yet because you are not connected to any database yet, you are only connected to database server mongodb).

2-

show dbs analytics_database 0.000GB local 0.000GB test_database 0.000GB

3-

use test_database switched to db test_database

4-

db.Collection.remove({"_id": ObjectId("5694a3590f6d451c1500002e")}, 1); WriteResult({ "nRemoved" : 1 })

now you see WriteResult({ "nRemoved" : 1 }) is 1 not 0.

Done.

How to troubleshoot an "AttributeError: __exit__" in multiproccesing in Python?

The reason behind this error is : Flask app is already running, hasn't shut down and in middle of that we try to start another instance by: with app.app_context(): #Code Before we use this with statement we need to make sure that scope of the previous running app is closed.

bash script use cut command at variable and store result at another variable

The awk solution is what I would use, but if you want to understand your problems with bash, here is a revised version of your script.

#!/bin/bash -vx

##config file with ip addresses like 10.10.10.1:80
file=config.txt

while read line ; do
  ##this line is not correct, should strip :port and store to ip var
  ip=$( echo "$line" |cut -d\: -f1 )
  ping $ip
done < ${file}

You could write your top line as

for line in $(cat $file) ; do ...

(but not recommended).

You needed command substitution $( ... ) to get the value assigned to $ip

reading lines from a file is usually considered more efficient with the while read line ... done < ${file} pattern.

I hope this helps.

TypeError: 'undefined' is not a function (evaluating '$(document)')

You can pass $ in function()

jQuery(document).ready(function($){

// jQuery code is in here

});

or you can replace $(document); with this jQuery(document);

or you can use jQuery.noConflict()

var jq=jQuery.noConflict();
jq(document).ready(function(){  
  jq('selector').show();
});

Is it possible to send a variable number of arguments to a JavaScript function?

This is a sample program for calculating sum of integers for variable arguments and array on integers. Hope this helps.

var CalculateSum = function(){
    calculateSumService.apply( null, arguments );
}

var calculateSumService = function(){
    var sum = 0;

    if( arguments.length === 1){
        var args = arguments[0];

        for(var i = 0;i<args.length; i++){
           sum += args[i]; 
        }
    }else{
        for(var i = 0;i<arguments.length; i++){
           sum += arguments[i]; 
        }        
    }

     alert(sum);

}


//Sample method call

// CalculateSum(10,20,30);         

// CalculateSum([10,20,30,40,50]);

// CalculateSum(10,20);

How to search a string in String array

In C#, if you can use an ArrayList, you can use the Contains method, which returns a boolean:

if MyArrayList.Contains("One")

How to format DateTime columns in DataGridView?

You can set the format in aspx, just add the property "DateFormatString" in your BoundField.

DataFormatString="{0:dd/MM/yyyy hh:mm:ss}"

Javascript - get array of dates between 2 dates

function (startDate, endDate, addFn, interval) {

 addFn = addFn || Date.prototype.addDays;
 interval = interval || 1;

 var retVal = [];
 var current = new Date(startDate);

 while (current <= endDate) {
  retVal.push(new Date(current));
  current = addFn.call(current, interval);
 }

 return retVal;

}

Unnamed/anonymous namespaces vs. static functions

Having learned of this feature only just now while reading your question, I can only speculate. This seems to provide several advantages over a file-level static variable:

  • Anonymous namespaces can be nested within one another, providing multiple levels of protection from which symbols can not escape.
  • Several anonymous namespaces could be placed in the same source file, creating in effect different static-level scopes within the same file.

I'd be interested in learning if anyone has used anonymous namespaces in real code.

Animate visibility modes, GONE and VISIBLE

You probably want to use an ExpandableListView, a special ListView that allows you to open and close groups.

Android ADB device offline, can't issue commands

In Linux: remove the directory ~/.android and restart ADB.

How to get index using LINQ?

myCars.TakeWhile(car => !myCondition(car)).Count();

It works! Think about it. The index of the first matching item equals the number of (not matching) item before it.

Story time

I too dislike the horrible standard solution you already suggested in your question. Like the accepted answer I went for a plain old loop although with a slight modification:

public static int FindIndex<T>(this IEnumerable<T> items, Predicate<T> predicate) {
    int index = 0;
    foreach (var item in items) {
        if (predicate(item)) break;
        index++;
    }
    return index;
}

Note that it will return the number of items instead of -1 when there is no match. But let's ignore this minor annoyance for now. In fact the horrible standard solution crashes in that case and I consider returning an index that is out-of-bounds superior.

What happens now is ReSharper telling me Loop can be converted into LINQ-expression. While most of the time the feature worsens readability, this time the result was awe-inspiring. So Kudos to the JetBrains.

Analysis

Pros

  • Concise
  • Combinable with other LINQ
  • Avoids newing anonymous objects
  • Only evaluates the enumerable until the predicate matches for the first time

Therefore I consider it optimal in time and space while remaining readable.

Cons

  • Not quite obvious at first
  • Does not return -1 when there is no match

Of course you can always hide it behind an extension method. And what to do best when there is no match heavily depends on the context.

npm ERR! registry error parsing json - While trying to install Cordova for Ionic Framework in Windows 8

In my case all Internet access must run through a proxy and npm was not configured with the proxy to reach http://registry.npmjs.org.

I ran npm install --log-level verbose to get more information and saw that the response had HTML stating I was not authenticated with the proxy.

Running the following fixed it (replacing below with your username/password/proxy address:

npm config set proxy 'username:[email protected]'
npm config set https-proxy 'username:[email protected]'

I do not advise putting the password in raw text instead using something like cntlm to set up a local proxy that delegates to the real proxy.

How to create XML file with specific structure in Java

Use JAXB: http://www.mkyong.com/java/jaxb-hello-world-example/

package com.mkyong.core;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

}
package com.mkyong.core;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBExample {
    public static void main(String[] args) {

      Customer customer = new Customer();
      customer.setId(100);
      customer.setName("mkyong");
      customer.setAge(29);

      try {

        File file = new File("C:\\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxbMarshaller.marshal(customer, file);
        jaxbMarshaller.marshal(customer, System.out);

      } catch (JAXBException e) {
        e.printStackTrace();
      }

    }
}

Excel compare two columns and highlight duplicates

There may be a simpler option, but you can use VLOOKUP to check if a value appears in a list (and VLOOKUP is a powerful formula to get to grips with anyway).

So for A1, you can set a conditional format using the following formula:

=NOT(ISNA(VLOOKUP(A1,$B:$B,1,FALSE)))

Copy and Paste Special > Formats to copy that conditional format to the other cells in column A.

What the above formula is doing:

  • VLOOKUP is looking up the value of Cell A1 (first parameter) against the whole of column B ($B:$B), in the first column (that's the 3rd parameter, redundant here, but typically VLOOKUP looks up a table rather than a column). The last parameter, FALSE, specifies that the match must be exact rather than just the closest match.
  • VLOOKUP will return #ISNA if no match is found, so the NOT(ISNA(...)) returns true for all cells which have a match in column B.

Change Timezone in Lumen or Laravel 5

Go to config -> app.php and change 'timezone' => 'Asia/Jakarta',

(this is my timezone)

How to include Javascript file in Asp.Net page

I assume that you are using MasterPage so within your master page you should have

<head runat="server">
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>

And within any of your pages based on that MasterPage add this

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <script src="js/yourscript.js" type="text/javascript"></script>
</asp:Content>

Convert char to int in C#

By default you use UNICODE so I suggest using faulty's method

int bar = int.Parse(foo.ToString());

Even though the numeric values under are the same for digits and basic Latin chars.

How to autosize and right-align GridViewColumn data in WPF?

I had trouble with the accepted answer (because I missed the HorizontalAlignment=Stretch portion and have adjusted the original answer).

This is another technique. It uses a Grid with a SharedSizeGroup.

Note: the Grid.IsSharedScope=true on the ListView.

<Window x:Class="WpfApplication6.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
    <ListView Name="lstCustomers" ItemsSource="{Binding Path=Collection}" Grid.IsSharedSizeScope="True">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="ID" Width="40">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                             <Grid>
                                  <Grid.ColumnDefinitions>
                                       <ColumnDefinition Width="Auto" SharedSizeGroup="IdColumn"/>
                                  </Grid.ColumnDefinitions>
                                  <TextBlock HorizontalAlignment="Right" Text={Binding Path=Id}"/>
                             </Grid>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" Width="Auto" />
                <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}" Width="Auto"/>
            </GridView>
        </ListView.View>
    </ListView>
</Grid>
</Window>

MySQL INNER JOIN Alias

You'll need to join twice:

SELECT home.*, away.*, g.network, g.date_start 
FROM game AS g
INNER JOIN team AS home
  ON home.importid = g.home
INNER JOIN team AS away
  ON away.importid = g.away
ORDER BY g.date_start DESC 
LIMIT 7

Using gradle to find dependency tree

Note that you may need to do something like ./gradlew <module_directory>:<module_name>:dependencies if the module has extra directory before reach its build.gradle. When in doubt, do ./gradlew tasks --all to check the name.

Returning Arrays in Java

It is returning the array, but all returning something (including an Array) does is just what it sounds like: returns the value. In your case, you are getting the value of numbers(), which happens to be an array (it could be anything and you would still have this issue), and just letting it sit there.

When a function returns anything, it is essentially replacing the line in which it is called (in your case: numbers();) with the return value. So, what your main method is really executing is essentially the following:

public static void main(String[] args) {
    {1,2,3};
}

Which, of course, will appear to do nothing. If you wanted to do something with the return value, you could do something like this:

public static void main(String[] args){
    int[] result = numbers();
    for (int i=0; i<result.length; i++) {
        System.out.print(result[i]+" ");
    }
}

Hive ParseException - cannot recognize input near 'end' 'string'

You can always escape the reserved keyword if you still want to make your query work!!

Just replace end with `end`

Here is the list of reserved keywords https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL

CREATE EXTERNAL TABLE moveProjects (cid string, `end` string, category string)
STORED BY 'org.apache.hadoop.hive.dynamodb.DynamoDBStorageHandler'
TBLPROPERTIES ("dynamodb.table.name" = "Projects",
    "dynamodb.column.mapping" = "cid:cid,end:end,category:category");

ORA-01653: unable to extend table by in tablespace ORA-06512

To resolve this error:

ORA-01653 unable to extend table by 1024 in tablespace your-tablespace-name

Just run this PL/SQL command for extended tablespace size automatically on-demand:

alter database datafile '<your-tablespace-name>.dbf' autoextend on maxsize unlimited;

I get this error in import big dump file, just run this command without stopping import routine or restarting the database.

Note: each data file has a limit of 32GB of size if you need more than 32GB you should add a new data file to your existing tablespace.

More info: alter_autoextend_on

Where to put Gradle configuration (i.e. credentials) that should not be committed?

If you have user specific credentials ( i.e each developer might have different username/password ) then I would recommend using the gradle-properties-plugin.

  1. Put defaults in gradle.properties
  2. Each developer overrides with gradle-local.properties ( this should be git ignored ).

This is better than overriding using $USER_HOME/.gradle/gradle.properties because different projects might have same property names.

Assign a class name to <img> tag instead of write it in css file?

Its depend. If you have more than two images in .column but you only need some images to have css applied then its better to add class to image directly instead of doing .column img{/*styling for image here*/}

In performance aspect i thing apply class to image is better because by doing so css will not look for possible child image.

How do I make a Mac Terminal pop-up/alert? Applescript?

Use this command to trigger the notification center notification from the terminal.

osascript -e 'display notification "Lorem ipsum dolor sit amet" with title "Title"'

Using Server.MapPath in external C# Classes in ASP.NET

System.Reflection.Assembly.GetAssembly(type).Location

IF the file you are trying to get is the assembly location for a type. But if the files are relative to the assembly location then you can use this with System.IO namespace to get the exact path of the file.

How to cd into a directory with space in the name?

ok i spent some frustrating time with this problem too. My little guide.

Open desktop for example. If you didnt switch your disc in cmd, type:

cd desktop

Now if you want to display subfolders:

cd, make 1 spacebar, and press tab 2 times

Now if you want to enter directory/file with SPACE IN NAME. Lets open some file name f.g., to open it we need to type:

cd file\ name

p.s. notice this space after slash :)

How to set text color in submit button?

.btn{
    font-size: 20px;
    color:black;
}

What does "var" mean in C#?

  • As the name suggested, var is variable without any data type.
  • If you don't know which type of data will be returned by any method, such cases are good for using var.
  • var is Implicit type which means system will define the data type itself. The compiler will infer its type based on the value to the right of the "=" operator.
  • int/string etc. are the explicit types as it is defined by you explicitly.
  • Var can only be defined in a method as a local variable
  • Multiple vars cannot be declared and initialized in a single statement. For example, var i=1, j=2; is invalid.
int i = 100;// explicitly typed 
var j = 100; // implicitly typed

OSError: [Errno 8] Exec format error

OSError: [Errno 8] Exec format error can happen if there is no shebang line at the top of the shell script and you are trying to execute the script directly. Here's an example that reproduces the issue:

>>> with open('a','w') as f: f.write('exit 0') # create the script
... 
>>> import os
>>> os.chmod('a', 0b111101101) # rwxr-xr-x make it executable                       
>>> os.execl('./a', './a')     # execute it                                            
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/os.py", line 312, in execl
    execv(file, args)
OSError: [Errno 8] Exec format error

To fix it, just add the shebang e.g., if it is a shell script; prepend #!/bin/sh at the top of your script:

>>> with open('a','w') as f: f.write('#!/bin/sh\nexit 0')
... 
>>> os.execl('./a', './a')

It executes exit 0 without any errors.


On POSIX systems, shell parses the command line i.e., your script won't see spaces around = e.g., if script is:

#!/usr/bin/env python
import sys
print(sys.argv)

then running it in the shell:

$ /usr/local/bin/script hostname = '<hostname>' -p LONGLIST

produces:

['/usr/local/bin/script', 'hostname', '=', '<hostname>', '-p', 'LONGLIST']

Note: no spaces around '='. I've added quotes around <hostname> to escape the redirection metacharacters <>.

To emulate the shell command in Python, run:

from subprocess import check_call

cmd = ['/usr/local/bin/script', 'hostname', '=', '<hostname>', '-p', 'LONGLIST']
check_call(cmd)

Note: no shell=True. And you don't need to escape <> because no shell is run.

"Exec format error" might indicate that your script has invalid format, run:

$ file /usr/local/bin/script

to find out what it is. Compare the architecture with the output of:

$ uname -m

How to download/upload files from/to SharePoint 2013 using CSOM?

Just a suggestion SharePoint 2013 online & on-prem file encoding is UTF-8 BOM. Make sure your file is UTF-8 BOM, otherwise your uploaded html and scripts may not rendered correctly in browser.

TypeError: a bytes-like object is required, not 'str' in python and CSV

You are opening the csv file in binary mode, it should be 'w'

import csv

# open csv file in write mode with utf-8 encoding
with open('output.csv','w',encoding='utf-8',newline='')as w:
    fieldnames = ["SNo", "States", "Dist", "Population"]
    writer = csv.DictWriter(w, fieldnames=fieldnames)
    # write list of dicts
    writer.writerows(list_of_dicts) #writerow(dict) if write one row at time

ADB Install Fails With INSTALL_FAILED_TEST_ONLY

In my case was by uploading an APK, that although it was signed with production certificate and was a release variant, was generated by the run play button from Android studio. Problem solved after generating APK from Gradle or from Build APK menu option.

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/

Reload chart data via JSON with Highcharts

data = [150,300]; // data from ajax or any other way chart.series[0].setData(data, true);

The setData will call redraw method.

Reference: http://api.highcharts.com/highcharts/Series.setData

Fling gesture detection on grid layout

My version of solution proposed by Thomas Fankhauser and Marek Sebera (does not handle vertical swipes):

SwipeInterface.java

import android.view.View;

public interface SwipeInterface {

    public void onLeftToRight(View v);

    public void onRightToLeft(View v);
}

ActivitySwipeDetector.java

import android.content.Context;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;

public class ActivitySwipeDetector implements View.OnTouchListener {

    static final String logTag = "ActivitySwipeDetector";
    private SwipeInterface activity;
    private float downX, downY;
    private long timeDown;
    private final float MIN_DISTANCE;
    private final int VELOCITY;
    private final float MAX_OFF_PATH;

    public ActivitySwipeDetector(Context context, SwipeInterface activity){
        this.activity = activity;
        final ViewConfiguration vc = ViewConfiguration.get(context);
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        MIN_DISTANCE = vc.getScaledPagingTouchSlop() * dm.density;
        VELOCITY = vc.getScaledMinimumFlingVelocity();
        MAX_OFF_PATH = MIN_DISTANCE * 2;            
    }

    public void onRightToLeftSwipe(View v){
        Log.i(logTag, "RightToLeftSwipe!");
        activity.onRightToLeft(v);
    }

    public void onLeftToRightSwipe(View v){
        Log.i(logTag, "LeftToRightSwipe!");
        activity.onLeftToRight(v);
    }

    public boolean onTouch(View v, MotionEvent event) {
        switch(event.getAction()){
        case MotionEvent.ACTION_DOWN: {
            Log.d("onTouch", "ACTION_DOWN");
            timeDown = System.currentTimeMillis();
            downX = event.getX();
            downY = event.getY();
            return true;
        }
        case MotionEvent.ACTION_UP: {
            Log.d("onTouch", "ACTION_UP");
            long timeUp = System.currentTimeMillis();
            float upX = event.getX();
            float upY = event.getY();

            float deltaX = downX - upX;
            float absDeltaX = Math.abs(deltaX); 
            float deltaY = downY - upY;
            float absDeltaY = Math.abs(deltaY);

            long time = timeUp - timeDown;

            if (absDeltaY > MAX_OFF_PATH) {
                Log.i(logTag, String.format("absDeltaY=%.2f, MAX_OFF_PATH=%.2f", absDeltaY, MAX_OFF_PATH));
                return v.performClick();
            }

            final long M_SEC = 1000;
            if (absDeltaX > MIN_DISTANCE && absDeltaX > time * VELOCITY / M_SEC) {
                if(deltaX < 0) { this.onLeftToRightSwipe(v); return true; }
                if(deltaX > 0) { this.onRightToLeftSwipe(v); return true; }
            } else {
                Log.i(logTag, String.format("absDeltaX=%.2f, MIN_DISTANCE=%.2f, absDeltaX > MIN_DISTANCE=%b", absDeltaX, MIN_DISTANCE, (absDeltaX > MIN_DISTANCE)));
                Log.i(logTag, String.format("absDeltaX=%.2f, time=%d, VELOCITY=%d, time*VELOCITY/M_SEC=%d, absDeltaX > time * VELOCITY / M_SEC=%b", absDeltaX, time, VELOCITY, time * VELOCITY / M_SEC, (absDeltaX > time * VELOCITY / M_SEC)));
            }

        }
        }
        return false;
    }

}

How to select id with max date group by category in PostgreSQL?

This is a perfect use-case for DISTINCT ON - a Postgres specific extension of the standard DISTINCT:

SELECT DISTINCT ON (category)
       id  -- , category, date  -- any other column (expression) from the same row
FROM   tbl
ORDER  BY category, date DESC;

Careful with descending sort order. If the column can be NULL, you may want to add NULLS LAST:

DISTINCT ON is simple and fast. Detailed explanation in this related answer:

For big tables with many rows per category consider an alternative approach:

How to run a task when variable is undefined in ansible?

Strictly stated you must check all of the following: defined, not empty AND not None.

For "normal" variables it makes a difference if defined and set or not set. See foo and bar in the example below. Both are defined but only foo is set.

On the other side registered variables are set to the result of the running command and vary from module to module. They are mostly json structures. You probably must check the subelement you're interested in. See xyz and xyz.msg in the example below:

cat > test.yml <<EOF
- hosts: 127.0.0.1

  vars:
    foo: ""          # foo is defined and foo == '' and foo != None
    bar:             # bar is defined and bar != '' and bar == None

  tasks:

  - debug:
      msg : ""
    register: xyz    # xyz is defined and xyz != '' and xyz != None
                     # xyz.msg is defined and xyz.msg == '' and xyz.msg != None

  - debug:
      msg: "foo is defined and foo == '' and foo != None"
    when: foo is defined and foo == '' and foo != None

  - debug:
      msg: "bar is defined and bar != '' and bar == None"
    when: bar is defined and bar != '' and bar == None

  - debug:
      msg: "xyz is defined and xyz != '' and xyz != None"
    when: xyz is defined and xyz != '' and xyz != None
  - debug:
      msg: "{{ xyz }}"

  - debug:
      msg: "xyz.msg is defined and xyz.msg == '' and xyz.msg != None"
    when: xyz.msg is defined and xyz.msg == '' and xyz.msg != None
  - debug:
      msg: "{{ xyz.msg }}"
EOF
ansible-playbook -v test.yml

Git fetch remote branch

To checkout myBranch that exists remotely and not a locally - This worked for me:

git fetch --all
git checkout myBranch

I got this message:

Branch myBranch set up to track remote branch myBranch from origin
Switched to a new branch 'myBranch'

Oracle PL/SQL : remove "space characters" from a string

Since you're comfortable with regular expressions, you probably want to use the REGEXP_REPLACE function. If you want to eliminate anything that matches the [:space:] POSIX class

REGEXP_REPLACE( my_value, '[[:space:]]', '' )


SQL> ed
Wrote file afiedt.buf

  1  select '|' ||
  2         regexp_replace( 'foo ' || chr(9), '[[:space:]]', '' ) ||
  3         '|'
  4*   from dual
SQL> /

'|'||
-----
|foo|

If you want to leave one space in place for every set of continuous space characters, just add the + to the regular expression and use a space as the replacement character.

with x as (
  select 'abc 123  234     5' str
    from dual
)
select regexp_replace( str, '[[:space:]]+', ' ' )
  from x

Curl command without using cache

The -H 'Cache-Control: no-cache' argument is not guaranteed to work because the remote server or any proxy layers in between can ignore it. If it doesn't work, you can do it the old-fashioned way, by adding a unique querystring parameter. Usually, the servers/proxies will think it's a unique URL and not use the cache.

curl "http://www.example.com?foo123"

You have to use a different querystring value every time, though. Otherwise, the server/proxies will match the cache again. To automatically generate a different querystring parameter every time, you can use date +%s, which will return the seconds since epoch.

curl "http://www.example.com?$(date +%s)"

How to position absolute inside a div?

The problem is described (among other) in this article.

#box is relatively positioned, which makes it part of the "flow" of the page. Your other divs are absolutely positioned, so they are removed from the page's "flow".

Page flow means that the positioning of an element effects other elements in the flow.

In other words, as #box now sees the dom, .a and .b are no longer "inside" #box.

To fix this, you would want to make everything relative, or everything absolute.

One way would be:

.a {
   position:relative;
   margin-top:10px;
   margin-left:10px;
   background-color:red;
   width:210px;
   padding: 5px;
}

importing go files in same folder

Any number of files in a directory are a single package; symbols declared in one file are available to the others without any imports or qualifiers. All of the files do need the same package foo declaration at the top (or you'll get an error from go build).

You do need GOPATH set to the directory where your pkg, src, and bin directories reside. This is just a matter of preference, but it's common to have a single workspace for all your apps (sometimes $HOME), not one per app.

Normally a Github path would be github.com/username/reponame (not just github.com/xxxx). So if you want to have main and another package, you may end up doing something under workspace/src like

github.com/
  username/
    reponame/
      main.go   // package main, importing "github.com/username/reponame/b"
      b/
        b.go    // package b

Note you always import with the full github.com/... path: relative imports aren't allowed in a workspace. If you get tired of typing paths, use goimports. If you were getting by with go run, it's time to switch to go build: run deals poorly with multiple-file mains and I didn't bother to test but heard (from Dave Cheney here) go run doesn't rebuild dirty dependencies.

Sounds like you've at least tried to set GOPATH to the right thing, so if you're still stuck, maybe include exactly how you set the environment variable (the command, etc.) and what command you ran and what error happened. Here are instructions on how to set it (and make the setting persistent) under Linux/UNIX and here is the Go team's advice on workspace setup. Maybe neither helps, but take a look and at least point to which part confuses you if you're confused.

Java double comparison epsilon

If you are dealing with money I suggest checking the Money design pattern (originally from Martin Fowler's book on enterprise architectural design).

I suggest reading this link for the motivation: http://wiki.moredesignpatterns.com/space/Value+Object+Motivation+v2

How to get absolute path to file in /resources folder of your project

You need to specifie path started from /

URL resource = YourClass.class.getResource("/abc");
Paths.get(resource.toURI()).toFile();

How to resolve conflicts in EGit

To resolve the conflicts, use Git stash to save away your uncommitted changes; then pull down the remote repository change set; then pop your local stash to reapply your uncommitted changes.

In Eclipse v4.5 (Mars) to stash changes (a relatively recent addition, wasn't in previous EGit) I do this: right-click on a top-level Eclipse project that's in Git control, pick Team, pick Stashes, pick Stash Changes; a dialog opens to request a stash commit message.

You must use the context menu on a top level project! If I right click on a directory or file within a Git-controlled project I don't get the appropriate context menu.

NameError: name 'datetime' is not defined

You need to import the module datetime first:

>>> import datetime

After that it works:

>>> import datetime
>>> date = datetime.date.today()
>>> date
datetime.date(2013, 11, 12)

Updating PartialView mvc 4

You can also try this.

 $(document).ready(function () {
            var url = "@(Html.Raw(Url.Action("ActionName", "ControllerName")))";
            $("#PartialViewDivId").load(url);
        setInterval(function () {
            var url = "@(Html.Raw(Url.Action("ActionName", "ControllerName")))";
            $("#PartialViewDivId").load(url);
        }, 30000); //Refreshes every 30 seconds

        $.ajaxSetup({ cache: false });  //Turn off caching
    });

It makes an initial call to load the div, and then subsequent calls are on a 30 second interval.

In the controller section you can update the object and pass the object to the partial view.

public class ControllerName: Controller
{
    public ActionResult ActionName()
    {
        .
        .   // code for update object
        .
        return PartialView("PartialViewName", updatedObject);
    }
}

Clicking submit button of an HTML form by a Javascript code

document.getElementById('loginSubmit').submit();

or, use the same code as the onclick handler:

changeAction('submitInput','loginForm');
document.forms['loginForm'].submit();

(Though that onclick handler is kind of stupidly-written: document.forms['loginForm'] could be replaced with this.)

Extract every nth element of a vector

I think you are asking two things which are not necessarily the same

I want to extract every 6th element of the original

You can do this by indexing a sequence:

foo <- 1:120
foo[1:20*6]

I would like to create a vector in which each element is the i+6th element of another vector.

An easy way to do this is to supplement a logical factor with FALSEs until i+6:

foo <- 1:120
i <- 1
foo[1:(i+6)==(i+6)]
[1]   7  14  21  28  35  42  49  56  63  70  77  84  91  98 105 112 119

i <- 10
foo[1:(i+6)==(i+6)]
[1]  16  32  48  64  80  96 112

How Does Modulus Divison Work

Modulus division is pretty simple. It uses the remainder instead of the quotient.

    1.0833... <-- Quotient
   __
12|13
   12
    1 <-- Remainder
    1.00 <-- Remainder can be used to find decimal values
     .96
     .040
     .036
     .0040 <-- remainder of 4 starts repeating here, so the quotient is 1.083333...

13/12 = 1R1, ergo 13%12 = 1.


It helps to think of modulus as a "cycle".

In other words, for the expression n % 12, the result will always be < 12.

That means the sequence for the set 0..100 for n % 12 is:

{0,1,2,3,4,5,6,7,8,9,10,11,0,1,2,3,4,5,6,7,8,9,10,11,0,[...],4}

In that light, the modulus, as well as its uses, becomes much clearer.

How do you debug PHP scripts?

1) I use print_r(). In TextMate, I have a snippet for 'pre' which expands to this:

echo "<pre>";
print_r();
echo "</pre>";

2) I use Xdebug, but haven't been able to get the GUI to work right on my Mac. It at least prints out a readable version of the stack trace.

Rails 4 LIKE query - ActiveRecord adds quotes

Instead of using the conditions syntax from Rails 2, use Rails 4's where method instead:

def self.search(search, page = 1 )
  wildcard_search = "%#{search}%"

  where("name ILIKE :search OR postal_code LIKE :search", search: wildcard_search)
    .page(page)
    .per_page(5)
end

NOTE: the above uses parameter syntax instead of ? placeholder: these both should generate the same sql.

def self.search(search, page = 1 )
  wildcard_search = "%#{search}%"

  where("name ILIKE ? OR postal_code LIKE ?", wildcard_search, wildcard_search)
    .page(page)
    .per_page(5)
end

NOTE: using ILIKE for the name - postgres case insensitive version of LIKE

pip: no module named _internal

These often comes from using pip to "update" system installed pip, and/or having multiple pip installs under user. My solution was to clean out the multiple installed pips under user, reinstall pip repo, then "pip install --user pip" as above.

See: https://github.com/pypa/pip/issues/5599 for an official complete discussion and fixes for the problem.

Change auto increment starting number?

just export the table with data .. then copy its sql like

CREATE TABLE IF NOT EXISTS `employees` (
  `emp_badgenumber` int(20) NOT NULL AUTO_INCREMENT,
  `emp_fullname` varchar(100) NOT NULL,
  `emp_father_name` varchar(30) NOT NULL,
  `emp_mobile` varchar(20) DEFAULT NULL,
  `emp_cnic` varchar(20) DEFAULT NULL,
  `emp_gender` varchar(10) NOT NULL,
  `emp_is_deleted` tinyint(4) DEFAULT '0',
  `emp_registration_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `emp_overtime_allowed` tinyint(4) DEFAULT '1',
  PRIMARY KEY (`emp_badgenumber`),
  UNIQUE KEY `bagdenumber` (`emp_badgenumber`),
  KEY `emp_badgenumber` (`emp_badgenumber`),
  KEY `emp_badgenumber_2` (`emp_badgenumber`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=111121326 ;

now change auto increment value and execute sql.

"register" keyword in C?

I have tested the register keyword under QNX 6.5.0 using the following code:

#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>
#include <sys/neutrino.h>
#include <sys/syspage.h>

int main(int argc, char *argv[]) {
    uint64_t cps, cycle1, cycle2, ncycles;
    double sec;
    register int a=0, b = 1, c = 3, i;

    cycle1 = ClockCycles();

    for(i = 0; i < 100000000; i++)
        a = ((a + b + c) * c) / 2;

    cycle2 = ClockCycles();
    ncycles = cycle2 - cycle1;
    printf("%lld cycles elapsed\n", ncycles);

    cps = SYSPAGE_ENTRY(qtime) -> cycles_per_sec;
    printf("This system has %lld cycles per second\n", cps);
    sec = (double)ncycles/cps;
    printf("The cycles in seconds is %f\n", sec);

    return EXIT_SUCCESS;
}

I got the following results:

-> 807679611 cycles elapsed

-> This system has 3300830000 cycles per second

-> The cycles in seconds is ~0.244600

And now without register int:

int a=0, b = 1, c = 3, i;

I got:

-> 1421694077 cycles elapsed

-> This system has 3300830000 cycles per second

-> The cycles in seconds is ~0.430700

C# adding a character in a string

Remember a string is immutable so you will need to create a new string.

Strings are IEnumerable so you should be able to run a for loop over it

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string alpha = "abcdefghijklmnopqrstuvwxyz";
            var builder = new StringBuilder();
            int count = 0;
            foreach (var c in alpha)
            {
                builder.Append(c);
                if ((++count % 5) == 0)
                {
                    builder.Append('-');
                }
            }
            Console.WriteLine("Before: {0}", alpha);
            alpha = builder.ToString();
            Console.WriteLine("After: {0}", alpha);
        }
    }
}

Produces this:

Before: abcdefghijklmnopqrstuvwxyz
After: abcde-fghij-klmno-pqrst-uvwxy-z

Configuration with name 'default' not found. Android Studio

Case matters I manually added a submodule :k3b-geohelper to the settings.gradle file

 include ':app', ':k3b-geohelper'

and everthing works fine on my mswindows build system

When i pushed the update to github the fdroid build system failed with

  Cannot evaluate module k3b-geohelper : Configuration with name 'default' not found

The final solution was that the submodule folder was named k3b-geoHelper not k3b-geohelper.

Under MSWindows case doesn-t matter but on linux system it does

Linux shell script for database backup

As a DBA, You must schedule the backup of MySQL Database in case of any issues so that you can recover your databases from the current backup.

Here, we are using mysqldump to take the backup of mysql databases and the same you can put into the script.

[orahow@oradbdb DB_Backup]$ cat .backup_script.sh

#!/bin/bash
# Database credentials
user="root"
password="1Loginxx"
db_name="orahowdb"
v_cnt=0
logfile_path=/DB_Backup
touch "$logfile_path/orahowdb_backup.log"
# Other options
backup_path="/DB_Backup"
date=$(date +"%d-%b-%Y-%H-%M-%p")
# Set default file permissions

Continue Reading .... MySQL Backup

jQuery .each() with input elements

You can use:

$(formId).serializeArray();

How to determine if a number is odd in JavaScript

This is what I did

//Array of numbers
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,32,23,643,67,5876,6345,34,3453];
//Array of even numbers
var evenNumbers = [];
//Array of odd numbers
var oddNumbers = [];

function classifyNumbers(arr){
  //go through the numbers one by one
  for(var i=0; i<=arr.length-1; i++){
     if (arr[i] % 2 == 0 ){
        //Push the number to the evenNumbers array
        evenNumbers.push(arr[i]);
     } else {
        //Push the number to the oddNumbers array
        oddNumbers.push(arr[i]);
     }
  }
}

classifyNumbers(numbers);

console.log('Even numbers: ' + evenNumbers);
console.log('Odd numbers: ' + oddNumbers);

For some reason I had to make sure the length of the array is less by one. When I don't do that, I get "undefined" in the last element of the oddNumbers array.

How to inject JPA EntityManager using spring

The latest Spring + JPA versions solve this problem fundamentally. You can learn more how to use Spring and JPA togather in a separate thread

How to get std::vector pointer to the raw data?

something.data() will return a pointer to the data space of the vector.

How to turn off the Eclipse code formatter for certain sections of Java code?

Not so pretty but works with default settings and for the first line as well:

String query = "" +
    "SELECT FOO, BAR, BAZ" +
    "  FROM ABC          " +
    " WHERE BAR > 4      ";

Equivalent of String.format in jQuery

Made a format function that takes either a collection or an array as arguments

Usage:

format("i can speak {language} since i was {age}",{language:'javascript',age:10});

format("i can speak {0} since i was {1}",'javascript',10});

Code:

var format = function (str, col) {
    col = typeof col === 'object' ? col : Array.prototype.slice.call(arguments, 1);

    return str.replace(/\{\{|\}\}|\{(\w+)\}/g, function (m, n) {
        if (m == "{{") { return "{"; }
        if (m == "}}") { return "}"; }
        return col[n];
    });
};

Excel Calculate the date difference from today from a cell of "7/6/2012 10:26:42"

For the difference between A1 and Today's date you could enter: =ABS(TODAY()-A1)

which returns the (fractional) number of days between the dates.

You're likely getting a #VALUE! error in your formula because Excel treats dates as numbers.

Length of a JavaScript object

Use Object.keys(myObject).length to get the length of object/array

_x000D_
_x000D_
var myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;

console.log(Object.keys(myObject).length); //3
_x000D_
_x000D_
_x000D_

Eclipse Workspaces: What for and why?

The whole point of a workspace is to group a set of related projects together that usually make up an application. The workspace framework comes down to the eclipse.core.resources plugin and it naturally by design makes sense.

Projects have natures, builders are attached to specific projects and as you change resources in one project you can see in real time compile or other issues in projects that are in the same workspace. So the strategy I suggest is have different workspaces for different projects you work on but without a workspace in eclipse there would be no concept of a collection of projects and configurations and after all it's an IDE tool.

If that does not make sense ask how Net Beans or Visual Studio addresses this? It's the same theme. Maven is a good example, checking out a group of related maven projects into a workspace lets you develop and see errors in real time. If not a workspace what else would you suggest? An RCP application can be a different beast depending on what its used for but in the true IDE sense I don't know what would be a better solution than a workspace or context of projects. Just my thoughts. - Duncan

Output Django queryset as JSON

For a efficient solution, you can use .values() function to get a list of dict objects and then dump it to json response by using i.e. JsonResponse (remember to set safe=False).

Once you have your desired queryset object, transform it to JSON response like this:

...
data = list(queryset.values())
return JsonResponse(data, safe=False)

You can specify field names in .values() function in order to return only wanted fields (the example above will return all model fields in json objects).

Windows equivalent to UNIX pwd

cd ,

it will give the current directory

D:\Folder\subFolder>cd ,
D:\Folder\subFolder

What is the best Java library to use for HTTP POST, GET etc.?

Google HTTP Java Client looks good to me because it can run on Android and App Engine as well.

Generic XSLT Search and Replace template

Here's one way in XSLT 2

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;','''')"/>   </xsl:template> </xsl:stylesheet> 

Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:variable name="apos">'</xsl:variable>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;',$apos)"/>   </xsl:template> </xsl:stylesheet> 

How to add to the PYTHONPATH in Windows, so it finds my modules/packages?

From Windows command line:

set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib

To set the PYTHONPATH permanently, add the line to your autoexec.bat. Alternatively, if you edit the system variable through the System Properties, it will also be changed permanently.

Apply CSS rules if browser is IE

A good way to avoid loading multiple CSS files or to have inline CSS is to hand a class to the body tag depending on the version of Internet Explorer. If you only need general IE hacks, you can do something like this, but it can be extended to be version specific:

<!--[if IE ]><body class="ie"><![endif]-->
<!--[if !IE]>--><body><!--<![endif]-->

Now in your css code, you can simply do:

.ie .abc {
  position:absolute;
  left:30;
  top:-10;
}

This also keeps your CSS files valid, as you do not have to use dirty (and invalid) CSS hacks.

String contains - ignore case

You can use java.util.regex.Pattern with the CASE_INSENSITIVE flag for case insensitive matching:

Pattern.compile(Pattern.quote(strptrn), Pattern.CASE_INSENSITIVE).matcher(str1).find();

String MinLength and MaxLength validation don't work (asp.net mvc)

They do now, with latest version of MVC (and jquery validate packages). mvc51-release-notes#Unobtrusive

Thanks to this answer for pointing it out!

C++ -- expected primary-expression before ' '

You don't need "string" in your call to wordLengthFunction().

int wordLength = wordLengthFunction(string word);

should be

int wordLength = wordLengthFunction(word);

How can I add JAR files to the web-inf/lib folder in Eclipse?

Add the jar file to your WEB-INF/lib folder. Right-click your project in Eclipse, and go to "Build Path > Configure Build Path" Add the "Web App Libraries" library This will ensure all WEB-INF/lib jars are included on the classpath. helped me..

Drag and drop in WEB-INF/lib folder and restart eclipse ans start webservice then create client

What is and how to fix System.TypeInitializationException error?

Had a simular issue getting the same exception. Took some time locating. In my case I had a static utility class with a constructor that threw the exception (wrapping it). So my issue was in the static constructor.

How do I make an editable DIV look like a text field?

The problem with all these is they don't address if the lines of text are long and much wider that the div overflow:auto does not ad a scroll bar that works right. Here is the perfect solution I found:

Create two divs. An inner div that is wide enough to handle the widest line of text and then a smaller outer one which acts at the holder for the inner div:

<div style="border:2px inset #AAA;cursor:text;height:120px;overflow:auto;width:500px;">
    <div style="width:800px;">

     now really long text like this can be put in the text area and it will really <br/>
     look and act more like a real text area bla bla bla <br/>

    </div>
</div>

SQL Query to fetch data from the last 30 days?

select status, timeplaced 
from orders 
where TIMEPLACED>'2017-06-12 00:00:00' 

Disable LESS-CSS Overwriting calc()

Using an escaped string (a.k.a. escaped value):

width: ~"calc(100% - 200px)";

Also, in case you need to mix Less math with escaped strings:

width: calc(~"100% - 15rem +" (10px+5px) ~"+ 2em");

Compiles to:

width: calc(100% - 15rem + 15px + 2em);

This works as Less concatenates values (the escaped strings and math result) with a space by default.

How to set a header in an HTTP response?

In my Controller, I merely added an HttpServletResponse parameter and manually added the headers, no filter or intercept required and it works fine:

httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET, OPTIONS");
httpServletResponse.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, X-Auth-Token, X-Csrf-Token, WWW-Authenticate, Authorization");
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "false");
httpServletResponse.setHeader("Access-Control-Max-Age", "3600");

Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing

Lets say an ArrayList object(myList) is filled with those numbers and in that, 2 numbers x and y are missing.So the possible solution can be:

int k = 1;
        while (k < 100) {
            if (!myList.contains(k)) {
                System.out.println("Missing No:" + k);
            }
            k++;
        }

img tag displays wrong orientation

I found part of the solution. Images now have metadata that specify the orientation of the photo. There is a new CSS spec for image-orientation.

Just add this to your CSS:

img {
    image-orientation: from-image;
}

According to the spec as of Jan 25 2016, Firefox and iOS Safari (behind a prefix) are the only browsers that support this. I'm seeing issues with Safari and Chrome still. However, mobile Safari seems to natively support orientation without the CSS tag.

I suppose we'll have to wait and see if browsers wills start supporting image-orientation.

How to return a specific status code and no contents from Controller?

This code might work for non-.NET Core MVC controllers:

this.HttpContext.Response.StatusCode = 418; // I'm a teapot
return Json(new { status = "mer" }, JsonRequestBehavior.AllowGet);

How To change the column order of An Existing Table in SQL Server 2008

If your table doesn't have any records you can just drop then create your table.

If it has records you can do it using your SQL Server Management Studio.

Just click your table > right click > click Design then you can now arrange the order of the columns by dragging the fields on the order that you want then click save.

Best Regards

find . -type f -exec chmod 644 {} ;

Piping to xargs is a dirty way of doing that which can be done inside of find.

find . -type d -exec chmod 0755 {} \;
find . -type f -exec chmod 0644 {} \;

You can be even more controlling with other options, such as:

find . -type d -user harry -exec chown daisy {} \;

You can do some very cool things with find and you can do some very dangerous things too. Have a look at "man find", it's long but is worth a quick read. And, as always remember:

  • If you are root it will succeed.
  • If you are in root (/) you are going to have a bad day.
  • Using /path/to/directory can make things a lot safer as you are clearly defining where you want find to run.

Python how to write to a binary file?

Use struct.pack to convert the integer values into binary bytes, then write the bytes. E.g.

newFile.write(struct.pack('5B', *newFileBytes))

However I would never give a binary file a .txt extension.

The benefit of this method is that it works for other types as well, for example if any of the values were greater than 255 you could use '5i' for the format instead to get full 32-bit integers.

How to check if a JavaScript variable is NOT undefined?

var lastname = "Hi";

if(typeof lastname !== "undefined")
{
  alert("Hi. Variable is defined.");
} 

jquery can't get data attribute value

Iyap . Its work Case sensitive in data name data-x10

var variable = $('#myButton').data("x10"); // we get the value of custom data attribute

How do you remove an invalid remote branch reference from Git?

I had a similar problem. None of the answers helped. In my case, I had two removed remote repositories showing up permanently.

My last idea was to remove all references to it by hand.

Let's say the repository is called “Repo”. I did:

find .git -name Repo 

So, I deleted the corresponding files and directories from the .git folder (this folder could be found in your Rails app or on your computer https://stackoverflow.com/a/19538763/6638513).

Then I did:

grep Repo -r .git

This found some text files in which I removed the corresponding lines. Now, everything seems to be fine.

Usually, you should leave this job to git.

jQuery Array of all selected checkboxes (by class)

You can also add underscore.js to your project and will be able to do it in one line:

_.map($("input[name='category_ids[]']:checked"), function(el){return $(el).val()})

Bootstrap push div content to new line

Do a row div.

Like this:

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">_x000D_
<div class="grid">_x000D_
    <div class="row">_x000D_
        <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 bg-success">Under me should be a DIV</div>_x000D_
        <div class="col-lg-6 col-md-6 col-sm-5 col-xs-12 bg-danger">Under me should be a DIV</div>_x000D_
    </div>_x000D_
    <div class="row">_x000D_
        <div class="col-lg-3 col-md-3 col-sm-4 col-xs-12 bg-warning">I am the last DIV</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Converting a generic list to a CSV string

You can create an extension method that you can call on any IEnumerable:

public static string JoinStrings<T>(
    this IEnumerable<T> values, string separator)
{
    var stringValues = values.Select(item =>
        (item == null ? string.Empty : item.ToString()));
    return string.Join(separator, stringValues.ToArray());
}

Then you can just call the method on the original list:

string commaSeparated = myList.JoinStrings(", ");

Preview an image before it is uploaded

For Multiple image upload (Modification to the @IvanBaev's Solution)

function readURL(input) {
    if (input.files && input.files[0]) {
        var i;
        for (i = 0; i < input.files.length; ++i) {
          var reader = new FileReader();
          reader.onload = function (e) {
              $('#form1').append('<img src="'+e.target.result+'">');
          }
          reader.readAsDataURL(input.files[i]);
        }
    }
}

http://jsfiddle.net/LvsYc/12330/

Hope this helps someone.

cursor.fetchall() vs list(cursor) in Python

You could use list comprehensions to bring the item in your tuple into a list:

conn = mysql.connector.connect()
cursor = conn.cursor()
sql = "SELECT column_name FROM db.table_name;"
cursor.execute(sql)

results = cursor.fetchall()
# bring the first item of the tuple in your results here
item_0_in_result = [_[0] for _ in results]

List the queries running on SQL Server

There are various management views built into the product. On SQL 2000 you'd use sysprocesses. On SQL 2K5 there are more views like sys.dm_exec_connections, sys.dm_exec_sessions and sys.dm_exec_requests.

There are also procedures like sp_who that leverage these views. In 2K5 Management Studio you also get Activity Monitor.

And last but not least there are community contributed scripts like the Who Is Active by Adam Machanic.

How to check if an integer is in a given range?

ValueRange range = java.time.temporal.ValueRange.of(minValue, maxValue);
range.isValidIntValue(x);

it returns true if minValue <= x <= MaxValue - i.e within the range

it returns false if x < minValue or x > maxValue - i.e outofrange

Use with if condition as shown below:

int value = 10;
if(ValueRange.of(0, 100).isValidIntValue(value)) {
    System.out.println("Value is with in the Range.");
} else {
    System.out.println("Value is out of the Range.");
}

below program checks, if any of the passed integer value in the hasTeen method is within the range of 13(inclusive) to 19(Inclusive)


import java.time.temporal.ValueRange;    
public class TeenNumberChecker {

    public static void main(String[] args) {
        System.out.println(hasTeen(9, 99, 19));
        System.out.println(hasTeen(23, 15, 42));
        System.out.println(hasTeen(22, 23, 34));

    }

    public static boolean hasTeen(int firstNumber, int secondNumber, int thirdNumber) {

        ValueRange range = ValueRange.of(13, 19);
        System.out.println("*********Int validation Start ***********");
        System.out.println(range.isIntValue());
        System.out.println(range.isValidIntValue(firstNumber));
        System.out.println(range.isValidIntValue(secondNumber));
        System.out.println(range.isValidIntValue(thirdNumber));
        System.out.println(range.isValidValue(thirdNumber));
        System.out.println("**********Int validation End**************");

        if (range.isValidIntValue(firstNumber) || range.isValidIntValue(secondNumber) || range.isValidIntValue(thirdNumber)) {
            return true;
        } else
            return false;
    }
}

******OUTPUT******

true as 19 is part of range

true as 15 is part of range

false as all three value passed out of range

Asserting successive calls to a mock method

You can use the Mock.call_args_list attribute to compare parameters to previous method calls. That in conjunction with Mock.call_count attribute should give you full control.

Displaying the build date

I just added pre-build event command:

powershell -Command Get-Date -Format 'yyyy-MM-ddTHH:mm:sszzz' > Resources\BuildDateTime.txt

in the project properties to generate a resource file that is then easy to read from the code.

How to apply box-shadow on all four sides?

Use this css code for all four sides: box-shadow: 0px 1px 7px 0px rgb(106, 111, 109);

How do I localize the jQuery UI Datepicker?

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src=">/js/datepicker-fr.js"></script>
<script>
jQuery(function() {
jQuery( "#datepicker" ).datepicker({minDate: 0 , dateFormat: 'mm/dd/yy'});
});

</script>

<script type="text/javascript">
$(document).ready(function(){
$('#datepicker').datepicker($.datepicker.regional['fr']);
});
</script>

How to convert JSON to XML or XML to JSON?

You can do these conversions also with the .NET Framework:

JSON to XML: by using System.Runtime.Serialization.Json

var xml = XDocument.Load(JsonReaderWriterFactory.CreateJsonReader(
    Encoding.ASCII.GetBytes(jsonString), new XmlDictionaryReaderQuotas()));

XML to JSON: by using System.Web.Script.Serialization

var json = new JavaScriptSerializer().Serialize(GetXmlData(XElement.Parse(xmlString)));

private static Dictionary<string, object> GetXmlData(XElement xml)
{
    var attr = xml.Attributes().ToDictionary(d => d.Name.LocalName, d => (object)d.Value);
    if (xml.HasElements) attr.Add("_value", xml.Elements().Select(e => GetXmlData(e)));
    else if (!xml.IsEmpty) attr.Add("_value", xml.Value);

    return new Dictionary<string, object> { { xml.Name.LocalName, attr } };
}

The representation of if-elseif-else in EL using JSF

One possible solution is:

<h:panelGroup rendered="#{bean.row == 10}">
    <div class="text-success">
        <h:outputText value="#{bean.row}"/>
    </div>
</h:panelGroup>

How to call a method in another class of the same package?

By calling method

public class a 
{
    void sum(int i,int k)
    {
        System.out.println("THe sum of the number="+(i+k));
    }
}
class b
{
    public static void main(String[] args)
    {
        a vc=new a();
        vc.sum(10 , 20);
    }
}

How to display the string html contents into webbrowser control?

For some reason the code supplied by m3z (with the DisplayHtml(string) method) is not working in my case (except first time). I'm always displaying html from string. Here is my version after the battle with the WebBrowser control:

webBrowser1.Navigate("about:blank");
while (webBrowser1.Document == null || webBrowser1.Document.Body == null)
    Application.DoEvents();
webBrowser1.Document.OpenNew(true).Write(html);

Working every time for me. I hope it helps someone.

Find the PID of a process that uses a port on Windows

Command:

netstat -aon | findstr 4723

Output:

TCP    0.0.0.0:4723           0.0.0.0:0                LISTENING       10396

Now cut the process ID, "10396", using the for command in Windows.

Command:

for /f "tokens=5" %a in ('netstat -aon ^| findstr 4723') do @echo %~nxa

Output:

10396

If you want to cut the 4th number of the value means "LISTENING" then command in Windows.

Command:

for /f "tokens=4" %a in ('netstat -aon ^| findstr 4723') do @echo %~nxa

Output:

LISTENING

jQuery keypress() event not firing?

e.which doesn't work in IE try e.keyCode, also you probably want to use keydown() instead of keypress() if you are targeting IE.

See http://unixpapa.com/js/key.html for more information.

How do I add a placeholder on a CharField in Django?

For a ModelForm, you can use the Meta class thus:

from django import forms

from .models import MyModel

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
        widgets = {
            'name': forms.TextInput(attrs={'placeholder': 'Name'}),
            'description': forms.Textarea(
                attrs={'placeholder': 'Enter description here'}),
        }

batch/bat to copy folder and content at once

I've been interested in the original question here and related ones.

For an answer, this week I did some experiments with XCOPY.

To help answer the original question, here I post the results of my experiments.

I did the experiments on Windows 7 64 bit Professional SP1 with the copy of XCOPY that came with the operating system.

For the experiments, I wrote some code in the scripting language Open Object Rexx and the editor macro language Kexx with the text editor KEdit.

XCOPY was called from the Rexx code. The Kexx code edited the screen output of XCOPY to focus on the crucial results.

The experiments all had to do with using XCOPY to copy one directory with several files and subdirectories.

The experiments consisted of 10 cases. Each case adjusted the arguments to XCOPY and called XCOPY once. All 10 cases were attempting to do the same copying operation.

Here are the main results:

(1) Of the 10 cases, only three did copying. The other 7 cases right away, just from processing the arguments to XCOPY, gave error messages, e.g.,

Invalid path

Access denied

with no files copied.

Of the three cases that did copying, they all did the same copying, that is, gave the same results.

(2) If want to copy a directory X and all the files and directories in directory X, in the hierarchical file system tree rooted at directory X, then apparently XCOPY -- and this appears to be much of the original question -- just will NOT do that.

One consequence is that if using XCOPY to copy directory X and its contents, then CAN copy the contents but CANNOT copy the directory X itself; thus, lose the time-date stamp on directory X, its archive bit, data on ownership, attributes, etc.

Of course if directory X is a subdirectory of directory Y, an XCOPY of Y will copy all of the contents of directory Y WITH directory X. So in this way can get a copy of directory X. However, the copy of directory X will have its time-date stamp of the time of the run of XCOPY and NOT the time-date stamp of the original directory X.

This change in time-date stamps can be awkward for a copy of a directory with a lot of downloaded Web pages: The HTML file of the Web page will have its original time-date stamp, but the corresponding subdirectory for files used by the HTML file will have the time-date stamp of the run of XCOPY. So, when sorting the copy on time date stamps, all the subdirectories, the HTML files and the corresponding subdirectories, e.g.,

x.htm

x_files

can appear far apart in the sort on time-date.

Hierarchical file systems go way back, IIRC to Multics at MIT in 1969, and since then lots of people have recognized the two cases, given a directory X, (i) copy directory X and all its contents and (ii) copy all the contents of X but not directory X itself. Well, if only from the experiments, XCOPY does only (ii).

So, the results of the 10 cases are below. For each case, in the results the first three lines have the first three arguments to XCOPY. So, the first line has the tree name of the directory to be copied, the 'source'; the second line has the tree name of the directory to get the copies, the 'destination', and the third line has the options for XCOPY. The remaining 1-2 lines have the results of the run of XCOPY.

One big point about the options is that options /X and /O result in result

Access denied

To see this, compare case 8 with the other cases that were the same, did not have /X and /O, but did copy.

These experiments have me better understand XCOPY and contribute an answer to the original question.

======= case 1 ==================
"k:\software\dir_time-date\"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_1\"
options = /E /F /G /H /K /O /R /V /X /Y
Result:  Invalid path
Result:  0 File(s) copied
======= case 2 ==================
"k:\software\dir_time-date\*"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_2\"
options = /E /F /G /H /K /O /R /V /X /Y
Result:  Access denied
Result:  0 File(s) copied
======= case 3 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_3\"
options = /E /F /G /H /K /O /R /V /X /Y
Result:  Access denied
Result:  0 File(s) copied
======= case 4 ==================
"k:\software\dir_time-date\"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_4\"
options = /E /F /G /H /K /R /V /Y
Result:  Invalid path
Result:  0 File(s) copied
======= case 5 ==================
"k:\software\dir_time-date\"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_5\"
options = /E /F /G /H /K /O /R /S /X /Y
Result:  Invalid path
Result:  0 File(s) copied
======= case 6 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_6\"
options = /E /F /G /H /I /K /O /R /S /X /Y
Result:  Access denied
Result:  0 File(s) copied
======= case 7 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_7"
options = /E /F /G /H /I /K /R /S /Y
Result:  20 File(s) copied
======= case 8 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_8"
options = /E /F /G /H /I /K /O /R /S /X /Y
Result:  Access denied
Result:  0 File(s) copied
======= case 9 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_9"
options = /I /S
Result:  20 File(s) copied
======= case 10 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_10"
options = /E /I /S
Result:  20 File(s) copied

How to change to an older version of Node.js

nvm install 0.5.0 #install previous version of choice

nvm alias default 0.5.0 #set it to default

nvm use default #use the new default as active version globally.

Without the last, the active version doesn't change to the new default. So, when you open a new terminal or restart server, the old default version remains active.

Jquery $.ajax fails in IE on cross domain calls

Jquery does this for you, only thing is to set $.support.cors = true; Then cross domain request works fine in all browsers for jquery users.

Is true == 1 and false == 0 in JavaScript?

When compare something with Boolean it works like following

Step 1: Convert boolean to Number Number(true) // 1 and Number(false) // 0

Step 2: Compare both sides

boolean == someting 
-> Number(boolean) === someting

If compare 1 and 2 with true you will get the following results

true == 1
-> Number(true) === 1
-> 1 === 1
-> true

And

true == 2
-> Number(true) === 1
-> 1 === 2
-> false

Getting the HTTP Referrer in ASP.NET

Belonging to other reply, I have added condition clause for getting null.

string ComingUrl = "";
if (Request.UrlReferrer != null)
{
    ComingUrl = System.Web.HttpContext.Current.Request.UrlReferrer.ToString();
}
else
{
    ComingUrl = "Direct"; // Your code
}

How to convert numbers between hexadecimal and decimal

    static string chex(byte e)                  // Convert a byte to a string representing that byte in hexadecimal
    {
        string r = "";
        string chars = "0123456789ABCDEF";
        r += chars[e >> 4];
        return r += chars[e &= 0x0F];
    }           // Easy enough...

    static byte CRAZY_BYTE(string t, int i)     // Take a byte, if zero return zero, else throw exception (i=0 means false, i>0 means true)
    {
        if (i == 0) return 0;
        throw new Exception(t);
    }

    static byte hbyte(string e)                 // Take 2 characters: these are hex chars, convert it to a byte
    {                                           // WARNING: This code will make small children cry. Rated R.
        e = e.ToUpper(); // 
        string msg = "INVALID CHARS";           // The message that will be thrown if the hex str is invalid

        byte[] t = new byte[]                   // Gets the 2 characters and puts them in seperate entries in a byte array.
        {                                       // This will throw an exception if (e.Length != 2).
            (byte)e[CRAZY_BYTE("INVALID LENGTH", e.Length ^ 0x02)], 
            (byte)e[0x01] 
        };

        for (byte i = 0x00; i < 0x02; i++)      // Convert those [ascii] characters to [hexadecimal] characters. Error out if either character is invalid.
        {
            t[i] -= (byte)((t[i] >= 0x30) ? 0x30 : CRAZY_BYTE(msg, 0x01));                                  // Check for 0-9
            t[i] -= (byte)((!(t[i] < 0x0A)) ? (t[i] >= 0x11 ? 0x07 : CRAZY_BYTE(msg, 0x01)) : 0x00);        // Check for A-F
        }           

        return t[0x01] |= t[0x00] <<= 0x04;     // The moment of truth.
    }

@Transactional(propagation=Propagation.REQUIRED)

To understand the various transactional settings and behaviours adopted for Transaction management, such as REQUIRED, ISOLATION etc. you'll have to understand the basics of transaction management itself.

Read Trasaction management for more on explanation.

Fill drop down list on selection of another drop down list

enter image description here

enter image description here

enter image description here

Model:

namespace MvcApplicationrazor.Models
{
    public class CountryModel
    {
        public List<State> StateModel { get; set; }
        public SelectList FilteredCity { get; set; }
    }
    public class State
    {
        public int Id { get; set; }
        public string StateName { get; set; }
    }
    public class City
    {
        public int Id { get; set; }
        public int StateId { get; set; }
        public string CityName { get; set; }
    }
}   

Controller:

public ActionResult Index()
        {
            CountryModel objcountrymodel = new CountryModel();
            objcountrymodel.StateModel = new List<State>();
            objcountrymodel.StateModel = GetAllState();
            return View(objcountrymodel);
        }


        //Action result for ajax call
        [HttpPost]
        public ActionResult GetCityByStateId(int stateid)
        {
            List<City> objcity = new List<City>();
            objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
            SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
            return Json(obgcity);
        }
        // Collection for state
        public List<State> GetAllState()
        {
            List<State> objstate = new List<State>();
            objstate.Add(new State { Id = 0, StateName = "Select State" });
            objstate.Add(new State { Id = 1, StateName = "State 1" });
            objstate.Add(new State { Id = 2, StateName = "State 2" });
            objstate.Add(new State { Id = 3, StateName = "State 3" });
            objstate.Add(new State { Id = 4, StateName = "State 4" });
            return objstate;
        }
        //collection for city
        public List<City> GetAllCity()
        {
            List<City> objcity = new List<City>();
            objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
            objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
            objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
            objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
            objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
            objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
            return objcity;
        }

View:

@model MvcApplicationrazor.Models.CountryModel
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
    function GetCity(_stateId) {
        var procemessage = "<option value='0'> Please wait...</option>";
        $("#ddlcity").html(procemessage).show();
        var url = "/Test/GetCityByStateId/";

        $.ajax({
            url: url,
            data: { stateid: _stateId },
            cache: false,
            type: "POST",
            success: function (data) {
                var markup = "<option value='0'>Select City</option>";
                for (var x = 0; x < data.length; x++) {
                    markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                }
                $("#ddlcity").html(markup).show();
            },
            error: function (reponse) {
                alert("error : " + reponse);
            }
        });

    }
</script>
<h4>
 MVC Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm())
{
    @Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
    <br />
    <br />
    <select id="ddlcity" name="ddlcity" style="width: 200px">

    </select>

    <br /><br />
  }

Adb install failure: INSTALL_CANCELED_BY_USER

In addition, any app lock password should be removed by SETTINGS>APP LOCK ,enter the set password and remove the lock. This worked for me on REDMI 4A

Adding hours to JavaScript Date object?

The below code is to add 4 hours to date(example today's date)

var today = new Date();
today.setHours(today.getHours() + 4);

It will not cause error if you try to add 4 to 23 (see the docs):

If a parameter you specify is outside of the expected range, setHours() attempts to update the date information in the Date object accordingly

Which characters are valid in CSS class names/selectors?

To my surprise most answers here are wrong. It turns out that:

Any character except NUL is allowed in CSS class names in CSS. (If CSS contains NUL (escaped or not), the result is undefined. [CSS-characters])

Mathias Bynens' answer links to explanation and demos showing how to use these names. Written down in CSS code, a class name may need escaping, but that doesn’t change the class name. E.g. an unnecessarily over-escaped representation will look different from other representations of that name, but it still refers to the same class name.

Most other (programming) languages don’t have that concept of escaping variable names (“identifiers”), so all representations of a variable have to look the same. This is not the case in CSS.

Note that in HTML there is no way to include space characters (space, tab, line feed, form feed and carriage return) in a class name attribute, because they already separate classes from each other.

So, if you need to turn a random string into a CSS class name: take care of NUL and space, and escape (accordingly for CSS or HTML). Done.

How do I sort a vector of pairs based on the second element of the pair?

With C++0x we can use lambda functions:

using namespace std;
vector<pair<int, int>> v;
        .
        .
sort(v.begin(), v.end(),
     [](const pair<int, int>& lhs, const pair<int, int>& rhs) {
             return lhs.second < rhs.second; } );

In this example the return type bool is implicitly deduced.

Lambda return types

When a lambda-function has a single statement, and this is a return-statement, the compiler can deduce the return type. From C++11, §5.1.2/4:

...

  • If the compound-statement is of the form { return expression ; } the type of the returned expression after lvalue-to-rvalue conversion (4.1), array-to-pointer conversion (4.2), and function-to-pointer conversion (4.3);
  • otherwise, void.

To explicitly specify the return type use the form []() -> Type { }, like in:

sort(v.begin(), v.end(),
     [](const pair<int, int>& lhs, const pair<int, int>& rhs) -> bool {
             if (lhs.second == 0)
                 return true;
             return lhs.second < rhs.second; } );

Converting a date in MySQL from string field

This:

STR_TO_DATE(t.datestring, '%d/%m/%Y')

...will convert the string into a datetime datatype. To be sure that it comes out in the format you desire, use DATE_FORMAT:

DATE_FORMAT(STR_TO_DATE(t.datestring, '%d/%m/%Y'), '%Y-%m-%d')

If you can't change the datatype on the original column, I suggest creating a view that uses the STR_TO_DATE call to convert the string to a DateTime data type.

Android error: Failed to install *.apk on device *: timeout

Try changing the ADB connection timeout. I think it defaults that to 5000ms and I changed mine to 10000ms to get rid of that problem.

If you are in Eclipse, you can do this by going through

Window -> Preferences -> Android -> DDMS -> ADB Connection Timeout (ms)

Multiple files upload (Array) with CodeIgniter 2.0

SO what I change is I load upload library each time

                $config = array();
                $config['upload_path'] = $filePath;
                $config['allowed_types'] = 'gif|jpg|png';
                $config['max_size']      = '0';
                $config['overwrite']     = FALSE;

                $files = $_FILES;
                $count = count($_FILES['nameUpload']['name']);


                for($i=0; $i<$count; $i++)
                {
                    $this->load->library('upload', $config);

                    $_FILES['nameUpload']['name']= $files['nameUpload']['name'][$i];
                    $_FILES['nameUpload']['type']= $files['nameUpload']['type'][$i];
                    $_FILES['nameUpload']['tmp_name']= $files['nameUpload']['tmp_name'][$i];
                    $_FILES['nameUpload']['error']= $files['nameUpload']['error'][$i];
                    $_FILES['nameUpload']['size']= $files['nameUpload']['size'][$i];

                    $this->upload->do_upload('nameUpload');
                }

And it work for me.

Check if value exists in Postgres array

When looking for the existence of a element in an array, proper casting is required to pass the SQL parser of postgres. Here is one example query using array contains operator in the join clause:

For simplicity I only list the relevant part:

table1 other_name text[]; -- is an array of text

The join part of SQL shown

from table1 t1 join table2 t2 on t1.other_name::text[] @> ARRAY[t2.panel::text]

The following also works

on t2.panel = ANY(t1.other_name)

I am just guessing that the extra casting is required because the parse does not have to fetch the table definition to figure the exact type of the column. Others please comment on this.

Linux delete file with size 0

You can use the command find to do this. We can match files with -type f, and match empty files using -size 0. Then we can delete the matches with -delete.

find . -type f -size 0 -delete

How to show all of columns name on pandas dataframe?

To obtain all the column names of a DataFrame, df_data in this example, you just need to use the command df_data.columns.values. This will show you a list with all the Column names of your Dataframe

Code:

df_data=pd.read_csv('../input/data.csv')
print(df_data.columns.values)

Output:

['PassengerId' 'Survived' 'Pclass' 'Name' 'Sex' 'Age' 'SibSp' 'Parch' 'Ticket' 'Fare' 'Cabin' 'Embarked']

What does "collect2: error: ld returned 1 exit status" mean?

Include: #include<stdlib.h>

and use System("cls") instead of clrscr()

Drop all tables command

I'd like to add to other answers involving dropping tables and not deleting the file, that you can also execute delete from sqlite_sequence to reset auto-increment sequences.

How to run multiple SQL commands in a single SQL connection?

using (var connection = new SqlConnection("Enter Your Connection String"))
    {
        connection.Open();
    
        using (var command = connection.CreateCommand())
        {
            command.CommandText = "Enter the First Command Here";
            command.ExecuteNonQuery();
    
            command.CommandText = "Enter Second Comand Here";
            command.ExecuteNonQuery();

    //Similarly You can Add Multiple
        }
    }

Querying data by joining two tables in two database on different servers

While I was having trouble join those two tables, I got away with doing exactly what I wanted by opening both remote databases at the same time. MySQL 5.6 (php 7.1) and the other MySQL 5.1 (php 5.6)

//Open a new connection to the MySQL server
$mysqli1 = new mysqli('server1','user1','password1','database1');
$mysqli2 = new mysqli('server2','user2','password2','database2');

//Output any connection error
if ($mysqli1->connect_error) {
    die('Error : ('. $mysqli1->connect_errno .') '. $mysqli1->connect_error);
} else { 
echo "DB1 open OK<br>";
}
if ($mysqli2->connect_error) {
    die('Error : ('. $mysqli2->connect_errno .') '. $mysqli2->connect_error);
} else { 
echo "DB2 open OK<br><br>";
}

If you get those two OKs on screen, then both databases are open and ready. Then you can proceed to do your querys.

$results = $mysqli1->query("SELECT * FROM video where video_id_old is NULL");
    while($row = $results->fetch_array()) {
        $theID = $row[0];
        echo "Original ID : ".$theID." <br>";
        $doInsert = $mysqli2->query("INSERT INTO video (...) VALUES (...)");
        $doGetVideoID = $mysqli2->query("SELECT video_id, time_stamp from video where user_id = '".$row[13]."' and time_stamp = ".$row[28]." ");
            while($row = $doGetVideoID->fetch_assoc()) {
                echo "New video_id : ".$row["video_id"]." user_id : ".$row["user_id"]." time_stamp : ".$row["time_stamp"]."<br>";
                $sql = "UPDATE video SET video_id_old = video_id, video_id = ".$row["video_id"]." where user_id = '".$row["user_id"]."' and video_id = ".$theID.";";
                $sql .= "UPDATE video_audio SET video_id = ".$row["video_id"]." where video_id = ".$theID.";";
                // Execute multi query if you want
                if (mysqli_multi_query($mysqli1, $sql)) {
                    // Query successful do whatever...
                }
            }
    }
// close connection 
$mysqli1->close();
$mysqli2->close();

I was trying to do some joins but since I got those two DBs open, then I can go back and forth doing querys by just changing the connection $mysqli1 or $mysqli2

It worked for me, I hope it helps... Cheers

JavaScript null check

Q: The function was called with no arguments, thus making data an undefined variable, and raising an error on data != null.

A: Yes, data will be set to undefined. See section 10.5 Declaration Binding Instantiation of the spec. But accessing an undefined value does not raise an error. You're probably confusing this with accessing an undeclared variable in strict mode which does raise an error.

Q: The function was called specifically with null (or undefined), as its argument, in which case data != null already protects the inner code, rendering && data !== undefined useless.

Q: The function was called with a non-null argument, in which case it will trivially pass both data != null and data !== undefined.

A: Correct. Note that the following tests are equivalent:

data != null
data != undefined
data !== null && data !== undefined

See section 11.9.3 The Abstract Equality Comparison Algorithm and section 11.9.6 The Strict Equality Comparison Algorithm of the spec.

How can I add shadow to the widget in flutter?

Screenshot:

enter image description here


  1. Using BoxShadow (more customizations):

    Container(
      width: 100,
      height: 100,
      decoration: BoxDecoration(
        color: Colors.teal,
        borderRadius: BorderRadius.circular(20),
        boxShadow: [
          BoxShadow(
            color: Colors.red,
            blurRadius: 4,
            offset: Offset(4, 8), // Shadow position
          ),
        ],
      ),
    )
    

  1. Using PhysicalModel:

    PhysicalModel(
      color: Colors.teal,
      elevation: 8,
      shadowColor: Colors.red,
      borderRadius: BorderRadius.circular(20),
      child: SizedBox(width: 100, height: 100),
    )
    

Setting Action Bar title and subtitle

Try This

Just go to your Manifest file. and You have define the label for each activity in your manifest file.

<activity
        android:name=".Search_Video"
        android:label="@string/app_name"
        android:screenOrientation="portrait">
    </activity>

here change

android:label="@string/your_title"

adding x and y axis labels in ggplot2

[Note: edited to modernize ggplot syntax]

Your example is not reproducible since there is no ex1221new (there is an ex1221 in Sleuth2, so I guess that is what you meant). Also, you don't need (and shouldn't) pull columns out to send to ggplot. One advantage is that ggplot works with data.frames directly.

You can set the labels with xlab() and ylab(), or make it part of the scale_*.* call.

library("Sleuth2")
library("ggplot2")
ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area() + 
  xlab("My x label") +
  ylab("My y label") +
  ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

enter image description here

ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area("Nitrogen") + 
  scale_x_continuous("My x label") +
  scale_y_continuous("My y label") +
  ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

enter image description here

An alternate way to specify just labels (handy if you are not changing any other aspects of the scales) is using the labs function

ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area() + 
  labs(size= "Nitrogen",
       x = "My x label",
       y = "My y label",
       title = "Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

which gives an identical figure to the one above.

Displaying one div on top of another

Here is the jsFiddle

#backdrop{
    border: 2px solid red;
    width: 400px;
    height: 200px;
    position: absolute;
}

#curtain {
    border: 1px solid blue;
    width: 400px;
    height: 200px;
    position: absolute;
}

Use Z-index to move the one you want on top.

What is a regular expression which will match a valid domain name without a subdomain?

This answer is for domain names (including service RRs), not host names (like an email hostname).

^(?=.{1,253}\.?$)(?:(?!-|[^.]+_)[A-Za-z0-9-_]{1,63}(?<!-)(?:\.|$)){2,}$

It is basically mkyong's answer and additionally:

  • Max length of 255 octets including length prefixes and null root.
  • Allow trailing '.' for explicit dns root.
  • Allow leading '_' for service domain RRs, (bugs: doesn't enforce 15 char max for _ labels, nor does it require at least one domain above service RRs)
  • Matches all possible TLDs.
  • Doesn't capture subdomain labels.

By Parts

Lookahead, limit max length between ^$ to 253 characters with optional trailing literal '.'

(?=.{1,253}\.?$)

Lookahead, next character is not a '-' and no '_' follows any characters before the next '.'. That is to say, enforce that the first character of a label isn't a '-' and only the first character may be a '_'.

(?!-|[^.]+_)

Between 1 and 63 of the allowed characters per label.

[A-Za-z0-9-_]{1,63}

Lookbehind, previous character not '-'. That is to say, enforce that the last character of a label isn't a '-'.

(?<!-)

Force a '.' at the end of every label except the last, where it is optional.

(?:\.|$)

Mostly combined from above, this requires at least two domain levels, which is not quite correct, but usually a reasonable assumption. Change from {2,} to + if you want to allow TLDs or unqualified relative subdomains through (eg, localhost, myrouter, to.)

(?:(?!-|[^.]+_)[A-Za-z0-9-_]{1,63}(?<!-)(?:\.|$)){2,}

Unit tests for this expression.

Flexbox: how to get divs to fill up 100% of the container width without wrapping?

To prevent the flex items from shrinking, set the flex shrink factor to 0:

The flex shrink factor determines how much the flex item will shrink relative to the rest of the flex items in the flex container when negative free space is distributed. When omitted, it is set to 1.

.boxcontainer .box {
  flex-shrink: 0;
}

_x000D_
_x000D_
* {_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
.wrapper {_x000D_
  width: 200px;_x000D_
  background-color: #EEEEEE;_x000D_
  border: 2px solid #DDDDDD;_x000D_
  padding: 1rem;_x000D_
}_x000D_
.boxcontainer {_x000D_
  position: relative;_x000D_
  left: 0;_x000D_
  border: 2px solid #BDC3C7;_x000D_
  transition: all 0.4s ease;_x000D_
  display: flex;_x000D_
}_x000D_
.boxcontainer .box {_x000D_
  width: 100%;_x000D_
  padding: 1rem;_x000D_
  flex-shrink: 0;_x000D_
}_x000D_
.boxcontainer .box:first-child {_x000D_
  background-color: #F47983;_x000D_
}_x000D_
.boxcontainer .box:nth-child(2) {_x000D_
  background-color: #FABCC1;_x000D_
}_x000D_
#slidetrigger:checked ~ .wrapper .boxcontainer {_x000D_
  left: -100%;_x000D_
}_x000D_
#overflowtrigger:checked ~ .wrapper {_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<input type="checkbox" id="overflowtrigger" />_x000D_
<label for="overflowtrigger">Hide overflow</label><br />_x000D_
<input type="checkbox" id="slidetrigger" />_x000D_
<label for="slidetrigger">Slide!</label>_x000D_
<div class="wrapper">_x000D_
  <div class="boxcontainer">_x000D_
    <div class="box">_x000D_
      First bunch of content._x000D_
    </div>_x000D_
    <div class="box">_x000D_
      Second load  of content._x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Does the join order matter in SQL?

for regular Joins, it doesn't. TableA join TableB will produce the same execution plan as TableB join TableA (so your C and D examples would be the same)

for left and right joins it does. TableA left Join TableB is different than TableB left Join TableA, BUT its the same than TableB right Join TableA

Convert the values in a column into row names in an existing data frame

As of 2016 you can also use the tidyverse.

library(tidyverse)
samp %>% remove_rownames %>% column_to_rownames(var="names")

Cannot download Docker images behind a proxy

As I am not allowed to comment yet:

For CentOS 7 I needed to activate the EnvironmentFile within "docker.service" like it is described here: Control and configure Docker with systemd.

Edit: I am adding my solution as stated out by Nilesh. I needed to open "/etc/systemd/system/docker.service" and I had to add within the section

[Service]

EnvironmentFile=-/etc/sysconfig/docker

Only then was the file "etc/sysconfig/docker" loaded on my system.

What is the simplest way to write the contents of a StringBuilder to a text file in .NET 1.1?

StreamWriter is available for NET 1.1. and for the Compact framework. Just open the file and apply the ToString to your StringBuilder:

    StringBuilder sb = new StringBuilder();
    sb.Append(......);

    StreamWriter sw = new StreamWriter("\\hereIAm.txt", true);
    sw.Write(sb.ToString());
    sw.Close();

Also, note that you say that you want to append debug messages to the file (like a log). In this case, the correct constructor for StreamWriter is the one that accepts an append boolean flag. If true then it tries to append to an existing file or create a new one if it doesn't exists.

Get input value from TextField in iOS alert in Swift

Swift 3/4

You can use the below extension for your convenience.

Usage inside a ViewController:

showInputDialog(title: "Add number",
                subtitle: "Please enter the new number below.",
                actionTitle: "Add",
                cancelTitle: "Cancel",
                inputPlaceholder: "New number",
                inputKeyboardType: .numberPad)
{ (input:String?) in
    print("The new number is \(input ?? "")")
}

The extension code:

extension UIViewController {
    func showInputDialog(title:String? = nil,
                         subtitle:String? = nil,
                         actionTitle:String? = "Add",
                         cancelTitle:String? = "Cancel",
                         inputPlaceholder:String? = nil,
                         inputKeyboardType:UIKeyboardType = UIKeyboardType.default,
                         cancelHandler: ((UIAlertAction) -> Swift.Void)? = nil,
                         actionHandler: ((_ text: String?) -> Void)? = nil) {

        let alert = UIAlertController(title: title, message: subtitle, preferredStyle: .alert)
        alert.addTextField { (textField:UITextField) in
            textField.placeholder = inputPlaceholder
            textField.keyboardType = inputKeyboardType
        }
        alert.addAction(UIAlertAction(title: actionTitle, style: .default, handler: { (action:UIAlertAction) in
            guard let textField =  alert.textFields?.first else {
                actionHandler?(nil)
                return
            }
            actionHandler?(textField.text)
        }))
        alert.addAction(UIAlertAction(title: cancelTitle, style: .cancel, handler: cancelHandler))

        self.present(alert, animated: true, completion: nil)
    }
}

Pass a javascript variable value into input type hidden value

Hidden Field :

<input type="hidden" name="year" id="year">

Script :

<script type="text/javascript">
     var year = new Date();
     document.getElementById("year").value=(year.getFullYear());
</script>

How to remove a variable from a PHP session array

To remove a specific variable from the session use:

session_unregister('variableName');

(see documentation) or

unset($_SESSION['variableName']);

NOTE: session_unregister() has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

Why do I get "warning longer object length is not a multiple of shorter object length"?

When you perform a boolean comparison between two vectors in R, the "expectation" is that both vectors are of the same length, so that R can compare each corresponding element in turn.

R has a much loved (or hated) feature called recycling, whereby in many circumstances if you try to do something where R would normally expect objects to be of the same length, it will automatically extend, or recycle, the shorter object to force both objects to be of the same length.

If the longer object is a multiple of the shorter, this amounts to simply repeating the shorter object several times. Oftentimes R programmers will take advantage of this to do things more compactly and with less typing.

But if they are not multiples, R will worry that you may have made a mistake, and perhaps didn't mean to perform that comparison, hence the warning.

Explore yourself with the following code:

> x <- 1:3
> y <- c(1,2,4)
> x == y
[1]  TRUE  TRUE FALSE
> y1 <- c(y,y)
> x == y1
[1]  TRUE  TRUE FALSE  TRUE  TRUE FALSE
> y2 <- c(y,2)
> x == y2
[1]  TRUE  TRUE FALSE FALSE
Warning message:
In x == y2 :
  longer object length is not a multiple of shorter object length

How to $watch multiple variable change in angular

Angular 1.3 provides $watchGroup specifically for this purpose:

https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watchGroup

This seems to provide the same ultimate result as a standard $watch on an array of expressions. I like it because it makes the intention clearer in the code.

When should I use Lazy<T>?

You should look this example to understand Lazy Loading architecture

private readonly Lazy<List<int>> list = new Lazy<List<int>>(() =>
{
    List<int> configList = new List<int>(Thread.CurrentThread.ManagedThreadId);
    return configList;
});
public void Execute()
{
    list.Value.Add(0);
    if (list.IsValueCreated)
    {
        list.Value.Add(1);
        list.Value.Add(2);

        foreach (var item in list.Value)
        {
            Console.WriteLine(item);
        }
    }
    else
    {
        Console.WriteLine("Value not created");
    }
}

--> output --> 0 1 2

but if this code dont write "list.Value.Add(0);"

output --> Value not created

Using scp to copy a file to Amazon EC2 instance?

I had exactly same problem, my solution was to

scp -i /path/pem -r /path/file/ ec2-user@public aws dns name: (leave it blank here)

once you done this part, get into ssh server and mv file to desired location

Angular 2 - View not updating after model changes

In my case, I had a very similar problem. I was updating my view inside a function that was being called by a parent component, and in my parent component I forgot to use @ViewChild(NameOfMyChieldComponent). I lost at least 3 hours just for this stupid mistake. i.e: I didn't need to use any of those methods:

  • ChangeDetectorRef.detectChanges()
  • ChangeDetectorRef.markForCheck()
  • ApplicationRef.tick()

Curl error: Operation timed out

In curl request add time out 0 so its infinite time set like CURLOPT_TIMEOUT set 0

Padding between ActionBar's home icon and title

I used AppBarLayout and custom ImageButton do to so.

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:elevation="0dp"
    android:background="@android:color/transparent"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

   <RelativeLayout
       android:layout_width="match_parent"
       android:layout_height="match_parent">

       <ImageView
           android:layout_width="32dp"
           android:layout_height="32dp"
           android:src="@drawable/selector_back_button"
           android:layout_centerVertical="true"
           android:layout_marginLeft="8dp"
           android:id="@+id/back_button"/>

       <android.support.v7.widget.Toolbar
           android:id="@+id/toolbar"
           android:layout_width="match_parent"
           android:layout_height="?attr/actionBarSize"
           app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
    </RelativeLayout>    
</android.support.design.widget.AppBarLayout>

My Java code:

findViewById(R.id.appbar).bringToFront();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
getSupportActionBar().setDisplayShowTitleEnabled(false);

How to configure log4j to only keep log files for the last seven days?

Inspite of starting a chrone job, for the task, we can use log4j2.properties file in config folder of logstash. Have a look at the link below, this will be helpful.

https://github.com/elastic/logstash/issues/7482

Send HTTP GET request with header

You do it exactly as you showed with this line:

get.setHeader("Content-Type", "application/x-zip");

So your header is fine and the problem is some other input to the web service. You'll want to debug that on the server side.

Why fragments, and when to use fragments instead of activities?

Fragments lives within the Activity and has:

  • its own lifecycle
  • its own layout
  • its own child fragments and etc.

Think of Fragments as a sub activity of the main activity it belongs to, it cannot exist of its own and it can be called/reused again and again. Hope this helps :)

CSS transition fade on hover

This will do the trick

.gallery-item
{
  opacity:1;
}

.gallery-item:hover
{
  opacity:0;
  transition: opacity .2s ease-out;
  -moz-transition: opacity .2s ease-out;
  -webkit-transition: opacity .2s ease-out;
  -o-transition: opacity .2s ease-out;
}

mailto link multiple body lines

  1. Use a single body parameter within the mailto string
  2. Use %0D%0A as newline

The mailto URI Scheme is specified by by RFC2368 (July 1998) and RFC6068 (October 2010).
Below is an extract of section 5 of this last RFC:

[...] line breaks in the body of a message MUST be encoded with "%0D%0A".
Implementations MAY add a final line break to the body of a message even if there is no trailing "%0D%0A" in the body [...]

See also in section 6 the example from the same RFC:

<mailto:[email protected]?body=send%20current-issue%0D%0Asend%20index>

The above mailto body corresponds to:

send current-issue
send index

count number of lines in terminal output

Pipe the result to wc using the -l (line count) switch:

grep -Rl "curl" ./ | wc -l

A CORS POST request works from plain JavaScript, but why not with jQuery?

You are sending "params" in js: request.send(params);

but "data" in jquery". Is data defined?: data:data,

Also, you have an error in the URL:

$.ajax( {url:url,
         type:"POST",
         dataType:"json",
         data:data, 
         success:function(data, textStatus, jqXHR) {alert("success");},
         error: function(jqXHR, textStatus, errorThrown) {alert("failure");}
});

You are mixing the syntax with the one for $.post


Update: I was googling around based on monsur answer, and I found that you need to add Access-Control-Allow-Headers: Content-Type (below is the full paragraph)

http://metajack.im/2010/01/19/crossdomain-ajax-for-xmpp-http-binding-made-easy/

How CORS Works

CORS works very similarly to Flash's crossdomain.xml file. Basically, the browser will send a cross-domain request to a service, setting the HTTP header Origin to the requesting server. The service includes a few headers like Access-Control-Allow-Origin to indicate whether such a request is allowed.

For the BOSH connection managers, it is enough to specify that all origins are allowed, by setting the value of Access-Control-Allow-Origin to *. The Content-Type header must also be white-listed in the Access-Control-Allow-Headers header.

Finally, for certain types of requests, including BOSH connection manager requests, the permissions check will be pre-flighted. The browser will do an OPTIONS request and expect to get back some HTTP headers that indicate which origins are allowed, which methods are allowed, and how long this authorization will last. For example, here is what the Punjab and ejabberd patches I did return for OPTIONS:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type 
Access-Control-Max-Age: 86400

How to set NODE_ENV to production/development in OS X

Daniel has a fantastic answer which is the better approach for the correct deployment (set and forget) process.

For those using express. You can use grunt-express-server which is fantastic as well. https://www.npmjs.org/package/grunt-express-server

Run cURL commands from Windows console

First you need to download the cURL executable. For Windows 64bit, download it from here and for Windows 32bit download from here After that, save the curl.exe file on your C: drive.

To use it, just open the command prompt and type in:

C:\curl http://someurl.com

How to find Oracle Service Name

With SQL Developer you should also find it without writing any query. Right click on your Connection/Propriety.

You should see the name on the left under something like "connection details" and should look like "Connectionname@servicename", or on the right, under the connection's details.

Convert a JSON string to object in Java ME?

JSON official site is where you should look at. It provides various libraries which can be used with Java, I've personally used this one, JSON-lib which is an implementation of the work in the site, so it has exactly the same class - methods etc in this page.

If you click the html links there you can find anything you want.

In short:

to create a json object and a json array, the code is:

JSONObject obj = new JSONObject();
obj.put("variable1", o1);
obj.put("variable2", o2);
JSONArray array = new JSONArray();
array.put(obj);

o1, o2, can be primitive types (long, int, boolean), Strings or Arrays.

The reverse process is fairly simple, I mean converting a string to json object/array.

String myString;

JSONObject obj = new JSONObject(myString);

JSONArray array = new JSONArray(myString);

In order to be correctly parsed you just have to know if you are parsing an array or an object.

Android Bluetooth Example

I have also used following link as others have suggested you for bluetooth communication.

http://developer.android.com/guide/topics/connectivity/bluetooth.html

The thing is all you need is a class BluetoothChatService.java

this class has following threads:

  1. Accept
  2. Connecting
  3. Connected

Now when you call start function of the BluetoothChatService like:

mChatService.start();

It starts accept thread which means it will start looking for connection.

Now when you call

mChatService.connect(<deviceObject>,false/true);

Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.

connect function will start connecting thread which will look for any device which is running accept thread.

When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:

connected(mmSocket, mmDevice, mSocketType);

this method starts connected thread in both the devices: Using this socket object connected thread obtains the input and output stream to the other device. And calls read function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.

BluetoothChatService also has a write method which takes byte[] as input and calls write method on connected thread.

mChatService.write("your message".getByte());

write method in connected thread just write this byte data to outputsream of the other device.

public void write(byte[] buffer) {
   try {
       mmOutStream.write(buffer);
    // Share the sent message back to the UI Activity
    // mHandler.obtainMessage(
    // BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
    // buffer).sendToTarget();
    } catch (IOException e) {
    Log.e(TAG, "Exception during write", e);
     }
}

Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.

How to quickly drop a user with existing privileges

I had to add one more line to REVOKE...

After running:

REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM username;
REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM username;
REVOKE ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public FROM username;

I was still receiving the error: username cannot be dropped because some objects depend on it DETAIL: privileges for schema public

I was missing this:

REVOKE USAGE ON SCHEMA public FROM username;

Then I was able to drop the role.

DROP USER username;

How to create a list of objects?

I think what you're of doing here is using a structure containing your class instances. I don't know the syntax for naming structures in python, but in perl I could create a structure obj.id[x] where x is an incremented integer. Then, I could just refer back to the specific class instance I needed by referencing the struct numerically. Is this anything in the direction of what you're trying to do?

git index.lock File exists when I try to commit, but cannot delete the file

On Linux, Unix, Git Bash, or Cygwin, try:

rm -f .git/index.lock

On Windows Command Prompt, try:

del .git\index.lock


For Windows:

  • From a PowerShell console opened as administrator, try

    rm -Force ./.git/index.lock
    
  • If that does not work, you must kill all git.exe processes

    taskkill /F /IM git.exe
    

    SUCCESS: The process "git.exe" with PID 20448 has been terminated.
    SUCCESS: The process "git.exe" with PID 11312 has been terminated.
    SUCCESS: The process "git.exe" with PID 23868 has been terminated.
    SUCCESS: The process "git.exe" with PID 27496 has been terminated.
    SUCCESS: The process "git.exe" with PID 33480 has been terminated.
    SUCCESS: The process "git.exe" with PID 28036 has been terminated. \

    rm -Force ./.git/index.lock
    

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

Your DemoApplication class is in the com.ag.digital.demo.boot package and your LoginBean class is in the com.ag.digital.demo.bean package. By default components (classes annotated with @Component) are found if they are in the same package or a sub-package of your main application class DemoApplication. This means that LoginBean isn't being found so dependency injection fails.

There are a couple of ways to solve your problem:

  1. Move LoginBean into com.ag.digital.demo.boot or a sub-package.
  2. Configure the packages that are scanned for components using the scanBasePackages attribute of @SpringBootApplication that should be on DemoApplication.

A few of other things that aren't causing a problem, but are not quite right with the code you've posted:

  • @Service is a specialisation of @Component so you don't need both on LoginBean
  • Similarly, @RestController is a specialisation of @Component so you don't need both on DemoRestController
  • DemoRestController is an unusual place for @EnableAutoConfiguration. That annotation is typically found on your main application class (DemoApplication) either directly or via @SpringBootApplication which is a combination of @ComponentScan, @Configuration, and @EnableAutoConfiguration.

Setting up Vim for Python

Some time ago I installed Valloric/YouCompleteMe and I find it really awesome. It provides you completion for file paths, function names, methods, variable names... Together with davidhalter/jedi-vim it makes vim great for python programming (the only thing missing now is a linter).

Command line to remove an environment variable from the OS level configuration

From PowerShell you can use the .NET [System.Environment]::SetEnvironmentVariable() method:

  • To remove a user environment variable named FOO:

    [Environment]::SetEnvironmentVariable('FOO', $null, 'User')
    

Note that $null is used to better signal the intent to remove the variable, though technically it is effectively the same as passing '' in this case.

  • To remove a system (machine-level) environment variable named FOO - requires elevation (must be run as administrator):

    [Environment]::SetEnvironmentVariable('FOO', $null, 'Machine')
    

Aside from faster execution, the advantage over the reg.exe-based method is that other applications are notified of the change, via a WM_SETTINGCHANGE message (though not all applications listen to that message).

What are the git concepts of HEAD, master, origin?

While this doesn't directly answer the question, there is great book available for free which will help you learn the basics called ProGit. If you would prefer the dead-wood version to a collection of bits you can purchase it from Amazon.

Passing parameter using onclick or a click binding with KnockoutJS

Use a binding, like in this example:

<a href="#new-search" data-bind="click:SearchManager.bind($data,'1')">
  Search Manager
</a>
var ViewModelStructure = function () {
    var self = this;
    this.SearchManager = function (search) {
        console.log(search);
    };
}();

how to open a page in new tab on button click in asp.net?

You have to use Javascript since code behind is server side only. I am pretty sure that this works.

<asp:Button ID="btnNewEntry" runat="Server" CssClass="button" Text="New Entry" OnClick="btnNewEntry_Click" OnClientClick="aspnetForm.target ='_blank';"/>

protected void btnNewEntry_Click(object sender, EventArgs e)
{
  Response.Redirect("New.aspx");
}

Creating random colour in Java?

I have used this simple and clever way for creating random color in Java,

Random random = new Random();
        System.out.println(String.format("#%06x", random.nextInt(256*256*256)));

Where #%06x gives you zero-padded hex (always 6 characters long).

How do I add an existing Solution to GitHub from Visual Studio 2013

OK this worked for me.

  1. Open the solution in Visual Studio 2013
  2. Select File | Add to Source Control
  3. Select the Microsoft Git Provider

That creates a local GIT repository

  1. Surf to GitHub
  2. Create a new repository DO NOT SELECT Initialize this repository with a README

That creates an empty repository with no Master branch

  1. Once created open the repository and copy the URL (it's on the right of the screen in the current version)
  2. Go back to Visual Studio
    • Make sure you have the Microsoft Git Provider selected under Tools/Options/Source Control/Plug-in Selection
  3. Open Team Explorer
  4. Select Home | Unsynced Commits
  5. Enter the GitHub URL into the yellow box (use HTTPS URL, not the default shown SSH one)
  6. Click Publish
  7. Select Home | Changes
  8. Add a Commit comment
  9. Select Commit and Push from the drop down

Your solution is now in GitHub

Simple regular expression for a decimal with a precision of 2

In general, i.e. unlimited decimal places:

^-?(([1-9]\d*)|0)(.0*[1-9](0*[1-9])*)?$.

App store link for "rate/review this app"

EDIT: iOS 11 Solution

This is the solution to my original answer (see below). When using the iOS 11 the following link format will work:

https://itunes.apple.com/us/app/appName/idAPP_ID?mt=8&action=write-review

Simply replace APP_ID with your specific app ID. The key to make the link work is the country code. The link above uses the us code but it actually doesn't matter which code is used. The user will automatically be redirected to his store.

iOS 11 Update:

It seems that none of the solutions presented in the other answers to get directly to the Review Page works on iOS 11.

The problem most likely is, that an app page in the iOS 11 App Store app does NOT have a Review Tab anymore. Instead the reviews are now located directly below the description and the screenshots. Of course it could still be possible to reach this section directly (e.g. with some kind of anchor), but it seems that this is not supported / intended by Apple.

Using one of the following links does not work anymore. They still bring the users to the App Store app but only to a blank page:

itms-apps://itunes.apple.com/app/idYOUR_APP_ID?action=write-review
itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=YOUR_APP_ID&onlyLatestVersion=true&pageNumber=0&sortOrdering=1&type=Purple+Software

Everyone how still uses these links should update their apps ASAP, because referring the users to a blank App Store page is most likely not what you intended.

Links which do not refer to the Review page but to the App page, still work however, e.g.

itms-apps://itunes.apple.com/app/idYOUR_APP_ID   (same as above, but without write-review parameter)

So, you can still get the users to your apps Store page, but not directly to the review section anymore. Users now have to scroll down to the review section manually to leave their feedback.

Without a question this a "great and awesome benefit for User Experience and will help developers to engage users to leave high quality reviews without annoying them". Well done Apple...

How to change an Android app's name?

change the app string resource to your new activity

date() method, "A non well formed numeric value encountered" does not want to format a date passed in $_POST

From the documentation for strtotime():

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

In your date string, you have 12-16-2013. 16 isn't a valid month, and hence strtotime() returns false.

Since you can't use DateTime class, you could manually replace the - with / using str_replace() to convert the date string into a format that strtotime() understands:

$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16

Java - No enclosing instance of type Foo is accessible

You've declared the class Thing as a non-static inner class. That means it must be associated with an instance of the Hello class.

In your code, you're trying to create an instance of Thing from a static context. That is what the compiler is complaining about.

There are a few possible solutions. Which solution to use depends on what you want to achieve.

  • Move Thing out of the Hello class.

  • Change Thing to be a static nested class.

    static class Thing
    
  • Create an instance of Hello before creating an instance of Thing.

    public static void main(String[] args)
    {
        Hello h = new Hello();
        Thing thing1 = h.new Thing(); // hope this syntax is right, typing on the fly :P
    }
    

The last solution (a non-static nested class) would be mandatory if any instance of Thing depended on an instance of Hello to be meaningful. For example, if we had:

public class Hello {
    public int enormous;

    public Hello(int n) {
        enormous = n;
    }

    public class Thing {
        public int size;

        public Thing(int m) {
            if (m > enormous)
                size = enormous;
            else
                size = m;
        }
    }
    ...
}

any raw attempt to create an object of class Thing, as in:

Thing t = new Thing(31);

would be problematic, since there wouldn't be an obvious enormous value to test 31 against it. An instance h of the Hello outer class is necessary to provide this h.enormous value:

...
Hello h = new Hello(30);
...
Thing t = h.new Thing(31);
...

Because it doesn't mean a Thing if it doesn't have a Hello.

For more information on nested/inner classes: Nested Classes (The Java Tutorials)

Set QLineEdit to accept only numbers

The best is QSpinBox.

And for a double value use QDoubleSpinBox.

QSpinBox myInt;
myInt.setMinimum(-5);
myInt.setMaximum(5);
myInt.setSingleStep(1);// Will increment the current value with 1 (if you use up arrow key) (if you use down arrow key => -1)
myInt.setValue(2);// Default/begining value
myInt.value();// Get the current value
//connect(&myInt, SIGNAL(valueChanged(int)), this, SLOT(myValueChanged(int)));

Declaring multiple variables in JavaScript

Another reason to avoid the single statement version (single var) is debugging. If an exception is thrown in any of the assignment lines the stack trace shows only the one line.

If you had 10 variables defined with the comma syntax you have no way to directly know which one was the culprit.

The individual statement version does not suffer from this ambiguity.

How can I copy the content of a branch to a new local branch?

With Git 2.15 (Q4 2017), "git branch" learned "-c/-C" to create a new branch by copying an existing one.

See commit c8b2cec (18 Jun 2017) by Ævar Arnfjörð Bjarmason (avar).
See commit 52d59cc, commit 5463caa (18 Jun 2017) by Sahil Dua (sahildua2305).
(Merged by Junio C Hamano -- gitster -- in commit 3b48045, 03 Oct 2017)

branch: add a --copy (-c) option to go with --move (-m)

Add the ability to --copy a branch and its reflog and configuration, this uses the same underlying machinery as the --move (-m) option except the reflog and configuration is copied instead of being moved.

This is useful for e.g. copying a topic branch to a new version, e.g. work to work-2 after submitting the work topic to the list, while preserving all the tracking info and other configuration that goes with the branch, and unlike --move keeping the other already-submitted branch around for reference.

Note: when copying a branch, you remain on your current branch.
As Junio C Hamano explains, the initial implementation of this new feature was modifying HEAD, which was not good:

When creating a new branch B by copying the branch A that happens to be the current branch, it also updates HEAD to point at the new branch.
It probably was made this way because "git branch -c A B" piggybacked its implementation on "git branch -m A B",

This does not match the usual expectation.
If I were sitting on a blue chair, and somebody comes and repaints it to red, I would accept ending up sitting on a chair that is now red (I am also OK to stand, instead, as there no longer is my favourite blue chair).

But if somebody creates a new red chair, modelling it after the blue chair I am sitting on, I do not expect to be booted off of the blue chair and ending up on sitting on the new red one.

Is there a short contains function for lists?

I came up with this one liner recently for getting True if a list contains any number of occurrences of an item, or False if it contains no occurrences or nothing at all. Using next(...) gives this a default return value (False) and means it should run significantly faster than running the whole list comprehension.

list_does_contain = next((True for item in list_to_test if item == test_item), False)

What's the best way to override a user agent CSS stylesheet rule that gives unordered-lists a 1em margin?

If You Are Able to Edit the Offending Stylesheet

If the user-agent stylesheet's style is causing problems for the browser it's supposed to fix, then you could try removing the offending style and testing that to ensure it doesn't have any unexpected adverse effects elsewhere.

If it doesn't, use the modified stylesheet. Fixing browser quirks is what these sheets are for - they fix issues, they aren't supposed to introduce new ones.

If You Are Not Able to Edit the Offending Stylesheet

If you're unable to edit the stylesheet that contains the offending line, you may consider using the !important keyword.

An example:

.override {
    border: 1px solid #000 !important;
}

.a_class {
    border: 2px solid red;
}

And the HTML:

<p class="a_class">content will have 2px red border</p>
<p class="override a_class">content will have 1px black border</p>

Live example

Try to use !important only where you really have to - if you can reorganize your styles such that you don't need it, this would be preferable.

Excel: Searching for multiple terms in a cell

Try using COUNT function like this

=IF(COUNT(SEARCH({"Romney","Obama","Gingrich"},C1)),1,"")

Note that you don't need the wildcards (as teylyn says) and unless there's a specific reason "1" doesn't need quotes (in fact that makes it a text value)

What is @RenderSection in asp.net MVC

Here the defination of Rendersection from MSDN

In layout pages, renders the content of a named section.MSDN

In _layout.cs page put

@RenderSection("Bottom",false)

Here render the content of bootom section and specifies false boolean property to specify whether the section is required or not.

@section Bottom{
       This message form bottom.
}

That meaning if you want to bottom section in all pages, then you must use false as the second parameter at Rendersection method.