Programs & Examples On #Multiple repositories

How do I work with a git repository within another repository?

I had issues with subtrees and submodules that the other answers suggest... mainly because I am using SourceTree and it seems fairly buggy.

Instead, I ended up using SymLinks and that seems to work well so I am posting it here as a possible alternative.

There is a complete guide here: http://www.howtogeek.com/howto/16226/complete-guide-to-symbolic-links-symlinks-on-windows-or-linux/

But basically you just need to mklink the two paths in an elevated command prompt. Make sure you use the /J hard link prefix. Something along these lines: mklink /J C:\projects\MainProject\plugins C:\projects\SomePlugin

You can also use relative folder paths and put it in a bat to be executed by each person when they first check out your project.

Example: mklink /J .\Assets\TaqtileTools ..\TaqtileHoloTools

Once the folder has been linked you may need to ignore the folder within your main repository that is referencing it. Otherwise you are good to go.

Note I've deleted my duplicate answer from another post as that post was marked as a duplicate question to this one.

Multiple maven repositories in one gradle file

you have to do like this in your project level gradle file

allprojects {
    repositories {
        jcenter()
        maven { url "http://dl.appnext.com/" }
        maven { url "https://maven.google.com" }
    }
}

How to resolve "Server Error in '/' Application" error?

It sounds like the admin has locked the "authentication" node of the web.config, which one can do in the global web.config pretty easily. Or, in a nutshell, this is working as designed.

How to check if IEnumerable is null or empty?

I built this off of the answer by @Matt Greer

He answered the OP's question perfectly.

I wanted something like this while maintaining the original capabilities of Any while also checking for null. I'm posting this in case anyone else needs something similar.

Specifically I wanted to still be able to pass in a predicate.

public static class Utilities
{
    /// <summary>
    /// Determines whether a sequence has a value and contains any elements.
    /// </summary>
    /// <typeparam name="TSource">The type of the elements of source.</typeparam>
    /// <param name="source">The <see cref="System.Collections.Generic.IEnumerable"/> to check for emptiness.</param>
    /// <returns>true if the source sequence is not null and contains any elements; otherwise, false.</returns>
    public static bool AnyNotNull<TSource>(this IEnumerable<TSource> source)
    {
        return source?.Any() == true;
    }

    /// <summary>
    /// Determines whether a sequence has a value and any element of a sequence satisfies a condition.
    /// </summary>
    /// <typeparam name="TSource">The type of the elements of source.</typeparam>
    /// <param name="source">An <see cref="System.Collections.Generic.IEnumerable"/> whose elements to apply the predicate to.</param>
    /// <param name="predicate">A function to test each element for a condition.</param>
    /// <returns>true if the source sequence is not null and any elements in the source sequence pass the test in the specified predicate; otherwise, false.</returns>
    public static bool AnyNotNull<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
    {
        return source?.Any(predicate) == true;
    }
}

The naming of the extension method could probably be better.

Windows service on Local Computer started and then stopped error

Use Timer and tick event to copy your files.

On start the service, start the time and specify the interval in the time.

So the service is keep running and copy the files ontick.

Hope it help.

C# constructors overloading

You can factor out your common logic to a private method, for example called Initialize that gets called from both constructors.

Due to the fact that you want to perform argument validation you cannot resort to constructor chaining.

Example:

public Point2D(double x, double y)
{
    // Contracts

    Initialize(x, y);
}

public Point2D(Point2D point)
{
    if (point == null)
        throw new ArgumentNullException("point");

    // Contracts

    Initialize(point.X, point.Y);
}

private void Initialize(double x, double y)
{
    X = x;
    Y = y;
}

PostgreSQL: how to convert from Unix epoch to date?

select to_timestamp(cast(epoch_ms/1000 as bigint))::date

worked for me

error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup

Your tried to turn that source file into an executable, which obviously isn't possible, because the mandatory entry point, the main function, isn't defined. Add a file main.cpp and define a main function. If you're working on the commandline (which I doubt), you can add /c to only compile and not link. This will produce an object file only, which needs to be linked into either a static or shared lib or an application (in which case you'll need an oject file with main defined).

_WinMain is Microsoft's name for main when linking.

Also: you're not running the code yet, you are compiling (and linking) it. C++ is not an interpreted language.

Send PHP variable to javascript function

You can pass PHP values to JavaScript. The PHP will execute server side so the value will be calculated and then you can echo it to the HTML containing the javascript. The javascript will then execute in the clients browser with the value PHP calculated server-side.

<script type="text/javascript">
    // Do something in JavaScript
    var x = <?php echo $calculatedValue; ?>;
    // etc..
</script>

How to add Web API to an existing ASP.NET MVC 4 Web Application project?

As soon as you add a "WebApi Controller" under controllers folder, Visual Studio takes care of dependencies automatically;

Visual Studio has added the full set of dependencies for ASP.NET Web API 2 to project 'MyTestProject'.

The Global.asax.cs file in the project may require additional changes to enable ASP.NET Web API.

  1. Add the following namespace references:

    using System.Web.Http; using System.Web.Routing;

  2. If the code does not already define an Application_Start method, add the following method:

    protected void Application_Start() { }

  3. Add the following lines to the beginning of the Application_Start method:

    GlobalConfiguration.Configure(WebApiConfig.Register);

Border for an Image view in Android?

Just add this code in your ImageView:

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

    <solid
        android:color="@color/white"/>

    <size
        android:width="20dp"
        android:height="20dp"/>
    <stroke
        android:width="4dp" android:color="@android:color/black"/>
    <padding android:left="1dp" android:top="1dp" android:right="1dp"
        android:bottom="1dp" />
</shape>

Exact difference between CharSequence and String in java

tl;dr

One is an interface (CharSequence) while other is a concrete implementation of that interface (String).

CharSequence animal = "cat"  // `String` object presented as the interface `CharSequence`.

Just like ArrayList is a List, and HashMap is a Map, so too String is a CharSequence.

As an interface, normally the CharSequence would be more commonly seen than String, but some twisted history resulted in the interface being defined years after the implementation. So in older APIs we often see String while in newer APIs we tend to see CharSequence used to define arguments and return types.

Details

Nowadays we know that generally an API/framework should focus on exporting interfaces primarily and concrete classes secondarily. But we did not always know this lesson so well.

The String class came first in Java. Only later did they place a front-facing interface, CharSequence.

Twisted History

A little history might help with understanding.

In its early days, Java was rushed to market a bit ahead of its time, due to the Internet/Web mania animating the industry. Some libraries were not as well thought-through as they should have been. String handling was one of those areas.

Also, Java was one of the earliest production-oriented non-academic Object-Oriented Programming (OOP) environments. The only successful real-world rubber-meets-the-road implementations of OOP before that was some limited versions of SmallTalk, then Objective-C with NeXTSTEP/OpenStep. So, many practical lessons were yet to be learned.

Java started with the String class and StringBuffer class. But those two classes were unrelated, not tied to each other by inheritance nor interface. Later, the Java team recognized that there should have been a unifying tie between string-related implementations to make them interchangeable. In Java 4 the team added the CharSequence interface and retroactively implemented that interface on String and String Buffer, as well as adding another implementation CharBuffer. Later in Java 5 they added StringBuilder, basically a unsynchronized and therefore somewhat faster version of StringBuffer.

So these string-oriented classes are a bit of a mess, and a little confusing to learn about. Many libraries and interfaces were built to take and return String objects. Nowadays such libraries should generally be built to expect CharSequence. But (a) String seems to still dominate the mindspace, and (b) there may be some subtle technical issues when mixing the various CharSequence implementations. With the 20/20 vision of hindsight we can see that all this string stuff could have been better handled, but here we are.

Ideally Java would have started with an interface and/or superclass that would be used in many places where we now use String, just as we use the Collection or List interfaces in place of the ArrayList or LinkedList implementations.

Interface Versus Class

The key difference about CharSequence is that it is an interface, not an implementation. That means you cannot directly instantiate a CharSequence. Rather you instantiate one of the classes that implements that interface.

For example, here we have x that looks like a CharSequence but underneath is actually a StringBuilder object.

CharSequence x = new StringBuilder( "dog" );  // Looks like a `CharSequence` but is actually a `StringBuilder` instance.

This becomes less obvious when using a String literal. Keep in mind that when you see source code with just quote marks around characters, the compiler is translating that into a String object.

CharSequence y = "cat";  // Looks like a `CharSequence` but is actually a `String` instance.

Literal versus constructor

There are some subtle differences between "cat" and new String("cat") as discussed in this other Question, but are irrelevant here.

Class Diagram

This class diagram may help to guide you. I noted the version of Java in which they appeared to demonstrate how much change has churned through these classes and interfaces.

diagram showing the various string-related classes and interfaces as of Java 8

Text Blocks

Other than adding more Unicode characters including a multitude of emoji, in recent years not much has changed in Java for working with text. Until text blocks.

Text blocks are a new way of better handling the tedium of string literals with multiple lines or character-escaping. This would make writing embedded code strings such as HTML, XML, SQL, or JSON much more convenient.

To quote JEP 378:

A text block is a multi-line string literal that avoids the need for most escape sequences, automatically formats the string in a predictable way, and gives the developer control over the format when desired.

The text blocks feature does not introduce a new data type. Text blocks are merely a new syntax for writing a String literal. A text block produces a String object, just like the conventional literal syntax. A text block produces a String object, which is also a CharSequence object, as discussed above.

SQL example

To quote JSR 378 again…

Using "one-dimensional" string literals.

String query = "SELECT \"EMP_ID\", \"LAST_NAME\" FROM \"EMPLOYEE_TB\"\n" +
               "WHERE \"CITY\" = 'INDIANAPOLIS'\n" +
               "ORDER BY \"EMP_ID\", \"LAST_NAME\";\n";

Using a "two-dimensional" block of text

String query = """
               SELECT "EMP_ID", "LAST_NAME" FROM "EMPLOYEE_TB"
               WHERE "CITY" = 'INDIANAPOLIS'
               ORDER BY "EMP_ID", "LAST_NAME";
               """;

Text blocks are found in Java 15 and later, per JEP 378: Text Blocks.

First previewed in Java 13, under JEP 355: Text Blocks (Preview). Then previewed again in Java 14 under JEP 368: Text Blocks (Second Preview).

This effort was preceded by JEP 326: Raw String Literals (Preview). The concepts were reworked to produce the Text Blocks feature instead.

What is your favorite C programming trick?

I like the "struct hack" for having a dynamically sized object. This site explains it pretty well too (though they refer to the C99 version where you can write "str[]" as the last member of a struct). you could make a string "object" like this:

struct X {
    int len;
    char str[1];
};

int n = strlen("hello world");
struct X *string = malloc(sizeof(struct X) + n);
strcpy(string->str, "hello world");
string->len = n;

here, we've allocated a structure of type X on the heap that is the size of an int (for len), plus the length of "hello world", plus 1 (since str1 is included in the sizeof(X).

It is generally useful when you want to have a "header" right before some variable length data in the same block.

How to properly add 1 month from now to current date in moment.js

You could try

moment().add(1, 'M').subtract(1, 'day').format('DD-MM-YYYY')

How can I remove a key from a Python dictionary?

Using the "del" keyword:

del dict[key]

JavaScript implementation of Gzip

Edit There appears to be a better LZW solution that handles Unicode strings correctly at http://pieroxy.net/blog/pages/lz-string/index.html (Thanks to pieroxy in the comments).


I don't know of any gzip implementations, but the jsolait library (the site seems to have gone away) has functions for LZW compression/decompression. The code is covered under the LGPL.

// LZW-compress a string
function lzw_encode(s) {
    var dict = {};
    var data = (s + "").split("");
    var out = [];
    var currChar;
    var phrase = data[0];
    var code = 256;
    for (var i=1; i<data.length; i++) {
        currChar=data[i];
        if (dict[phrase + currChar] != null) {
            phrase += currChar;
        }
        else {
            out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
            dict[phrase + currChar] = code;
            code++;
            phrase=currChar;
        }
    }
    out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
    for (var i=0; i<out.length; i++) {
        out[i] = String.fromCharCode(out[i]);
    }
    return out.join("");
}

// Decompress an LZW-encoded string
function lzw_decode(s) {
    var dict = {};
    var data = (s + "").split("");
    var currChar = data[0];
    var oldPhrase = currChar;
    var out = [currChar];
    var code = 256;
    var phrase;
    for (var i=1; i<data.length; i++) {
        var currCode = data[i].charCodeAt(0);
        if (currCode < 256) {
            phrase = data[i];
        }
        else {
           phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
        }
        out.push(phrase);
        currChar = phrase.charAt(0);
        dict[code] = oldPhrase + currChar;
        code++;
        oldPhrase = phrase;
    }
    return out.join("");
}

Displaying a Table in Django from Database

If you want to table do following steps:-

views.py:

def view_info(request):
    objs=Model_name.objects.all()
    ............
    return render(request,'template_name',{'objs':obj})

.html page

 {% for item in objs %}
    <tr> 
         <td>{{ item.field1 }}</td>
         <td>{{ item.field2 }}</td>
         <td>{{ item.field3 }}</td>
         <td>{{ item.field4 }}</td>
    </tr>
       {% endfor %}

Read all files in a folder and apply a function to each data frame

Here is a tidyverse option that might not the most elegant, but offers some flexibility in terms of what is included in the summary:

library(tidyverse)
dir_path <- '~/path/to/data/directory/'
file_pattern <- 'Df\\.[0-9]\\.csv' # regex pattern to match the file name format

read_dir <- function(dir_path, file_name){
  read_csv(paste0(dir_path, file_name)) %>% 
    mutate(file_name = file_name) %>%                # add the file name as a column              
    gather(variable, value, A:B) %>%                 # convert the data from wide to long
    group_by(file_name, variable) %>% 
    summarize(sum = sum(value, na.rm = TRUE),
              min = min(value, na.rm = TRUE),
              mean = mean(value, na.rm = TRUE),
              median = median(value, na.rm = TRUE),
              max = max(value, na.rm = TRUE))
  }

df_summary <- 
  list.files(dir_path, pattern = file_pattern) %>% 
  map_df(~ read_dir(dir_path, .))

df_summary
# A tibble: 8 x 7
# Groups:   file_name [?]
  file_name variable   sum   min  mean median   max
  <chr>     <chr>    <int> <dbl> <dbl>  <dbl> <dbl>
1 Df.1.csv  A           34     4  5.67    5.5     8
2 Df.1.csv  B           22     1  3.67    3       9
3 Df.2.csv  A           21     1  3.5     3.5     6
4 Df.2.csv  B           16     1  2.67    2.5     5
5 Df.3.csv  A           30     0  5       5      11
6 Df.3.csv  B           43     1  7.17    6.5    15
7 Df.4.csv  A           21     0  3.5     3       8
8 Df.4.csv  B           42     1  7       6      16

Android: How to use webcam in emulator?

UPDATE

In Android Studio AVD:

  1. Open AVD Manager:

AVD menu

  1. Add/Edit AVD:

Specific AVD strip

  1. Click Advanced Settings in the bottom of the screen:

AVD Advanced Settings

  1. Set your camera of choice as the front/back cameras:

AVD Camera Settings

ORA-12514 TNS:listener does not currently know of service requested in connect descriptor

For me this was caused by using a dynamic ipadress using installation. I reinstalled Oracle using a static ipadress and then everything was fine

eclipse won't start - no java virtual machine was found

I had same problem after updating java. Then I paste

-vm
C:\Program Files\Java\jre6\bin\javaw.exe

to show the path of javaw.exe in eclipse.ini file.

Hope this will help you.

Getting The ASCII Value of a character in a C# string

Here is another alternative. It will of course give you a bad result if the input char is not ascii. I've not perf tested it but I think it would be pretty fast:

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GetAsciiVal(string s, int index) {
    return GetAsciiVal(s[index]);
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GetAsciiVal(char c) {
    return unchecked(c & 0xFF);
}

jquery .on() method with load event

Refer to http://api.jquery.com/on/

It says

In all browsers, the load, scroll, and error events (e.g., on an <img> element) do not bubble. In Internet Explorer 8 and lower, the paste and reset events do not bubble. Such events are not supported for use with delegation, but they can be used when the event handler is directly attached to the element generating the event.

If you want to do something when a new input box is added then you can simply write the code after appending it.

$('#add').click(function(){
        $('body').append(x);
        // Your code can be here
    });

And if you want the same code execute when the first input box within the document is loaded then you can write a function and call it in both places i.e. $('#add').click and document's ready event

Declare a variable as Decimal

You can't declare a variable as Decimal - you have to use Variant (you can use CDec to populate it with a Decimal type though).

Implementing autocomplete

I know you already have several answers, but I was on a similar situation where my team didn't want to depend on a heavy libraries or anything related to bootstrap since we are using material so I made our own autocomplete control, using material-like styles, you can use my autocomplete or at least you can give a look to give you some guiadance, there was not much documentation on simple examples on how to upload your components to be shared on NPM.

sed with literal string--not input file

My version using variables in a bash script:

Find any backslashes and replace with forward slashes:

input="This has a backslash \\"

output=$(echo "$input" | sed 's,\\,/,g')

echo "$output"

How do I disable form fields using CSS?

A variation to the pointer-events: none; solution, which resolves the issue of the input still being accessible via it's labeled control or tabindex, is to wrap the input in a div, which is styled as a disabled text input, and setting input { visibility: hidden; } when the input is "disabled".
Ref: https://developer.mozilla.org/en-US/docs/Web/CSS/visibility#Values

_x000D_
_x000D_
div.dependant {_x000D_
  border: 0.1px solid rgb(170, 170, 170);_x000D_
  background-color: rgb(235,235,228);_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
input[type="checkbox"]:not(:checked) ~ div.dependant:first-of-type {_x000D_
  display: inline-block;_x000D_
}_x000D_
input[type="checkbox"]:checked ~ div.dependant:first-of-type {_x000D_
  display: contents;_x000D_
}_x000D_
input[type="checkbox"]:not(:checked) ~ div.dependant:first-of-type > input {_x000D_
  visibility: hidden;_x000D_
}
_x000D_
<form>_x000D_
  <label for="chk1">Enable textbox?</label>_x000D_
  <input id="chk1" type="checkbox" />_x000D_
  <br />_x000D_
  <label for="text1">Input textbox label</label>_x000D_
  <div class="dependant">_x000D_
    <input id="text1" type="text" />_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

The disabled styling applied in the snippet above is taken from the Chrome UI and may not be visually identical to disabled inputs on other browsers. Possibly it can be customised for individual browsers using engine-specific CSS extension -prefixes. Though at a glance, I don't think it could:
Microsoft CSS extensions, Mozilla CSS extensions, WebKit CSS extensions

It would seem far more sensible to introduce an additional value visibility: disabled or display: disabled or perhaps even appearance: disabled, given that visibility: hidden already affects the behavior of the applicable elements any associated control elements.

How to encrypt String in Java

Warning

Do not use this as some kind of security measurement.

The encryption mechanism in this post is a One-time pad, which means that the secret key can be easily recovered by an attacker using 2 encrypted messages. XOR 2 encrypted messages and you get the key. That simple!

Pointed out by Moussa


I am using Sun's Base64Encoder/Decoder which is to be found in Sun's JRE, to avoid yet another JAR in lib. That's dangerous from point of using OpenJDK or some other's JRE. Besides that, is there another reason I should consider using Apache commons lib with Encoder/Decoder?

public class EncryptUtils {
    public static final String DEFAULT_ENCODING = "UTF-8"; 
    static BASE64Encoder enc = new BASE64Encoder();
    static BASE64Decoder dec = new BASE64Decoder();

    public static String base64encode(String text) {
        try {
            return enc.encode(text.getBytes(DEFAULT_ENCODING));
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }//base64encode

    public static String base64decode(String text) {
        try {
            return new String(dec.decodeBuffer(text), DEFAULT_ENCODING);
        } catch (IOException e) {
            return null;
        }
    }//base64decode

    public static void main(String[] args) {
        String txt = "some text to be encrypted";
        String key = "key phrase used for XOR-ing";
        System.out.println(txt + " XOR-ed to: " + (txt = xorMessage(txt, key)));

        String encoded = base64encode(txt);       
        System.out.println(" is encoded to: " + encoded + " and that is decoding to: " + (txt = base64decode(encoded)));
        System.out.print("XOR-ing back to original: " + xorMessage(txt, key));
    }

    public static String xorMessage(String message, String key) {
        try {
            if (message == null || key == null) return null;

            char[] keys = key.toCharArray();
            char[] mesg = message.toCharArray();

            int ml = mesg.length;
            int kl = keys.length;
            char[] newmsg = new char[ml];

            for (int i = 0; i < ml; i++) {
                newmsg[i] = (char)(mesg[i] ^ keys[i % kl]);
            }//for i

            return new String(newmsg);
        } catch (Exception e) {
            return null;
        }
    }//xorMessage
}//class

How to grep Git commit diffs or contents for a certain word?

vim-fugitive is versatile for that kind of examining in Vim.

Use :Ggrep to do that. For more information you can install vim-fugitive and look up the turorial by :help Grep. And this episode: exploring-the-history-of-a-git-repository will guide you to do all that.

Is there a way to create key-value pairs in Bash script?

in older bash (or in sh) that does not support declare -A, following style can be used to emulate key/value

# key
env=staging


# values
image_dev=gcr.io/abc/dev
image_staging=gcr.io/abc/stage
image_production=gcr.io/abc/stable

img_var_name=image_$env

# active_image=${!var_name}
active_image=$(eval "echo \$$img_var_name")

echo $active_image

How can I Remove .DS_Store files from a Git repository?

In some situations you may also want to ignore some files globally. For me, .DS_Store is one of them. Here's how:

git config --global core.excludesfile /Users/mat/.gitignore

(Or any file of your choice)

Then edit the file just like a repo's .gitignore. Note that I think you have to use an absolute path.

placeholder for select tag

     <select>
         <option value="" disabled selected hidden> placeholder</option>
         <option value="op1">op1</option>
         <option value="op2">op2</option>
         <option value="op3">op3</option>
         <option value="op4">op4</option>
     </select>

Create iOS Home Screen Shortcuts on Chrome for iOS

Can't change the default browser, but try this (found online a while ago). Add a bookmark in Safari called "Open in Chrome" with the following.

javascript:location.href=%22googlechrome%22+location.href.substring(4);

Will open the current page in Chrome. Not as convenient, but maybe someone will find it useful.

Source

Works for me.

How do I convert uint to int in C#?

Assuming you want to simply lift the 32bits from one type and dump them as-is into the other type:

uint asUint = unchecked((uint)myInt);
int asInt = unchecked((int)myUint);

The destination type will blindly pick the 32 bits and reinterpret them.

Conversely if you're more interested in keeping the decimal/numerical values within the range of the destination type itself:

uint asUint = checked((uint)myInt);
int asInt = checked((int)myUint);

In this case, you'll get overflow exceptions if:

  • casting a negative int (eg: -1) to an uint
  • casting a positive uint between 2,147,483,648 and 4,294,967,295 to an int

In our case, we wanted the unchecked solution to preserve the 32bits as-is, so here are some examples:

Examples

int => uint

int....: 0000000000 (00-00-00-00)
asUint.: 0000000000 (00-00-00-00)
------------------------------
int....: 0000000001 (01-00-00-00)
asUint.: 0000000001 (01-00-00-00)
------------------------------
int....: -0000000001 (FF-FF-FF-FF)
asUint.: 4294967295 (FF-FF-FF-FF)
------------------------------
int....: 2147483647 (FF-FF-FF-7F)
asUint.: 2147483647 (FF-FF-FF-7F)
------------------------------
int....: -2147483648 (00-00-00-80)
asUint.: 2147483648 (00-00-00-80)

uint => int

uint...: 0000000000 (00-00-00-00)
asInt..: 0000000000 (00-00-00-00)
------------------------------
uint...: 0000000001 (01-00-00-00)
asInt..: 0000000001 (01-00-00-00)
------------------------------
uint...: 2147483647 (FF-FF-FF-7F)
asInt..: 2147483647 (FF-FF-FF-7F)
------------------------------
uint...: 4294967295 (FF-FF-FF-FF)
asInt..: -0000000001 (FF-FF-FF-FF)
------------------------------

Code

int[] testInts = { 0, 1, -1, int.MaxValue, int.MinValue };
uint[] testUints = { uint.MinValue, 1, uint.MaxValue / 2, uint.MaxValue };

foreach (var Int in testInts)
{
    uint asUint = unchecked((uint)Int);
    Console.WriteLine("int....: {0:D10} ({1})", Int, BitConverter.ToString(BitConverter.GetBytes(Int)));
    Console.WriteLine("asUint.: {0:D10} ({1})", asUint, BitConverter.ToString(BitConverter.GetBytes(asUint)));
    Console.WriteLine(new string('-',30));
}
Console.WriteLine(new string('=', 30));
foreach (var Uint in testUints)
{
    int asInt = unchecked((int)Uint);
    Console.WriteLine("uint...: {0:D10} ({1})", Uint, BitConverter.ToString(BitConverter.GetBytes(Uint)));
    Console.WriteLine("asInt..: {0:D10} ({1})", asInt, BitConverter.ToString(BitConverter.GetBytes(asInt)));
    Console.WriteLine(new string('-', 30));
}  

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

There is a another best/effective way to solve this error,

for example, let's take a loop which counts till 10 thousand, here you may get the error Out of memory, do to solve it you can give the computer time to recover.

So, you can sleep for 400-500ms before you're loop counts the next number :

new Thread(new Runnable() {
            public void run() {
                try {
                    sleep(550); // 550 ms (milli seconds)
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

By doing this, will make you're program slower but you don't get any error till the heap space is full again, so by waiting some ms, you can prevent that error.

You can apply this method other than loop.

Hope it helped you, :D

Jenkins Host key verification failed

  • Make sure we are not editing any of the default sshd_config properties to skip the error

  • Host Verification Failed - Definitely a missing entry of hostname in known_hosts file

  • Login to the server where the process is failing and do the following:

    1. Sudo to the user running the process

    2. ssh-copy-id destinationuser@destinationhostname

    3. It will prompt like this for the first time, say yes and it will also ask password for the first time:

      The authenticity of host 'sample.org (205.214.640.91)' can't be established.
      RSA key fingerprint is 97:8c:1b:f2:6f:14:6b:5c:3b:ec:aa:46:46:74:7c:40.
      Are you sure you want to continue connecting (yes/no)? *yes*
      

      Password prompt ? give password

    4. Now from the server where process is running, do ssh destinationuser@destinationhostname. It should login without a password.

      Note: Do not change the default permissions of files in the user's .ssh directory, you will end up with different issues

MySQL - Trigger for updating same table after insert

DELIMITER $$

DROP TRIGGER IF EXISTS `setEditStatus`$$
CREATE TRIGGER `setEditStatus` **BEFORE** INSERT on ACCOUNTS
FOR EACH ROW BEGIN

    SET NEW.STATUS = 'E';

END$$

DELIMITER ;

What's the main difference between Java SE and Java EE?

The biggest difference are the enterprise services (hence the ee) such as an application server supporting EJBs etc.

How do I trim leading/trailing whitespace in a standard way?

C++ STL style

std::string Trimed(const std::string& s)
{
    std::string::const_iterator begin = std::find_if(s.begin(),
                                                 s.end(),
                                                 [](char ch) { return !std::isspace(ch); });

    std::string::const_iterator   end = std::find_if(s.rbegin(),
                                                 s.rend(),
                                                 [](char ch) { return !std::isspace(ch); }).base();
    return std::string(begin, end);
}

http://ideone.com/VwJaq9

String isNullOrEmpty in Java?

If you are doing android development, you can use:

TextUtils.isEmpty (CharSequence str) 

Added in API level 1 Returns true if the string is null or 0-length.

Difference between ref and out parameters in .NET

out:

In C#, a method can return only one value. If you would like to return more than one value, you can use the out keyword. The out modifier returns as return-by-reference. The simplest answer is that the keyword “out” is used to get the value from the method.

  • You don't need to initialize the value in the calling function.
  • You must assign the value in the called function, otherwise the compiler will report an error.

ref:

In C#, when you pass a value type such as int, float, double etc. as an argument to the method parameter, it is passed by value. Therefore, if you modify the parameter value, it does not affect argument in the method call. But if you mark the parameter with “ref” keyword, it will reflect in the actual variable.

  • You need to initialize the variable before you call the function.
  • It’s not mandatory to assign any value to the ref parameter in the method. If you don’t change the value, what is the need to mark it as “ref”?

Maven does not find JUnit tests to run

I struggle with this problem. In my case I wasn't importing the right @Test annotation.

1) Check if the @Test is from org.junit.jupiter.api.Test (if you are using Junit 5).

2) With Junit5 instead of @RunWith(SpringRunner.class), use @ExtendWith(SpringExtension.class)

import org.junit.jupiter.api.Test;

@ExtendWith(SpringExtension.class)
@SpringBootTest
@AutoConfigureMockMvc
@TestPropertySource(locations = "classpath:application.properties")    
public class CotacaoTest {
    @Test
    public void testXXX() {

    }
}

How to change heatmap.2 color range in R?

I got the color range to be asymmetric simply by changing the symkey argument to FALSE

symm=F,symkey=F,symbreaks=T, scale="none"

Solved the color issue with colorRampPalette with the breaks argument to specify the range of each color, e.g.

colors = c(seq(-3,-2,length=100),seq(-2,0.5,length=100),seq(0.5,6,length=100))

my_palette <- colorRampPalette(c("red", "black", "green"))(n = 299)

Altogether

heatmap.2(as.matrix(SeqCountTable), col=my_palette, 
    breaks=colors, density.info="none", trace="none", 
        dendrogram=c("row"), symm=F,symkey=F,symbreaks=T, scale="none")

How to: Create trigger for auto update modified date with SQL Server 2008

My approach:

  • define a default constraint on the ModDate column with a value of GETDATE() - this handles the INSERT case

  • have a AFTER UPDATE trigger to update the ModDate column

Something like:

CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
    UPDATE dbo.TimeEntry
    SET ModDate = GETDATE()
    WHERE ID IN (SELECT DISTINCT ID FROM Inserted)

Create a copy of a table within the same database DB2

Two steps works fine:

create table bu_x as (select a,b,c,d from x ) WITH no data;

insert into bu_x (a,b,c,d) select select a,b,c,d from x ;

Why does using from __future__ import print_function breaks Python2-style print?

First of all, from __future__ import print_function needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print as a function now. That's the whole point of from __future__ import print_function; to bring the print function from Python 3 into Python 2.6+.

from __future__ import print_function

import sys, os, time

for x in range(0,10):
    print(x, sep=' ', end='')  # No need for sep here, but okay :)
    time.sleep(1)

__future__ statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

The documentation also mentions that the only things that can precede a __future__ statement are the module docstring, comments, blank lines, and other future statements.

Check if argparse optional argument is set or not

If your argument is positional (ie it doesn't have a "-" or a "--" prefix, just the argument, typically a file name) then you can use the nargs parameter to do this:

parser = argparse.ArgumentParser(description='Foo is a program that does things')
parser.add_argument('filename', nargs='?')
args = parser.parse_args()

if args.filename is not None:
    print('The file name is {}'.format(args.filename))
else:
    print('Oh well ; No args, no problems')

Convert Java String to sql.Timestamp

You could use Timestamp.valueOf(String). The documentation states that it understands timestamps in the format yyyy-mm-dd hh:mm:ss[.f...], so you might need to change the field separators in your incoming string.

Then again, if you're going to do that then you could just parse it yourself and use the setNanos method to store the microseconds.

How to reset the use/password of jenkins on windows?

I created a new user with "admin" and new password on the installation steps. But after sometime, i wanted to sign in again and that password was showing incorrect, so i used the initial password again to login.

The initial password can be found in the below location:-

C:\Program Files(x86)\Jenkins\secrets\initialAdminPassword

try this method

Rownum in postgresql

Postgresql > 8.4

SELECT 
    row_number() OVER (ORDER BY col1) AS i, 
    e.col1, 
    e.col2, 
    ... 
FROM ... 

How to send Basic Auth with axios

For some reasons, this simple problem is blocking many developers. I struggled for many hours with this simple thing. This problem as many dimensions:

  1. CORS (if you are using a frontend and backend on different domains et ports.
  2. Backend CORS Configuration
  3. Basic Authentication configuration of Axios

CORS

My setup for development is with a vuejs webpack application running on localhost:8081 and a spring boot application running on localhost:8080. So when trying to call rest API from the frontend, there's no way that the browser will let me receive a response from the spring backend without proper CORS settings. CORS can be used to relax the Cross Domain Script (XSS) protection that modern browsers have. As I understand this, browsers are protecting your SPA from being an attack by an XSS. Of course, some answers on StackOverflow suggested to add a chrome plugin to disable XSS protection but this really does work AND if it was, would only push the inevitable problem for later.

Backend CORS configuration

Here's how you should setup CORS in your spring boot app:

Add a CorsFilter class to add proper headers in the response to a client request. Access-Control-Allow-Origin and Access-Control-Allow-Headers are the most important thing to have for basic authentication.

    public class CorsFilter implements Filter {

...
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        response.setHeader("Access-Control-Allow-Origin", "http://localhost:8081");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
        **response.setHeader("Access-Control-Allow-Headers", "authorization, Content-Type");**
        response.setHeader("Access-Control-Max-Age", "3600");

        filterChain.doFilter(servletRequest, servletResponse);

    }
...
}

Add a configuration class which extends Spring WebSecurityConfigurationAdapter. In this class you will inject your CORS filter:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
...
    @Bean
    CorsFilter corsFilter() {
        CorsFilter filter = new CorsFilter();
        return filter;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.addFilterBefore(corsFilter(), SessionManagementFilter.class) //adds your custom CorsFilter
          .csrf()
          .disable()
          .authorizeRequests()
          .antMatchers("/api/login")
          .permitAll()
          .anyRequest()
          .authenticated()
          .and()
          .httpBasic()
          .authenticationEntryPoint(authenticationEntryPoint)
          .and()
          .authenticationProvider(getProvider());
    }
...
}

You don't have to put anything related to CORS in your controller.

Frontend

Now, in the frontend you need to create your axios query with the Authorization header:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://unpkg.com/vue"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
    <p>{{ status }}</p>
</div>
<script>
    var vm = new Vue({
        el: "#app",
        data: {
            status: ''
        },
        created: function () {
            this.getBackendResource();
        },
        methods: {
            getBackendResource: function () {
                this.status = 'Loading...';
                var vm = this;
                var user = "aUserName";
                var pass = "aPassword";
                var url = 'http://localhost:8080/api/resource';

                var authorizationBasic = window.btoa(user + ':' + pass);
                var config = {
                    "headers": {
                        "Authorization": "Basic " + authorizationBasic
                    }
                };
                axios.get(url, config)
                    .then(function (response) {
                        vm.status = response.data[0];
                    })
                    .catch(function (error) {
                        vm.status = 'An error occured.' + error;
                    })
            }
        }
    })
</script>
</body>
</html>

Hope this helps.

Using CSS :before and :after pseudo-elements with inline CSS?

As mentioned before, you can't use inline elements for styling pseudo classes. Before and after pseudo classes are states of elements, not actual elements. You could only possibly use JavaScript for this.

The view 'Index' or its master was not found.

I added viewlocationformat to RazorViewEngine and worked for me.

ViewLocationFormats = new[] {
            "~/Views/{1}/{0}.cshtml",
            "~/Views/Shared/{0}.cshtml",
            "~/Areas/Admin/Views/{1}/{0}.cshtml",
            "~/Areas/Admin/Views/Shared/{0}.cshtml"
        };

SQL Server copy all rows from one table into another i.e duplicate table

Don't have sql server around to test but I think it's just:

insert into newtable select * from oldtable;

Why do we assign a parent reference to the child object in Java?

This situation happens when you have several implementations. Let me explain. Supppose you have several sorting algorithm and you want to choose at runtime the one to implement, or you want to give to someone else the capability to add his implementation. To solve this problem you usually create an abstract class (Parent) and have different implementation (Child). If you write:

Child c = new Child();

you bind your implementation to Child class and you can't change it anymore. Otherwise if you use:

Parent p = new Child();

as long as Child extends Parent you can change it in the future without modifying the code.

The same thing can be done using interfaces: Parent isn't anymore a class but a java Interface.

In general you can use this approch in DAO pattern where you want to have several DB dependent implementations. You can give a look at FactoryPatter or AbstractFactory Pattern. Hope this can help you.

Adding an onclick event to a table row

selectRowToInput();
function selectRowToInput(){
var table = document.getElementById("table");
var rows = table.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++)
{
    var currentRow = table.rows[i];
    currentRow.onclick = function() {

       rows=this.rowIndex;
        console.log(rows);  
    };
}

}

JFrame Exit on close Java

The following code works for me:

System.exit(home.EXIT_ON_CLOSE);

How can I create a table with borders in Android?

I used this solution: in TableRow, I created for every cell LinearLayout with vertical line and actual cell in it, and after every TableRow, I added a horizontal line.

Look at the code below:

<TableLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:shrinkColumns="1">

    <TableRow            
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

            <LinearLayout 
                android:orientation="horizontal"
                android:layout_height="match_parent"
                android:layout_weight="1">

                <TextView 
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:gravity="center"/>

            </LinearLayout>

            <LinearLayout 
                android:orientation="horizontal"
                android:layout_height="match_parent"
                android:layout_weight="1">

                <View
                    android:layout_height="match_parent"
                    android:layout_width="1dp"
                    android:background="#BDCAD2"/>

                <TextView 
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:gravity="center"/>

            </LinearLayout>
      </TableRow>

      <View
        android:layout_height="1dip"
        android:background="#BDCAD2" />

      <!-- More TableRows -->
</TableLayout>

Hope it will help.

How can I make space between two buttons in same div?

Another way to achieve this is to add a class .btn-space in your buttons

  <button type="button" class="btn btn-outline-danger btn-space"
  </button>
  <button type="button" class="btn btn-outline-primary btn-space"
  </button>

and define this class as follows

.btn-space {
    margin-right: 15px;
}

Best C# API to create PDF

Update:

I'm not sure when or if the license changed for the iText# library, but it is licensed under AGPL which means it must be licensed if included with a closed-source product. The question does not (currently) require free or open-source libraries. One should always investigate the license type of any library used in a project.


I have used iText# with success in .NET C# 3.5; it is a port of the open source Java library for PDF generation and it's free.

There is a NuGet package available for iTextSharp version 5 and the official developer documentation, as well as C# examples, can be found at itextpdf.com

JavaScript - Getting HTML form values

My 5 cents here, using form.elements which allows you to query each field by it's name, not only by iteration:

const form = document.querySelector('form[name="valform"]');
const ccValidation = form.elements['cctextbox'].value;
const ccType = form.elements['cardtype'].value;

Difference between webdriver.Dispose(), .Close() and .Quit()

Close() - It is used to close the browser or page currently which is having the focus.

Quit() - It is used to shut down the web driver instance or destroy the web driver instance(Close all the windows).

Dispose() - I am not aware of this method.

Converting a factor to numeric without losing information R (as.numeric() doesn't seem to work)

First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.

For example,

> z <- factor(letters[c(3, 2, 3, 4)])

# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d

# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"

here, z has 4 elements.
The index is 2, 1, 2, 3 in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.

Then, as.numeric converts simply the index part of factor into numeric.
as.character handles the index and levels, and generates character vector expressed by its level.

?as.numeric says that Factors are handled by the default method.

Spring JPA and persistence.xml

Just to confirm though you probably did...

Did you include the

<!--  tell spring to use annotation based congfigurations -->
<context:annotation-config />
<!--  tell spring where to find the beans -->
<context:component-scan base-package="zz.yy.abcd" />

bits in your application context.xml?

Also I'm not so sure you'd be able to use a jta transaction type with this kind of setup? Wouldn't that require a data source managed connection pool? So try RESOURCE_LOCAL instead.

Duplicate and rename Xcode project & associated folders

I'm posting this since I have always been struggling when renaming a project in XCode.

Renaming the project is good and simple but this doesn't rename the source folder. Here is a step by step of what I have done that worked great in Xcode 4 and 5 thanks to the links below.

REF links:
Rename Project.
Rename Source Folder and other files.

1- Backup your project.

If you are using git, commit any changes, make a copy of the entire project folder and backup in time machine before making any changes (this step is not required but I highly recommended).

2- Open your project.

3- Slow double click or hit enter on the Project name (blue top icon) and rename it to whatever you like.

NOTE: After you rename the project and press ‘enter’ it will suggest to automatically change all project-name-related entries and will allow you to de-select some of them if you want. Select all of them and click ok.

4- Rename the Scheme

a) Click the menu right next to the stop button and select Manage Schemes.

b) Single-slow-click or hit enter on the old name scheme and rename it to whatever you like.

c) Click ok.

5 - Build and run to make sure it works.

NOTES: At this point all of the important project files should be renamed except the comments in the classes created when the project was created nor the source folder. Next we will rename the folder in the file system.

6- Close the project.

7- Rename the main and the source folder.

8- Right click the project bundle .xcodeproj file and select “Show Package Contents” from the context menu. Open the .pbxproj file with any text editor.

9- Search and replace any occurrence of the original folder name with the new folder name.

10- Save the file.

11- Open XCode project, test it.

12- Done.

EDIT 10/11/19:

There is a tool to rename projects in Xcode I haven't tried it enough to comment on it. https://github.com/appculture/xcode-project-renamer

Facebook database design?

Have a look at the following database schema, reverse engineered by Anatoly Lubarsky:

Facebook Schema

Is there a simple way to increment a datetime object one month in Python?

>>> now
datetime.datetime(2016, 1, 28, 18, 26, 12, 980861)
>>> later = now.replace(month=now.month+1)
>>> later
datetime.datetime(2016, 2, 28, 18, 26, 12, 980861)

EDIT: Fails on

y = datetime.date(2016, 1, 31); y.replace(month=2) results in ValueError: day is out of range for month

Ther is no simple way to do it, but you can use your own function like answered below.

Create a remote branch on GitHub

It looks like github has a simple UI for creating branches. I opened the branch drop-down and it prompts me to "Find or create a branch ...". Type the name of your new branch, then click the "create" button that appears.

To retrieve your new branch from github, use the standard git fetch command.

create branch github ui

I'm not sure this will help your underlying problem, though, since the underlying data being pushed to the server (the commit objects) is the same no matter what branch it's being pushed to.

html text input onchange event

onChange doesn't fire until you lose focus later. If you want to be really strict with instantaneous changes of all sorts, use:

<input
   type       = "text" 
   onchange   = "myHandler();"
   onkeypress = "this.onchange();"
   onpaste    = "this.onchange();"
   oninput    = "this.onchange();"
/>

How do I connect to this localhost from another computer on the same network?

If you are on Windows, use ipconfig to get the local IPv4 address, and then specify that under your Apache configuration file: httpd.conf, like:

Listen: 10.20.30.40:80

Restart your Apache server and test it from other computer on the network.

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

I don't understand why nobody points to the specific issue and some answers are totally misleading, especially the accepted answer. The issue is that the OP did not pick a rule that could possibly override the margin property that is set by the User Agent (UA) directly on the ul tag. Let's consider all the rules with a margin property used by the OP.

body {

margin:0px;
...
}

The body element is way up in the DOM and the UA rule matches an element below, so the UA wins. It's the way inheritance works. Inheritance is the means by which, in the absence of any specific declarations from any source applied by the CSS cascade, a property value of an element is obtained from its parent element. Specificity on the parent element is useless, because the UA rule matches directly the element.

#mainNav{
    margin:0 auto;
    ...
}

This is a better attempt, a more specific selector #mainNav, which matches the mainNav element lower in the DOM, but the same principle applies, because the ul element is still below this element in the DOM.

#mainNav ul li{
    ...
    margin:0;
    ...
}

This went too far down in the DOM! Now, the selector matches the li element, which is below the ul element.

So, assuming that the UA rule used the selector ul and not !important, which is most likely the case, the solution would have been a simple ul { margin: 0; }, but it would be safer to make it more specific, say #mainNav ul { margin: 0 }.

Angularjs - Pass argument to directive

Controller code

myApp.controller('mainController', ['$scope', '$log', function($scope, $log) {
    $scope.person = {
        name:"sangeetha PH",
       address:"first Block"
    }
}]);

Directive Code

myApp.directive('searchResult',function(){
   return{
       restrict:'AECM',
       templateUrl:'directives/search.html',
       replace: true,
       scope:{
           personName:"@",
           personAddress:"@"
       }
   } 
});

USAGE

File :directives/search.html
content:

<h1>{{personName}} </h1>
<h2>{{personAddress}}</h2>

the File where we use directive

<search-result person-name="{{person.name}}" person-address="{{person.address}}"></search-result>

how can I connect to a remote mongo server from Mac OS terminal

You are probably connecting fine but don't have sufficient privileges to run show dbs.

You don't need to run the db.auth if you pass the auth in the command line:

mongo somewhere.mongolayer.com:10011/my_database -u username -p password

Once you connect are you able to see collections?

> show collections

If so all is well and you just don't have admin privileges to the database and can't run the show dbs

How do I determine height and scrolling position of window in jQuery?

$(window).height()

$(window).width()

There is also a plugin to jquery to determine element location and offsets

http://plugins.jquery.com/project/dimensions

scrolling offset = offsetHeight property of an element

Is Constructor Overriding Possible?

It should also be noted that you can't override the constructor in the subclass with the constructor of the superclass's name. The rule of OOPS tells that a constructor should have name as its class name. If we try to override the superclass constructor it will be seen as an unknown method without a return type.

Android: How to set password property in an edit text?

The only way that worked for me using code (not XML) is this one:

etPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());

How can I get date in application run by node.js?

NodeJS (and newer browsers) have a nice shortcut to get the current time in milliseconds.

var timeInMss = Date.now()

Which has a performance boost compared with

var timeInMss = new Date().getTime()

Because you do not need to create a new object.

Java optional parameters

This is an old question maybe even before actual Optional type was introduced but these days you can consider few things: - use method overloading - use Optional type which has advantage of avoiding passing NULLs around Optional type was introduced in Java 8 before it was usually used from third party lib such as Google's Guava. Using optional as parameters / arguments can be consider as over-usage as the main purpose was to use it as a return time.

Ref: https://itcodehub.blogspot.com/2019/06/using-optional-type-in-java.html

Could not open a connection to your authentication agent

Try to the following steps:

1) Open Git Bash and run: cd ~/.ssh

2) Try to run agent : eval $(ssh-agent)

3) Right now, you can run the following command : ssh-add -l

ToggleButton in C# WinForms

This is my simple codes I hope it can help you

private void button2_Click(object sender, EventArgs e)
    {
        if (button2.Text == "ON")
        {
            panel_light.BackColor = Color.Yellow; //symbolizes light turned on

            button2.Text = "OFF";
        }

        else if (button2.Text == "OFF")
        {
            panel_light.BackColor = Color.Black; //symbolizes light turned off

            button2.Text = "ON";
        }
    }

select2 onchange event only works once

$('#search_code').select2({
.
.
.
.
}).on("change", function (e) {
      var str = $("#s2id_search_code .select2-choice span").text();
      DOSelectAjaxProd(e.val, str);
});

Resize image with javascript canvas (smoothly)

Based on K3N answer, I rewrite code generally for anyone wants

var oc = document.createElement('canvas'), octx = oc.getContext('2d');
    oc.width = img.width;
    oc.height = img.height;
    octx.drawImage(img, 0, 0);
    while (oc.width * 0.5 > width) {
       oc.width *= 0.5;
       oc.height *= 0.5;
       octx.drawImage(oc, 0, 0, oc.width, oc.height);
    }
    oc.width = width;
    oc.height = oc.width * img.height / img.width;
    octx.drawImage(img, 0, 0, oc.width, oc.height);

UPDATE JSFIDDLE DEMO

Here is my ONLINE DEMO

How to run (not only install) an android application using .apk file?

I created terminal aliases to install and run an apk using a single command.

// I use ZSH, here is what I added to my .zshrc file (config file)
// at ~/.zshrc
// If you use bash shell, append it to ~/.bashrc

# Have the adb accessible, by including it in the PATH
export PATH="/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:path/to/android_sdk/platform-tools/"

# Setup your Android SDK path in ANDROID_HOME variable
export ANDROID_HOME=~/sdks/android_sdk

# Setup aapt tool so it accessible using a single command
alias aapt="$ANDROID_HOME/build-tools/27.0.3/aapt"

# Install APK to device
# Use as: apkinstall app-debug.apk
alias apkinstall="adb devices | tail -n +2 | cut -sf 1 | xargs -I X adb -s X install -r $1"
# As an alternative to apkinstall, you can also do just ./gradlew installDebug

# Alias for building and installing the apk to connected device
# Run at the root of your project
# $ buildAndInstallApk
alias buildAndInstallApk='./gradlew assembleDebug && apkinstall ./app/build/outputs/apk/debug/app-debug.apk'

# Launch your debug apk on your connected device
# Execute at the root of your android project
# Usage: launchDebugApk
alias launchDebugApk="adb shell monkey -p `aapt dump badging ./app/build/outputs/apk/debug/app-debug.apk | grep -e 'package: name' | cut -d \' -f 2` 1"

# ------------- Single command to build+install+launch apk------------#
# Execute at the root of your android project
# Use as: buildInstallLaunchDebugApk
alias buildInstallLaunchDebugApk="buildAndInstallApk && launchDebugApk"

Note: Here I am building, installing and launching the debug apk which is usually in the path: ./app/build/outputs/apk/debug/app-debug.apk, when this command is executed from the root of the project

If you would like to install and run any other apk, simply replace the path for debug apk with path of your own apk

Here is the gist for the same. I created this because I was having trouble working with Android Studio build reaching around 28 minutes, so I switched over to terminal builds which were around 3 minutes. You can read more about this here

Explanation:

The one alias that I think needs explanation is the launchDebugApk alias. Here is how it is broken down:

The part aapt dump badging ./app/build/outputs/apk/debug/app-debug.apk | grep -e 'package: name basically uses the aapt tool to extract the package name from the apk.

Next, is the command: adb shell monkey -p com.package.name 1, which basically uses the monkey tool to open up the default launcher activity of the installed app on the connected device. The part of com.package.name is replaced by our previous command which takes care of getting the package name from the apk.

AngularJS ng-class if-else expression

The above solutions didn't work for me for classes with background images somehow. What I did was I create a default class (the one you need in else) and set class='defaultClass' and then the ng-class="{class1:abc,class2:xyz}"

<span class="booking_warning" ng-class="{ process_success: booking.bookingStatus == 'BOOKING_COMPLETED' || booking.bookingStatus == 'BOOKING_PROCESSED', booking_info: booking.bookingStatus == 'INSTANT_BOOKING_REQUEST_RECEIVED' || booking.bookingStatus == 'BOOKING_PENDING'}"> <strong>{{booking.bookingStatus}}</strong> </span>

P.S: The classes that are in condition should override the default class i.e marked as !important

Capture Signature using HTML5 and iPad

Here's another canvas based version with variable width (based on drawing velocity) curves: demo at http://szimek.github.io/signature_pad and code at https://github.com/szimek/signature_pad.

signature sample

Make a div into a link

This option doesn’t require an empty.gif as in the most upvoted answer:

HTML:

 <div class="feature">
       <a href="http://www.example.com"></a>
 </div>

CSS:

 div.feature {
        position: relative;
    }

    div.feature a {
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        text-decoration: none; /* No underlines on the link */
        z-index: 10; /* Places the link above everything else in the div */
        background-color: #FFF; /* Fix to make div clickable in IE */
        opacity: 0; /* Fix to make div clickable in IE */
        filter: alpha(opacity=1); /* Fix to make div clickable in IE */
    }

As proposed at http://www.digitalskydesign.com/how-to-make-an-entire-div-a-link-using-css/

How to manage a redirect request after a jQuery Ajax call

I just wanted to latch on to any ajax requests for the entire page. @SuperG got me started. Here is what I ended up with:

// redirect ajax requests that are redirected, not found (404), or forbidden (403.)
$('body').bind('ajaxComplete', function(event,request,settings){
        switch(request.status) {
            case 301: case 404: case 403:                    
                window.location.replace("http://mysite.tld/login");
                break;
        }
});

I wanted to specifically check for certain http status codes to base my decision on. However, you can just bind to ajaxError to get anything other than success (200 only perhaps?) I could have just written:

$('body').bind('ajaxError', function(event,request,settings){
    window.location.replace("http://mysite.tld/login");
}

What is the difference between json.dump() and json.dumps() in python?

The functions with an s take string parameters. The others take file streams.

Java HashMap performance optimization / alternative

The popular hashing methods used are not really very good for large sets and, as pointed out above, the hash used is particularly bad. Better is to use a hash algorithm with high mixing and coverage such as BuzHash (sample implementation at http://www.java2s.com/Code/Java/Development-Class/AveryefficientjavahashalgorithmbasedontheBuzHashalgoritm.htm)

jQuery: click function exclude children.

To do this, stop the click on the child using .stopPropagation:

$(".example").click(function(){
  $(this).fadeOut("fast");
}).children().click(function(e) {
  return false;
});

This will stop the child clicks from bubbling up past their level so the parent won't receive the click.

.not() is used a bit differently, it filters elements out of your selector, for example:

<div class="bob" id="myID"></div>
<div class="bob"></div>

$(".bob").not("#myID"); //removes the element with myID

For clicking, your problem is that the click on a child bubbles up to the parent, not that you've inadvertently attached a click handler to the child.

Android: show/hide a view using an animation

Set the attribute android:animateLayoutChanges="true" inside the parent layout .

Put the view in a layout if its not and set android:animateLayoutChanges="true" for that layout.

NOTE: This works only from API Level 11+ (Android 3.0)

Converting string to Date and DateTime

If you wish to accept dates using American ordering (month, date, year) for European style formats (using dash or period as day, month, year) while still accepting other formats, you can extend the DateTime class:

/**
 * Quietly convert European format to American format
 *
 * Accepts m-d-Y, m-d-y, m.d.Y, m.d.y, Y-m-d, Y.m.d
 * as well as all other built-in formats
 * 
 */
class CustomDateTime extends DateTime 
{
  public function __construct(string $time="now", DateTimeZone $timezone = null) 
  {
    // convert m-d-y or m.d.y to m/d/y to avoid PHP parsing as d-m-Y (substr avoids microtime error)
    $time = str_replace(['-','.'], '/', substr($time, 0, 10)) . substr($time, 10 );

    parent::__construct($time, $timezone);
  }
}

// usage:
$date = new CustomDateTime('7-24-2019');
print $date->format('Y-m-d');

// => '2019-07-24'

Or, you can make a function to accept m-d-Y and output Y-m-d:

/**
 * Accept dates in various m, d, y formats and return as Y-m-d
 * 
 * Changes PHP's default behaviour for dates with dashes or dots.
 * Accepts:
 *   m-d-y, m-d-Y, Y-m-d,
 *   m.d.y, m.d.Y, Y.m.d,
 *   m/d/y, m/d/Y, Y/m/d,
 *   ... and all other formats natively supported 
 * 
 * Unsupported formats or invalid dates will generate an Exception
 * 
 * @see https://www.php.net/manual/en/datetime.formats.date.php PHP formats supported
 * @param  string $d various representations of date
 * @return string    Y-m-d or '----' for null or blank
 */
function asYmd($d) {
  if(is_null($d) || $d=='') { return '----'; }

  // convert m-d-y or m.d.y to m/d/y to avoid PHP parsing as d-m-Y
  $d = str_replace(['-','.'], '/', $d);

  return (new DateTime($d))->format('Y-m-d');
}

// usage:

<?= asYmd('7-24-2019') ?>

// or

<?php echo asYmd('7-24-2019'); ?>

How do you debug MySQL stored procedures?

I do something very similar to you.

I'll usually include a DEBUG param that defaults to false and I can set to true at run time. Then wrap the debug statements into an "If DEBUG" block.

I also use a logging table with many of my jobs so that I can review processes and timing. My Debug code gets output there as well. I include the calling param name, a brief description, row counts affected (if appropriate), a comments field and a time stamp.

Good debugging tools is one of the sad failings of all SQL platforms.

How do I center this form in css?

You can try

form {
    margin-left: 25%;
    margin-right:25%;
    width: 50%;
}

Or

form {
    margin-left: 15%;
    margin-right:15%;
    width: 70%;
}

'list' object has no attribute 'shape'

Alternatively, you can use np.shape(...)

For instance:

import numpy as np

a=[1,2,3]

and np.shape(a) will give an output of (3,)

How to resolve TypeError: can only concatenate str (not "int") to str

Python working a bit differently to JavaScript for example, the value you are concatenating needs to be same type, both int or str...

So for example the code below throw an error:

print( "Alireza" + 1980)

like this:

Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    print( "Alireza" + 1980)
TypeError: can only concatenate str (not "int") to str

To solve the issue, just add str to your number or value like:

print( "Alireza" + str(1980))

And the result as:

Alireza1980

Angles between two n-dimensional vectors in Python

import math

def dotproduct(v1, v2):
  return sum((a*b) for a, b in zip(v1, v2))

def length(v):
  return math.sqrt(dotproduct(v, v))

def angle(v1, v2):
  return math.acos(dotproduct(v1, v2) / (length(v1) * length(v2)))

Note: this will fail when the vectors have either the same or the opposite direction. The correct implementation is here: https://stackoverflow.com/a/13849249/71522

How to use CURL via a proxy?

root@APPLICATIOSERVER:/var/www/html# php connectiontest.php
61e23468-949e-4103-8e08-9db09249e8s1 OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to 10.172.123.1:80 root@APPLICATIOSERVER:/var/www/html#

Post declaring the proxy settings in the php script file issue has been fixed.

$proxy = '10.172.123.1:80';
curl_setopt($cSession, CURLOPT_PROXY, $proxy); // PROXY details with port

How to insert an element after another element in JavaScript without using a library?

You can actually a method called after() in newer version of Chrome, Firefox and Opera. The downside of this method is that Internet Explorer doesn't support it yet.

Example:

// You could create a simple node
var node = document.createElement('p')

// And then get the node where you want to append the created node after
var existingNode = document.getElementById('id_of_the_element')

// Finally you can append the created node to the exisitingNode
existingNode.after(node)

A simple HTML Code to test that is:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
     <p id='up'>Up</p>_x000D_
    <p id="down">Down</p>_x000D_
  <button id="switchBtn" onclick="switch_place()">Switch place</button>_x000D_
  <script>_x000D_
    function switch_place(){_x000D_
      var downElement = document.getElementById("down")_x000D_
      var upElement = document.getElementById("up")_x000D_
      downElement.after(upElement);_x000D_
      document.getElementById('switchBtn').innerHTML = "Switched!"_x000D_
    }_x000D_
  </script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

As expected, it moves the up element after the down element

How to get First and Last record from a sql query?

select *
from {Table_Name}
where {x_column_name}=(
    select d.{x_column_name} 
    from (
        select rownum as rno,{x_column_name}
        from {Table_Name})d
        where d.rno=(
            select count(*)
            from {Table_Name}));

How do you load custom UITableViewCells from Xib files?

  1. Create your own customized class AbcViewCell subclass from UITableViewCell (Make sure your class file name and nib file name are the same)

  2. Create this extension class method.

    extension UITableViewCell {
        class func fromNib<T : UITableViewCell>() -> T {
            return Bundle.main.loadNibNamed(String(describing: T.self), owner: nil, options: nil)?[0] as! T
        }
    }
    
  3. Use it.

    let cell: AbcViewCell = UITableViewCell.fromNib()

How to use a Bootstrap 3 glyphicon in an html select

If you are using the glyphicon as the first character of the string, you can use the html char (see https://glyphicons.bootstrapcheatsheets.com/) and then apply the font to the first character of the element:

    option::first-letter{
        font-family: Glyphicons Halflings;
    }

How to query MongoDB with "like"?

FullName like 'last' with status==’Pending’ between two dates:

db.orders.find({
      createdAt:{$gt:ISODate("2017-04-25T10:08:16.111Z"),
      $lt:ISODate("2017-05-05T10:08:16.111Z")},
      status:"Pending",
      fullName:/last/}).pretty();

status== 'Pending' and orderId LIKE ‘PHA876174’:

db.orders.find({
     status:"Pending",
     orderId:/PHA876174/
     }).pretty();

What Java FTP client library should I use?

Apache commons-nets get updates more frequently recently, while Enterprise DT library seems to update even more frequently.

td widths, not working?

You can't specify units in width/height attributes of a table; these are always in pixels, but you should not use them at all since they are deprecated.

Postgres FOR LOOP

I just ran into this question and, while it is old, I figured I'd add an answer for the archives. The OP asked about for loops, but their goal was to gather a random sample of rows from the table. For that task, Postgres 9.5+ offers the TABLESAMPLE clause on WHERE. Here's a good rundown:

https://www.2ndquadrant.com/en/blog/tablesample-in-postgresql-9-5-2/

I tend to use Bernoulli as it's row-based rather than page-based, but the original question is about a specific row count. For that, there's a built-in extension:

https://www.postgresql.org/docs/current/tsm-system-rows.html

CREATE EXTENSION tsm_system_rows;

Then you can grab whatever number of rows you want:

select * from playtime tablesample system_rows (15);

Allow only numeric value in textbox using Javascript

or

function isNumber(n){
  return (parseFloat(n) == n);
}

http://jsfiddle.net/Vj2Kk/2/

Convert multidimensional array into single array

This single line would do that:

$array = array_column($array, 'plan');

The first argument is an array | The second argument is an array key.

For details, go to official documentation: https://www.php.net/manual/en/function.array-column.php.

Storing images in SQL Server?

In my experience, storing to the url to the images stored in another location is the best way for a simple project.

Code signing is required for product type 'Application' in SDK 'iOS5.1'

The other issue here lies under Code Signing Identity under the Build Settings. Be sure that it contains the Code Signing Identity: "iOS Developer" as opposed to "Don't Code Sign." This will allow you to deploy it to your iOS device. Especially, if you have downloaded a GitHub example or something to this effect.

How can I create an editable dropdownlist in HTML?

A combobox is unfortunately something that was left out of the HTML specifications.

The only way to manage it, rather unfortunately, is to roll your own or use a pre-built one. This one looks quite simple. I use this one for an open-source app although unfortunately you have to pay for commercial usage.

Same Navigation Drawer in different Activities

With @Kevin van Mierlo 's answer, you are also capable of implementing several drawers. For instance, the default menu located on the left side (start), and a further optional menu, located on the right side, which is only shown when determinate fragments are loaded.

I've been able to do that.

Change a branch name in a Git repo

Assuming you're currently on the branch you want to rename:

git branch -m newname

This is documented in the manual for git-branch, which you can view using

man git-branch

or

git help branch

Specifically, the command is

git branch (-m | -M) [<oldbranch>] <newbranch>

where the parameters are:

   <oldbranch>
       The name of an existing branch to rename.

   <newbranch>
       The new name for an existing branch. The same restrictions as for <branchname> apply.

<oldbranch> is optional, if you want to rename the current branch.

CSS/Javascript to force html table row on a single line

As cletus said, you should use white-space: nowrap to avoid the line wrapping, and overflow:hidden to hide the overflow. However, in order for a text to be considered overflow, you should set the td/th width, so in case the text requires more than the specified width, it will be considered an overflow, and will be hidden.

Also, if you give a sample web page, responders can provide an updated page with the fix you like.

How to count lines of Java code using IntelliJ IDEA?

Statistic plugins works fine!

Here is a quick case:

  1. Ctrl+Shift+A and serach for "Statistic" to open the panel.
  2. You will see panel as the screenshot and then click Refresh for whole project or select your project or file and Refresh on selection for only selection.

statistic

How do I set the figure title and axes labels font size in Matplotlib?

Others have provided answers for how to change the title size, but as for the axes tick label size, you can also use the set_tick_params method.

E.g., to make the x-axis tick label size small:

ax.xaxis.set_tick_params(labelsize='small')

or, to make the y-axis tick label large:

ax.yaxis.set_tick_params(labelsize='large')

You can also enter the labelsize as a float, or any of the following string options: 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', or 'xx-large'.

Java: convert seconds to minutes, hours and days

my quick answer with basic java arithmetic calculation is this:

First consider the following values:

1 Minute = 60 Seconds
1 Hour = 3600 Seconds ( 60 * 60 )
1 Day = 86400 Second ( 24 * 3600 )
  1. First divide the input by 86400, if you you can get a number greater than 0 , this is the number of days. 2.Again divide the remained number you get from the first calculation by 3600, this will give you the number of hours
  2. Then divide the remainder of your second calculation by 60 which is the number of Minutes
  3. Finally the remained number from your third calculation is the number of seconds

the code snippet is as follows:

int input=500000;
int numberOfDays;
int numberOfHours;
int numberOfMinutes;
int numberOfSeconds;

numberOfDays = input / 86400;
numberOfHours = (input % 86400 ) / 3600 ;
numberOfMinutes = ((input % 86400 ) % 3600 ) / 60 
numberOfSeconds = ((input % 86400 ) % 3600 ) % 60  ;

I hope to be helpful to you.

How can I display an image from a file in Jupyter Notebook?

When using GenomeDiagram with Jupyter (iPython), the easiest way to display images is by converting the GenomeDiagram to a PNG image. This can be wrapped using an IPython.display.Image object to make it display in the notebook.

from Bio.Graphics import GenomeDiagram
from Bio.SeqFeature import SeqFeature, FeatureLocation
from IPython.display import display, Image
gd_diagram = GenomeDiagram.Diagram("Test diagram")
gd_track_for_features = gd_diagram.new_track(1, name="Annotated Features")
gd_feature_set = gd_track_for_features.new_set()
gd_feature_set.add_feature(SeqFeature(FeatureLocation(25, 75), strand=+1))
gd_diagram.draw(format="linear", orientation="landscape", pagesize='A4',
                fragments=1, start=0, end=100)
Image(gd_diagram.write_to_string("PNG"))

[See Notebook]

How to load all modules in a folder?

List all python (.py) files in the current folder and put them as __all__ variable in __init__.py

from os.path import dirname, basename, isfile, join
import glob
modules = glob.glob(join(dirname(__file__), "*.py"))
__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]

How to enumerate an object's properties in Python?

I think it's worth showing the difference between the various options mentioned - often a picture is worth a thousand words.

>>> from pprint import pprint
>>> import inspect
>>>
>>> class a():
    x = 1               # static class member
    def __init__(self):
        self.y = 2      # static instance member
    @property
    def dyn_prop(self): # dynamic property
        print('DYNPROP WAS HERE')
        return 3
    def test(self):     # function member
        pass
    @classmethod
    def myclassmethod(cls): # class method; static methods behave the same
        pass

>>> i = a()
>>> pprint(i.__dict__)
{'y': 2}
>>> pprint(vars(i))
{'y': 2}
>>> pprint(dir(i))
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'dyn_prop',
 'myclassmethod',
 'test',
 'x',
 'y']
>>> pprint(inspect.getmembers(i))
DYNPROP WAS HERE
[('__class__', <class '__main__.a'>),
 ('__delattr__',
  <method-wrapper '__delattr__' of a object at 0x000001CB891BC7F0>),
 ('__dict__', {'y': 2}),
 ('__dir__', <built-in method __dir__ of a object at 0x000001CB891BC7F0>),
 ('__doc__', None),
 ('__eq__', <method-wrapper '__eq__' of a object at 0x000001CB891BC7F0>),
 ('__format__', <built-in method __format__ of a object at 0x000001CB891BC7F0>),
 ('__ge__', <method-wrapper '__ge__' of a object at 0x000001CB891BC7F0>),
 ('__getattribute__',
  <method-wrapper '__getattribute__' of a object at 0x000001CB891BC7F0>),
 ('__gt__', <method-wrapper '__gt__' of a object at 0x000001CB891BC7F0>),
 ('__hash__', <method-wrapper '__hash__' of a object at 0x000001CB891BC7F0>),
 ('__init__',
  <bound method a.__init__ of <__main__.a object at 0x000001CB891BC7F0>>),
 ('__init_subclass__',
  <built-in method __init_subclass__ of type object at 0x000001CB87CA6A70>),
 ('__le__', <method-wrapper '__le__' of a object at 0x000001CB891BC7F0>),
 ('__lt__', <method-wrapper '__lt__' of a object at 0x000001CB891BC7F0>),
 ('__module__', '__main__'),
 ('__ne__', <method-wrapper '__ne__' of a object at 0x000001CB891BC7F0>),
 ('__new__', <built-in method __new__ of type object at 0x00007FFCA630AB50>),
 ('__reduce__', <built-in method __reduce__ of a object at 0x000001CB891BC7F0>),
 ('__reduce_ex__',
  <built-in method __reduce_ex__ of a object at 0x000001CB891BC7F0>),
 ('__repr__', <method-wrapper '__repr__' of a object at 0x000001CB891BC7F0>),
 ('__setattr__',
  <method-wrapper '__setattr__' of a object at 0x000001CB891BC7F0>),
 ('__sizeof__', <built-in method __sizeof__ of a object at 0x000001CB891BC7F0>),
 ('__str__', <method-wrapper '__str__' of a object at 0x000001CB891BC7F0>),
 ('__subclasshook__',
  <built-in method __subclasshook__ of type object at 0x000001CB87CA6A70>),
 ('__weakref__', None),
 ('dyn_prop', 3),
 ('myclassmethod', <bound method a.myclassmethod of <class '__main__.a'>>),
 ('test', <bound method a.test of <__main__.a object at 0x000001CB891BC7F0>>),
 ('x', 1),
 ('y', 2)]

To summarize:

  • vars() and __dict__ only return instance-local properties;
  • dir() returns everything, but only as a list of string member names; dynamic properties are not called;
  • inspect.getmembers() returns everything, as a list of tuples (name, value); it actually runs dynamic properties, and accepts an optional predicate argument that can filter out members by value.

So my common-sense approach is typically to use dir() on the command line, and getmembers() in programs, unless specific performance considerations apply.

Note that, to keep things cleaner, I did not include __slots__ - if present, it was explicitly put there to be queried, and should be used directly. I also did not cover metaclasses, which can get a bit hairy (most people will never use them anyway).

TypeError: $(...).on is not a function

If you are using old version of jQuery(< 1.7) then you can use "bind" instead of "on". This will only work in case you are using old version, since as of jQuery 3.0, "bind" has been deprecated.

How to change Status Bar text color in iOS

Simply calling

[[UINavigationBar appearance] setBarStyle:UIBarStyleBlack];

in the

-(BOOL)application:(UIApplication *)application 
           didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
}

method of my AppDelegate works great for me in iOS7.

How to use adb pull command?

I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.

I found a link doing the same thing. Try following these steps.

How to copy selected files from Android with adb pull

When is del useful in Python?

Once I had to use:

del serial
serial = None

because using only:

serial = None

didn't release the serial port fast enough to immediately open it again. From that lesson I learned that del really meant: "GC this NOW! and wait until it's done" and that is really useful in a lot of situations. Of course, you may have a system.gc.del_this_and_wait_balbalbalba(obj).

How to pass a textbox value from view to a controller in MVC 4?

When you want to pass new information to your application, you need to use POST form. In Razor you can use the following

View Code:

@* By default BeginForm use FormMethod.Post *@
@using(Html.BeginForm("Update")){
     @Html.Hidden("id", Model.Id)
     @Html.Hidden("productid", Model.ProductId)
     @Html.TextBox("qty", Model.Quantity)
     @Html.TextBox("unitrate", Model.UnitRate)
     <input type="submit" value="Update" />
}

Controller's actions

[HttpGet]
public ActionResult Update(){
     //[...] retrive your record object
     return View(objRecord);
}

[HttpPost]
public ActionResult Update(string id, string productid, int qty, decimal unitrate)
{
      if (ModelState.IsValid){
           int _records = UpdatePrice(id,productid,qty,unitrate);
           if (_records > 0){                    {
              return RedirectToAction("Index1", "Shopping");
           }else{                   
                ModelState.AddModelError("","Can Not Update");
           }
      }
      return View("Index1");
 }

Note that alternatively, if you want to use @Html.TextBoxFor(model => model.Quantity) you can either have an input with the name (respectecting case) "Quantity" or you can change your POST Update() to receive an object parameter, that would be the same type as your strictly typed view. Here's an example:

Model

public class Record {
    public string Id { get; set; }
    public string ProductId { get; set; }
    public string Quantity { get; set; }
    public decimal UnitRate { get; set; }
}

View

@using(Html.BeginForm("Update")){
     @Html.HiddenFor(model => model.Id)
     @Html.HiddenFor(model => model.ProductId)
     @Html.TextBoxFor(model=> model.Quantity)
     @Html.TextBoxFor(model => model.UnitRate)
     <input type="submit" value="Update" />
}

Post Action

[HttpPost]
public ActionResult Update(Record rec){ //Alternatively you can also use FormCollection object as well 
   if(TryValidateModel(rec)){
        //update code
   }
   return View("Index1");
}

Why am I getting "void value not ignored as it ought to be"?

srand doesn't return anything so you can't initialize a with its return value because, well, because it doesn't return a value. Did you mean to call rand as well?

How to send parameters from a notification-click to an activity?

AndroidManifest.xml

Include launchMode="singleTop"

<activity android:name=".MessagesDetailsActivity"
        android:launchMode="singleTop"
        android:excludeFromRecents="true"
        />

SMSReceiver.java

Set the flags for the Intent and PendingIntent

Intent intent = new Intent(context, MessagesDetailsActivity.class);
    intent.putExtra("smsMsg", smsObject.getMsg());
    intent.putExtra("smsAddress", smsObject.getAddress());
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent contentIntent = PendingIntent.getActivity(context, notification_id, intent, PendingIntent.FLAG_UPDATE_CURRENT);

MessageDetailsActivity.java

onResume() - gets called everytime, load the extras.

Intent intent = getIntent();
    String extraAddress = intent.getStringExtra("smsAddress");
    String extraBody = intent.getStringExtra("smsMsg");

Hope it helps, it was based on other answers here on stackoverflow, but this is the most updated that worked for me.

Javascript seconds to minutes and seconds

To get the number of full minutes, divide the number of total seconds by 60 (60 seconds/minute):

var minutes = Math.floor(time / 60);

And to get the remaining seconds, multiply the full minutes with 60 and subtract from the total seconds:

var seconds = time - minutes * 60;

Now if you also want to get the full hours too, divide the number of total seconds by 3600 (60 minutes/hour · 60 seconds/minute) first, then calculate the remaining seconds:

var hours = Math.floor(time / 3600);
time = time - hours * 3600;

Then you calculate the full minutes and remaining seconds.

Bonus:

Use the following code to pretty-print the time (suggested by Dru)

function str_pad_left(string,pad,length) {
    return (new Array(length+1).join(pad)+string).slice(-length);
}

var finalTime = str_pad_left(minutes,'0',2)+':'+str_pad_left(seconds,'0',2);

How can I add shadow to the widget in flutter?

this is how I did it

    Container(
  decoration: new BoxDecoration(
    boxShadow: [
      BoxShadow(
        color: Colors.grey[200],
        blurRadius: 2.0, // has the effect of softening the shadow
        spreadRadius: 2.0, // has the effect of extending the shadow
        offset: Offset(
          5.0, // horizontal, move right 10
          5.0, // vertical, move down 10
        ),
      )
    ],
  ),
  child: Container( 
       color: Colors.white, //in your example it's blue, pink etc..
       child: //your content
  )

How to make a Qt Widget grow with the window size?

The accepted answer (its image) is wrong, at least now in QT5. Instead you should assign a layout to the root object/widget (pointing to the aforementioned image, it should be the MainWindow instead of centralWidget). Also note that you must have at least one QObject created beneath it for this to work. Do this and your ui will become responsive to window resizing.

Variable length (Dynamic) Arrays in Java

How about using a List instead? For example, ArrayList<integer>

Maven project version inheritance - do I have to specify the parent version?

eFox's answer worked for a single project, but not when I was referencing a module from another one (the pom.xml were still stored in my .m2 with the property instead of the version).

However, it works if you combine it with the flatten-maven-plugin, since it generates the poms with the correct version, not the property.

The only option I changed in the plug-in definition is the outputDirectory, it's empty by default, but I prefer to have it in target, which is set in my .gitignore configuration:

<plugin>
   <groupId>org.codehaus.mojo</groupId>
   <artifactId>flatten-maven-plugin</artifactId>
   <version>1.0.1</version>
   <configuration>
      <updatePomFile>true</updatePomFile>
      <outputDirectory>target</outputDirectory>
   </configuration>
   <executions>
      <execution>
         <id>flatten</id>
         <phase>process-resources</phase>
         <goals>
            <goal>flatten</goal>
         </goals>
      </execution>
   </executions>
</plugin>

The plug-in configuration goes in the parent pom.xml

Remove header and footer from window.print()

If you happen to scroll down to this point, I found a solution for Firefox. It will print contents from a specific div without the footers and headers. You can customize as you wish.

Firstly, download and install this addon : JSPrintSetup.

Secondly, write this function:

<script>
function PrintElem(elem)
{
    var mywindow = window.open('', 'PRINT', 'height=400,width=600');
    mywindow.document.write('<html><head><title>' + document.title  + '</title>');
    mywindow.document.write('</head><body >');
    mywindow.document.write(elem);
    mywindow.document.write('</body></html>');
    mywindow.document.close(); // necessary for IE >= 10
    mywindow.focus(); // necessary for IE >= 10*/

   //jsPrintSetup.setPrinter('PDFCreator'); //set the printer if you wish
   jsPrintSetup.setSilentPrint(1);

   //sent empty page header
   jsPrintSetup.setOption('headerStrLeft', '');
   jsPrintSetup.setOption('headerStrCenter', '');
   jsPrintSetup.setOption('headerStrRight', '');

   // set empty page footer
   jsPrintSetup.setOption('footerStrLeft', '');
   jsPrintSetup.setOption('footerStrCenter', '');
   jsPrintSetup.setOption('footerStrRight', '');

   // print my window silently. 
   jsPrintSetup.printWindow(mywindow);
   jsPrintSetup.setSilentPrint(1); //change to 0 if you want print dialog

    mywindow.close();

    return true;
}
</script>

Thirdly, In your code, wherever you want to write the print code, do this (I have used JQuery. You can use plain javascript):

<script>
$("#print").click(function () {
    var contents = $("#yourDivToPrint").html();
    PrintElem(contents);
})
</script>

Obviously, you need the link to click:

<a href="#" id="print">Print my Div</a>

And your div to print:

<div id="yourDivToPrint">....</div>

How do you share constants in NodeJS modules?

I don't think is a good practice to invade the GLOBAL space from modules, but in scenarios where could be strictly necessary to implement it:

Object.defineProperty(global,'MYCONSTANT',{value:'foo',writable:false,configurable:false});

It has to be considered the impact of this resource. Without proper naming of those constants, the risk of OVERWRITTING already defined global variables, is something real.

dynamically add and remove view to viewpager

I did a similar program. hope this would help you.In its first activity four grid data can be selected. On the next activity, there is a view pager which contains two mandatory pages.And 4 more pages will be there, which will be visible corresponding to the grid data selected.

Following is the mainactivty MainActivity

    package com.example.jeffy.viewpagerapp;
    import android.content.Context;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.database.Cursor;
    import android.database.SQLException;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.os.Bundle;
    import android.os.Parcel;
    import android.support.design.widget.FloatingActionButton;
    import android.support.design.widget.Snackbar;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.util.Log;
    import android.view.View;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.AdapterView;
    import android.widget.Button;
    import android.widget.GridView;
    import java.lang.reflect.Array;
    import java.util.ArrayList;
    public class MainActivity extends AppCompatActivity {
    SharedPreferences pref;
    SharedPreferences.Editor editor;
    GridView gridView;
    Button button;
    private static final String DATABASE_NAME = "dbForTest.db";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_NAME = "diary";
    private static final String TITLE = "id";
    private static final String BODY = "content";
    DBHelper  dbHelper = new DBHelper(this);
    ArrayList<String> frags = new ArrayList<String>();
    ArrayList<FragmentArray> fragmentArray = new ArrayList<FragmentArray>();
    String[] selectedData;
    Boolean port1=false,port2=false,port3=false,port4=false;
    int Iport1=1,Iport2=1,Iport3=1,Iport4=1,location;



    // This Data show in grid ( Used by adapter )
        CustomGridAdapter customGridAdapter = new           CustomGridAdapter(MainActivity.this,GRID_DATA);
    static final String[ ] GRID_DATA = new String[] {
            "1" ,
            "2",
            "3" ,
            "4"
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        frags.add("TabFragment3");
        frags.add("TabFragment4");
        frags.add("TabFragment5");
        frags.add("TabFragment6");
        dbHelper = new DBHelper(this);
        dbHelper.insertContact(1,0);
        dbHelper.insertContact(2,0);
        dbHelper.insertContact(3,0);
        dbHelper.insertContact(4,0);
        final Bundle selected = new Bundle();
        button = (Button) findViewById(R.id.button);
        pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
        editor = pref.edit();
        gridView = (GridView) findViewById(R.id.gridView1);

        gridView.setAdapter(customGridAdapter);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
              //view.findViewById(R.id.grid_item_image).setVisibility(View.VISIBLE);
                location = position + 1;
                if (position == 0) {
                    Iport1++;
                    Iport1 = Iport1 % 2;
                    if (Iport1 % 2 == 1) {
                        //dbHelper.updateContact(1,1);
                        view.findViewById(R.id.grid_item_image).setVisibility(View.VISIBLE);
                        dbHelper.updateContact(1,1);
                    } else {
                        //dbHelper.updateContact(1,0);
                        view.findViewById(R.id.grid_item_image).setVisibility(View.INVISIBLE);
                        dbHelper.updateContact(1, 0);
                    }
                }
                if (position == 1) {
                    Iport2++;
                    Iport1 = Iport1 % 2;
                    if (Iport2 % 2 == 1) {
                        //dbHelper.updateContact(2,1);
                        view.findViewById(R.id.grid_item_image).setVisibility(View.VISIBLE);
                        dbHelper.updateContact(2, 1);
                    } else {
                        //dbHelper.updateContact(2,0);
                        view.findViewById(R.id.grid_item_image).setVisibility(View.INVISIBLE);
                        dbHelper.updateContact(2,0);
                    }
                }
                if (position == 2) {
                    Iport3++;
                    Iport3 = Iport3 % 2;
                    if (Iport3 % 2 == 1) {
                        //dbHelper.updateContact(3,1);
                        view.findViewById(R.id.grid_item_image).setVisibility(View.VISIBLE);
                        dbHelper.updateContact(3, 1);
                    } else {
                        //dbHelper.updateContact(3,0);
                        view.findViewById(R.id.grid_item_image).setVisibility(View.INVISIBLE);
                        dbHelper.updateContact(3, 0);
                    }
                }
                if (position == 3) {
                    Iport4++;
                    Iport4 = Iport4 % 2;
                    if (Iport4 % 2 == 1) {
                        //dbHelper.updateContact(4,1);
                       view.findViewById(R.id.grid_item_image).setVisibility(View.VISIBLE);
                        dbHelper.updateContact(4, 1);
                    } else {
                        //dbHelper.updateContact(4,0);
                       view.findViewById(R.id.grid_item_image).setVisibility(View.INVISIBLE);
                        dbHelper.updateContact(4,0);
                    }
                }
            }
        });
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editor.putInt("port1", Iport1);
                editor.putInt("port2", Iport2);
                editor.putInt("port3", Iport3);
                editor.putInt("port4", Iport4);
                Intent i = new Intent(MainActivity.this,Main2Activity.class);
                if(Iport1==1)
                    i.putExtra("3","TabFragment3");
                else
                    i.putExtra("3", "");
                if(Iport2==1)
                    i.putExtra("4","TabFragment4");
                else
                    i.putExtra("4","");
                if(Iport3==1)
                    i.putExtra("5", "TabFragment5");
                else
                    i.putExtra("5","");
                if(Iport4==1)
                    i.putExtra("6", "TabFragment6");
                else
                    i.putExtra("6","");
                dbHelper.updateContact(0, Iport1);
                dbHelper.updateContact(1, Iport2);
                dbHelper.updateContact(2, Iport3);
                dbHelper.updateContact(3, Iport4);
                startActivity(i);
            }
        });
    }
}

Here TabFragment1,TabFragment2 etc are fragment to be displayed on the viewpager.And I am not showing the layouts since they are out of scope of this project.

MainActivity will intent to Main2Activity Main2Activity

    package com.example.jeffy.viewpagerapp;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;

import java.util.ArrayList;

public class Main2Activity extends AppCompatActivity {

    private ViewPager pager = null;
    private PagerAdapter pagerAdapter = null;
    DBHelper dbHelper;
    Cursor rs;
    int port1,port2,port3,port4;
    //-----------------------------------------------------------------------------
    @Override
    public void onCreate (Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Toolbar toolbar = (Toolbar) findViewById(R.id.MyToolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        CollapsingToolbarLayout collapsingToolbar =
                (CollapsingToolbarLayout) findViewById(R.id.collapse_toolbar);


        NestedScrollView scrollView = (NestedScrollView) findViewById (R.id.nested);
        scrollView.setFillViewport (true);

        ArrayList<String > selectedPort = new ArrayList<String>();

        Intent intent = getIntent();
        String Tab3 = intent.getStringExtra("3");
        String Tab4 = intent.getStringExtra("4");
        String Tab5 = intent.getStringExtra("5");
        String Tab6 = intent.getStringExtra("6");

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.addTab(tabLayout.newTab().setText("View"));
        tabLayout.addTab(tabLayout.newTab().setText("All"));

        selectedPort.add("TabFragment1");
        selectedPort.add("TabFragment2");
        if(Tab3!=null && !TextUtils.isEmpty(Tab3))
        selectedPort.add(Tab3);
        if(Tab4!=null && !TextUtils.isEmpty(Tab4))
        selectedPort.add(Tab4);
        if(Tab5!=null && !TextUtils.isEmpty(Tab5))
        selectedPort.add(Tab5);
        if(Tab6!=null && !TextUtils.isEmpty(Tab6))
        selectedPort.add(Tab6);



        dbHelper = new DBHelper(this);
//        rs=dbHelper.getData(1);
//        port1 = rs.getInt(rs.getColumnIndex("id"));
//
//        rs=dbHelper.getData(2);
//        port2 = rs.getInt(rs.getColumnIndex("id"));
//
//        rs=dbHelper.getData(3);
//        port3 = rs.getInt(rs.getColumnIndex("id"));
//
//        rs=dbHelper.getData(4);
//        port4 = rs.getInt(rs.getColumnIndex("id"));


        Log.i(">>>>>>>>>>>>>>", "port 1" + port1 + "port 2" + port2 + "port 3" + port3 + "port 4" + port4);

        if(Tab3!=null && !TextUtils.isEmpty(Tab3))
        tabLayout.addTab(tabLayout.newTab().setText("Tab 0"));
        if(Tab3!=null && !TextUtils.isEmpty(Tab4))
        tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
        if(Tab3!=null && !TextUtils.isEmpty(Tab5))
        tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
        if(Tab3!=null && !TextUtils.isEmpty(Tab6))
        tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
        final PagerAdapter adapter = new PagerAdapter
                (getSupportFragmentManager(), tabLayout.getTabCount(), selectedPort);
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
//        setContentView(R.layout.activity_main2);
//        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//        setSupportActionBar(toolbar);

//        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
//        tabLayout.addTab(tabLayout.newTab().setText("View"));
//        tabLayout.addTab(tabLayout.newTab().setText("All"));
//        tabLayout.addTab(tabLayout.newTab().setText("Tab 0"));
//        tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
//        tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
//        tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
//        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);


}
    }

ViewPagerAdapter Viewpageradapter.class

package com.example.jeffy.viewpagerapp;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Jeffy on 25-01-2016.
 */
public class PagerAdapter extends FragmentStatePagerAdapter {
    int mNumOfTabs;

    List<String> values;

    public PagerAdapter(FragmentManager fm, int NumOfTabs, List<String> Port) {
        super(fm);
        this.mNumOfTabs = NumOfTabs;
        this.values= Port;
    }


    @Override
    public Fragment getItem(int position) {


        String fragmentName = values.get(position);
        Class<?> clazz = null;
        Object fragment = null;
        try {
            clazz = Class.forName("com.example.jeffy.viewpagerapp."+fragmentName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            fragment = clazz.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return (Fragment) fragment;
    }

    @Override
    public int getCount() {
        return values.size();
    }
}

Layout for main2activity acticity_main2.xml

    <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/main_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/MyAppbar"
            android:layout_width="match_parent"
            android:layout_height="256dp"
            android:fitsSystemWindows="true">

            <android.support.design.widget.CollapsingToolbarLayout
                android:id="@+id/collapse_toolbar"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:layout_scrollFlags="scroll|exitUntilCollapsed"
                android:background="@color/material_deep_teal_500"
                android:fitsSystemWindows="true">

                <ImageView
                    android:id="@+id/bgheader"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:scaleType="centerCrop"
                    android:fitsSystemWindows="true"
                    android:background="@drawable/screen"
                    app:layout_collapseMode="pin" />

                <android.support.v7.widget.Toolbar
                    android:id="@+id/MyToolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    app:layout_collapseMode="parallax" />





            </android.support.design.widget.CollapsingToolbarLayout>

        </android.support.design.widget.AppBarLayout>

        <android.support.v4.widget.NestedScrollView
            android:layout_width="match_parent"
            android:id="@+id/nested"
            android:layout_height="match_parent"
            android:layout_gravity="fill_vertical"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/MyToolbar"
            android:background="?attr/colorPrimary"
            android:elevation="6dp"
            android:minHeight="?attr/actionBarSize"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>


        <android.support.v4.view.ViewPager
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/view_pager"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

        </android.support.v4.view.ViewPager>
    </LinearLayout>


        </android.support.v4.widget.NestedScrollView>

    </android.support.design.widget.CoordinatorLayout>

Mainactivity layout
activity_main.xml

        <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.jeffy.viewpagerapp.MainActivity"
    tools:showIn="@layout/activity_main">


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <GridView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/gridView1"
        android:numColumns="2"
        android:gravity="center"
        android:columnWidth="100dp"
        android:stretchMode="columnWidth"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

    </GridView>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="SAVE"
        android:id="@+id/button" />

</LinearLayout>




</RelativeLayout>

Hope this would help someone... Click up button please if this helped you

How do I find a list of Homebrew's installable packages?

From the man page:

search, -S text|/text/
Perform a substring search of formula names for text. If text is surrounded with slashes,
then it is interpreted as a regular expression. If no search term is given,
all available formula are displayed.

For your purposes, brew search will suffice.

how to have two headings on the same line in html

Add a span with the style="float: right" element inside the h1 element. So you can add a "goto top of the page" link, with a unicode arrow link button.

<h1 id="myAnchor">Headline Text
<span style="float: right"><a href="#top" aria-hidden="true">?</a></span>
</h1>

Carriage return in C?

Program prints ab, goes back one character and prints si overwriting the b resulting asi. Carriage return returns the caret to the first column of the current line. That means the ha will be printed over as and the result is hai

Trigger 404 in Spring-MVC controller?

Simply you can use web.xml to add error code and 404 error page. But make sure 404 error page must not locate under WEB-INF.

<error-page>
    <error-code>404</error-code>
    <location>/404.html</location>
</error-page>

This is the simplest way to do it but this have some limitation. Suppose if you want to add the same style for this page that you added other pages. In this way you can't to that. You have to use the @ResponseStatus(value = HttpStatus.NOT_FOUND)

Converting from signed char to unsigned char and back again?

This is one of the reasons why C++ introduced the new cast style, which includes static_cast and reinterpret_cast

There's two things you can mean by saying conversion from signed to unsigned, you might mean that you wish the unsigned variable to contain the value of the signed variable modulo the maximum value of your unsigned type + 1. That is if your signed char has a value of -128 then CHAR_MAX+1 is added for a value of 128 and if it has a value of -1, then CHAR_MAX+1 is added for a value of 255, this is what is done by static_cast. On the other hand you might mean to interpret the bit value of the memory referenced by some variable to be interpreted as an unsigned byte, regardless of the signed integer representation used on the system, i.e. if it has bit value 0b10000000 it should evaluate to value 128, and 255 for bit value 0b11111111, this is accomplished with reinterpret_cast.

Now, for the two's complement representation this happens to be exactly the same thing, since -128 is represented as 0b10000000 and -1 is represented as 0b11111111 and likewise for all in between. However other computers (usually older architectures) may use different signed representation such as sign-and-magnitude or ones' complement. In ones' complement the 0b10000000 bitvalue would not be -128, but -127, so a static cast to unsigned char would make this 129, while a reinterpret_cast would make this 128. Additionally in ones' complement the 0b11111111 bitvalue would not be -1, but -0, (yes this value exists in ones' complement,) and would be converted to a value of 0 with a static_cast, but a value of 255 with a reinterpret_cast. Note that in the case of ones' complement the unsigned value of 128 can actually not be represented in a signed char, since it ranges from -127 to 127, due to the -0 value.

I have to say that the vast majority of computers will be using two's complement making the whole issue moot for just about anywhere your code will ever run. You will likely only ever see systems with anything other than two's complement in very old architectures, think '60s timeframe.

The syntax boils down to the following:

signed char x = -100;
unsigned char y;

y = (unsigned char)x;                    // C static
y = *(unsigned char*)(&x);               // C reinterpret
y = static_cast<unsigned char>(x);       // C++ static
y = reinterpret_cast<unsigned char&>(x); // C++ reinterpret

To do this in a nice C++ way with arrays:

jbyte memory_buffer[nr_pixels];
unsigned char* pixels = reinterpret_cast<unsigned char*>(memory_buffer);

or the C way:

unsigned char* pixels = (unsigned char*)memory_buffer;

How do you modify the web.config appSettings at runtime?

And if you want to avoid the restart of the application, you can move out the appSettings section:

<appSettings configSource="Config\appSettings.config"/>

to a separate file. And in combination with ConfigurationSaveMode.Minimal

var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
config.Save(ConfigurationSaveMode.Minimal);

you can continue to use the appSettings section as the store for various settings without causing application restarts and without the need to use a file with a different format than the normal appSettings section.

How to horizontally center a floating element of a variable width?

Assuming the element which is floated and will be centered is a div with an id="content" ...

<body>
<div id="wrap">
   <div id="content">
   This will be centered
   </div>
</div>
</body>

And apply the following CSS:

#wrap {
    float: left;
    position: relative;
    left: 50%;
}

#content {
    float: left;
    position: relative;
    left: -50%;
}

Here is a good reference regarding that.

Redirect stderr and stdout in Bash

For situation, when "piping" is necessary you can use :

|&

For example:

echo -ne "15\n100\n"|sort -c |& tee >sort_result.txt

or

TIMEFORMAT=%R;for i in `seq 1 20` ; do time kubectl get pods |grep node >>js.log  ; done |& sort -h

This bash-based solutions can pipe STDOUT and STDERR separately (from STDERR of "sort -c" or from STDERR to "sort -h").

How to convert list to string

>>> L = [1,2,3]       
>>> " ".join(str(x) for x in L)
'1 2 3'

How to list only the file names that changed between two commits?

To supplement @artfulrobot's answer, if you want to show changed files between two branches:

git diff --name-status mybranch..myotherbranch

Be careful on precedence. If you place the newer branch first then it would show files as deleted rather than added.

Adding a grep can refine things further:

git diff --name-status mybranch..myotherbranch | grep "A\t"

That will then show only files added in myotherbranch.

Reloading submodules in IPython

My standard practice for reloading is to combine both methods following first opening of IPython:

from IPython.lib.deepreload import reload
%load_ext autoreload
%autoreload 2

Loading modules before doing this will cause them not to be reloaded, even with a manual reload(module_name). I still, very rarely, get inexplicable problems with class methods not reloading that I've not yet looked into.

How to make a shape with left-top round rounded corner and left-bottom rounded corner?

It looks like a bug http://code.google.com/p/android/issues/detail?id=939.

Finally I have to write something like this:

 <stroke android:width="3dp"
         android:color="#555555"
         />

 <padding android:left="1dp"
          android:top="1dp"
          android:right="1dp"
          android:bottom="1dp"
          /> 

 <corners android:radius="1dp"
  android:bottomRightRadius="2dp" android:bottomLeftRadius="0dp" 
  android:topLeftRadius="2dp" android:topRightRadius="0dp"/> 

I have to specify android:bottomRightRadius="2dp" for left-bottom rounded corner (another bug here).

Why do table names in SQL Server start with "dbo"?

Microsoft introduced schema in version 2008. For those who didn’t know about schema, and those who didn’t care, objects were put into a default schema dbo.

dbo stands for DataBase Owner, but that’s not really important.

Think of a schema as you would a folder for files:

  • You don’t need to refer to the schema if the object is in the same or default schema
  • You can reference an object in a different schema by using the schema as a prefix, the way you can reference a file in a different folder.
  • You can’t have two objects with the same name in a single schema, but you can in different schema
  • Using schema can help you to organise a larger number of objects
  • Schema can also be assigned to particular users and roles, so you can control access to who can do what.

You can always access any object from any schema.

Because dbo is the default, you normally don’t need to specify it within a single database:

SELECT * FROM customers;
SELECT * FROM dbo.customers;

mean the same thing.

I am inclined to disagree with the notion of always using the dbo. prefix, since the more you clutter your code with unnecessary detail, the harder it is to read and manage.

For the most part, you can ignore the schema. However, the schema will make itself apparent in the following situations:

  1. If you view the tables in either the object navigator or in an external application, such as Microsoft Excel or Access, you will see the dbo. prefix. You can still ignore it.

  2. If you reference a table in another database, you will need its full name in the form database.schema.table:

    SELECT * FROM bookshop.dbo.customers;
    
  3. For historical reasons, if you write a user defined scalar function, you will need to call it with the schema prefix:

    CREATE FUNCTION tax(@amount DECIMAL(6,2) RETURNS DECIMAL(6,2) AS
    BEGIN
        RETURN @amount * 0.1;
    END;
    GO
    SELECT total, dbo.tax(total) FROM pricelist;
    

    This does not apply to other objects, such as table functions, procedures and views.

You can use schema to overcome naming conflicts. For example, if every user has a personal schema, they can create additional objects without having to fight with other users over the name.

Open file dialog and select a file using WPF controls and C#

var ofd = new Microsoft.Win32.OpenFileDialog() {Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif"}; 
var result = ofd.ShowDialog();
if (result == false) return;
textBox1.Text = ofd.FileName;

How to select only the records with the highest date in LINQ

It could be something like:

var qry = from t in db.Lasttraces
          group t by t.AccountId into g
          orderby t.Date
          select new { g.AccountId, Date = g.Max(e => e.Date) };

What is the difference between function and procedure in PL/SQL?

In dead simple way it makes this meaning.

Functions :

These subprograms return a single value; mainly used to compute and return a value.

Procedure :

These subprograms do not return a value directly; mainly used to perform an action.

Example Program:

CREATE OR REPLACE PROCEDURE greetings

BEGIN 

dbms_output.put_line('Hello World!');

END ;
/

Executing a Standalone Procedure :

A standalone procedure can be called in two ways:

• Using the EXECUTE keyword • Calling the name of procedure from a PL/SQL block

The procedure can also be called from another PL/SQL block:

BEGIN 
greetings;
END;
/

Function:

CREATE OR REPLACE FUNCTION totalEmployees 
RETURN number IS
total number(3) := 0;
BEGIN 
SELECT count(*) into total 
FROM employees;
RETURN total; 
END;
/

Following program calls the function totalCustomers from an another block

DECLARE 
c number(3);
BEGIN 
c := totalEmployees();
dbms_output.put_line('Total no. of Employees: ' || c);
END;
/

Allow multi-line in EditText view in Android?

EditText has singleLine property. You can set in the XML or by calling setSingleLine(false); http://developer.android.com/reference/android/widget/TextView.html#setSingleLine%28%29

How to get browser width using JavaScript code?

var w = window.innerWidth;
var h = window.innerHeight;
var ow = window.outerWidth; //including toolbars and status bar etc.
var oh = window.outerHeight;

Both return integers and don't require jQuery. Cross-browser compatible.

I often find jQuery returns invalid values for width() and height()

How to $watch multiple variable change in angular


UPDATE

Angular offers now the two scope methods $watchGroup (since 1.3) and $watchCollection. Those have been mentioned by @blazemonger and @kargold.


This should work independent of the types and values:

$scope.$watch('[age,name]', function () { ... }, true);

You have to set the third parameter to true in this case.

The string concatenation 'age + name' will fail in a case like this:

<button ng-init="age=42;name='foo'" ng-click="age=4;name='2foo'">click</button>

Before the user clicks the button the watched value would be 42foo (42 + foo) and after the click 42foo (4 + 2foo). So the watch function would not be called. So better use an array expression if you cannot ensure, that such a case will not appear.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <link href="//cdn.jsdelivr.net/jasmine/1.3.1/jasmine.css" rel="stylesheet" />
        <script src="//cdn.jsdelivr.net/jasmine/1.3.1/jasmine.js"></script>
        <script src="//cdn.jsdelivr.net/jasmine/1.3.1/jasmine-html.js"></script>
        <script src="http://code.angularjs.org/1.2.0-rc.2/angular.js"></script>
        <script src="http://code.angularjs.org/1.2.0-rc.2/angular-mocks.js"></script>
        <script>

angular.module('demo', []).controller('MainCtrl', function ($scope) {

    $scope.firstWatchFunctionCounter = 0;
    $scope.secondWatchFunctionCounter = 0;

    $scope.$watch('[age, name]', function () { $scope.firstWatchFunctionCounter++; }, true);
    $scope.$watch('age + name', function () { $scope.secondWatchFunctionCounter++; });
});

describe('Demo module', function () {
    beforeEach(module('demo'));
    describe('MainCtrl', function () {
        it('watch function should increment a counter', inject(function ($controller, $rootScope) {
            var scope = $rootScope.$new();
            scope.age = 42;
            scope.name = 'foo';
            var ctrl = $controller('MainCtrl', { '$scope': scope });
            scope.$digest();

            expect(scope.firstWatchFunctionCounter).toBe(1);
            expect(scope.secondWatchFunctionCounter).toBe(1);

            scope.age = 4;
            scope.name = '2foo';
            scope.$digest();

            expect(scope.firstWatchFunctionCounter).toBe(2);
            expect(scope.secondWatchFunctionCounter).toBe(2); // This will fail!
        }));
    });
});


(function () {
    var jasmineEnv = jasmine.getEnv();
    var htmlReporter = new jasmine.HtmlReporter();
    jasmineEnv.addReporter(htmlReporter);
    jasmineEnv.specFilter = function (spec) {
        return htmlReporter.specFilter(spec);
    };
    var currentWindowOnload = window.onload;
    window.onload = function() {
        if (currentWindowOnload) {
            currentWindowOnload();
        }
        execJasmine();
    };
    function execJasmine() {
        jasmineEnv.execute();
    }
})();

        </script>
    </head>
    <body></body>
</html>

http://plnkr.co/edit/2DwCOftQTltWFbEDiDlA?p=preview

PS:

As stated by @reblace in a comment, it is of course possible to access the values:

$scope.$watch('[age,name]', function (newValue, oldValue) {
    var newAge  = newValue[0];
    var newName = newValue[1];
    var oldAge  = oldValue[0];
    var oldName = oldValue[1];
}, true);

-bash: export: `=': not a valid identifier

You cannot put spaces around the = sign when you do:

export foo=bar

Remove the spaces you have and you should be good to go.

If you type:

export foo = bar

the shell will interpret that as a request to export three names: foo, = and bar. = isn't a valid variable name, so the command fails. The variable name, equals sign and it's value must not be separated by spaces for them to be processed as a simultaneous assignment and export.

How to ignore conflicts in rpm installs

The --force option will reinstall already installed packages or overwrite already installed files from other packages. You don't want this normally.

If you tell rpm to install all RPMs from some directory, then it does exactly this. rpm will not ignore RPMs listed for installation. You must manually remove the unneeded RPMs from the list (or directory). It will always overwrite the files with the "latest RPM installed" whichever order you do it in.

You can remove the old RPM and rpm will resolve the dependency with the newer version of the installed RPM. But this will only work, if none of the to be installed RPMs depends exactly on the old version.

If you really need different versions of the same RPM, then the RPM must be relocatable. You can then tell rpm to install the specific RPM to a different directory. If the files are not conflicting, then you can just install different versions with rpm -i (zypper in can not install different versions of the same RPM). I am packaging for example ruby gems as relocatable RPMs at work. So I can have different versions of the same gem installed.

I don't know on which files your RPMs are conflicting, but if all of them are "just" man pages, then you probably can simply overwrite the new ones with the old ones with rpm -i --replacefiles. The only problem with this would be, that it could confuse somebody who is reading the old man page and thinks it is for the actual version. Another problem would be the rpm --verify command. It will complain for the new package if the old one has overwritten some files.

Is this possibly a duplicate of https://serverfault.com/questions/522525/rpm-ignore-conflicts?

How to list all functions in a Python module?

For completeness' sake, I'd like to point out that sometimes you may want to parse code instead of importing it. An import will execute top-level expressions, and that could be a problem.

For example, I'm letting users select entry point functions for packages being made with zipapp. Using import and inspect risks running astray code, leading to crashes, help messages being printed out, GUI dialogs popping up and so on.

Instead I use the ast module to list all the top-level functions:

import ast
import sys

def top_level_functions(body):
    return (f for f in body if isinstance(f, ast.FunctionDef))

def parse_ast(filename):
    with open(filename, "rt") as file:
        return ast.parse(file.read(), filename=filename)

if __name__ == "__main__":
    for filename in sys.argv[1:]:
        print(filename)
        tree = parse_ast(filename)
        for func in top_level_functions(tree.body):
            print("  %s" % func.name)

Putting this code in list.py and using itself as input, I get:

$ python list.py list.py
list.py
  top_level_functions
  parse_ast

Of course, navigating an AST can be tricky sometimes, even for a relatively simple language like Python, because the AST is quite low-level. But if you have a simple and clear use case, it's both doable and safe.

Though, a downside is that you can't detect functions that are generated at runtime, like foo = lambda x,y: x*y.

MySQL direct INSERT INTO with WHERE clause

you can use UPDATE command.

UPDATE table_name SET name=@name, email=@email, phone=@phone WHERE client_id=@client_id

How to align two elements on the same line without changing HTML

This is what I used for similar type of use case as yours.

<style type="text/css">
#element1 {display:inline-block; width:45%; padding:10px}
#element2 {display:inline-block; width:45%; padding:10px}
</style>

<div id="element1">
 element 1 markup
</div>
<div id="element2">
 element 2 markup
</div>

Adjust your width and padding as per your requirement. Note - Do not exceed 'width' more than 100% altogether (ele1_width+ ele2_width) to add 'padding', keep it less than 100%.

How to include an HTML page into another HTML page without frame/iframe?

If you're willing to use jquery, there is a handy jquery plugin called "inc".

I use it often for website prototyping, where I just want to present the client with static HTML with no backend layer that can be quickly created/edited/improved/re-presented

http://johannburkard.de/blog/programming/javascript/inc-a-super-tiny-client-side-include-javascript-jquery-plugin.html

For example, things like the menu and footer need to be shown on every page, but you dont want to end up with a copy-and-paste-athon

You can include a page fragment as follows

<p class="inc:footer.htm"></p>

Spring MVC How take the parameter value of a GET HTTP Request in my controller method?

As explained in the documentation, by using an @RequestParam annotation:

public @ResponseBody String byParameter(@RequestParam("foo") String foo) {
    return "Mapped by path + method + presence of query parameter! (MappingController) - foo = "
           + foo;
}

Detect touch press vs long press vs movement?

I was just dealing with this mess after wanting longclick to not end with a click event.

Here's what I did.

public boolean onLongClick(View arg0) {
    Toast.makeText(getContext(), "long click", Toast.LENGTH_SHORT).show();
    longClicked = true;
    return false;
}

public void onClick(View arg0) {
    if(!longClicked){
        Toast.makeText(getContext(), "click", Toast.LENGTH_SHORT).show();
    }
    longClick = false; // sets the clickability enabled
}

boolean longClicked = false;

It's a bit of a hack but it works.

Interfaces — What's the point?

I know I am very late.. (almost nine years), but if someone wants small explanation then you can go for this:

In simple words, you use Interface when you know what an Object can do or what function we are going to implement on an object.. Example Insert,Update, and Delete.

interface ICRUD{
      void InsertData(); // will insert data
      void UpdateData(); // will update data
      void DeleteData(); // will delete data
}

Important Note: Interfaces are ALWAYS public.

Hope this helps.

View RDD contents in Python Spark?

By latest document, you can use rdd.collect().foreach(println) on the driver to display all, but it may cause memory issues on the driver, best is to use rdd.take(desired_number)

https://spark.apache.org/docs/2.2.0/rdd-programming-guide.html

To print all elements on the driver, one can use the collect() method to first bring the RDD to the driver node thus: rdd.collect().foreach(println). This can cause the driver to run out of memory, though, because collect() fetches the entire RDD to a single machine; if you only need to print a few elements of the RDD, a safer approach is to use the take(): rdd.take(100).foreach(println).

How to go from Blob to ArrayBuffer

Just to complement Mr @potatosalad answer.

You don't actually need to access the function scope to get the result on the onload callback, you can freely do the following on the event parameter:

var arrayBuffer;
var fileReader = new FileReader();
fileReader.onload = function(event) {
    arrayBuffer = event.target.result;
};
fileReader.readAsArrayBuffer(blob);

Why this is better? Because then we may use arrow function without losing the context

var fileReader = new FileReader();
fileReader.onload = (event) => {
    this.externalScopeVariable = event.target.result;
};
fileReader.readAsArrayBuffer(blob);

Disabling enter key for form

In your form tag just paste this:

onkeypress="return event.keyCode != 13;"

Example

<input type="text" class="search" placeholder="search" onkeypress="return event.keyCode != 13;">

This can be useful if you want to do search when typing and ignoring ENTER.

/// Grab the search term
const searchInput = document.querySelector('.search')
/// Update search term when typing
searchInput.addEventListener('keyup', displayMatches)

How do I change file permissions in Ubuntu

So that you don't mess up other permissions already on the file, use the flag +, such as via

sudo chmod -R o+rw /var/www

How to scroll the page when a modal dialog is longer than the screen?

In the end I had had to make changes to the content of the page behind the modal screen to ensure that it never got long enough to scroll the page.

Once I did that, the problems I encountered when applying position: absolute to the dialog were resolved as the user could no longer scroll down the page.

How to specify a port number in SQL Server connection string?

The correct SQL connection string for SQL with specify port is use comma between ip address and port number like following pattern: xxx.xxx.xxx.xxx,yyyy

What are the best PHP input sanitizing functions?

Sanitizers

Sanitize is a function to check (and remove) harmful data from user input which can harm the software. Sanitizing user input is the most secure method of user input validation to strip out anything that is not on the whitelist.

PHP Support

5.4.0 - 5.4.45, 5.5.0 - 5.5.38, 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.34, 7.3.0 - 7.3.27, 7.4.0 - 7.4.15, 8.0.0 - 8.0.2

<?php
require_once("path/to/Sanitizers.php");

use Sanitizers\Sanitizers\Sanitizer;

\\ passing `true` in Sanitizer class enables exceptions
$sanitize = new Sanitizer(true);
try {
    echo $sanitize->Username($_GET['username']);
} catch (Exception $e) {
    echo "Could not Sanitize user input." 
    var_dump($e);
}
?>

Download the latest release

See Sanitizers GitHub project.

Bootstrap css hides portion of container below navbar navbar-fixed-top

I know this thread is old, but i just got into that exactly problem and i fixed it by just using the page-header class in my page, under the nav. Also i used the <nav> tag instead of <div> but i am not sure it would present any different behavior.

Using the page-header as a container for the page, you won't need to mess with the <body>, only if you disagree with the default space that the page-header gives you.

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
   <div class="container-fluid">_x000D_
        <nav class="navbar navbar-default navbar-fixed-top">_x000D_
    _x000D_
            <div class="navbar-header">_x000D_
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">_x000D_
                    <span class="sr-only">Toggle navigation</span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                </button>_x000D_
                <a class="navbar-brand" href="#">Bootstrap</a>_x000D_
            </div>_x000D_
            <div id="navbar" class="navbar-collapse collapse">_x000D_
                <ul class="nav navbar-nav">_x000D_
                    <li class="active"><a href="#">Home</a></li>_x000D_
                    <li class="dropdown">_x000D_
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>_x000D_
                            <ul class="dropdown-menu">_x000D_
                                <li><a href="#">Action</a></li>_x000D_
                                <li><a href="#">Another action</a></li>_x000D_
                                <li><a href="#">Something else here</a></li>_x000D_
                                <li role="separator" class="divider"></li>_x000D_
                                <li class="dropdown-header">Nav header</li>_x000D_
                                <li><a href="#">Separated link</a></li>_x000D_
                                <li><a href="#">One more separated link</a></li>_x000D_
                            </ul>_x000D_
                        </li>_x000D_
                </ul>_x000D_
                <div class="navbar-right">_x000D_
                </div>_x000D_
            </div>_x000D_
        </nav>_x000D_
    </div>_x000D_
    <div class="page-header">_x000D_
        <div class="clearfix">_x000D_
            <div class="col-md-12">_x000D_
                <div class="col-md-8 col-sm-6 col-xs-12">_x000D_
                    <h1>Registration form <br /><small>A Bootstrap template showing a registration form with standard fields</small></h1>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
    </div>_x000D_
        <div class="container">_x000D_
        <div class="row">_x000D_
            <form role="form">_x000D_
                <div class="col-lg-6">_x000D_
                    <div class="well well-sm"><strong><span class="glyphicon glyphicon-asterisk"></span>Required Field</strong></div>_x000D_
                    <div class="form-group">_x000D_
                        <label for="InputName">Enter Name</label>_x000D_
                        <div class="input-group">_x000D_
                            <input type="text" class="form-control" name="InputName" id="InputName" placeholder="Enter Name" required>_x000D_
                            <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>_x000D_
                        </div>_x000D_
                    </div>_x000D_
                    <div class="form-group">_x000D_
                        <label for="InputEmail">Enter Email</label>_x000D_
                        <div class="input-group">_x000D_
                            <input type="email" class="form-control" id="InputEmailFirst" name="InputEmail" placeholder="Enter Email" required>_x000D_
                            <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>_x000D_
                        </div>_x000D_
                    </div>_x000D_
                    <div class="form-group">_x000D_
                        <label for="InputEmail">Confirm Email</label>_x000D_
                        <div class="input-group">_x000D_
                            <input type="email" class="form-control" id="InputEmailSecond" name="InputEmail" placeholder="Confirm Email" required>_x000D_
                            <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>_x000D_
                        </div>_x000D_
                    </div>_x000D_
                    <div class="form-group">_x000D_
                        <label for="InputMessage">Enter Message</label>_x000D_
                        <div class="input-group">_x000D_
                            <textarea name="InputMessage" id="InputMessage" class="form-control" rows="5" required></textarea>_x000D_
                            <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>_x000D_
                        </div>_x000D_
                    </div>_x000D_
                    <input type="submit" name="submit" id="submit" value="Submit" class="btn btn-info pull-right">_x000D_
                </div>_x000D_
            </form>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

MySQL Job failed to start

Check the file permissions, if edited

Fail:

$ sudo chmod 776 /etc/mysql/my.cnf
$ sudo service mysql restart
mysql stop/waiting
start: Job failed to start

Ok:

$ sudo chmod 774 /etc/mysql/my.cnf
$ sudo service mysql restart
stop: Unknown instance:
mysql start/running, process 9564

How to export iTerm2 Profiles

There is another way to do this.

From iTerm2 2.9.20140923 you can use Dynamic Profiles as stated in the documentation page:

Dynamic Profiles is a feature that allows you to store your profiles in a file outside the usual macOS preferences database. Profiles may be changed at runtime by editing one or more plist files (formatted as JSON, XML, or in binary). Changes are picked up immediately.

So it is possible to create a file like this one:

    {
        "Profiles": [{
                "Name": "MYSERVER1",
                "Guid": "MYSERVER1",
                "Custom Command": "Yes",
                "Command": "ssh [email protected]",
                "Shortcut": "M",
                "Tags": [
                    "LOCAL", "THATCOMPANY", "WORK", "NOCLOUD"
                ],
                "Badge Text": "SRV1",
            },
            {
                "Name": "MYOCEANSERVER1",
                "Guid": "MYOCEANSERVER1",
                "Custom Command": "Yes",
                "Command": "ssh [email protected]",
                "Shortcut": "O",
                "Tags": [
                    "THATCOMPANY", "WORK", "DIGITALOCEAN"
                ],
                "Badge Text": "PPOCEAN1",
            },
            {
                "Name": "PI1",
                "Guid": "PI1",
                "Custom Command": "Yes",
                "Command": "ssh [email protected]",
                "Shortcut": "1",
                "Tags": [
                    "LOCAL", "PERSONAL", "RASPBERRY", "SMALL"
                ],
                "Badge Text": "LocalServer",
            },
            {
                "Name": "VUZERO",
                "Guid": "VUZERO",
                "Custom Command": "Yes",
                "Command": "ssh [email protected]",
                "Shortcut": "0",
                "Tags": [
                    "LOCAL", "PERSONAL", "SMALL"
                ],
                "Badge Text": "TeleVision",
            }
        ]
    }

in the folder ~/Library/Application\ Support/iTerm2/DynamicProfiles/ and share it across different machines. This enables you to retain some visual differences among iterm2 installations such as font type or dimension, while synchronising remote hosts, shortcuts, commands, and even a small badge to quickly identify a session

badge

How do I create an Excel chart that pulls data from multiple sheets?

2007 is more powerful with ribbon..:=) To add new series in chart do: Select Chart, then click Design in Chart Tools on the ribbon, On the Design ribbon, select "Select Data" in Data Group, Then you will see the button for Add to add new series.

Hope that will help.

How can I plot separate Pandas DataFrames as subplots?

You may not need to use Pandas at all. Here's a matplotlib plot of cat frequencies:

enter image description here

x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)

f, axes = plt.subplots(2, 1)
for c, i in enumerate(axes):
  axes[c].plot(x, y)
  axes[c].set_title('cats')
plt.tight_layout()

How to write dynamic variable in Ansible playbook

I would first suggest that you step back and look at organizing your plays to not require such complexity, but if you really really do, use the following:

   vars:
    myvariable: "{{[param1|default(''), param2|default(''), param3|default('')]|join(',')}}"

How to do multiline shell script in Ansible

Adding a space before the EOF delimiter allows to avoid cmd:

- shell: |
    cat <<' EOF'
    This is a test.
    EOF

sql select with column name like

You cannot with standard SQL. Column names are not treated like data in SQL.

If you use a SQL engine that has, say, meta-data tables storing column names, types, etc. you may select on that table instead.

HTTP Status 405 - HTTP method POST is not supported by this URL java servlet

It's because you're calling doGet() without actually implementing doGet(). It's the default implementation of doGet() that throws the error saying the method is not supported.

Access elements in json object like an array

I found a straight forward way of solving this, with the use of JSON.parse.

Let's assume the json below is inside the variable jsontext.

[
  ["Blankaholm", "Gamleby"],
  ["2012-10-23", "2012-10-22"],
  ["Blankaholm. Under natten har det varit inbrott", "E22 i med Gamleby. Singelolycka. En bilist har.],
  ["57.586174","16.521841"], ["57.893162","16.406090"]
]

The solution is this:

var parsedData = JSON.parse(jsontext);

Now I can access the elements the following way:

var cities = parsedData[0];

How to exclude records with certain values in sql select

SELECT  DISTINCT a.StoreID
FROM    tableName a
        LEFT JOIN tableName b 
          ON a.StoreID = b.StoreID AND b.ClientID = 5
WHERE   b.StoreID IS NULL

OUTPUT

+---------+
¦ STOREID ¦
¦---------¦
¦       3 ¦
+---------+

Python dictionary: are keys() and values() always the same order?

For what it's worth, some heavy used production code I have written is based on this assumption and I never had a problem with it. I know that doesn't make it true though :-)

If you don't want to take the risk I would use iteritems() if you can.

for key, value in myDictionary.iteritems():
    print key, value

How to generate a random string of a fixed length in Go?

Here is a simple and performant solution for a cryptographically secure random string.

package main

import (
    "crypto/rand"
    "unsafe"
    "fmt"
)

var alphabet = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

func main() {
    fmt.Println(generate(16))
}

func generate(size int) string {
    b := make([]byte, size)
    rand.Read(b)
    for i := 0; i < size; i++ {
        b[i] = alphabet[b[i] / 5]
    }
    return *(*string)(unsafe.Pointer(&b))
}

Benchmark

Benchmark  95.2 ns/op      16 B/op      1 allocs/op

Check if an image is loaded (no errors) with jQuery

As I understand the .complete property is non-standard. It may not be universal... I notice it seem to work differently in Firefox verses IE. I am loading a number of images in javascript then checking if complete. In Firefox, this seems to work great. In IE, it doesn't because the images appear to be loading on another thread. It works only if I put a delay between my assignment to image.src and when I check the image.complete property.

Using image.onload and image.onerror isn't working for me, either, because I need to pass a parameter to know which image I am talking about when the function is called. Any way of doing that seems to fail because it actually seems to pass the same function, not different instances of the same function. So the value I pass into it to identify the image always ends up being the last value in the loop. I cannot think of any way around this problem.

On Safari and Chrome, I am seeing the image.complete true and the naturalWidth set even when the error console shows a 404 for that image... and I intentionally removed that image to test this. But the above works well for Firefox and IE.

merge two object arrays with Angular 2 and TypeScript?

The spread operator is kinda cool.

this.results = [ ...this.results, ...data.results];

The spread operator allows you to easily place an expanded version of an array into another array.

You can read about spread operator here.

How can I get the content of CKEditor using JQuery?

I was having issues with the getData() not working every time especially when dealing with live ajax.

Was able to get around it by running:

for(var instanceName in CKEDITOR.instances){
    CKEDITOR.instances[instanceName].updateElement();
}

Then use jquery to get the value from the textarea.

How to set only time part of a DateTime variable in C#

Use the constructor that allows you to specify the year, month, day, hours, minutes, and seconds:

var dateNow = DateTime.Now;
var date = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, 4, 5, 6);

How do I tell matplotlib that I am done with a plot?

You can use figure to create a new plot, for example, or use close after the first plot.

Vertical Text Direction

Here is an example of some SVG code I used to get three lines of vertical text into a table column heading. Other angles are possible with a bit of tweaking. I believe most browsers support SVG these days.

<svg height="150" width="40">
  <text font-weight="bold" x="-150" y="10" transform="rotate(-90 0 0)">Jane Doe</text>
  <text x="-150" y="25" transform="rotate(-90 0 0)">0/0&nbsp;&nbsp;&nbsp;&nbsp;0/0</text>
  <text x="-150" y="40" transform="rotate(-90 0 0)">2015-06-06</text>
  Sorry, your browser does not support inline SVG.
</svg>

How to remove word wrap from textarea?

textarea {
  white-space: pre;
  overflow-wrap: normal;
  overflow-x: scroll;
}

white-space: nowrap also works if you don't care about whitespace, but of course you don't want that if you're working with code (or indented paragraphs or any content where there might deliberately be multiple spaces) ... so i prefer pre.

overflow-wrap: normal (was word-wrap in older browsers) is needed in case some parent has changed that setting; it can cause wrapping even if pre is set.

also -- contrary to the currently accepted answer -- textareas do often wrap by default. pre-wrap seems to be the default on my browser.

Turn off textarea resizing

This is works for me

_x000D_
_x000D_
<textarea_x000D_
  type='text'_x000D_
  style="resize: none"_x000D_
>_x000D_
Some text_x000D_
</textarea>
_x000D_
_x000D_
_x000D_

Index all *except* one item in python

The simplest way I found was:

mylist[:x] + mylist[x+1:]

that will produce your mylist without the element at index x.

Example

mylist = [0, 1, 2, 3, 4, 5]
x = 3
mylist[:x] + mylist[x+1:]

Result produced

mylist = [0, 1, 2, 4, 5]

Chrome hangs after certain amount of data transfered - waiting for available socket

The message:

Waiting for available socket...

is shown, because you've reached a limit on the ssl_socket_pool either per Host, Proxy or Group.

Here are the maximum number of HTTP connections which you can make with a Chrome browser:

  • The maximum number of connections per proxy is 32 connections. This can be changed in Policy List.
  • Maximum per Host: 6 connections.

    This is likely hardcoded in the source code of the web browser, so you can't change it.

  • Total 256 HTTP connections pooled per browser.

Source: Enterprise networking for Chrome devices

The above limits can be checked or flushed at chrome://net-internals/#sockets (or in real-time at chrome://net-internals/#events&q=type:SOCKET%20is:active).


Your issue with audio can be related to Chrome bug 162627 where HTML5 audio fails to load and it hits max simultaneous connections per server:proxy. This is still active issue at the time of writing (2016).

Much older issue related to HTML5 video request stay pending, then it's probably related to Issue #234779 which has been fixed 2014. And related to SPDY which can be found in Issue 324653: SPDY issue: waiting for available sockets, but this was already fixed in 2014, so probably it's not related.

Other related issue now marked as duplicate can be found in Issue 401845: Failure to preload audio metadata. Loaded only 6 of 10+ which was related to the problem with the media player code leaving a bunch of paused requests hanging around.


This also may be related to some Chrome adware or antivirus extensions using your sockets in the backgrounds (like Sophos or Kaspersky), so check for Network activity in DevTools.

How to differ sessions in browser-tabs?

Note: The solution here needs to be done at application design stage. It would be difficult to engineer this in later.

Use a hidden field to pass around the session identifier.

For this to work each page must include a form:

<form method="post" action="/handler">

  <input type="hidden" name="sessionId" value="123456890123456890ABCDEF01" />
  <input type="hidden" name="action" value="" />

</form>

Every action on your side, including navigation, POSTs the form back (setting the action as appropriate). For "unsafe" requests, you could include another parameter, say containing a JSON value of the data to be submitted:

<input type="hidden" name="action" value="completeCheckout" />
<input type="hidden" name="data" value='{ "cardNumber" : "4111111111111111", ... ' />

As there are no cookies, each tab will be independent and will have no knowledge of other sessions in the same browser.

Lots of advantages, particularly when it comes to security:

  • No reliance on JavaScript or HTML5.
  • Inherently protects against CSRF.
  • No reliance on cookies, so protects against POODLE.
  • Not vulnerable to session fixation.
  • Can prevent back button use, which is desirable when you want users to follow a set path through your site (which means logic bugs that can sometimes be attacked by out-of-order requests, can be prevented).

Some disadvantages:

  • Back button functionality may be desired.
  • Not very effective with caching as every action is a POST.

Further information here.