Programs & Examples On #Dopostback

__doPostBack is a javascript method that allows to trigger a postback from the client.

iFrame onload JavaScript event

Your code is correct. Just test to ensure it is being called like:

<script>
function doIt(){
  alert("here i am!");
  __doPostBack('ctl00$ctl00$bLogout','')
}
</script>

<iframe onload="doIt()"></iframe>

Use Excel VBA to click on a button in Internet Explorer, when the button has no "name" associated

With the kind help from Tim Williams, I finally figured out the last détails that were missing. Here's the final code below.

Private Sub Open_multiple_sub_pages_from_main_page()


Dim i As Long
Dim IE As Object
Dim Doc As Object
Dim objElement As Object
Dim objCollection As Object
Dim buttonCollection As Object
Dim valeur_heure As Object


' Create InternetExplorer Object
Set IE = CreateObject("InternetExplorer.Application")
' You can uncoment Next line To see form results
IE.Visible = True

' Send the form data To URL As POST binary request
IE.navigate "http://webpage.com/"

' Wait while IE loading...
While IE.Busy
        DoEvents
Wend


Set objCollection = IE.Document.getElementsByTagName("input")

i = 0
While i < objCollection.Length
    If objCollection(i).Name = "txtUserName" Then
        ' Set text for search
        objCollection(i).Value = "1234"
    End If
    If objCollection(i).Name = "txtPwd" Then
        ' Set text for search
        objCollection(i).Value = "password"
    End If

    If objCollection(i).Type = "submit" And objCollection(i).Name = "btnSubmit" Then ' submit button if found and set
        Set objElement = objCollection(i)
    End If
    i = i + 1
Wend
objElement.Click    ' click button to load page

' Wait while IE re-loading...
While IE.Busy
        DoEvents
Wend

' Show IE
IE.Visible = True
Set Doc = IE.Document

Dim links, link

Dim j As Integer                                                                    'variable to count items
j = 0
Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")
n = links.Length
While j <= n                                    'loop to go thru all "a" item so it loads next page
    links(j).Click
    While IE.Busy
        DoEvents
    Wend
    '-------------Do stuff here:  copy field value and paste in excel sheet.  Will post another question for this------------------------
    IE.Document.getElementById("DetailToolbar1_lnkBtnSave").Click              'save
    Do While IE.Busy
        Application.Wait DateAdd("s", 1, Now)                                   'wait
    Loop
    IE.Document.getElementById("DetailToolbar1_lnkBtnCancel").Click            'close
    Do While IE.Busy
        Application.Wait DateAdd("s", 1, Now)                                   'wait
    Loop
    Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")
    j = j + 2
Wend    
End Sub

Confirm postback OnClientClick button ASP.NET

Try this:

function Confirm() {
    var confirm_value = document.createElement("INPUT");
    confirm_value.type = "hidden";
    confirm_value.name = "confirm_value";

        if (confirm("Your asking")) {
            confirm_value.value = "Yes";
            document.forms[0].appendChild(confirm_value);
        }
    else {
        confirm_value.value = "No";
        document.forms[0].appendChild(confirm_value);
    }
}

In Button call function:

<asp:Button ID="btnReprocessar" runat="server" Text="Reprocessar" Height="20px" OnClick="btnReprocessar_Click" OnClientClick="Confirm()"/>

In class .cs call method:

        protected void btnReprocessar_Click(object sender, EventArgs e)
    {
        string confirmValue = Request.Form["confirm_value"];
        if (confirmValue == "Yes")
        {

        }
    }

How to use __doPostBack()

Old question, but I'd like to add something: when calling doPostBack() you can use the server handler method for the action.

For an example:

__doPostBack('<%= btn.UniqueID%>', 'my args');

Will fire, on server:

protected void btn_Click(object sender, EventArgs e)

I didn't find a better way to get the argument, so I'm still using Request["__EVENTARGUMENT"].

ASP.NET postback with JavaScript

First, don't use update panels. They are the second most evil thing that Microsoft has ever created for the web developer.

Second, if you must use update panels, try setting the UpdateMode property to Conditional. Then add a trigger to an Asp:Hidden control that you add to the page. Assign the change event as the trigger. In your dragstop event, change the value of the hidden control.

This is untested, but the theory seems sound... If this does not work, you could try the same thing with an asp:button, just set the display:none style on it and use the click event instead of the change event.

Android, How to limit width of TextView (and add three dots at the end of text)?

In order to work with the android:ellipsize attribute, you have to limit the layout width of the TextView, such that the text is out of bounds from view of TextView.

So, android:layout_width attribute plays a key role here, set it accordingly.

One example can be:

<TextView        
    android:layout_width="120dp"
    android:layout_height="wrap_content"
    android:ellipsize="end"
    android:text="This is a very long text to be displayed"
    android:textSize="12sp"
    android:maxLines="1"            
     />

Now, here if the text in android:text="This is a very long text to be displayed" goes out of view from TextView with a android:layout_width="120dp", android:ellipsize="end" will truncate the text and place ...(3 dots) after it. i.e. This is very long... will be displayed in the TextView.

Fastest Way of Inserting in Entity Framework

I would recommend this article on how to do bulk inserts using EF.

Entity Framework and slow bulk INSERTs

He explores these areas and compares perfomance:

  1. Default EF (57 minutes to complete adding 30,000 records)
  2. Replacing with ADO.NET Code (25 seconds for those same 30,000)
  3. Context Bloat- Keep the active Context Graph small by using a new context for each Unit of Work (same 30,000 inserts take 33 seconds)
  4. Large Lists - Turn off AutoDetectChangesEnabled (brings the time down to about 20 seconds)
  5. Batching (down to 16 seconds)
  6. DbTable.AddRange() - (performance is in the 12 range)

How do I create a folder in a GitHub repository?

For the ones using the web browser, you can do the following:

  • Once in the master repository, click on Create new file.
  • In the name of file box at the top, enter the name of your folder
  • Use the / key after the name of the folder. Using this forward slash creates the folder
  • You can see a new box appear next to the folder name wherein you can type the name of your file.
  • In the Commit new file box at the bottom of the page, you can type the description for your file.
  • Select the radio button Commit directly to the master branch.
  • Click on the Commit new file button
  • You will see the new directory will be created.

What is the difference between IQueryable<T> and IEnumerable<T>?

In simple words other major difference is that IEnumerable execute select query on server side, load data in-memory on client side and then filter data while IQueryable execute select query on server side with all filters.

text-align: right on <select> or <option>

I was facing the same issue in which I need to align selected placeholder value to the right of the select box & also need to align options to right but when I have used direction: rtl; to select & applied some right padding to select then all options also getting shift to the right by padding as I only want to apply padding to selected placeholder.

I have fixed the issue by the following the style:

select:first-child{
  text-indent: 24%;
  direction: rtl;
  padding-right: 7px;
}

select option{
  direction: rtl;
}

You can change text-indent as per your requirement. Hope it will help you.

Escape double quotes in a string

In C# you can use the backslash to put special characters to your string. For example, to put ", you need to write \". There are a lot of characters that you write using the backslash: Backslash with a number:

  • \000 null
  • \010 backspace
  • \011 horizontal tab
  • \012 new line
  • \015 carriage return
  • \032 substitute
  • \042 double quote
  • \047 single quote
  • \134 backslash
  • \140 grave accent

Backslash with othe character

  • \a Bell (alert)
  • \b Backspace
  • \f Formfeed
  • \n New line
  • \r Carriage return
  • \t Horizontal tab
  • \v Vertical tab
  • \' Single quotation mark
  • \" Double quotation mark
  • \ Backslash
  • \? Literal question mark
  • \ ooo ASCII character in octal notation
  • \x hh ASCII character in hexadecimal notation
  • \x hhhh Unicode character in hexadecimal notation if this escape sequence is used in a wide-character constant or a Unicode string literal. For example, WCHAR f = L'\x4e00' or WCHAR b[] = L"The Chinese character for one is \x4e00".

How to register multiple implementations of the same interface in Asp.Net Core?

Extending the solution of @rnrneverdies. Instead of ToString(), following options can also be used- 1) With common property implementation, 2) A service of services suggested by @Craig Brunetti.

public interface IService { }
public class ServiceA : IService
{
    public override string ToString()
    {
        return "A";
    }
}

public class ServiceB : IService
{
    public override string ToString()
    {
        return "B";
    }

}

/// <summary>
/// extension method that compares with ToString value of an object and returns an object if found
/// </summary>
public static class ServiceProviderServiceExtensions
{
    public static T GetService<T>(this IServiceProvider provider, string identifier)
    {
        var services = provider.GetServices<T>();
        var service = services.FirstOrDefault(o => o.ToString() == identifier);
        return service;
    }
}

public void ConfigureServices(IServiceCollection services)
{
    //Initials configurations....

    services.AddSingleton<IService, ServiceA>();
    services.AddSingleton<IService, ServiceB>();
    services.AddSingleton<IService, ServiceC>();

    var sp = services.BuildServiceProvider();
    var a = sp.GetService<IService>("A"); //returns instance of ServiceA
    var b = sp.GetService<IService>("B"); //returns instance of ServiceB

    //Remaining configurations....
}

Convert bytes to int?

Lists of bytes are subscriptable (at least in Python 3.6). This way you can retrieve the decimal value of each byte individually.

>>> intlist = [64, 4, 26, 163, 255]
>>> bytelist = bytes(intlist)       # b'@x04\x1a\xa3\xff'

>>> for b in bytelist:
...    print(b)                     # 64  4  26  163  255

>>> [b for b in bytelist]           # [64, 4, 26, 163, 255]

>>> bytelist[2]                     # 26 

How to get the current branch name in Git?

Using earlier ideas; assuming sha1 is 40 characters; and chasing references (yea, should delete the debug print lines :-):

git reflog | awk '
$3 == "checkout:" && (sha == "" || sha == $1 ) {
  from=$(NF - 2)
  to=$NF
  print from, to, length(from) > "/dev/stderr"
  if (length(from) != 40) { print from ; exit; }
  sha=substr(from, 1, 7)
  print sha > "/dev/stderr"
}
'

gives the raw output:

$ git status
HEAD detached at 147049c
[...]
$ ./gime-branch.sh
a47be8d2167641088b66bf8f5c2bf7d3da0c642c HEAD^ 40
a47be8d
master HEAD^ 6
master

Proper Linq where clauses

The second one would be more efficient as it just has one predicate to evaluate against each item in the collection where as in the first one, it's applying the first predicate to all items first and the result (which is narrowed down at this point) is used for the second predicate and so on. The results get narrowed down every pass but still it involves multiple passes.

Also the chaining (first method) will work only if you are ANDing your predicates. Something like this x.Age == 10 || x.Fat == true will not work with your first method.

python: NameError:global name '...‘ is not defined

You need to call self.a() to invoke a from b. a is not a global function, it is a method on the class.

You may want to read through the Python tutorial on classes some more to get the finer details down.

Jquery in React is not defined

Try add jQuery to your project, like

npm i jquery --save

or if you use bower

bower i jquery --save

then

import $ from 'jquery'; 

Can you append strings to variables in PHP?

PHP syntax is little different in case of concatenation from JavaScript. Instead of (+) plus a (.) period is used for string concatenation.

<?php

$selectBox = '<select name="number">';
for ($i=1;$i<=100;$i++)
{
    $selectBox += '<option value="' . $i . '">' . $i . '</option>'; // <-- (Wrong) Replace + with .
    $selectBox .= '<option value="' . $i . '">' . $i . '</option>'; // <-- (Correct) Here + is replaced .
}
$selectBox += '</select>'; // <-- (Wrong) Replace + with .
$selectBox .= '</select>'; // <-- (Correct) Here + is replaced .
echo $selectBox;

?>

Get the index of the object inside an array, matching a condition

As of 2016, you're supposed to use Array.findIndex (an ES2015/ES6 standard) for this:

_x000D_
_x000D_
a = [_x000D_
  {prop1:"abc",prop2:"qwe"},_x000D_
  {prop1:"bnmb",prop2:"yutu"},_x000D_
  {prop1:"zxvz",prop2:"qwrq"}];_x000D_
    _x000D_
index = a.findIndex(x => x.prop2 ==="yutu");_x000D_
_x000D_
console.log(index);
_x000D_
_x000D_
_x000D_

It's supported in Google Chrome, Firefox and Edge. For Internet Explorer, there's a polyfill on the linked page.

Performance note

Function calls are expensive, therefore with really big arrays a simple loop will perform much better than findIndex:

_x000D_
_x000D_
let test = [];_x000D_
_x000D_
for (let i = 0; i < 1e6; i++)_x000D_
    test.push({prop: i});_x000D_
_x000D_
_x000D_
let search = test.length - 1;_x000D_
let count = 100;_x000D_
_x000D_
console.time('findIndex/predefined function');_x000D_
    let fn = obj => obj.prop === search;_x000D_
_x000D_
    for (let i = 0; i < count; i++)_x000D_
        test.findIndex(fn);_x000D_
console.timeEnd('findIndex/predefined function');_x000D_
_x000D_
_x000D_
console.time('findIndex/dynamic function');_x000D_
    for (let i = 0; i < count; i++)_x000D_
        test.findIndex(obj => obj.prop === search);_x000D_
console.timeEnd('findIndex/dynamic function');_x000D_
_x000D_
_x000D_
console.time('loop');_x000D_
    for (let i = 0; i < count; i++) {_x000D_
        for (let index = 0; index < test.length; index++) {_x000D_
            if (test[index].prop === search) {_x000D_
                break;_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
console.timeEnd('loop');
_x000D_
_x000D_
_x000D_

As with most optimizations, this should be applied with care and only when actually needed.

Keeping session alive with Curl and PHP

Yup, often called a 'cookie jar' Google should provide many examples:

http://devzone.zend.com/16/php-101-part-10-a-session-in-the-cookie-jar/

http://curl.haxx.se/libcurl/php/examples/cookiejar.html <- good example IMHO

Copying that last one here so it does not go away...

Login to on one page and then get another page passing all cookies from the first page along Written by Mitchell

<?php
/*
This script is an example of using curl in php to log into on one page and 
then get another page passing all cookies from the first page along with you.
If this script was a bit more advanced it might trick the server into 
thinking its netscape and even pass a fake referer, yo look like it surfed 
from a local page.
*/

$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"http://www.myterminal.com/checkpwd.asp");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "UserID=username&password=passwd");

ob_start();      // prevent any output
curl_exec ($ch); // execute the curl command
ob_end_clean();  // stop preventing output

curl_close ($ch);
unset($ch);

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"http://www.myterminal.com/list.asp");

$buf2 = curl_exec ($ch);

curl_close ($ch);

echo "<PRE>".htmlentities($buf2);
?>  

JavaScript Chart Library

Check out Google Visualization API, which is kind of a generalization of the simpler Chart API

Beautiful way to remove GET-variables with PHP?

If the URL that you are trying to remove the query string from is the current URL of the PHP script, you can use one of the previously mentioned methods. If you just have a string variable with a URL in it and you want to strip off everything past the '?' you can do:

$pos = strpos($url, "?");
$url = substr($url, 0, $pos);

Curl GET request with json parameter

If you want to send your data inside the body, then you have to make a POST or PUT instead of GET.

For me, it looks like you're trying to send the query with uri parameters, which is not related to GET, you can also put these parameters on POST, PUT and so on.

The query is an optional part, separated by a question mark ("?"), that contains additional identification information that is not hierarchical in nature. The query string syntax is not generically defined, but it is commonly organized as a sequence of = pairs, with the pairs separated by a semicolon or an ampersand.

For example:

curl http://server:5050/a/c/getName?param0=foo&param1=bar

How to convert password into md5 in jquery?

Fiddle: http://jsfiddle.net/33HMj/

Js:

var md5 = function(value) {
    return CryptoJS.MD5(value).toString();
}

$("input").keyup(function () {
     var value = $(this).val(),
         hash = md5(value);
     $(".test").html(hash);
 });

Convert ASCII TO UTF-8 Encoding

Use mb_convert_encoding to convert an ASCII to UTF-8. More info here

$string = "chárêctërs";
print(mb_detect_encoding ($string));

$string = mb_convert_encoding($string, "UTF-8");
print(mb_detect_encoding ($string));

Setting up Eclipse with JRE Path

This may sound dumb, but it may be a fresh, or damaged install, so is the JDK installed? If not, go to the download site and download the latest version of Java JRE. Like I said, this may sound dumb, but it solved my problem.

http://www.oracle.com/technetwork/java/javase/downloads/index.html

How to show hidden divs on mouseover?

Option 1 Each div is specifically identified, so any other div (without the specific IDs) on the page will not obey the :hover pseudo-class.

<style type="text/css">
  #div1, #div2, #div3{  
    display:none;  
  }  
  #div1:hover, #div2:hover, #div3:hover{  
    display:block;  
  }
</style>

Option 2 All divs on the page, regardless of IDs, have the hover effect.

<style type="text/css">
  div{  
    display:none;  
  }  
  div:hover{  
    display:block;  
  }
</style>

How do I read the contents of a Node.js stream into a string variable?

What do you think about this ?

// lets have a ReadableStream as a stream variable

const chunks = [];

for await (let chunk of stream) {
    chunks.push(chunk)
}

const buffer  = Buffer.concat(chunks);
const str = buffer.toString("utf-8")

What is the difference between instanceof and Class.isAssignableFrom(...)?

isAssignableFrom(A, B) =

if (A == B) return true
else if (B == java.lang.Object) return false
else return isAssignableFrom(A, getSuperClass(B))

The pseudo code above is a definition of, if references of type/class A is assignable from references of type/class B. It is a recursive definition. To some it may be helpful, for others it may be confusing. I add it in case somebody should find it useful. This is just an attempt to capture my understanding, it is not the official definition. It is used in a certain Java VM implementation and works for many example programs, so while I cannot guarentee that it captures all aspects of isAssignableFrom, it is not completely off.

Multi-dimensional associative arrays in JavaScript

Just use a regular JavaScript object, which would 'read' the same way as your associative arrays. You have to remember to initialize them first as well.

var obj = {};

obj['fred'] = {};
if('fred' in obj ){ } // can check for the presence of 'fred'
if(obj.fred) { } // also checks for presence of 'fred'
if(obj['fred']) { } // also checks for presence of 'fred'

// The following statements would all work
obj['fred']['apples'] = 1;
obj.fred.apples = 1;
obj['fred'].apples = 1;

// or build or initialize the structure outright
var obj = { fred: { apples: 1, oranges: 2 }, alice: { lemons: 1 } };

If you're looking over values, you might have something that looks like this:

var people = ['fred', 'alice'];
var fruit = ['apples', 'lemons'];

var grid = {};
for(var i = 0; i < people.length; i++){
    var name = people[i];
    if(name in grid == false){
        grid[name] = {}; // must initialize the sub-object, otherwise will get 'undefined' errors
    }

    for(var j = 0; j < fruit.length; j++){
        var fruitName = fruit[j];
        grid[name][fruitName] = 0;
    }
}

Sort an Array by keys based on another Array?

There you go:

function sortArrayByArray(array $array, array $orderArray) {
    $ordered = array();
    foreach ($orderArray as $key) {
        if (array_key_exists($key, $array)) {
            $ordered[$key] = $array[$key];
            unset($array[$key]);
        }
    }
    return $ordered + $array;
}

Open an image using URI in Android's default gallery image viewer

I use this it works for me

Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), 1);

Convert string into Date type on Python

>>> from datetime import datetime
>>> year, month, day = map(int, my_date.split('-'))
>>> date_object = datetime(year, month, day)

How do I put a border around an Android textview?

Changing Konstantin Burov answer because not work in my case:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@android:color/white" />
            <stroke android:width="2dip" android:color="#4fa5d5"/>
            <corners android:radius="7dp"/>
        </shape>
    </item>
</selector>

compileSdkVersion 26 (Android 8.0), minSdkVersion 21 (Android 5.0), targetSdkVersion 26, implementation 'com.android.support:appcompat-v7:26.1.0', gradle:4.1

DB2 SQL error: SQLCODE: -206, SQLSTATE: 42703

That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:

DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87

Double check your table definition. Maybe you just missed adding something.

I also tried google-ing this problem and saw this:

http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode

What's the difference between eval, exec, and compile?

exec is for statement and does not return anything. eval is for expression and returns value of expression.

expression means "something" while statement means "do something".

Format / Suppress Scientific Notation from Python Pandas Aggregation Results

Setting a fixed number of decimal places globally is often a bad idea since it is unlikely that it will be an appropriate number of decimal places for all of your various data that you will display regardless of magnitude. Instead, try this which will give you scientific notation only for large and very small values (and adds a thousands separator unless you omit the ","):

pd.set_option('display.float_format', lambda x: '%,g' % x)

Or to almost completely suppress scientific notation without losing precision, try this:

pd.set_option('display.float_format', str)

What does the percentage sign mean in Python

The modulus operator. The remainder when you divide two number.

For Example:

>>> 5 % 2 = 1 # remainder of 5 divided by 2 is 1
>>> 7 % 3 = 1 # remainer of 7 divided by 3 is 1
>>> 3 % 1 = 0 # because 1 divides evenly into 3

Laravel Redirect Back with() Message

Laravel 5 and later

Controller

 return redirect()->back()->with('success', 'your message,here');   

Blade:

@if (\Session::has('success'))
    <div class="alert alert-success">
        <ul>
            <li>{!! \Session::get('success') !!}</li>
        </ul>
    </div>
@endif

Trying to get property of non-object MySQLi result

I have been working on to write a custom module in Drupal 7 and got the same error:

Notice: Trying to get property of non-object

My code is something like this:

function example_node_access($node, $op, $account) {
  if ($node->type == 'page' && $op == 'update') {
    drupal_set_message('This poll has been published, you may not make changes to it.','error');
    return NODE_ACCESS_DENY;    
  }
}

Solution: I just added a condition if (is_object($sqlResult)), and everything went fine.

Here is my final code:

function mediaten_node_access($node, $op, $account) {

    if (is_object($node)){

     if ($node->type == 'page' && $op == 'update') {
       drupal_set_message('This poll has been published, you may not make changes.','error');
       return NODE_ACCESS_DENY;    
      }

    }

}

How do I get my page title to have an icon?

<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />

add this to your HTML Head. Of course the file "favicon.ico" has to exist. I think 16x16 or 32x32 pixel files are best.

Best way to check for "empty or null value"

A lot of the answers are the shortest way, not the necessarily the best way if the column has lots of nulls. Breaking the checks up allows the optimizer to evaluate the check faster as it doesn't have to do work on the other condition.

(stringexpression IS NOT NULL AND trim(stringexpression) != '')

The string comparison doesn't need to be evaluated since the first condition is false.

Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList?

In Java 8 you can use Files.write() method with two arguments: Path and List<String>, something like this:

List<String> clubNames = clubs.stream()
    .map(Club::getName)
    .collect(Collectors.toList())

try {
    Files.write(Paths.get(fileName), clubNames);
} catch (IOException e) {
    log.error("Unable to write out names", e);
}

How can I sort a dictionary by key?

from operator import itemgetter
# if you would like to play with multiple dictionaries then here you go:
# Three dictionaries that are composed of first name and last name.
user = [
    {'fname': 'Mo', 'lname': 'Mahjoub'},
    {'fname': 'Abdo', 'lname': 'Al-hebashi'},
    {'fname': 'Ali', 'lname': 'Muhammad'}
]
#  This loop will sort by the first and the last names.
# notice that in a dictionary order doesn't matter. So it could put the first name first or the last name first. 
for k in sorted (user, key=itemgetter ('fname', 'lname')):
    print (k)

# This one will sort by the first name only.
for x in sorted (user, key=itemgetter ('fname')):
    print (x)

Sort JavaScript object by key

This is an old question, but taking the cue from Mathias Bynens' answer, I've made a short version to sort the current object, without much overhead.

    Object.keys(unordered).sort().forEach(function(key) {
        var value = unordered[key];
        delete unordered[key];
        unordered[key] = value;
    });

after the code execution, the "unordered" object itself will have the keys alphabetically sorted.

What are XAND and XOR

To add to this, since I was just dealing with it, if you are looking for an "equivalence gate" or a "coincedence gate" as your XAND, what you really have is just "equals".

If you think about it, given XOR from above:

F XOR F = F
F XOR T = T
T XOR F = T
T XOR T = F

And we expect XAND should be:

F XAND F = T
F XAND T = F
T XAND F = F
T XAND T = T

And isn't this exactly the same?

F == F = T
F == T = F
T == F = F
T == T = T

Git Clone: Just the files, please?

Why not perform a clone and then delete the .git directory so that you just have a bare working copy?

Edit: Or in fact why use clone at all? It's a bit confusing when you say that you want a git repo but without a .git directory. If you mean that you just want a copy of some state of the tree then why not do cp -R in the shell instead of the git clone and then delete the .git afterwards.

Adding an img element to a div with javascript

function image()
{
    //dynamically add an image and set its attribute
    var img=document.createElement("img");
    img.src="p1.jpg"
    img.id="picture"
    var foo = document.getElementById("fooBar");
    foo.appendChild(img);
}

<span id="fooBar">&nbsp;</span>

grunt: command not found when running from terminal

I'm guessing you used Brew to install Node, so the guide here might be helpful http://madebyhoundstooth.com/blog/install-node-with-homebrew-on-os-x/.

You need to ensure that the npm/bin is in your path as it describes export PATH="/usr/local/share/npm/bin:$PATH". This is the location that npm will install the bin stubs for the installed packages.


The nano version will also work as described here http://architectryan.com/2012/10/02/add-to-the-path-on-mac-os-x-mountain-lion/ but a restart of Terminal may be required to have the new path picked up.

Split array into chunks

I just wrote this with the help of a groupBy function.

_x000D_
_x000D_
// utils_x000D_
const group = (source) => ({_x000D_
  by: (grouping) => {_x000D_
    const groups = source.reduce((accumulator, item) => {_x000D_
      const name = JSON.stringify(grouping(item));_x000D_
      accumulator[name] = accumulator[name] || [];_x000D_
      accumulator[name].push(item);_x000D_
      return accumulator;_x000D_
    }, {});_x000D_
_x000D_
    return Object.keys(groups).map(key => groups[key]);_x000D_
  }_x000D_
});_x000D_
_x000D_
const chunk = (source, size) => group(source.map((item, index) => ({ item, index })))_x000D_
.by(x => Math.floor(x.index / size))_x000D_
.map(x => x.map(v => v.item));_x000D_
_x000D_
_x000D_
// 103 items_x000D_
const arr = [6,2,6,6,0,7,4,9,3,1,9,6,1,2,7,8,3,3,4,6,8,7,6,9,3,6,3,5,0,9,3,7,0,4,1,9,7,5,7,4,3,4,8,9,0,5,1,0,0,8,0,5,8,3,2,5,6,9,0,0,1,5,1,7,0,6,1,6,8,4,9,8,9,1,6,5,4,9,1,6,6,1,8,3,5,5,7,0,8,3,1,7,1,1,7,6,4,9,7,0,5,1,0];_x000D_
_x000D_
const chunks = chunk(arr, 10);_x000D_
_x000D_
console.log(JSON.stringify(chunks));
_x000D_
_x000D_
_x000D_

How to select specific form element in jQuery?

although it is invalid html but you can use selector context to limit your selector in your case it would be like :

$("input[name='name']" , "#form2").val("Hello World! ");

http://api.jquery.com/jquery/#selector-context

Uncaught TypeError: Cannot read property 'msie' of undefined - jQuery tools

Here is the jQuery Tools bug on GitHub. You can try one of the patches.

edit — it doesn't look to me as if jQuery Tools is getting much support. I personally would not begin a new project with a dependency on that library unless I were prepared to take over support myself.

Specify system property to Maven project

properties-maven-plugin plugin may help:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>properties-maven-plugin</artifactId>
    <version>1.0.0</version>
    <executions>
        <execution>
            <goals>
                <goal>set-system-properties</goal>
            </goals>
            <configuration>
                <properties>
                    <property>
                        <name>my.property.name</name>
                        <value>my.property.value</value>
                    </property>
                </properties>
            </configuration>
        </execution>
    </executions>
</plugin>

How to change package name of an Android Application

I found the easiest solution was to use Regexxer to replace "com.package.name" with "com.newpackage.name", then rename the directories properly. Super easy, super fast.

Java - using System.getProperty("user.dir") to get the home directory

"user.dir" is the current working directory, not the home directory It is all described here.

http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

Also, by using \\ instead of File.separator, you will lose portability with *nix system which uses / for file separator.

How to show progress dialog in Android?

This is the good way to use dialog

private class YourAsyncTask extends AsyncTask<Void, Void, Void> {

   ProgressDialog dialog = new ProgressDialog(IncidentFormActivity.this);

   @Override
    protected void onPreExecute() {
        //set message of the dialog
        dialog.setMessage("Loading...");
        //show dialog
        dialog.show();
        super.onPreExecute();
    }

   protected Void doInBackground(Void... args) {
    // do background work here
    return null;
   }

   protected void onPostExecute(Void result) {
     // do UI work here
     if(dialog != null && dialog.isShowing()){
       dialog.dismiss()
     }

  }
}

Why maven settings.xml file is not there?

You can verify where your Setting.xml is by pressing shortcut Ctrl+3, you will see Quick Access on top right side of Eclipse, then search setting.xml in searchbox. If you got setting.xml it will show up in search. Click that, and it will open the window showing directory path wherever it is stored. Your Maven Global Settings should be as such:

Global Setting C:\maven\apache-maven-3.5.0\conf\settings.xml
User Setting %userprofile%\\.m2\setting.xml
You can use global setting usually and leave the second option user setting untouched. Store your setting.xml in Global Setting

While loop in batch

@echo off

set countfiles=10

:loop

set /a countfiles -= 1

echo hi

if %countfiles% GTR 0 goto loop

pause

on the first "set countfiles" the 10 you see is the amount it will loop the echo hi is the thing you want to loop

...i'm 5 years late

Making view resize to its parent when added with addSubview

You can always do it in your UIViews - (void)didMoveToSuperview method. It will get called when added or removed from your parent (nil when removed). At that point in time just set your size to that of your parent. From that point on the autoresize mask should work properly.

How do I get java logging output to appear on a single line?

This is what I'm using.

public class VerySimpleFormatter extends Formatter {

    private static final String PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";

    @Override
    public String format(final LogRecord record) {
        return String.format(
                "%1$s %2$-7s %3$s\n",
                new SimpleDateFormat(PATTERN).format(
                        new Date(record.getMillis())),
                record.getLevel().getName(), formatMessage(record));
    }
}

You'll get something like...

2016-08-19T17:43:14.295+09:00 INFO    Hey~
2016-08-19T17:43:16.068+09:00 SEVERE  Seriously?
2016-08-19T17:43:16.068+09:00 WARNING I'm warning you!!!

How do I fit an image (img) inside a div and keep the aspect ratio?

What worked for me was:

<div style='display: inline-flex; width: 80px; height: 80px;'>
<img style='max-width: 100%; max-height: 100%' src='image file'>
</div>

inline-flex was required to keep the images from going outside of the div.

How do you test a public/private DSA keypair?

Delete the public keys and generate new ones from the private keys. Keep them in separate directories, or use a naming convention to keep them straight.

Python: One Try Multiple Except

Yes, it is possible.

try:
   ...
except FirstException:
   handle_first_one()

except SecondException:
   handle_second_one()

except (ThirdException, FourthException, FifthException) as e:
   handle_either_of_3rd_4th_or_5th()

except Exception:
   handle_all_other_exceptions()

See: http://docs.python.org/tutorial/errors.html

The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)

Dynamically load JS inside JS

The jQuery.getScript() method is a shorthand of the Ajax function (with the dataType attribute: $.ajax({ url: url,dataType: "script"}))

If you want the scripts to be cachable, either use RequireJS or follow jQuery's example on extending the jQuery.getScript method similar to the following.

jQuery.cachedScript = function( url, options ) {

  // Allow user to set any option except for dataType, cache, and url
  options = $.extend( options || {}, {
    dataType: "script",
    cache: true,
    url: url
  });

  // Use $.ajax() since it is more flexible than $.getScript
  // Return the jqXHR object so we can chain callbacks
  return jQuery.ajax( options );
};

// Usage
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
  console.log( textStatus );
});

Reference: jQuery.getScript() | jQuery API Documentation

Type of expression is ambiguous without more context Swift

I got this error when I put a space before a comma in the parameters when calling a function.

eg, I used:

myfunction(parameter1: parameter1 , parameter2: parameter2)

Whereas it should have been:

myfunction(parameter1: parameter1, parameter2: parameter2)

Deleting the space got rid of the error message

Xcode - Warning: Implicit declaration of function is invalid in C99

should call the function properly; like- Fibonacci:input

Which is the correct C# infinite loop, for (;;) or while (true)?

Personally, I have always preferred for(;;) precisely because it has no condition (as opposed to while (true) which has an always-true one). However, this is really a very minor style point, which I don't feel is worth arguing about either way. I've yet to see a C# style guideline that mandated or forbade either approach.

Recommended way to save uploaded files in a servlet application

Store it anywhere in an accessible location except of the IDE's project folder aka the server's deploy folder, for reasons mentioned in the answer to Uploaded image only available after refreshing the page:

  1. Changes in the IDE's project folder does not immediately get reflected in the server's work folder. There's kind of a background job in the IDE which takes care that the server's work folder get synced with last updates (this is in IDE terms called "publishing"). This is the main cause of the problem you're seeing.

  2. In real world code there are circumstances where storing uploaded files in the webapp's deploy folder will not work at all. Some servers do (either by default or by configuration) not expand the deployed WAR file into the local disk file system, but instead fully in the memory. You can't create new files in the memory without basically editing the deployed WAR file and redeploying it.

  3. Even when the server expands the deployed WAR file into the local disk file system, all newly created files will get lost on a redeploy or even a simple restart, simply because those new files are not part of the original WAR file.

It really doesn't matter to me or anyone else where exactly on the local disk file system it will be saved, as long as you do not ever use getRealPath() method. Using that method is in any case alarming.

The path to the storage location can in turn be definied in many ways. You have to do it all by yourself. Perhaps this is where your confusion is caused because you somehow expected that the server does that all automagically. Please note that @MultipartConfig(location) does not specify the final upload destination, but the temporary storage location for the case file size exceeds memory storage threshold.

So, the path to the final storage location can be definied in either of the following ways:

  • Hardcoded:

      File uploads = new File("/path/to/uploads");
    
  • Environment variable via SET UPLOAD_LOCATION=/path/to/uploads:

      File uploads = new File(System.getenv("UPLOAD_LOCATION"));
    
  • VM argument during server startup via -Dupload.location="/path/to/uploads":

      File uploads = new File(System.getProperty("upload.location"));
    
  • *.properties file entry as upload.location=/path/to/uploads:

      File uploads = new File(properties.getProperty("upload.location"));
    
  • web.xml <context-param> with name upload.location and value /path/to/uploads:

      File uploads = new File(getServletContext().getInitParameter("upload.location"));
    
  • If any, use the server-provided location, e.g. in JBoss AS/WildFly:

      File uploads = new File(System.getProperty("jboss.server.data.dir"), "uploads");
    

Either way, you can easily reference and save the file as follows:

File file = new File(uploads, "somefilename.ext");

try (InputStream input = part.getInputStream()) {
    Files.copy(input, file.toPath());
}

Or, when you want to autogenerate an unique file name to prevent users from overwriting existing files with coincidentally the same name:

File file = File.createTempFile("somefilename-", ".ext", uploads);

try (InputStream input = part.getInputStream()) {
    Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}

How to obtain part in JSP/Servlet is answered in How to upload files to server using JSP/Servlet? and how to obtain part in JSF is answered in How to upload file using JSF 2.2 <h:inputFile>? Where is the saved File?

Note: do not use Part#write() as it interprets the path relative to the temporary storage location defined in @MultipartConfig(location).

See also:

Why does integer division in C# return an integer and not a float?

While it is common for new programmer to make this mistake of performing integer division when they actually meant to use floating point division, in actual practice integer division is a very common operation. If you are assuming that people rarely use it, and that every time you do division you'll always need to remember to cast to floating points, you are mistaken.

First off, integer division is quite a bit faster, so if you only need a whole number result, one would want to use the more efficient algorithm.

Secondly, there are a number of algorithms that use integer division, and if the result of division was always a floating point number you would be forced to round the result every time. One example off of the top of my head is changing the base of a number. Calculating each digit involves the integer division of a number along with the remainder, rather than the floating point division of the number.

Because of these (and other related) reasons, integer division results in an integer. If you want to get the floating point division of two integers you'll just need to remember to cast one to a double/float/decimal.

Creating a daemon in Linux

I can stop at the first requirement "A daemon which cannot be stopped ..."

Not possible my friend; however, you can achieve the same with a much better tool, a kernel module.

http://www.infoq.com/articles/inotify-linux-file-system-event-monitoring

All daemons can be stopped. Some are more easily stopped than others. Even a daemon pair with the partner in hold down, respawning the partner if lost, can be stopped. You just have to work a little harder at it.

Why doesn't Java support unsigned ints?

I've heard stories that they were to be included close to the orignal Java release. Oak was the precursor to Java, and in some spec documents there was mention of usigned values. Unfortunately these never made it into the Java language. As far as anyone has been able to figure out they just didn't get implemented, likely due to a time constraint.

How to permanently export a variable in Linux?

If it suits anyone, here are some brief guidelines for adding environment variables permanently.

vi ~/.bash_profile

Add the variables to the file:

export DISPLAY=:0
export JAVA_HOME=~/opt/openjdk11

Immediately apply all changes:

source ~/.bash_profile

Source: https://www.serverlab.ca/tutorials/linux/administration-linux/how-to-set-environment-variables-in-linux/

How to convert string date to Timestamp in java?

You can convert String to Timestamp:

String inDate = "01-01-1990"
DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
Timestamp ts = new Timestamp(((java.util.Date)df.parse(inDate)).getTime());

Python for and if on one line

The reason it prints "three" is because you didnt define your array. The equivalent to what you're doing is:

arr = []
for i in array :
    if i == "two" :
        arr.push(i)
print(i)

You are asking for the last element it looked through, which is not what you should be doing. You need to be storing the array to a variable in order to get the element.

The english equivalent of what you are doing is:

You: "I need you to print all the elements in this array that equal two, but in an array. And each time you cycle through the list, define the current element as I."
Computer: "Here: ["two"]"
You: "Now tell me 'i'"
Computer: "'i' is equal to "three"
You: "Why?"

The reason 'i' is equal to "three" is because three was the last thing that was defined as I

the computer did:

i = "one"
i = "two"
i = "three"

print(["two"])

Because you asked it to.

If you want the index, go here If you want the values in an array, define the array, like this:

MyArray = [(i) for i in my_list if i=="two"]

Android- create JSON Array and JSON Object

Here's a simpler (but not so short) version which doesn't require try-catch:

Map<String, String> data = new HashMap<>();
data.put("user", "[email protected]");
data.put("pass", "123");

JSONObject jsonData = new JSONObject(data);

If you want to add a jsonObject into a field, you can do this way:

data.put("socialMedia", (new JSONObject()).put("facebookId", "1174989895893400"));
data.put("socialMedia", (new JSONObject()).put("googleId", "106585039098745627377"));

Unfortunately it needs a try-catch because of the put() method.

IF you want to avoid try-catch again (not very recommended, but it's ok if you can guarantee well formated json strings), you might do this way:

data.put("socialMedia", "{ 'facebookId': '1174989895893400' }");

You can do the same about JsonArrays and so on.

Cheers.

how to clear localstorage,sessionStorage and cookies in javascript? and then retrieve?

The standard Web Storage, does not say anything about the restoring any of these. So there won't be any standard way to do it. You have to go through the way the browsers implement these, or find a way to backup these before you delete them.

How to generate a range of numbers between two numbers?

The solution I've developed and used for quite some time now (riding some on the shared works of others) is slightly similar to at least one posted. It doesn't reference any tables and returns an unsorted range of up to 1048576 values (2^20) and can include negatives if desired. You can of course sort the result if necessary. It runs pretty quickly, especially on smaller ranges.

Select value from dbo.intRange(-500, 1500) order by value  -- returns 2001 values

create function dbo.intRange 
(   
    @Starting as int,
    @Ending as int
)
returns table
as
return (
    select value
    from (
        select @Starting +
            ( bit00.v | bit01.v | bit02.v | bit03.v
            | bit04.v | bit05.v | bit06.v | bit07.v
            | bit08.v | bit09.v | bit10.v | bit11.v
            | bit12.v | bit13.v | bit14.v | bit15.v
            | bit16.v | bit17.v | bit18.v | bit19.v
            ) as value
        from       (select 0 as v union ALL select 0x00001 as v) as bit00
        cross join (select 0 as v union ALL select 0x00002 as v) as bit01
        cross join (select 0 as v union ALL select 0x00004 as v) as bit02
        cross join (select 0 as v union ALL select 0x00008 as v) as bit03
        cross join (select 0 as v union ALL select 0x00010 as v) as bit04
        cross join (select 0 as v union ALL select 0x00020 as v) as bit05
        cross join (select 0 as v union ALL select 0x00040 as v) as bit06
        cross join (select 0 as v union ALL select 0x00080 as v) as bit07
        cross join (select 0 as v union ALL select 0x00100 as v) as bit08
        cross join (select 0 as v union ALL select 0x00200 as v) as bit09
        cross join (select 0 as v union ALL select 0x00400 as v) as bit10
        cross join (select 0 as v union ALL select 0x00800 as v) as bit11
        cross join (select 0 as v union ALL select 0x01000 as v) as bit12
        cross join (select 0 as v union ALL select 0x02000 as v) as bit13
        cross join (select 0 as v union ALL select 0x04000 as v) as bit14
        cross join (select 0 as v union ALL select 0x08000 as v) as bit15
        cross join (select 0 as v union ALL select 0x10000 as v) as bit16
        cross join (select 0 as v union ALL select 0x20000 as v) as bit17
        cross join (select 0 as v union ALL select 0x40000 as v) as bit18
        cross join (select 0 as v union ALL select 0x80000 as v) as bit19
    ) intList
    where @Ending - @Starting < 0x100000
        and intList.value between @Starting and @Ending
)

Filtering a pyspark dataframe using isin by exclusion

df.filter((df.bar != 'a') & (df.bar != 'b'))

How do I convert a TimeSpan to a formatted string?

   public static class TimeSpanFormattingExtensions
   {
      public static string ToReadableString(this TimeSpan span)
      {
         return string.Join(", ", span.GetReadableStringElements()
            .Where(str => !string.IsNullOrWhiteSpace(str)));
      }

      private static IEnumerable<string> GetReadableStringElements(this TimeSpan span)
      {
         yield return GetDaysString((int)Math.Floor(span.TotalDays));
         yield return GetHoursString(span.Hours);
         yield return GetMinutesString(span.Minutes);
         yield return GetSecondsString(span.Seconds);
      }

      private static string GetDaysString(int days)
      {
         if (days == 0)
            return string.Empty;

         if (days == 1)
            return "1 day";

         return string.Format("{0:0} days", days);
      }

      private static string GetHoursString(int hours)
      {
         if (hours == 0)
            return string.Empty;

         if (hours == 1)
            return "1 hour";

         return string.Format("{0:0} hours", hours);
      }

      private static string GetMinutesString(int minutes)
      {
         if (minutes == 0)
            return string.Empty;

         if (minutes == 1)
            return "1 minute";

         return string.Format("{0:0} minutes", minutes);
      }

      private static string GetSecondsString(int seconds)
      {
         if (seconds == 0)
            return string.Empty;

         if (seconds == 1)
            return "1 second";

         return string.Format("{0:0} seconds", seconds);
      }
   }

Git on Windows: How do you set up a mergetool?

Under Cygwin, the only thing that worked for me is the following:

git config --global merge.tool myp4merge
git config --global mergetool.myp4merge.cmd 'p4merge.exe "$(cygpath -wla $BASE)" "$(cygpath -wla $LOCAL)" "$(cygpath -wla $REMOTE)" "$(cygpath -wla $MERGED)"'
git config --global diff.tool myp4diff
git config --global difftool.myp4diff.cmd 'p4merge.exe "$(cygpath -wla $LOCAL)" "$(cygpath -wla $REMOTE)"'

Also, I like to turn off the prompt message for difftool:

git config --global difftool.prompt false

Run CRON job everyday at specific time

From cron manual http://man7.org/linux/man-pages/man5/crontab.5.html:

Lists are allowed. A list is a set of numbers (or ranges) separated by commas. Examples: "1,2,5,9", "0-4,8-12".

So in this case it would be:

30 10,14 * * *

Why can't I make a vector of references?

As the other comments suggest, you are confined to using pointers. But if it helps, here is one technique to avoid facing directly with pointers.

You can do something like the following:

vector<int*> iarray;
int default_item = 0; // for handling out-of-range exception

int& get_item_as_ref(unsigned int idx) {
   // handling out-of-range exception
   if(idx >= iarray.size()) 
      return default_item;
   return reinterpret_cast<int&>(*iarray[idx]);
}

Using an HTTP PROXY - Python

I encountered this on jython client. The server was only talking TLS and the client using SSL context.

javax.net.ssl.SSLContext.getInstance("SSL")

Once the client was to TLS, things started working.

Parse usable Street Address, City, State, Zip from a string

RecogniContact is a Windows COM object that parses US and European addresses. You can try it right on http://www.loquisoft.com/index.php?page=8

Why doesn't calling a Python string method do anything unless you assign its output?

All string functions as lower, upper, strip are returning a string without modifying the original. If you try to modify a string, as you might think well it is an iterable, it will fail.

x = 'hello'
x[0] = 'i' #'str' object does not support item assignment

There is a good reading about the importance of strings being immutable: Why are Python strings immutable? Best practices for using them

How to send parameters with jquery $.get()

Try this:

$.ajax({
    type: 'get',
    url: 'manageproducts.do',
    data: 'option=1',
    success: function(data) {

        availableProductNames = data.split(",");

        alert(availableProductNames);

    }
});

Also You have a few errors in your sample code, not sure if that was causing the error or it was just a typo upon entering the question.

Swift: Display HTML data in a label or textView

Swift 5

extension String {
    func htmlAttributedString() -> NSAttributedString? {
        guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
        guard let html = try? NSMutableAttributedString(
            data: data,
            options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html],
            documentAttributes: nil) else { return nil }
        return html
    }
}

Call:

myLabel.attributedText = "myString".htmlAttributedString()

Skip a submodule during a Maven build

The notion of multi-module projects is there to service the needs of codependent segments of a project. Such a client depends on the services which in turn depends on say EJBs or data-access routines. You could group your continuous integration (CI) tests in this manner. I would rationalize that by saying that the CI tests need to be in lock-step with application logic changes.

Suppose your project is structured as:

project-root
  |
  + --- ci
  |
  + --- client
  |
  + --- server

The project-root/pom.xml defines modules

<modules>
  <module>ci</module>
  <module>client</module>
  <module>server</module>
</modules>

The ci/pom.xml defines profiles such as:

... 
<profiles>
  <profile>
    <id>default</id>
    <activation>
      <activeByDefault>true</activeByDefault>
    </activation>
    <plugin>
       <artifactId>maven-surefire-plugin</artifactId>
       <configuration>
         <skip>true</skip>
       </configuration>
     </plugin>
  </profile>
  <profile>
    <id>CI</id>
    <plugin>
       <artifactId>maven-surefire-plugin</artifactId>
       <configuration>
         <skip>false</skip>
       </configuration>
     </plugin>
  </profile>
</profiles>

This will result in Maven skipping tests in this module except when the profile named CI is active. Your CI server must be instructed to execute mvn clean package -P CI. The Maven web site has an in-depth explanation of the profiling mechanism.

CSS way to horizontally align table

<style>
    .abc {
        text-align: center;
    }
</style>

<table class="abc">
    <tr>
        <td>Item1</td>
        <td>Item2</td>
    </tr>
</table>

Remove a cookie

Set the value to "" and the expiry date to yesterday (or any date in the past)

setcookie("hello", "", time()-3600);

Then the cookie will expire the next time the page loads.

Cloud Firestore collection count

As far as I know there is no build-in solution for this and it is only possible in the node sdk right now. If you have a

db.collection('someCollection')

you can use

.select([fields])

to define which field you want to select. If you do an empty select() you will just get an array of document references.

example:

db.collection('someCollection').select().get().then( (snapshot) => console.log(snapshot.docs.length) );

This solution is only a optimization for the worst case of downloading all documents and does not scale on large collections!

Also have a look at this:
How to get a count of number of documents in a collection with Cloud Firestore

How to check if two words are anagrams

I know this is an old question. However, I'm hoping this can be of help to someone. The time complexity of this solution is O(n^2).

public boolean areAnagrams(final String word1, final String word2) {
        if (word1.length() != word2.length())
            return false;

        if (word1.equals(word2))
            return true;

        if (word1.length() == 0 && word2.length() == 0)
            return true;

        String secondWord = word2;
        for (int i = 0; i < word1.length(); i++) {
            if (secondWord.indexOf(word1.charAt(i)) == -1)
                return false;

            secondWord = secondWord.replaceFirst(word1.charAt(i) + "", "");
        }

        if (secondWord.length() > 0)
            return false;

        return true;
}

Use xml.etree.ElementTree to print nicely formatted xml files

You could use the library lxml (Note top level link is now spam) , which is a superset of ElementTree. Its tostring() method includes a parameter pretty_print - for example:

>>> print(etree.tostring(root, pretty_print=True))
<root>
  <child1/>
  <child2/>
  <child3/>
</root>

PHP code to get selected text of a combo box

You can achive this with creating new array:

<?php
$array = array(1 => "Toyota", 2 => "Nissan", 3 => "BMW");

if (isset ($_POST['search'])) {
  $maker = mysql_real_escape_string($_POST['Make']);
  echo $array[$maker];
}
?>

Failed to find target with hash string 'android-25'

I got similar problem

1: I tried to resolve with the answer which is marked correct above But I was not able to get the system setting which was quit amazing (On MacBook).

Most of the time such errors & issues comes because of replacing your grade file with other grade file ,due which gradel does not sync properly and while building the project issue comes . The issue is bascially related to non syncing for platform tools

Solution a: Go to File and then to Your project strucutre -modules -app-Properties -build tool version -click on options which is required for your project (if required build tool version not there chose any other). This will sync the grade file and now you can go to gradel and change target version and build tool version as per your requirement .you will prompted to download the required platform tool to sync it , now click on install tool version and let project to build

Solution b: Try Anuja Ans if you can get option of system setting and install platform tool.

joining two select statements

SELECT *
FROM
  (First_query) AS ONE
LEFT OUTER JOIN
  (Second_query ) AS TWO ON ONE.First_query_ID = TWO.Second_Query_ID;

How to get first N number of elements from an array

To get the first n elements of an array, use

array.slice(0, n);

Mobile website "WhatsApp" button to send message to a specific number

To send a Whatsapp message from a website, use the below URL.

URL: https://api.whatsapp.com/send?phone=XXXXX&text=dummy

Here the phone and text are parameters were one of them is required.

  • phone: To whom we need to send the message
  • text: The text needs to share.

This URL is also can be used. It displays a blank screen if there is no application found!

URL: whatsapp://send?text=The text to share!

Note: All the above will work in web, only if WhatsApp desktop app is installed

How to set the size of a column in a Bootstrap responsive table

Bootstrap 4.0

Be aware of all migration changes from Bootstrap 3 to 4. On the table you now need to enable flex box by adding the class d-flex, and drop the xs to allow bootstrap to automatically detect the viewport.

<div class="container-fluid">
    <table id="productSizes" class="table">
        <thead>
            <tr class="d-flex">
                <th class="col-1">Size</th>
                <th class="col-3">Bust</th>
                <th class="col-3">Waist</th>
                <th class="col-5">Hips</th>
            </tr>
        </thead>
        <tbody>
            <tr class="d-flex">
                <td class="col-1">6</td>
                <td class="col-3">79 - 81</td>
                <td class="col-3">61 - 63</td>
                <td class="col-5">89 - 91</td>
            </tr>
            <tr class="d-flex">
                <td class="col-1">8</td>
                <td class="col-3">84 - 86</td>
                <td class="col-3">66 - 68</td>
                <td class="col-5">94 - 96</td>
            </tr>
        </tbody>
    </table>

bootply

Bootstrap 3.2

Table column width use the same layout as grids do; using col-[viewport]-[size]. Remember the column sizes should total 12; 1 + 3 + 3 + 5 = 12 in this example.

        <thead>
            <tr>
                <th class="col-xs-1">Size</th>
                <th class="col-xs-3">Bust</th>
                <th class="col-xs-3">Waist</th>
                <th class="col-xs-5">Hips</th>
            </tr>
        </thead>

Remember to set the <th> elements rather than the <td> elements so it sets the whole column. Here is a working BOOTPLY.

Thanks to @Dan for reminding me to always work mobile view (col-xs-*) first.

"Permission Denied" trying to run Python on Windows 10

Add the path of python folder in environmental variable and it will work

1.search environmental variable

2.look for system variable section and find variable named path in it

3.double click on path and add new path which directs towards python folder and that's it.

the python folder is usually in C:\Users["user name"]\AppData\Local\Programs\Python\Python39

PHP - Check if the page run on Mobile or Desktop browser

This script should work:

<?php

        $useragent=$_SERVER['HTTP_USER_AGENT'];
        if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4)))

        { 
            //echo "mobile";
        }
        else{
           // echo "desktop";
        }
?>

I came across it here: http://detectmobilebrowsers.com/ .

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)

It is because your Maven not able to find settings file. If deleting .m2 not work, try below solution

Go to your JOB configuration

than to the Build section

Add build step :- Invoke top level maven target and fill Maven version and Goal

than click on Advance button and mention settings file path as mention in image enter image description here

Gradle sync failed: failed to find Build Tools revision 24.0.0 rc1

  1. Follow the below procedure to solve the error.

  2. Go to File -> Project structure.

enter image description here

  1. From the drop down box, you will know all the version of build tools that are installed in your android studio.
  2. Look for a higher version. If Gradle cannot find 24.0.0, check if 24.0.1 is present in drop down.
  3. Do a complete code search. Find all the places where "24.0.0" is found. Replace it with "24.0.1"
  4. Do a gradle sync.

How to get primary key column in Oracle?

Select constraint_name,constraint_type from user_constraints where table_name** **= ‘TABLE_NAME’ ;

(This will list the primary key and then)

Select column_name,position from user_cons_cloumns where constraint_name=’PK_XYZ’; 

(This will give you the column, here PK_XYZ is the primay key name)

codeigniter, result() vs. result_array()

result_array() returns Associative Array type data. Returning pure array is slightly faster than returning an array of objects. result() is recursive in that it returns an std class object where as result_array() just returns a pure array, so result_array() would be choice regarding performance.

How to tell bash that the line continues on the next line

The character is a backslash \

From the bash manual:

The backslash character ‘\’ may be used to remove any special meaning for the next character read and for line continuation.

VBA array sort function?

This is what I use to sort in memory - it can easily be expanded to sort an array.

Sub sortlist()

    Dim xarr As Variant
    Dim yarr As Variant
    Dim zarr As Variant

    xarr = Sheets("sheet").Range("sing col range")
    ReDim yarr(1 To UBound(xarr), 1 To 1)
    ReDim zarr(1 To UBound(xarr), 1 To 1)

    For n = 1 To UBound(xarr)
        zarr(n, 1) = 1
    Next n

    For n = 1 To UBound(xarr) - 1
        y = zarr(n, 1)
        For a = n + 1 To UBound(xarr)
            If xarr(n, 1) > xarr(a, 1) Then
                y = y + 1
            Else
                zarr(a, 1) = zarr(a, 1) + 1
            End If
        Next a
        yarr(y, 1) = xarr(n, 1)
    Next n

    y = zarr(UBound(xarr), 1)
    yarr(y, 1) = xarr(UBound(xarr), 1)

    yrng = "A1:A" & UBound(yarr)
    Sheets("sheet").Range(yrng) = yarr

End Sub

how do you insert null values into sql server

If you're using SSMS (or old school Enterprise Manager) to edit the table directly, press CTRL+0 to add a null.

Change the URL in the browser without loading the new page using JavaScript

What is working for me is - history.replaceState() function which is as follows -

history.replaceState(data,"Title of page"[,'url-of-the-page']);

This will not reload page, you can make use of it with event of javascript

How do I sort an NSMutableArray with custom objects in it?

iOS 4 blocks will save you :)

featuresArray = [[unsortedFeaturesArray sortedArrayUsingComparator: ^(id a, id b)  
{
    DMSeatFeature *first = ( DMSeatFeature* ) a;
    DMSeatFeature *second = ( DMSeatFeature* ) b;

    if ( first.quality == second.quality )
        return NSOrderedSame;
    else
    {
        if ( eSeatQualityGreen  == m_seatQuality || eSeatQualityYellowGreen == m_seatQuality || eSeatQualityDefault  == m_seatQuality )
        {
            if ( first.quality < second.quality )
                return NSOrderedAscending;
            else
                return NSOrderedDescending;
        }
        else // eSeatQualityRed || eSeatQualityYellow
        {
            if ( first.quality > second.quality )
                return NSOrderedAscending;
            else
                return NSOrderedDescending;
        } 
    }
}] retain];

http://sokol8.blogspot.com/2011/04/sorting-nsarray-with-blocks.html a bit of description

How can I show a hidden div when a select option is selected?

Being more generic, passing values from calling element (which is easier to maintain).

  • Specify the start condition in the text field (display:none)
  • Pass the required option value to show/hide on ("Other")
  • Pass the target and field to show/hide ("TitleOther")

_x000D_
_x000D_
function showHideEle(selectSrc, targetEleId, triggerValue) { _x000D_
 if(selectSrc.value==triggerValue) {_x000D_
  document.getElementById(targetEleId).style.display = "inline-block";_x000D_
 } else {_x000D_
  document.getElementById(targetEleId).style.display = "none";_x000D_
 }_x000D_
} 
_x000D_
<select id="Title"_x000D_
   onchange="showHideEle(this, 'TitleOther', 'Other')">_x000D_
      <option value="">-- Choose</option>_x000D_
      <option value="Mr">Mr</option>_x000D_
      <option value="Mrs">Mrs</option>_x000D_
      <option value="Miss">Miss</option>_x000D_
      <option value="Other">Other --&gt;</option>      _x000D_
</select>_x000D_
<input id="TitleOther" type="text" title="Title other" placeholder="Other title" _x000D_
    style="display:none;"/>
_x000D_
_x000D_
_x000D_

How do I sort a dictionary by value?

Beside using builtin module etc, i try solve it manually..... first i made a function whose job is to returning minimal value each items of the dict :

def returnminDict(_dct):
    dict_items = _dct.items()
    list_items = list(dict_items)
    init_items = list_items[0]
    for i in range(len(list_items)):
        if list_items[i][1] > init_items[1]:
           continue
        else:
           init_items = list_items[i]
    return init_items

Second, now we have a function which return item that has minimal value, then i make a new dict then loop over the dict :

def SelectDictSort(_dct):
    new_dict = {}
    while _dct:
        mindict = returnminDict(_dct)
        new_dict.update(dict((mindict,)))
        _dct.pop(mindict[0])
    return new_dict

i try this SelectDictSort({2: 5, 5: 1, 4: 3, 1: 1, 0: 1, 9: 2, 8: 2}) will return :

{0: 1, 1: 1, 5: 1, 8: 2, 9: 2, 4: 3, 2: 5}

Hmmm... i dont know which is correct but this what i have tried....

(updated code from retrun new_dct to return new_dict)

How to implement OnFragmentInteractionListener

In addition to @user26409021 's answer, If you have added a ItemFragment, The message in the ItemFragment is;

Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener} interface.

And You should add in your activity;

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener, ItemFragment.OnListFragmentInteractionListener {

//the code is omitted

 public void onListFragmentInteraction(DummyContent.DummyItem uri){
    //you can leave it empty
}

Here the dummy item is what you have on the bottom of your ItemFragment

Windows 7 environment variable not working in path

%M2% and %JAVA_HOME% need to be added to a PATH variable in the USER variables, not the SYSTEM variables.

Sequence Permission in Oracle

Just another bit. in some case i found no result on all_tab_privs! i found it indeed on dba_tab_privs. I think so that this last table is better to check for any grant available on an object (in case of impact analysis). The statement becomes:

    select * from dba_tab_privs where table_name = 'sequence_name';

how to set the query timeout from SQL connection string

See:- ConnectionStrings content on this subject. There is no default command timeout property.

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op

I was getting this warning when I wanted to show a popup (bootstrap modal) on success/failure callback of Ajax request. Additionally setState was not working and my popup modal was not being shown.

Below was my situation-

<Component /> (Containing my Ajax function)
    <ChildComponent />
        <GrandChildComponent /> (Containing my PopupModal, onSuccess callback)

I was calling ajax function of component from grandchild component passing a onSuccess Callback (defined in grandchild component) which was setting state to show popup modal.

I changed it to -

<Component /> (Containing my Ajax function, PopupModal)
    <ChildComponent />
        <GrandChildComponent /> 

Instead I called setState (onSuccess Callback) to show popup modal in component (ajax callback) itself and problem solved.

In 2nd case: component was being rendered twice (I had included bundle.js two times in html).

Get Wordpress Category from Single Post

<div class="post_category">
        <?php $category = get_the_category();
             $allcategory = get_the_category(); 
        foreach ($allcategory as $category) {
        ?>
           <a class="btn"><?php echo $category->cat_name;; ?></a>
        <?php 
        }
        ?>
 </div>

How do I create a constant in Python?

There's no const keyword as in other languages, however it is possible to create a Property that has a "getter function" to read the data, but no "setter function" to re-write the data. This essentially protects the identifier from being changed.

Here is an alternative implementation using class property:

Note that the code is far from easy for a reader wondering about constants. See explanation below

def constant(f):
    def fset(self, value):
        raise TypeError
    def fget(self):
        return f()
    return property(fget, fset)

class _Const(object):
    @constant
    def FOO():
        return 0xBAADFACE
    @constant
    def BAR():
        return 0xDEADBEEF

CONST = _Const()

print CONST.FOO
##3131964110

CONST.FOO = 0
##Traceback (most recent call last):
##    ...
##    CONST.FOO = 0
##TypeError: None

Code Explanation:

  1. Define a function constant that takes an expression, and uses it to construct a "getter" - a function that solely returns the value of the expression.
  2. The setter function raises a TypeError so it's read-only
  3. Use the constant function we just created as a decoration to quickly define read-only properties.

And in some other more old-fashioned way:

(The code is quite tricky, more explanations below)

class _Const(object):
    @apply
    def FOO():
        def fset(self, value):
            raise TypeError
        def fget(self):
            return 0xBAADFACE
        return property(**locals())

CONST = _Const()

print CONST.FOO
##3131964110

CONST.FOO = 0
##Traceback (most recent call last):
##    ...
##    CONST.FOO = 0
##TypeError: None

Note that the @apply decorator seems to be deprecated.

  1. To define the identifier FOO, firs define two functions (fset, fget - the names are at my choice).
  2. Then use the built-in property function to construct an object that can be "set" or "get".
  3. Note hat the property function's first two parameters are named fset and fget.
  4. Use the fact that we chose these very names for our own getter & setter and create a keyword-dictionary using the ** (double asterisk) applied to all the local definitions of that scope to pass parameters to the property function

Delete a row from a table by id

How about:

function deleteRow(rowid)  
{   
    var row = document.getElementById(rowid);
    row.parentNode.removeChild(row);
}

And, if that fails, this should really work:

function deleteRow(rowid)  
{   
    var row = document.getElementById(rowid);
    var table = row.parentNode;
    while ( table && table.tagName != 'TABLE' )
        table = table.parentNode;
    if ( !table )
        return;
    table.deleteRow(row.rowIndex);
}

IntelliJ IDEA "The selected directory is not a valid home for JDK"

I had the same issue. But I figured it out by choosing this path:

First at all, you need to select the C:\ folder. Then, you select Program Files. After it, you select java, and finally the jdk you downloaded. In my case, I downloaded the JDK1.8.0_60 version.

To resume the path:

C:\Program Files\java\jdk1.8.0_60

After you are done with it, you can click on the button next. Then you select the create project from templates. This will create a java application with a main() method. After it, you click next to create the name of you project.

I hope this helps you.

Trying to merge 2 dataframes but get ValueError

this simple solution works for me

    final = pd.concat([df, rankingdf], axis=1, sort=False)

but you may need to drop some duplicate column first.

How to parse JSON with VBA without external libraries?

I've found this script example useful (from http://www.mrexcel.com/forum/excel-questions/898899-json-api-excel.html#post4332075 ):

Sub getData()

    Dim Movie As Object
    Dim scriptControl As Object

    Set scriptControl = CreateObject("MSScriptControl.ScriptControl")
    scriptControl.Language = "JScript"

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "http://www.omdbapi.com/?t=frozen&y=&plot=short&r=json", False
        .send
        Set Movie = scriptControl.Eval("(" + .responsetext + ")")
        .abort
        With Sheets(2)
            .Cells(1, 1).Value = Movie.Title
            .Cells(1, 2).Value = Movie.Year
            .Cells(1, 3).Value = Movie.Rated
            .Cells(1, 4).Value = Movie.Released
            .Cells(1, 5).Value = Movie.Runtime
            .Cells(1, 6).Value = Movie.Director
            .Cells(1, 7).Value = Movie.Writer
            .Cells(1, 8).Value = Movie.Actors
            .Cells(1, 9).Value = Movie.Plot
            .Cells(1, 10).Value = Movie.Language
            .Cells(1, 11).Value = Movie.Country
            .Cells(1, 12).Value = Movie.imdbRating
        End With
    End With

End Sub

Count number of vector values in range with R

There are also the %<% and %<=% comparison operators in the TeachingDemos package which allow you to do this like:

sum( 2 %<% x %<% 5 )
sum( 2 %<=% x %<=% 5 )

which gives the same results as:

sum( 2 < x & x < 5 )
sum( 2 <= x & x <= 5 )

Which is better is probably more a matter of personal preference.

Download multiple files with a single action

Easiest way would be to serve the multiple files bundled up into a ZIP file.

I suppose you could initiate multiple file downloads using a bunch of iframes or popups, but from a usability standpoint, a ZIP file is still better. Who wants to click through ten "Save As" dialogs that the browser will bring up?

Predefined type 'System.ValueTuple´2´ is not defined or imported

It's part of the .NET Framework 4.7.

As long as you don't target the above framework or higher (or .NET Core 2.0 / .NET Standard 2.0), you'll need to reference ValueTuple. Do this by adding the System.ValueTuple NuGet Package

SQL Server : GROUP BY clause to get comma-separated values

SELECT  [ReportId], 
        SUBSTRING(d.EmailList,1, LEN(d.EmailList) - 1) EmailList
FROM
        (
            SELECT DISTINCT [ReportId]
            FROM Table1
        ) a
        CROSS APPLY
        (
            SELECT [Email] + ', ' 
            FROM Table1 AS B 
            WHERE A.[ReportId] = B.[ReportId]
            FOR XML PATH('')
        ) D (EmailList) 

SQLFiddle Demo

How to check if a string is numeric?

public static boolean isNumeric(String string) {
    if (string == null || string.isEmpty()) {
        return false;
    }
    int i = 0;
    int stringLength = string.length();
    if (string.charAt(0) == '-') {
        if (stringLength > 1) {
            i++;
        } else {
            return false;
        }
    }
    if (!Character.isDigit(string.charAt(i))
            || !Character.isDigit(string.charAt(stringLength - 1))) {
        return false;
    }
    i++;
    stringLength--;
    if (i >= stringLength) {
        return true;
    }
    for (; i < stringLength; i++) {
        if (!Character.isDigit(string.charAt(i))
                && string.charAt(i) != '.') {
            return false;
        }
    }
    return true;
}

JavaScript TypeError: Cannot read property 'style' of null

simply I think you are missing a single quote in your code

if ((hr==20)) document.write("Good Night"); document.getElementById('Night"here").style.display=''

it should be like this

if ((hr==20)) document.write("Good Night"); document.getElementById('Night').style.display=''

Error type 3 Error: Activity class {} does not exist

Got to android/app/build.gradle and search for

 buildTypes {
     ....
 }

You might have something like

buildTypes {
    debug {
        ...
    }
    release {
        ...
    }
    customBuildType {
        ...
    }
}

Chose the buildType you want to start and then start the App the following

react-native run-android --variant=[buildType] --appIdSuffix '[buildType]'

So,

react-native run-android --variant=debug --appIdSuffix 'debug'

String comparison using '==' vs. 'strcmp()'

if ($password === $password2) { ... } is not a safe thing to do when comparing passwords or password hashes where one of the inputs is user controlled.
In that case it creates a timing oracle allowing an attacker to derive the actual password hash from execution time differences.
Use if (hash_equals($password, $password2)) { ... } instead, because hash_equals performs "timing attack safe string comparison".

How to get all options in a drop-down list by Selenium WebDriver using C#?

 WebElement element = driver.findElement(By.id("inst_state"));
        Select s = new Select(element);
        List <WebElement> elementcount = s.getOptions();

        System.out.println(elementcount.size());
        for(int i=0 ;i<elementcount.size();i++)
        {
            String value = elementcount.get(i).getText();
            System.out.println(value);

        }

How can I change the default Mysql connection timeout when connecting through python?

I know this is an old question but just for the record this can also be done by passing appropriate connection options as arguments to the _mysql.connect call. For example,

con = _mysql.connect(host='localhost', user='dell-pc', passwd='', db='test',
          connect_timeout=1000)

Notice the use of keyword parameters (host, passwd, etc.). They improve the readability of your code.

For detail about different arguments that you can pass to _mysql.connect, see MySQLdb API documentation

how to count the spaces in a java string?

Your code will count the number of tabs and not the number of spaces. Also, the number of tabs will be one less than arr.length.

No 'Access-Control-Allow-Origin' header is present on the requested resource- AngularJS

This is a CORS issue. There are some settings you can change in angular - these are the ones I typically set in the Angular .config method (not all are related to CORS):

$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.withCredentials = true;
delete $httpProvider.defaults.headers.common["X-Requested-With"];
$httpProvider.defaults.headers.common["Accept"] = "application/json";
$httpProvider.defaults.headers.common["Content-Type"] = "application/json";

You also need to configure your webservice - the details of this will depend on the server side language you are using. If you use a network monitoring tool you will see it sends an OPTIONS request initially. Your server needs to respond appropriately to allow the CORS request.

The reason it works in your brower is because it isn't make a cross-origin request - whereas your Angular code is.

How to escape single quotes in MySQL

If you use prepared statements, the driver will handle any escaping. For example (Java):

Connection conn = DriverManager.getConnection(driverUrl);
conn.setAutoCommit(false);
PreparedStatement prepped = conn.prepareStatement("INSERT INTO tbl(fileinfo) VALUES(?)");
String line = null;
while ((line = br.readLine()) != null) {
    prepped.setString(1, line);
    prepped.executeQuery();
}
conn.commit();
conn.close();

How to make a machine trust a self-signed Java application

SERIOUS DISCLAIMER

This solution has a serious security flaw. Please use at your own risk.
Have a look at the comments on this post, and look at all the answers to this question.


OK, I had to go to the customer premises and found a solution. I:

  • Exported the keystore that holds the signing keys in PKCS #12 format
  • Opened control panel Java -> Security tab
  • Clicked Manage certificates
  • Imported this new keystore as a secure site CA

Then I opened the JAWS application without any warning. This is a little bit cumbersome, but much cheaper than buying a signed certificate!

How can I generate a 6 digit unique number?

I would use an algorithm, brute force could be as follows:

First time through loop: Generate a random number between 100,000 through 999,999 and call that x1

Second time through the loop Generate a random number between 100,000 and x1 call this xt2, then generate a random number between x1 and 999,999 call this xt3, then randomly choose x2 or x3, call this x2

Nth time through the loop Generate random number between 100,000 and x1, x1 and x2, and x2 through 999,999 and so forth...

watch out for endpoints, also watch out for x1

How to list records with date from the last 10 days?

Just generalising the query if you want to work with any given date instead of current date:

SELECT Table.date
  FROM Table 
  WHERE Table.date > '2020-01-01'::date - interval '10 day'

How to generate graphs and charts from mysql database in php

I use highcharts. They are very interactive (and very fancy I might add). You do have to get a little creative to access data from MySQL database, but if you have a general understanding of JavaScript and PHP, you should have no problems.

View a file in a different Git branch without changing branches

This should work:

git show branch:file

Where branch can be any ref (branch, tag, HEAD, ...) and file is the full path of the file. To export it you could use

git show branch:file > exported_file

You should also look at VonC's answers to some related questions:

UPDATE 2015-01-19:

Nowadays you can use relative paths with git show a1b35:./file.txt.

Add Variables to Tuple

Another tactic not yet mentioned is using appending to a list, and then converting the list to a tuple at the end:

mylist = []
for x in range(5):
    mylist.append(x)
mytuple = tuple(mylist)
print mytuple

returns

(0, 1, 2, 3, 4)

I sometimes use this when I have to pass a tuple as a function argument, which is often necessary for the numpy functions.

Xcode Error: "The app ID cannot be registered to your development team."

My problem was I was modifying the settings for the wrong version of my app.

enter image description here

I had "Debug" selected instead of "Release", so my bundle identifier was not accurate when it came time to Archive.

SVN Repository Search

Just a note, FishEye (and a lot of other Atlassian products) have a $10 Starter Editions, which in the case of FishEye gives you 5 repositories and access for up to 10 committers. The money goes to charity in this case.

www.atlassian.com/starter

Jquery ajax call click event submit button

You did not add # before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.

See documentation: http://api.jquery.com/category/selectors/
its your friend.

Try this:

It seems that id: $("#Shareitem").val() is wrong if you want to pass the value of

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

you need to change this line:

id: $("#Shareitem").val()

by

id: $("#id").val()

All together:

 <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script>
    $(document).ready(function(){
      $("#Shareitem").click(function(e){
          e.preventDefault();
        $.ajax({type: "POST",
                url: "/imball-reagens/public/shareitem",
                data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
                success:function(result){
          $("#sharelink").html(result);
        }});
      });
    });
    </script>

Where's my JSON data in my incoming Django request?

If you are posting JSON to Django, I think you want request.body (request.raw_post_data on Django < 1.4). This will give you the raw JSON data sent via the post. From there you can process it further.

Here is an example using JavaScript, jQuery, jquery-json and Django.

JavaScript:

var myEvent = {id: calEvent.id, start: calEvent.start, end: calEvent.end,
               allDay: calEvent.allDay };
$.ajax({
    url: '/event/save-json/',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: $.toJSON(myEvent),
    dataType: 'text',
    success: function(result) {
        alert(result.Result);
    }
});

Django:

def save_events_json(request):
    if request.is_ajax():
        if request.method == 'POST':
            print 'Raw Data: "%s"' % request.body   
    return HttpResponse("OK")

Django < 1.4:

  def save_events_json(request):
    if request.is_ajax():
        if request.method == 'POST':
            print 'Raw Data: "%s"' % request.raw_post_data
    return HttpResponse("OK")

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

Can JavaScript connect with MySQL?

Client-side JavaScript cannot access MySQL without some kind of bridge. But the above bold statements that JavaScript is just a client-side language are incorrect -- JavaScript can run client-side and server-side, as with Node.js.

Node.js can access MySQL through something like https://github.com/sidorares/node-mysql2

You might also develop something using Socket.IO

Did you mean to ask whether a client-side JS app can access MySQL? I am not sure if such libraries exist, but they are possible.

EDIT: Since writing, we now have MySQL Cluster:

The MySQL Cluster JavaScript Driver for Node.js is just what it sounds like it is – it’s a connector that can be called directly from your JavaScript code to read and write your data. As it accesses the data nodes directly, there is no extra latency from passing through a MySQL Server and need to convert from JavaScript code//objects into SQL operations. If for some reason, you’d prefer it to pass through a MySQL Server (for example if you’re storing tables in InnoDB) then that can be configured.

How to make inactive content inside a div?

Without using an overlay, you can use pointer-events: none on the div in CSS, but this does not work in IE or Opera.

div.disabled
{
  pointer-events: none;

  /* for "disabled" effect */
  opacity: 0.5;
  background: #CCC;
}

Reference

where is gacutil.exe?

You can use the version in Windows SDK but sometimes it might not be the same version of the .NET Framework your using, getting you the following error:

Microsoft (R) .NET Global Assembly Cache Utility. Version 3.5.21022.8 Copyright (c) Microsoft Corporation. All rights reserved. Failure adding assembly to the cache: This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.

In .NET 4.0 you'll need to search inside Microsoft SDK v8.0A, e.g.: C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools (in my case I only have the 32 bit version installed by Visual Studio 2012).

Push method in React Hooks (useState)?

// Save search term state to React Hooks with spread operator and wrapper function

// Using .concat(), no wrapper function (not recommended)
setSearches(searches.concat(query))

// Using .concat(), wrapper function (recommended)
setSearches(searches => searches.concat(query))

// Spread operator, no wrapper function (not recommended)
setSearches([...searches, query])

// Spread operator, wrapper function (recommended)
setSearches(searches => [...searches, query])

https://medium.com/javascript-in-plain-english/how-to-add-to-an-array-in-react-state-3d08ddb2e1dc

Failed to start mongod.service: Unit mongod.service not found

As per documentation:

Run this command to reload the daemon:

sudo systemctl daemon-reload

After this you need to restart the mongod service:

sudo systemctl start mongod

To verify that MongoDB has started, run:

sudo systemctl status mongod

To ensure that MongoDB will start following a system reboot, run:

sudo systemctl enable mongod

Java: random long number in 0 <= x < n range

If you want a uniformly distributed pseudorandom long in the range of [0,m), try using the modulo operator and the absolute value method combined with the nextLong() method as seen below:

Math.abs(rand.nextLong()) % m;

Where rand is your Random object.

The modulo operator divides two numbers and outputs the remainder of those numbers. For example, 3 % 2 is 1 because the remainder of 3 and 2 is 1.

Since nextLong() generates a uniformly distributed pseudorandom long in the range of [-(2^48),2^48) (or somewhere in that range), you will need to take the absolute value of it. If you don't, the modulo of the nextLong() method has a 50% chance of returning a negative value, which is out of the range [0,m).

What you initially requested was a uniformly distributed pseudorandom long in the range of [0,100). The following code does so:

Math.abs(rand.nextLong()) % 100;

Bootstrap modal z-index

I found this question as I had a similar problem. While data-backdrop does "solve" the issue; I found another problem in my markup.

I had the button which launched this modal and the modal dialog itself was in the footer. The problem is that the footer was defined as navbar_fixed_bottom, and that contained position:fixed.

After I moved the dialog outside of the fixed section, everything worked as expected.

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

I think your EmpID column is string and you forget to use ' ' in your value.

Because when you write EmpID=" + id.Text, your command looks like EmpID = 12345 instead of EmpID = '12345'

Change your SqlCommand to

SqlCommand cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID='" + id.Text +"'", con);

Or as a better way you can (and should) always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.

SqlCommand cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con);
cmd.Parameters.AddWithValue("@id", id.Text);

I think your EmpID column keeps your employee id's, so it's type should some numerical type instead of character.

Visual Studio 2012 Web Publish doesn't copy files

I have (had) the same problem for several projects. The only ones hit seem to be web projects. Deleting and recreating the profile solves the problem only once. Additionaly, comparing the publishxml generated yields no differences, so it does not seem related to the profile at all.

The workaround mentioned by OP to change build problems back and forth seems the only reliable solution at this time.

Populating a database in a Laravel migration file

I know this is an old post but since it comes up in a google search I thought I'd share some knowledge here. @erin-geyer pointed out that mixing migrations and seeders can create headaches and @justamartin countered that sometimes you want/need data to be populated as part of your deployment.

I'd go one step further and say that sometimes it is desirable to be able to roll out data changes consistently so that you can for example deploy to staging, see that all is well, and then deploy to production with confidence of the same results (and not have to remember to run some manual step).

However, there is still value in separating out the seed and the migration as those are two related but distinct concerns. Our team has compromised by creating migrations which call seeders. This looks like:

public function up()
{
    Artisan::call( 'db:seed', [
        '--class' => 'SomeSeeder',
        '--force' => true ]
    );
}

This allows you to execute a seed one time just like a migration. You can also implement logic that prevents or augments behavior. For example:

public function up()
{
    if ( SomeModel::count() < 10 )
    {
        Artisan::call( 'db:seed', [
            '--class' => 'SomeSeeder',
            '--force' => true ]
        );
    }
}

This would obviously conditionally execute your seeder if there are less than 10 SomeModels. This is useful if you want to include the seeder as a standard seeder that executed when you call artisan db:seed as well as when you migrate so that you don't "double up". You may also create a reverse seeder so that rollbacks works as expected, e.g.

public function down()
{
    Artisan::call( 'db:seed', [
        '--class' => 'ReverseSomeSeeder',
        '--force' => true ]
    );
}

The second parameter --force is required to enable to seeder to run in a production environment.

How to darken a background using CSS?

Use an :after psuedo-element:

.overlay {
    position: relative;
    transition: all 1s;
}

.overlay:after {
    content: '\A';
    position: absolute;
    width: 100%; 
    height:100%;
    top:0; 
    left:0;
    background:rgba(0,0,0,0.5);
    opacity: 1;
    transition: all 0.5s;
    -webkit-transition: all 0.5s;
    -moz-transition: all 0.5s;
}
.overlay:hover:after {
    opacity: 0;
}

Check out my pen >

http://codepen.io/craigocurtis/pen/KzXYad

How can I disable ARC for a single file in a project?

GO to App -> then Targets -> Build Phases -> Compile Source

Now, Select the file in which you want to disable ARC

paste this snippet "-fno-objc-arc" After pasting press ENTER

in each file where you want to disable ARC.

What are the ascii values of up down left right?

You can utilzed the special function for activating the navigation for your programming purpose. Below is the sample code for it.

   void Specialkey(int key, int x, int y)
    {
    switch(key)
    {
    case GLUT_KEY_UP: 
/*Do whatever you want*/        
         break; 
    case GLUT_KEY_DOWN: 
/*Do whatever you want*/
                 break;
    case GLUT_KEY_LEFT:
/*Do whatever you want*/
                 break;
    case GLUT_KEY_RIGHT:
/*Do whatever you want*/
                 break;
    }

    glutPostRedisplay();
    }

Add this to your main function

glutSpecialFunc(Specialkey);

Hope this will to solve the problem!

Your password does not satisfy the current policy requirements

You have to change MySQL password policy to LOW.

login as root

mysql -u root -p

change policy

SET GLOBAL validate_password_policy=LOW;

or

SET GLOBAL validate_password_policy=0;

exit

exit

restart MySQL service

sudo service mysql restart

You have to change the MySQL password policy to Low = 0 / Medium = 1 / High = 2.

SET GLOBAL validate_password_policy=0;
SET GLOBAL validate_password_policy=1;    
SET GLOBAL validate_password_policy=2;

How to build and run Maven projects after importing into Eclipse IDE

  1. Right Click on your project
  2. Go to Maven>Update Project
  3. Check the Force Update of Snapshots/Releases Checkbox
  4. Click Ok

That's all. You can see progression of build in left below corner.

Why is there no SortedList in Java?

Because the concept of a List is incompatible with the concept of an automatically sorted collection. The point of a List is that after calling list.add(7, elem), a call to list.get(7) will return elem. With an auto-sorted list, the element could end up in an arbitrary position.

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

Simply put: NONE.

Feel free to downvote, but I still think there are no real benefits over non-REST HTTP. All current answers are invalid. Arguments from the currently most voted answer:

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

1. Simple

With REST you need additional communication layer for your server-side and client-side scripts => it's actually more complicated than use of non-REST HTTP.

2. Caching

Caching can be controlled by HTTP headers sent by server. REST does not add any features missing in non-REST.

3. Organization

REST does not help you organize things. It forces you to use API supported by server-side library you are using. You can organize your application the same way (or better) when you are using non-REST approach. E.g. see Model-View-Controller or MVC routing.

4. Easy to use/implement

Not true at all. It all depends on how well you organize and document your application. REST will not magically make your application better.

How to add text to JFrame?

Instead of wasting your time to design a JFrame just to display a error message, you can use an JOptionPane which is by default modal:

import javax.swing.JOptionPane;

public class Main {

    public static void main(String[] args) {
        JOptionPane.showMessageDialog(null, "Your message goes here!","Message", JOptionPane.ERROR_MESSAGE);
    }
}

enter image description here

P.S. Stop using Windowbuilder if you want to learn Swing.

unable to set private key file: './cert.pem' type PEM

I had the same issue, eventually I found a solution that works without splitting the file, by following Petter Ivarrson's answer

My problem was when converting .p12 certificate to .pem. I used:

openssl pkcs12 -in cert.p12 -out cert.pem

This converts and exports all certificates (CA + CLIENT) together with a private key into one file.

The problem was when I tried to verify if the hashes of certificate and key are matching by running:

// Get certificate HASH
openssl x509 -noout -modulus -in cert.pem | openssl md5

// Get private key HASH
openssl rsa -noout -modulus -in cert.pem | openssl md5

This displayed different hashes and that was the reason CURL failed. See here: https://michaelheap.com/curl-58-unable-to-set-private-key-file-server-key-type-pem/

I guess that was because all certificates are inside a file (CA + CLIENT) and CURL takes CA certificate instead of CLIENT one. Because CA is first in the list.

So the solution was to export only CLIENT certificate together with private key:

openssl pkcs12 -in cert.p12 -out cert.pem -clcerts
``

Now when I re-run the verification:
```sh
openssl x509 -noout -modulus -in cert.pem | openssl md5
openssl rsa -noout -modulus -in cert.pem | openssl md5

HASHES MATCHED !!!

So I was able to make a curl request by running

curl -ivk --cert ./cert.pem:KeyChoosenByMeWhenIrunOpenSSL https://thesite.com

without problems!!!

That being said... I think the best solution is to split the certificates into separate file and use them separately like Petter Ivarsson wrote:

curl --insecure --key key.pem --cacert ca.pem --cert client.pem:KeyChoosenByMeWhenIrunOpenSSL https://thesite.com

CSS to stop text wrapping under image

If you want the margin-left to work on a span element you'll need to make it display: inline-block or display:block as well.

How to convert all elements in an array to integer in JavaScript?

The point against parseInt-approach:

There's no need to use lambdas and/or give radix parameter to parseInt, just use parseFloat or Number instead.


Reasons:

  1. It's working:

    var src = "1,2,5,4,3";
    var ids = src.split(',').map(parseFloat); // [1, 2, 5, 4, 3]
    
    var obj = {1: ..., 3: ..., 4: ..., 7: ...};
    var keys= Object.keys(obj); // ["1", "3", "4", "7"]
    var ids = keys.map(parseFloat); // [1, 3, 4, 7]
    
    var arr = ["1", 5, "7", 11];
    var ints= arr.map(parseFloat); // [1, 5, 7, 11]
    ints[1] === "5" // false
    ints[1] === 5   // true
    ints[2] === "7" // false
    ints[2] === 7   // true
    
  2. It's shorter.

  3. It's a tiny bit quickier and takes advantage of cache, when parseInt-approach - doesn't:

      // execution time measure function
      // keep it simple, yeah?
    > var f = (function (arr, c, n, m) {
          var i,t,m,s=n();
          for(i=0;i++<c;)t=arr.map(m);
          return n()-s
      }).bind(null, "2,4,6,8,0,9,7,5,3,1".split(','), 1000000, Date.now);
    
    > f(Number) // first launch, just warming-up cache
    > 3971 // nice =)
    
    > f(Number)
    > 3964 // still the same
    
    > f(function(e){return+e})
    > 5132 // yup, just little bit slower
    
    > f(function(e){return+e})
    > 5112 // second run... and ok.
    
    > f(parseFloat)
    > 3727 // little bit quicker than .map(Number)
    
    > f(parseFloat)
    > 3737 // all ok
    
    > f(function(e){return parseInt(e,10)})
    > 21852 // awww, how adorable...
    
    > f(function(e){return parseInt(e)})
    > 22928 // maybe, without '10'?.. nope.
    
    > f(function(e){return parseInt(e)})
    > 22769 // second run... and nothing changes.
    
    > f(Number)
    > 3873 // and again
    > f(parseFloat)
    > 3583 // and again
    > f(function(e){return+e})
    > 4967 // and again
    
    > f(function(e){return parseInt(e,10)})
    > 21649 // dammit 'parseInt'! >_<
    

Notice: In Firefox parseInt works about 4 times faster, but still slower than others. In total: +e < Number < parseFloat < parseInt

Counter inside xsl:for-each loop

Try inserting <xsl:number format="1. "/><xsl:value-of select="."/><xsl:text> in the place of ???.

Note the "1. " - this is the number format. More info: here

How to extract custom header value in Web API message handler?

For ASP.NET you can get the header directly from parameter in controller method using this simple library/package. It provides a [FromHeader] attribute just like you have in ASP.NET Core :). For example:

    ...
    using RazHeaderAttribute.Attributes;

    [Route("api/{controller}")]
    public class RandomController : ApiController 
    {
        ...
        // GET api/random
        [HttpGet]
        public IEnumerable<string> Get([FromHeader("pages")] int page, [FromHeader] string rows)
        {
            // Print in the debug window to be sure our bound stuff are passed :)
            Debug.WriteLine($"Rows {rows}, Page {page}");
            ...
        }
    }

Python, Matplotlib, subplot: How to set the axis range?

If you have multiple subplots, i.e.

fig, ax = plt.subplots(4, 2)

You can use the same y limits for all of them. It gets limits of y ax from first plot.

plt.setp(ax, ylim=ax[0,0].get_ylim())

How to create large PDF files (10MB, 50MB, 100MB, 200MB, 500MB, 1GB, etc.) for testing purposes?

Partly it depends on what you are trying to increase the size of... number of pages, number of images, size of a single image. In my experience, the vast bulk (90%+) of any given 'large' PDF file will be the images.

You could try using a pro product like Adobe InDesign to quickly build a large project and export it as a PDF.

Adobe Acrobat Pro has built-in tools to optimize PDF files -- you try using the tools to 'un-optimize' your file. :)

Git cli: get user info from username

git config user.name
git config user.email

I believe these are the commands you are looking for.

Here is where I found them: http://alvinalexander.com/git/git-show-change-username-email-address

warning: Insecure world writable dir /usr/local/bin in PATH, mode 040777

If you're running OSX and getting this often, another good thing to consider is to use a built-in OSX permissions fixing tool. If you didn't change the mode of your directories, something else did and there's a chance that other directories have overgenerous permissions as well - this tool will reset them back all to factory defaults, which is a good security idea. There's a great guide on the Apple stackextange about this very process.

Relational Database Design Patterns?

Depends what you mean by a pattern. If you're thinking Person/Company/Transaction/Product and such, then yes - there are a lot of generic database schemas already available.

If you're thinking Factory, Singleton... then no - you don't need any of these as they're too low level for DB programming.

If you're thinking database object naming, then it's under the category of conventions, not design per se.

BTW, S.Lott, one-to-many and many-to-many relationships aren't "patterns". They're the basic building blocks of the relational model.

Visual Studio can't 'see' my included header files

I know this is an older question, but none of the above answers worked for me. In my case, the issue turned out to be that I had absolute include paths but without drive letters. Compilation was fine, but Visual Studio couldn't find an include file when I right-clicked and tried to open it. Adding the drive letters to my include paths corrected the problem.

I would never recommend hard-coding drive letters in any aspect of your project files; either use relative paths, macros, environment variables, or some mix of the tree for any permanent situation. However, in this case, I'm working in some temporary projects where absolute paths were necessary in the short term. Not being able to right-click to open the files was extremely frustrating, and hopefully this will help others.

How to install VS2015 Community Edition offline

Go to https://www.visualstudio.com/en-us/downloads/download-visual-studio-vs.aspx

Navigate to "Visual studio downloads", select "Visual studio 2015"

enter image description here

Next, choose format "ISO"

enter image description here

Reason for Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

Your query will work in MYSQL if you set to disable ONLY_FULL_GROUP_BY server mode (and by default It is). But in this case, you are using different RDBMS. So to make your query work, add all non-aggregated columns to your GROUP BY clause, eg

SELECT col1, col2, SUM(col3) totalSUM
FROM tableName
GROUP BY col1, col2

Non-Aggregated columns means the column is not pass into aggregated functions like SUM, MAX, COUNT, etc..

Running PHP script from the command line

I was looking for a resolution to this issue in Windows, and it seems to be that if you don't have the environments vars ok, you need to put the complete directory. For eg. with a file in the same directory than PHP:

F:\myfolder\php\php.exe -f F:\myfolder\php\script.php

Fatal error: Call to a member function bind_param() on boolean

You should always try as much as possible to always put your statements in a try catch block ... it will always help in situations like this and will let you know whats wrong. Perhaps the table name or column name is wrong.

jquery: change the URL address without redirecting?

This is achieved through URL rewriting, not through URL obfuscating, which can't be done.

Another way to do this, as has been mentioned is by changing the hashtag, with

window.location.hash = "/2131/"

How to remove files that are listed in the .gitignore but still on the repository?

As the files in .gitignore are not being tracked, you can use the git clean command to recursively remove files that are not under version control.

Use git clean -xdn to perform a dry run and see what will be removed.
Then use git clean -xdf to execute it.

Basically, git clean -h or man git-clean(in unix) will give you help.

Be aware that this command will also remove new files that are not in the staging area.

Hope it helps.

Postgres error on insert - ERROR: invalid byte sequence for encoding "UTF8": 0x00

If you need to store null characters in text fields and don't want to change your data type other than text then you can follow my solution too:

Before insert:

myValue = myValue.replaceAll("\u0000", "SomeVerySpecialText")

After select:

myValue = myValue.replaceAll("SomeVerySpecialText","\u0000")

I've used "null" as my SomeVerySpecialText which I am sure that there will be no any "null" string in my values at all.

how to get all child list from Firebase android

Firebase stores a sequence of values in this format:

"-K-Y_Rhyxy9kfzIWw7Jq": "Value 1"
"-K-Y_RqDV_zbNLPJYnOA": "Value 2"
"-K-Y_SBoKvx6gAabUPDK": "Value 3"

If that is how you have them, you are getting the wrong type. The above structure is represented as a Map, not as a List:

mFirebaseRef = new Firebase(FIREBASE_URL);

mFirebaseRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Map<String, Object> td = (HashMap<String,Object>) dataSnapshot.getValue();

        List<Object> values = td.values();

        //notifyDataSetChanged();
    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {

    }
});

Javascript Array Alert

If you want to see the array as an array, you can say

alert(JSON.stringify(aCustomers));

instead of all those document.writes.

http://jsfiddle.net/5b2eb/

However, if you want to display them cleanly, one per line, in your popup, do this:

alert(aCustomers.join("\n"));

http://jsfiddle.net/5b2eb/1/

403 Forbidden vs 401 Unauthorized HTTP responses

TL;DR

  • 401: A refusal that has to do with authentication
  • 403: A refusal that has NOTHING to do with authentication

Practical Examples

If apache requires authentication (via .htaccess), and you hit Cancel, it will respond with a 401 Authorization Required

If nginx finds a file, but has no access rights (user/group) to read/access it, it will respond with 403 Forbidden

RFC (2616 Section 10)

401 Unauthorized (10.4.2)

Meaning 1: Need to authenticate

The request requires user authentication. ...

Meaning 2: Authentication insufficient

... If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. ...

403 Forbidden (10.4.4)

Meaning: Unrelated to authentication

... Authorization will not help ...

More details:

  • The server understood the request, but is refusing to fulfill it.

  • It SHOULD describe the reason for the refusal in the entity

  • The status code 404 (Not Found) can be used instead

    (If the server wants to keep this information from client)

'module' object has no attribute 'DataFrame'

Please make sure that your file name should not be panda.py or pd.py. Also, make sure that panda is there in your Lib/site-packages directory, if not that you need to install panda using below command line:

pip install pandas

if you work with proxy then try calling below in command prompt:

python.exe -m pip install pandas --proxy="YOUR_PROXY_IP:PORT"

How to correctly use the ASP.NET FileUpload control

Adding a FileUpload control from the code behind should work just fine, where the HasFile property should be available (for instance in your Click event).

If the properties don't appear to be available (either as a compiler error or via intellisense), you probably are referencing a different variable than you think you are.

jQuery .attr("disabled", "disabled") not working in Chrome

If you are using jQuery < 1.6 do this:

jQuery("input[type='text']").attr("disabled", 'disabled');

If you are using jQuery 1.6+:

jQuery("input[type='text']").prop("disabled", true);

See this question: .prop() vs .attr() for references why.

Or you can try this:

$('input:text').attr("disabled", 'disabled');

see here for info on :text

Add image in pdf using jspdf

No need to add any extra base64 library. Simple 5 line solution -

var img = new Image();
img.src = path.resolve('sample.jpg');

var doc = new jsPDF('p', 'mm', 'a3');  // optional parameters
doc.addImage(img, 'JPEG', 1, 2);
doc.save("new.pdf");

SQL - How to find the highest number in a column?

If you've just inserted a record into the Customers table and you need the value of the recently populated ID field, you can use the SCOPE_IDENTITY function. This is only useful when the INSERT has occurred within the same scope as the call to SCOPE_IDENTITY.

INSERT INTO Customers(ID, FirstName, LastName)
Values
(23, 'Bob', 'Smith')

SET @mostRecentId = SCOPE_IDENTITY()

This may or may not be useful for you, but it's a good technique to be aware of. It will also work with auto-generated columns.

Remove an item from a dictionary when its key is unknown

The dict.pop(key[, default]) method allows you to remove items when you know the key. It returns the value at the key if it removes the item otherwise it returns what is passed as default. See the docs.'

Example:

>>> dic = {'a':1, 'b':2}
>>> dic
{'a': 1, 'b': 2}
>>> dic.pop('c', 0)
0
>>> dic.pop('a', 0)
1
>>> dic
{'b': 2}

Changing the row height of a datagridview

you can do that on RowAdded Event :

_data_grid_view.RowsAdded += new System.Windows.Forms.DataGridViewRowsAddedEventHandler(this._data_grid_view_RowsAdded);

private void _data_grid_view_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            _data_grid_view.Rows[e.RowIndex].Height = 42;
        }

when a row add to the dataGridView it just change it height to 42.

Is there an eval() function in Java?

There is no standard Java class or method that will do what you want. Your options include:

  • Select and use some third-party expression evaluation library. For example JEL or any of the half dozen libraries listed here.

  • Wrap the expression in the Java source code for a class with an eval method, send that to the Java compiler, and then load the resulting compiled class.

  • Use some scripting language that can be called from Java as an expression evaluator. Possibilities include Javascript, BeanShell, and so on.

  • Write your own expression evaluator from scratch.

The first approach is probably simplest. The second and third approaches are a potential security risk if you get the expression to be evaluated from an untrusted user. (Think code injection.)

Can't import Numpy in Python

Disabling pyright worked perfectly for me on VS.

Android Viewpager as Image Slide Gallery

Hoho.. It should be very easy to use Gallery to implement this, using ViewPager is much harder. But i still encourage to use ViewPager since Gallery really have many problems and is deprecated since android 4.2.

In PagerAdapter there is a method getPageWidth() to control page size, but only by this you cannot achieve your target.

Try to read the following 2 articles for help.

multiple-view-viewpager-options

viewpager-container

Perl: Use s/ (replace) and return new string

If you wanted to make your own (for semantic reasons or otherwise), see below for an example, though s/// should be all you need:

#!/usr/bin/perl -w    

use strict;     

   main();   

   sub main{    
      my $foo = "blahblahblah";          
      print '$foo: ' , replace("lah","ar",$foo) , "\n";  #$foo: barbarbar

   }        

   sub replace {
      my ($from,$to,$string) = @_;
      $string =~s/$from/$to/ig;                          #case-insensitive/global (all occurrences)

      return $string;
   }

Angularjs ng-model doesn't work inside ng-if

You can do it like this and you mod function will work perfect let me know if you want a code pen

  <div ng-repeat="icon in icons">                   
                <div class="row" ng-if="$index % 3 == 0 ">
                    <i class="col col-33 {{icons[$index + n].icon}} custom-icon"></i>
                    <i class="col col-33 {{icons[$index + n + 1].icon}} custom-icon"></i>
                    <i class="col col-33 {{icons[$index + n + 2].icon}} custom-icon"></i>
                </div>
         </div>

Timer for Python game

New to the python world!
I need a System Time independent Stopwatch so I did translate my old C++ class into Python:

from ctypes.wintypes import DWORD
import win32api
import datetime

class Stopwatch:

    def __init__(self):
        self.Restart()

    def Restart(self):
        self.__ulStartTicks = DWORD(win32api.GetTickCount()).value

    def ElapsedMilliSecs(self):
        return DWORD(DWORD(win32api.GetTickCount()).value-DWORD(self.__ulStartTicks).value).value

    def ElapsedTime(self):
        return datetime.timedelta(milliseconds=self.ElapsedMilliSecs())

This has no 49 days run over issue due to DWORD math but NOTICE that GetTickCount has about 15 milliseconds granularity so do not use this class if your need 1-100 milliseconds elapsed time ranges.

Any improvement or feedback is welcome!