Programs & Examples On #Center align

How to center an iframe horizontally?

HTML:

<div id="all">
    <div class="sub">div</div>
    <iframe>ss</iframe>
</div>

CSS:

#all{
    width:100%;
    float:left;
    text-align:center;
}
div.sub, iframe {
    width: 100px;
    height: 50px;
    margin: 0 auto;
    background-color: #777;

}

Centering controls within a form in .NET (Winforms)?

You could achieve this with the use of anchors. Or more precisely the non use of them.

Controls are anchored by default to the top left of the form which means when the form size will be changed, their distance from the top left side of the form will remain constant. If you change the control anchor to bottom left, then the control will keep the same distance from the bottom and left sides of the form when the form if resized.

Turning off the anchor in a direction will keep the control centered in that direction when resizing.

NOTE: Turning off anchoring via the properties window in VS2015 may require entering None, None (instead of default Top,Left)

Align a div to center

No, it isn't.

You can either have content bubble up to the right of an element (float: left) or to the left of an element (float: right), there is no provision for having content bubble up on both sides.

in a "using" block is a SqlConnection closed on return or exception?

  1. Yes
  2. Yes.

Either way, when the using block is exited (either by successful completion or by error) it is closed.

Although I think it would be better to organize like this because it's a lot easier to see what is going to happen, even for the new maintenance programmer who will support it later:

using (SqlConnection connection = new SqlConnection(connectionString)) 
{    
    int employeeID = findEmployeeID();    
    try    
    {
        connection.Open();
        SqlCommand command = new SqlCommand("UpdateEmployeeTable", connection);
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.Add(new SqlParameter("@EmployeeID", employeeID));
        command.CommandTimeout = 5;

        command.ExecuteNonQuery();    
    } 
    catch (Exception) 
    { 
        /*Handle error*/ 
    }
}

How to define hash tables in Bash?

I agree with @lhunath and others that the associative array are the way to go with Bash 4. If you are stuck to Bash 3 (OSX, old distros that you cannot update) you can use also expr, which should be everywhere, a string and regular expressions. I like it especially when the dictionary is not too big.

  1. Choose 2 separators that you will not use in keys and values (e.g. ',' and ':' )
  2. Write your map as a string (note the separator ',' also at beginning and end)

    animals=",moo:cow,woof:dog,"
    
  3. Use a regex to extract the values

    get_animal {
        echo "$(expr "$animals" : ".*,$1:\([^,]*\),.*")"
    }
    
  4. Split the string to list the items

    get_animal_items {
        arr=$(echo "${animals:1:${#animals}-2}" | tr "," "\n")
        for i in $arr
        do
            value="${i##*:}"
            key="${i%%:*}"
            echo "${value} likes to $key"
        done
    }
    

Now you can use it:

$ animal = get_animal "moo"
cow
$ get_animal_items
cow likes to moo
dog likes to woof

Cross-browser custom styling for file upload button

The best example is this one, No hiding, No jQuery, It's completely pure CSS

http://css-tricks.com/snippets/css/custom-file-input-styling-webkitblink/

_x000D_
_x000D_
.custom-file-input::-webkit-file-upload-button {_x000D_
    visibility: hidden;_x000D_
}_x000D_
_x000D_
.custom-file-input::before {_x000D_
    content: 'Select some files';_x000D_
    display: inline-block;_x000D_
    background: -webkit-linear-gradient(top, #f9f9f9, #e3e3e3);_x000D_
    border: 1px solid #999;_x000D_
    border-radius: 3px;_x000D_
    padding: 5px 8px;_x000D_
    outline: none;_x000D_
    white-space: nowrap;_x000D_
    -webkit-user-select: none;_x000D_
    cursor: pointer;_x000D_
    text-shadow: 1px 1px #fff;_x000D_
    font-weight: 700;_x000D_
    font-size: 10pt;_x000D_
}_x000D_
_x000D_
.custom-file-input:hover::before {_x000D_
    border-color: black;_x000D_
}_x000D_
_x000D_
.custom-file-input:active::before {_x000D_
    background: -webkit-linear-gradient(top, #e3e3e3, #f9f9f9);_x000D_
}
_x000D_
<input type="file" class="custom-file-input">
_x000D_
_x000D_
_x000D_

Calculating frames per second in a game

In (c++ like) pseudocode these two are what I used in industrial image processing applications that had to process images from a set of externally triggered camera's. Variations in "frame rate" had a different source (slower or faster production on the belt) but the problem is the same. (I assume that you have a simple timer.peek() call that gives you something like the nr of msec (nsec?) since application start or the last call)

Solution 1: fast but not updated every frame

do while (1)
{
    ProcessImage(frame)
    if (frame.framenumber%poll_interval==0)
    {
        new_time=timer.peek()
        framerate=poll_interval/(new_time - last_time)
        last_time=new_time
    }
}

Solution 2: updated every frame, requires more memory and CPU

do while (1)
{
   ProcessImage(frame)
   new_time=timer.peek()
   delta=new_time - last_time
   last_time = new_time
   total_time += delta
   delta_history.push(delta)
   framerate= delta_history.length() / total_time
   while (delta_history.length() > avg_interval)
   {
      oldest_delta = delta_history.pop()
      total_time -= oldest_delta
   }
} 

Can we cast a generic object to a custom object type in javascript?

This is not exactly an answer, rather sharing my findings, and hopefully getting some critical argument for/against it, as specifically I am not aware how efficient it is.

I recently had a need to do this for my project. I did this using Object.assign, more precisely it is done something like this:Object.assign(new Person(...), anObjectLikePerson).

Here is link to my JSFiddle, and also the main part of the code:

function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;

  this.getFullName = function() {
    return this.lastName + ' ' + this.firstName;
  }
}

var persons = [{
  lastName: "Freeman",
  firstName: "Gordon"
}, {
  lastName: "Smith",
  firstName: "John"
}];

var stronglyTypedPersons = [];
for (var i = 0; i < persons.length; i++) {
  stronglyTypedPersons.push(Object.assign(new Person("", ""), persons[i]));
}

How can I define colors as variables in CSS?

If you write the css file as an xsl template, you could read color values from a simple xml file. Then create the css with an xslt processor.

colors.xml:

<?xml version="1.0"?>
<colors>
    <background>#ccc</background>
</colors>

styles.xsl:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" version="1.0" encoding="iso-8859-1"/>
    <xsl:template match="/">body {
    background-color: <xsl:value-of select="/colors/background" />;
}
</xsl:template>
</xsl:stylesheet>

Command to render css: xsltproc -o styles.css styles.xsl colors.xml

styles.css:

body {
    background-color: #ccc;
}

restart mysql server on windows 7

I just have the same problem, just open the task manager, go to services tab and search MySQL_One service, rigth click and start, this works for very good.

How do I set the background color of my main screen in Flutter?

you should return Scaffold widget and add your widget inside Scaffold

suck as this code :

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return Scaffold(
          backgroundColor: Colors.white,
          body: Center(child: new Text("Hello, World!"));
    );
  }
}

How to pass parameters to a modal?

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

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

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

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

  $scope.test = test;
};

See plunkr

Powershell command to hide user from exchange address lists

For Office 365 users or Hybrid exchange, go to using Internet Explorer or Edge, go to the exchange admin center, choose hybrid, setup, chose the right button for hybrid or exchange online.

To connect:

Connect-EXOPSSession

To see the relevant mailboxes:

Get-mailbox -filter {ExchangeUserAccountControl -eq 'AccountDisabled' -and RecipientType -eq 'UserMailbox' -and RecipientTypeDetails -ne 'SharedMailbox' }

To block based on the above idea of 0KB size:

Get-mailbox -filter {ExchangeUserAccountControl -eq 'AccountDisabled' -and RecipientTypeDetails -ne 'SharedMailbox' -and RecipientType -eq 'UserMailbox' } | Set-Mailbox -MaxReceiveSize 0KB -HiddenFromAddressListsEnabled $true

Javascript date regex DD/MM/YYYY

Scape slashes is simply use \ before / and it will be escaped. (\/=> /).

Otherwise you're regex DD/MM/YYYY could be next:

/^[0-9]{2}[\/]{1}[0-9]{2}[\/]{1}[0-9]{4}$/g

Explanation:

  • [0-9]: Just Numbers
  • {2} or {4}: Length 2 or 4. You could do {2,4} as well to length between two numbers (2 and 4 in this case)
  • [\/]: Character /
  • g : Global -- Or m: Multiline (Optional, see your requirements)
  • $: Anchor to end of string. (Optional, see your requirements)
  • ^: Start of string. (Optional, see your requirements)

An example of use:

_x000D_
_x000D_
var regex = /^[0-9]{2}[\/][0-9]{2}[\/][0-9]{4}$/g;

var dates = ["2009-10-09", "2009.10.09", "2009/10/09", "200910-09", "1990/10/09", 
    "2016/0/09", "2017/10/09", "2016/09/09", "20/09/2016", "21/09/2016", "22/09/2016",
    "23/09/2016", "19/09/2016", "18/09/2016", "25/09/2016", "21/09/2018"];

//Iterate array
dates.forEach(
    function(date){
        console.log(date + " matches with regex?");
      console.log(regex.test(date));
    });
_x000D_
_x000D_
_x000D_

Of course you can use as boolean:

if(regex.test(date)){
     //do something
}

Max length UITextField

In Swift 4

10 Characters limit for text field and allow to delete(backspace)

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if textField ==  userNameFTF{
            let char = string.cString(using: String.Encoding.utf8)
            let isBackSpace = strcmp(char, "\\b")
            if isBackSpace == -92 {
                return true
            }
            return textField.text!.count <= 9
        }
        return true
    }

MySQL: Curdate() vs Now()

Actually MySQL provide a lot of easy to use function in daily life without more effort from user side-

NOW() it produce date and time both in current scenario whereas CURDATE() produce date only, CURTIME() display time only, we can use one of them according to our need with CAST or merge other calculation it, MySQL rich in these type of function.

NOTE:- You can see the difference using query select NOW() as NOWDATETIME, CURDATE() as NOWDATE, CURTIME() as NOWTIME ;

How I can filter a Datatable?

You can use DataView.

DataView dv = new DataView(yourDatatable);
dv.RowFilter = "query"; // query example = "id = 10"


http://www.csharp-examples.net/dataview-rowfilter/

What is the current choice for doing RPC in Python?

You could try Ladon. It serves up multiple web server protocols at once so you can offer more flexibility at the client side.

http://pypi.python.org/pypi/ladon

changing source on html5 video tag

Try moving the OGG source to the top. I've noticed Firefox sometimes gets confused and stops the player when the one it wants to play, OGG, isn't first.

Worth a try.

How to add leading zeros for for-loop in shell?

Just a note: I have experienced different behaviours on different versions of bash:

  • version 3.1.17(1)-release-(x86_64-suse-linux) and
  • Version 4.1.17(9)-release (x86_64-unknown-cygwin))

for the former (3.1) for nn in (00..99) ; do ... works but for nn in (000..999) ; do ... does not work both will work on version 4.1 ; haven't tested printf behaviour (bash --version gave the version info)

Cheers, Jan

CSS table td width - fixed, not flexible

Just divide the number of td to 100%. Example, you have 4 td's:

<html>
<table>
<tr>
<td style="width:25%">This is a text</td>
<td style="width:25%">This is some text, this is some text</td>
<td style="width:25%">This is another text, this is another text</td>
<td style="width:25%">This is the last text, this is the last text</td>
</tr>
</table>
</html>

We use 25% in each td to maximize the 100% space of the entire table

Swift Bridging Header import issue

I experienced that kind of error, when I was adding a Today Extension to my app. The build target for the extension was generated with the same name of bridging header as my app's build target. This was leading to the error, because the extension does not see the files listed in the bridging header of my app.

The only thing You need to to is delete or change the name of the bridging header for the extension and all will be fine.

Hope that this will help.

How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?

I found a possible solution, but... I don't know if it's a good solution.

@Entity
public class Role extends Identifiable {

    @ManyToMany(cascade ={CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinTable(name="Role_Permission",
            joinColumns=@JoinColumn(name="Role_id"),
            inverseJoinColumns=@JoinColumn(name="Permission_id")
        )
    public List<Permission> getPermissions() {
        return permissions;
    }

    public void setPermissions(List<Permission> permissions) {
        this.permissions = permissions;
    }
}

@Entity
public class Permission extends Identifiable {

    @ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinTable(name="Role_Permission",
            joinColumns=@JoinColumn(name="Permission_id"),
            inverseJoinColumns=@JoinColumn(name="Role_id")
        )
    public List<Role> getRoles() {
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }

I have tried this and it works. When you delete Role, also the relations are deleted (but not the Permission entities) and when you delete Permission, the relations with Role are deleted too (but not the Role instance). But we are mapping a unidirectional relation two times and both entities are the owner of the relation. Could this cause some problems to Hibernate? Which type of problems?

Thanks!

The code above is from another post related.

jQuery check if Cookie exists, if not create it

Try this very simple:

            var cookieExist = $.cookie("status");
            if(cookieExist == "null" ){
                alert("Cookie Is Null");

            }

Convert Java string to Time, NOT Date

You might want to take a look at this example:

public static void main(String[] args) {

    String myTime = "10:30:54";
    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
    Date date = null;
    try {
        date = sdf.parse(myTime);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    String formattedTime = sdf.format(date);

    System.out.println(formattedTime);

}

How do you get the path to the Laravel Storage folder?

For Laravel 5.x, use $storage_path = storage_path().

From the Laravel 5.0 docs:

storage_path

Get the fully qualified path to the storage directory.

Note also that, for Laravel 5.1 and above, per the Laravel 5.1 docs:

You may also use the storage_path function to generate a fully qualified path to a given file relative to the storage directory:

$path = storage_path('app/file.txt');

How to select count with Laravel's fluent query builder?

$count = DB::table('category_issue')->count();

will give you the number of items.

For more detailed information check Fluent Query Builder section in beautiful Laravel Documentation.

Set up a scheduled job?

I had exactly the same requirement a while ago, and ended up solving it using APScheduler (User Guide)

It makes scheduling jobs super simple, and keeps it independent for from request-based execution of some code. Following is a simple example.

from apscheduler.schedulers.background import BackgroundScheduler

scheduler = BackgroundScheduler()
job = None

def tick():
    print('One tick!')\

def start_job():
    global job
    job = scheduler.add_job(tick, 'interval', seconds=3600)
    try:
        scheduler.start()
    except:
        pass

Hope this helps somebody!

Remove Rows From Data Frame where a Row matches a String

if you wish to using dplyr, for to remove row "Foo":

df %>%
 filter(!C=="Foo")

Converting byte array to string in javascript

If your array is encoded in UTF-8 and you can't use the TextDecoder API because it is not supported on IE:

  1. You can use the FastestSmallestTextEncoderDecoder polyfill recommended by the Mozilla Developer Network website;
  2. You can use this function also provided at the MDN website:

_x000D_
_x000D_
function utf8ArrayToString(aBytes) {_x000D_
    var sView = "";_x000D_
    _x000D_
    for (var nPart, nLen = aBytes.length, nIdx = 0; nIdx < nLen; nIdx++) {_x000D_
        nPart = aBytes[nIdx];_x000D_
        _x000D_
        sView += String.fromCharCode(_x000D_
            nPart > 251 && nPart < 254 && nIdx + 5 < nLen ? /* six bytes */_x000D_
                /* (nPart - 252 << 30) may be not so safe in ECMAScript! So...: */_x000D_
                (nPart - 252) * 1073741824 + (aBytes[++nIdx] - 128 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128_x000D_
            : nPart > 247 && nPart < 252 && nIdx + 4 < nLen ? /* five bytes */_x000D_
                (nPart - 248 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128_x000D_
            : nPart > 239 && nPart < 248 && nIdx + 3 < nLen ? /* four bytes */_x000D_
                (nPart - 240 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128_x000D_
            : nPart > 223 && nPart < 240 && nIdx + 2 < nLen ? /* three bytes */_x000D_
                (nPart - 224 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128_x000D_
            : nPart > 191 && nPart < 224 && nIdx + 1 < nLen ? /* two bytes */_x000D_
                (nPart - 192 << 6) + aBytes[++nIdx] - 128_x000D_
            : /* nPart < 127 ? */ /* one byte */_x000D_
                nPart_x000D_
        );_x000D_
    }_x000D_
    _x000D_
    return sView;_x000D_
}_x000D_
_x000D_
let str = utf8ArrayToString([50,72,226,130,130,32,43,32,79,226,130,130,32,226,135,140,32,50,72,226,130,130,79]);_x000D_
_x000D_
// Must show 2H2 + O2 ? 2H2O_x000D_
console.log(str);
_x000D_
_x000D_
_x000D_

Copy/Paste from Excel to a web page

For any future googlers ending up here like me, I used @tatu Ulmanen's concept and just turned it into an array of objects. This simple function takes a string of pasted excel (or Google sheet) data (preferably from a textarea) and turns it into an array of objects. It uses the first row for column/property names.

function excelToObjects(stringData){
    var objects = [];
    //split into rows
    var rows = stringData.split('\n');

    //Make columns
    columns = rows[0].split('\t');

    //Note how we start at rowNr = 1, because 0 is the column row
    for (var rowNr = 1; rowNr < rows.length; rowNr++) {
        var o = {};
        var data = rows[rowNr].split('\t');

        //Loop through all the data
        for (var cellNr = 0; cellNr < data.length; cellNr++) {
            o[columns[cellNr]] = data[cellNr];
        }

        objects.push(o);
    }

    return objects;
}

Hopefully it helps someone in the future.

NSRange from Swift Range?

let text:String = "Hello Friend"

let searchRange:NSRange = NSRange(location:0,length: text.characters.count)

let range:Range`<Int`> = Range`<Int`>.init(start: searchRange.location, end: searchRange.length)

A top-like utility for monitoring CUDA activity on a GPU

I created a batch file with the following code in a windows machine to monitor every second. It works for me.

:loop
cls
"C:\Program Files\NVIDIA Corporation\NVSMI\nvidia-smi"
timeout /T 1
goto loop

nvidia-smi exe is usually located in "C:\Program Files\NVIDIA Corporation" if you want to run the command only once.

How does one Display a Hyperlink in React Native App?

Use React Native Hyperlink (Native <A> tag):

Install:

npm i react-native-a

import:

import A from 'react-native-a'

Usage:

  1. <A>Example.com</A>
  2. <A href="example.com">Example</A>
  3. <A href="https://example.com">Example</A>
  4. <A href="example.com" style={{fontWeight: 'bold'}}>Example</A>

How to get ASCII value of string in C#

From MSDN

string value = "9quali52ty3";

// Convert the string into a byte[].
byte[] asciiBytes = Encoding.ASCII.GetBytes(value);

You now have an array of the ASCII value of the bytes. I got the following:

57 113 117 97 108 105 53 50 116 121 51

jQuery getJSON save result into variable

You can't get value when calling getJSON, only after response.

var myjson;
$.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
    myjson = json;
});

How to sort an array in descending order in Ruby

What about:

 a.sort {|x,y| y[:bar]<=>x[:bar]}

It works!!

irb
>> a = [
?>   { :foo => 'foo', :bar => 2 },
?>   { :foo => 'foo', :bar => 3 },
?>   { :foo => 'foo', :bar => 5 },
?> ]
=> [{:bar=>2, :foo=>"foo"}, {:bar=>3, :foo=>"foo"}, {:bar=>5, :foo=>"foo"}]

>>  a.sort {|x,y| y[:bar]<=>x[:bar]}
=> [{:bar=>5, :foo=>"foo"}, {:bar=>3, :foo=>"foo"}, {:bar=>2, :foo=>"foo"}]

Using Intent in an Android application to show another activity

b1 = (Button) findViewById(R.id.click_me);
        b1.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                Intent i = new Intent(MainActivity.this, SecondActivity.class);
                startActivity(i);

            }
        });

Number of rows affected by an UPDATE in PL/SQL

You use the sql%rowcount variable.

You need to call it straight after the statement which you need to find the affected row count for.

For example:

set serveroutput ON; 
DECLARE 
    i NUMBER; 
BEGIN 
    UPDATE employees 
    SET    status = 'fired' 
    WHERE  name LIKE '%Bloggs'; 
    i := SQL%rowcount; 
    --note that assignment has to precede COMMIT
    COMMIT; 
    dbms_output.Put_line(i); 
END; 

how to get html content from a webview?

I would suggest instead of trying to extract the HTML from the WebView, you extract the HTML from the URL. By this, I mean using a third party library such as JSoup to traverse the HTML for you. The following code will get the HTML from a specific URL for you

public static String getHtml(String url) throws ClientProtocolException, IOException {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = httpClient.execute(httpGet, localContext);
        String result = "";

        BufferedReader reader = new BufferedReader(
            new InputStreamReader(
                response.getEntity().getContent()
            )
        );

        String line = null;
        while ((line = reader.readLine()) != null){
            result += line + "\n";
        }
        return result;
    }

How to find Current open Cursors in Oracle

1)your id should have sys dba access 2)

select sum(a.value) total_cur, avg(a.value) avg_cur, max(a.value) max_cur, 
 s.username, s.machine
 from v$sesstat a, v$statname b, v$session s 
 where a.statistic# = b.statistic# and s.sid=a.sid
 and b.name = 'opened cursors current' 
 group by s.username, s.machine
 order by 1 desc;

jQuery AJAX form data serialize using PHP

try it , but first be sure what is you response console.log(response) on ajax success from server

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var form=$("#myForm");
$("#smt").click(function(){
$.ajax({
        type:"POST",
        url:form.attr("action"),
        data:form.serialize(),

        success: function(response){
        if(response === 1){
            //load chech.php file  
        }  else {
            //show error
        }
        }
    });
});
});

Order by multiple columns with Doctrine

In Doctrine 2.x you can't pass multiple order by using doctrine 'orderBy' or 'addOrderBy' as above examples. Because, it automatically adds the 'ASC' at the end of the last column name when you left the second parameter blank, such as in the 'orderBy' function.

For an example ->orderBy('a.fist_name ASC, a.last_name ASC') will output SQL something like this 'ORDER BY first_name ASC, last_name ASC ASC'. So this is SQL syntax error. Simply because default of the orderBy or addOrderBy is 'ASC'.

To add multiple order by's you need to use 'add' function. And it will be like this.

->add('orderBy','first_name ASC, last_name ASC'). This will give you the correctly formatted SQL.

More info on add() function. https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/query-builder.html#low-level-api

Hope this helps. Cheers!

Observable Finally on Subscribe

The only thing which worked for me is this

fetchData()
  .subscribe(
    (data) => {
       //Called when success
     },
    (error) => {
       //Called when error
    }
  ).add(() => {
       //Called when operation is complete (both success and error)
  });

Rails ActiveRecord date between

If you only want to get one day it would be easier this way:

Comment.all(:conditions => ["date(created_at) = ?", some_date])

Get loop count inside a Python FOR loop

The pythonic way is to use enumerate:

for idx,item in enumerate(list):

Difference between JSONObject and JSONArray

The difference is the same as a (Hash)Map vs List.

JSONObject:

  • Contains named values (key->value pairs, tuples or whatever you want to call them)
    • like {ID : 1}
  • Order of elements is not important
    • a JSONObject of {id: 1, name: 'B'} is equal to {name: 'B', id: 1}.

JSONArray:

  • Contains only series values
    • like [1, 'value']
  • Order of values is important
    • array of [1,'value'] is not the same as ['value',1]

Example

JSON Object --> { "":""}

JSON Array --> [ , , , ]

{"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}

How to send data to COM PORT using JAVA?

The Java Communications API (also known as javax.comm) provides applications access to RS-232 hardware (serial ports): http://www.oracle.com/technetwork/java/index-jsp-141752.html

cmd line rename file with date and time

Digging up the old thread because all solutions have missed the simplest fix...

It is failing because the substitution of the time variable results in a space in the filename, meaning it treats the last part of the filename as a parameter into the command.

The simplest solution is to just surround the desired filename in quotes "filename".

Then you can have any date pattern you want (with the exception of those illegal characters such as /,\,...)

I would suggest reverse date order YYYYMMDD-HHMM:

ren "somefile.txt" "somefile-%date:~10,4%%date:~7,2%%date:~4,2%-%time:~0,2%%time:~3,2%.txt"

How to use the ProGuard in Android Studio?

Try renaming your 'proguard-rules.txt' file to 'proguard-android.txt' and remove the reference to 'proguard-rules.txt' in your gradle file. The getDefaultProguardFile(...) call references a different default proguard file, one provided by Google and not that in your project. So remove this as well, so that here the gradle file reads:

buildTypes {
    release {
        runProguard true
        proguardFile 'proguard-android.txt'
    }
}

How to get the previous page URL using JavaScript?

You can use the following to get the previous URL.

var oldURL = document.referrer;
alert(oldURL);

How to check whether the user uploaded a file in PHP?

In general when the user upload the file, the PHP server doen't catch any exception mistake or errors, it means that the file is uploaded successfully. https://www.php.net/manual/en/reserved.variables.files.php#109648

if ( boolval( $_FILES['image']['error'] === 0 ) ) {
    // ...
}

Check for special characters (/*-+_@&$#%) in a string?

Use the regular Expression below in to validate a string to make sure it contains numbers, letters, or space only:

[a-zA-Z0-9 ]

Detect a finger swipe through JavaScript on the iPhone and Android

I had trouble with touchend handler firing continuously while the user was dragging a finger around. I don't know if that's due to something I'm doing wrong or not but I rewired this to accumulate moves with touchmove and touchend actually fires the callback.

I also needed to have a large number of these instances and so I added enable/disable methods.

And a threshold where a short swipe doesn't fire. Touchstart zero's the counters each time.

You can change the target_node on the fly. Enable on creation is optional.

/** Usage: */
touchevent = new Modules.TouchEventClass(callback, target_node);
touchevent.enable();
touchevent.disable();

/** 
*
*   Touch event module
*
*   @param method   set_target_mode
*   @param method   __touchstart
*   @param method   __touchmove
*   @param method   __touchend
*   @param method   enable
*   @param method   disable
*   @param function callback
*   @param node     target_node
*/
Modules.TouchEventClass = class {

    constructor(callback, target_node, enable=false) {

        /** callback function */
        this.callback = callback;

        this.xdown = null;
        this.ydown = null;
        this.enabled = false;
        this.target_node = null;

        /** move point counts [left, right, up, down] */
        this.counts = [];

        this.set_target_node(target_node);

        /** Enable on creation */
        if (enable === true) {
            this.enable();
        }

    }

    /** 
    *   Set or reset target node
    *
    *   @param string/node target_node
    *   @param string      enable (optional)
    */
    set_target_node(target_node, enable=false) {

        /** check if we're resetting target_node */
        if (this.target_node !== null) {

            /** remove old listener */
           this.disable();
        }

        /** Support string id of node */
        if (target_node.nodeName === undefined) {
            target_node = document.getElementById(target_node);
        }

        this.target_node = target_node;

        if (enable === true) {
            this.enable();
        }
    }

    /** enable listener */
    enable() {
        this.enabled = true;
        this.target_node.addEventListener("touchstart", this.__touchstart.bind(this));
        this.target_node.addEventListener("touchmove", this.__touchmove.bind(this));
        this.target_node.addEventListener("touchend", this.__touchend.bind(this));
    }

    /** disable listener */
    disable() {
        this.enabled = false;
        this.target_node.removeEventListener("touchstart", this.__touchstart);
        this.target_node.removeEventListener("touchmove", this.__touchmove);
        this.target_node.removeEventListener("touchend", this.__touchend);
    }

    /** Touchstart */
    __touchstart(event) {
        event.stopPropagation();
        this.xdown = event.touches[0].clientX;
        this.ydown = event.touches[0].clientY;

        /** reset count of moves in each direction, [left, right, up, down] */
        this.counts = [0, 0, 0, 0];
    }

    /** Touchend */
    __touchend(event) {
        let max_moves = Math.max(...this.counts);
        if (max_moves > 500) { // set this threshold appropriately
            /** swipe happened */
            let index = this.counts.indexOf(max_moves);
            if (index == 0) {
                this.callback("left");
            } else if (index == 1) {
                this.callback("right");
            } else if (index == 2) {
                this.callback("up");
            } else {
                this.callback("down");
            }
        }
    }

    /** Touchmove */
    __touchmove(event) {

        event.stopPropagation();
        if (! this.xdown || ! this.ydown) {
            return;
        }

        let xup = event.touches[0].clientX;
        let yup = event.touches[0].clientY;

        let xdiff = this.xdown - xup;
        let ydiff = this.ydown - yup;

        /** Check x or y has greater distance */
        if (Math.abs(xdiff) > Math.abs(ydiff)) {
            if (xdiff > 0) {
                this.counts[0] += Math.abs(xdiff);
            } else {
                this.counts[1] += Math.abs(xdiff);
            }
        } else {
            if (ydiff > 0) {
                this.counts[2] += Math.abs(ydiff);
            } else {
                this.counts[3] += Math.abs(ydiff);
            }
        }
    }
}

Get Absolute Position of element within the window in wpf

Hm. You have to specify window you clicked in Mouse.GetPosition(IInputElement relativeTo) Following code works well for me

protected override void OnMouseDown(MouseButtonEventArgs e)
    {
        base.OnMouseDown(e);
        Point p = e.GetPosition(this);
    }

I suspect that you need to refer to the window not from it own class but from other point of the application. In this case Application.Current.MainWindow will help you.

How do I force Maven to use my local repository rather than going out to remote repos to retrieve artifacts?

The dependency has a snapshot version. For snapshots, Maven will check the local repository and if the artifact found in the local repository is too old, it will attempt to find an updated one in the remote repositories. That is probably what you are seeing.

Note that this behavior is controlled by the updatePolicy directive in the repository configuration (which is daily by default for snapshot repositories).

Watching variables contents in Eclipse IDE

You can do so by these ways.

Add watchpoint and while debugging you can see variable in debugger window perspective under variable tab. OR Add System.out.println("variable = " + variable); and see in console.

How update the _id of one MongoDB Document?

To do it for your whole collection you can also use a loop (based on Niels example):

db.status.find().forEach(function(doc){ 
    doc._id=doc.UserId; db.status_new.insert(doc);
});
db.status_new.renameCollection("status", true);

In this case UserId was the new ID I wanted to use

Comparing two arrays of objects, and exclude the elements who match values into new array in JS

well, this using lodash or vanilla javascript it depends on the situation.

but for just return the array that contains the duplicates it can be achieved by the following, offcourse it was taken from @1983

var result = result1.filter(function (o1) {
    return result2.some(function (o2) {
        return o1.id === o2.id; // return the ones with equal id
   });
});
// if you want to be more clever...
let result = result1.filter(o1 => result2.some(o2 => o1.id === o2.id));

html5 audio player - jquery toggle click play/pause?

You can call native methods trough trigger in jQuery. Just do this:

$('.play').trigger("play");

And the same for pause: $('.play').trigger("pause");

EDIT: as F... pointed out in the comments, you can do something similar to access properties: $('.play').prop("paused");

How can I run MongoDB as a Windows service?

These are the steps to install MongoDB as Windows Service :

  1. Create a log directory, e.g. C:\MongoDB\log

  2. Create a db directory, e.g. C:\MongoDB\db

  3. Prepare a configuration file with following lines

    dbpath=C:\MongoDB\db

    logpath=C:\MongoDB\log

    Place the configuration file with name mongod.cfg in folder "C:\MongoDB\"

  4. Following command will install the Windows Service on your sc.exe create MongoDB binPath= "\"C:\MongoDB\Server\3.4\bin\mongod.exe\" --service --config=\"C:\MongoDB\mongod.cfg\" DisplayName= "MongoDB 3.4" start= "auto"

  5. Once you run this command, you will get the [SC] CreateService SUCCESS

  6. Run following command on Command Prompt

    net start MongoDB

System.Data.SqlClient.SqlException: Login failed for user

I faced the same situation. Create your connection string as follows.

Replace

"connectionString": "Data Source=server name;Initial Catalog=DB name;User id=user id;Password=password;Integrated Security=True;MultipleActiveResultSets=True"

by

"connectionString": "Server=server name; Database=Treat; User Id=user id; Password=password; Trusted_Connection=False; MultipleActiveResultSets=true"

Java character array initializer

You initialized and declared your String to "Hi there", initialized your char[] array with the correct size, and you began a loop over the length of the array which prints an empty string combined with a given element being looked at in the array. At which point did you factor in the functionality to put in the characters from the String into the array?

When you attempt to print each element in the array, you print an empty String, since you're adding 'nothing' to an empty String, and since there was no functionality to add in the characters from the input String to the array. You have everything around it correctly implemented, though. This is the code that should go after you initialize the array, but before the for-loop that iterates over the array to print out the elements.

for (int count = 0; count < ini.length(); count++) {
  array[count] = ini.charAt(count);
}

It would be more efficient to just combine the for-loops to print each character out right after you put it into the array.

for (int count = 0; count < ini.length(); count++) {
  array[count] = ini.charAt(count);
  System.out.println(array[count]);
}

At this point, you're probably wondering why even put it in a char[] when I can just print them using the reference to the String object ini itself.

String ini = "Hi there";

for (int count = 0; count < ini.length(); count++) {
   System.out.println(ini.charAt(count));
}

Definitely read about Java Strings. They're fascinating and work pretty well, in my opinion. Here's a decent link: https://www.javatpoint.com/java-string

String ini = "Hi there"; // stored in String constant pool

is stored differently in memory than

String ini = new String("Hi there"); // stored in heap memory and String constant pool

, which is stored differently than

char[] inichar = new char[]{"H", "i", " ", "t", "h", "e", "r", "e"};
String ini = new String(inichar); // converts from char array to string

.

updating table rows in postgres using subquery

@Mayur "4.2 [Using query with complex JOIN]" with Common Table Expressions (CTEs) did the trick for me.

WITH cte AS (
SELECT e.id, e.postcode
FROM employees e
LEFT JOIN locations lc ON lc.postcode=cte.postcode
WHERE e.id=1
)
UPDATE employee_location SET lat=lc.lat, longitude=lc.longi
FROM cte
WHERE employee_location.id=cte.id;

Hope this helps... :D

Redirect on Ajax Jquery Call

For ExpressJs router:

router.post('/login', async(req, res) => {
    return res.send({redirect: '/yoururl'});
})

Client-side:

    success: function (response) {
        if (response.redirect) {
            window.location = response.redirect
        }
    },

How to make nginx to listen to server_name:port

The server_namedocs directive is used to identify virtual hosts, they're not used to set the binding.

netstat tells you that nginx listens on 0.0.0.0:80 which means that it will accept connections from any IP.

If you want to change the IP nginx binds on, you have to change the listendocs rule.
So, if you want to set nginx to bind to localhost, you'd change that to:

listen 127.0.0.1:80;

In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).

Select subset of columns in data.table R

Use with=FALSE:

cols = paste("V", c(1,2,3,5), sep="")

dt[, !cols, with=FALSE]

I suggest going through the "Introduction to data.table" vignette.


Update: From v1.10.2 onwards, you can also do:

dt[, ..cols]

See the first NEWS item under v1.10.2 here for additional explanation.

onKeyPress Vs. onKeyUp and onKeyDown

KeyPress, KeyUp and KeyDown are analogous to, respectively: Click, MouseUp, and MouseDown.

  1. Down happens first
  2. Press happens second (when text is entered)
  3. Up happens last (when text input is complete).

The exception is webkit, which has an extra event in there:

keydown
keypress
textInput     
keyup

Below is a snippet you can use to see for yourself when the events get fired:

_x000D_
_x000D_
window.addEventListener("keyup", log);
window.addEventListener("keypress", log);
window.addEventListener("keydown", log);

function log(event){
  console.log( event.type );
}
_x000D_
_x000D_
_x000D_

Make element fixed on scroll

I wouldn't bother with jQuery or LESS. A javascript framework is overkill in my opinion.

window.addEventListener('scroll', function (evt) {

  // This value is your scroll distance from the top
  var distance_from_top = document.body.scrollTop;

  // The user has scrolled to the tippy top of the page. Set appropriate style.
  if (distance_from_top === 0) {

  }

  // The user has scrolled down the page.
  if(distance_from_top > 0) {

  }

});

Why is Github asking for username/password when following the instructions on screen and pushing a new repo?

Because you are using HTTPS way.HTTPS requires that you type your account access every time you try to push or pull,but there is one way too, called SSH, and it lets you to tell git, that I give you permission with my account for this pc, and never ask me again about any user access. To use it, you have to generate SSH key and add it into your Github's account just one time.To do that, you can follow these steps

How To Generate SSH key for Github

Custom Drawable for ProgressBar/ProgressDialog

I was having some trouble using an Indeterminate Progress Dialog with the solution here, after some work and trial and error I got it to work.

First, create the animation you want to use for the Progress Dialog. In my case I used 5 images.

../res/anim/progress_dialog_icon_drawable_animation.xml:

<animation-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/icon_progress_dialog_drawable_1" android:duration="150" />
    <item android:drawable="@drawable/icon_progress_dialog_drawable_2" android:duration="150" />
    <item android:drawable="@drawable/icon_progress_dialog_drawable_3" android:duration="150" />
    <item android:drawable="@drawable/icon_progress_dialog_drawable_4" android:duration="150" />
    <item android:drawable="@drawable/icon_progress_dialog_drawable_5" android:duration="150" />
</animation-list>

Where you want to show a ProgressDialog:

dialog = new ProgressDialog(Context.this);
dialog.setIndeterminate(true);
dialog.setIndeterminateDrawable(getResources().getDrawable(R.anim.progress_dialog_icon_drawable_animation));
dialog.setMessage("Some Text");
dialog.show();

This solution is really simple and worked for me, you could extend ProgressDialog and make it override the drawable internally, however, this was really too complicated for what I needed so I did not do it.

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

Resolution

To work around this problem, use one of the following methods:

Symptoms

If you use the Response.End, Response.Redirect, or Server.Transfer method, a ThreadAbortException exception occurs. You can use a try-catch statement to catch this exception.

Cause

The Response.End method ends the page execution and shifts the execution to the Application_EndRequest event in the application's event pipeline. The line of code that follows Response.End is not executed.

This problem occurs in the Response.Redirect and Server.Transfer methods because both methods call Response.End internally.

Status

This behavior is by design.

Properties

Article ID: 312629 - Last Review: August 30, 2012 - Revision: 4.0

Applies to

  • Microsoft ASP.NET 4.5
  • Microsoft ASP.NET 4
  • Microsoft ASP.NET 3.5
  • Microsoft ASP.NET 2.0
  • Microsoft ASP.NET 1.1
  • Microsoft ASP.NET 1.0

Keywords: kbexcepthandling kbprb KB312629

Source: PRB: ThreadAbortException Occurs If You Use Response.End, Response.Redirect, or Server.Transfer

Oracle SQL Developer: Failure - Test failed: The Network Adapter could not establish the connection?

only start listner then u can connect with database. command run on editor:

lsnrctl start

its work fine.

Can grep show only words that match search pattern?

You can also try pcregrep. There is also a -w option in grep, but in some cases it doesn't work as expected.

From Wikipedia:

cat fruitlist.txt
apple
apples
pineapple
apple-
apple-fruit
fruit-apple

grep -w apple fruitlist.txt
apple
apple-
apple-fruit
fruit-apple

javascript cell number validation

If number is your form element, then its length will be undefined since elements don't have length. You want

if (number.value.length != 10) { ... }

An easier way to do all the validation at once, though, would be with a regex:

var val = number.value
if (/^\d{10}$/.test(val)) {
    // value is ok, use it
} else {
    alert("Invalid number; must be ten digits")
    number.focus()
    return false
}

\d means "digit," and {10} means "ten times." The ^ and $ anchor it to the start and end, so something like asdf1234567890asdf does not match.

How to import local packages without gopath

Run:

go mod init yellow

Then create a file yellow.go:

package yellow

func Mix(s string) string {
   return s + "Yellow"
}

Then create a file orange/orange.go:

package main
import "yellow"

func main() {
   s := yellow.Mix("Red")
   println(s)
}

Then build:

go build

https://golang.org/doc/code.html

How to convert 'binary string' to normal string in Python3?

Decode it.

>>> b'a string'.decode('ascii')
'a string'

To get bytes from string, encode it.

>>> 'a string'.encode('ascii')
b'a string'

enum - getting value of enum on string conversion

I implemented access using the following

class D(Enum):
    x = 1
    y = 2

    def __str__(self):
        return '%s' % self.value

now I can just do

print(D.x) to get 1 as result.

You can also use self.name in case you wanted to print x instead of 1.

How to make a node.js application run permanently?

If you just want to run your node app in the terminal always, just use screen.

Install on ubuntu/ debian:

sudo apt-get install screen

Usage:

$ screen
$ node /path/to/app.js

ctrl + a and then ctrl + d to dismiss

To get is back:

One screen: screen -r

If there's more than one you can list all the screens with: screen -ls

And then: screen -r pid_number

Error:Failed to open zip file. Gradle's dependency cache may be corrupt

Repair Gradle Installation

This usually happens when something goes wrong in Android Studio's first launch (eg. system crash, connection loss or whatever).

To resolve this issue close Android Studio and delete the following directory's content, necessary files will be downloaded on IDE's next launch.

macOS: ~/.gradle/wrapper/dists

Linux: ~/.gradle/wrapper/dists

Windows: C:\Users\your-username\.gradle\wrapper\dists

While downloading Gradle manually works, I recommend letting Android Studio itself to do it.

Primitive type 'short' - casting in Java

EDIT: Okay, now we know it's Java...

Section 4.2.2 of the Java Language Specification states:

The Java programming language provides a number of operators that act on integral values:

[...]

  • The numerical operators, which result in a value of type int or long:
  • [...]
  • The additive operators + and - (§15.18)

  • In other words, it's like C# - the addition operator (when applied to integral types) only ever results in int or long, which is why you need to cast to assign to a short variable.

    Original answer (C#)

    In C# (you haven't specified the language, so I'm guessing), the only addition operators on primitive types are:

    int operator +(int x, int y);
    uint operator +(uint x, uint y);
    long operator +(long x, long y);
    ulong operator +(ulong x, ulong y);
    float operator +(float x, float y);
    double operator +(double x, double y);
    

    These are in the C# 3.0 spec, section 7.7.4. In addition, decimal addition is defined:

    decimal operator +(decimal x, decimal y);
    

    (Enumeration addition, string concatenation and delegate combination are also defined there.)

    As you can see, there's no short operator +(short x, short y) operator - so both operands are implicitly converted to int, and the int form is used. That means the result is an expression of type "int", hence the need to cast.

    Android: How do bluetooth UUIDs work?

    To sum up: UUid is used to uniquely identify applications. Each application has a unique UUid

    So, use the same UUid for each device

    What's the difference between a temp table and table variable in SQL Server?

    There are a few differences between Temporary Tables (#tmp) and Table Variables (@tmp), although using tempdb isn't one of them, as spelt out in the MSDN link below.

    As a rule of thumb, for small to medium volumes of data and simple usage scenarios you should use table variables. (This is an overly broad guideline with of course lots of exceptions - see below and following articles.)

    Some points to consider when choosing between them:

    • Temporary Tables are real tables so you can do things like CREATE INDEXes, etc. If you have large amounts of data for which accessing by index will be faster then temporary tables are a good option.

    • Table variables can have indexes by using PRIMARY KEY or UNIQUE constraints. (If you want a non-unique index just include the primary key column as the last column in the unique constraint. If you don't have a unique column, you can use an identity column.) SQL 2014 has non-unique indexes too.

    • Table variables don't participate in transactions and SELECTs are implicitly with NOLOCK. The transaction behaviour can be very helpful, for instance if you want to ROLLBACK midway through a procedure then table variables populated during that transaction will still be populated!

    • Temp tables might result in stored procedures being recompiled, perhaps often. Table variables will not.

    • You can create a temp table using SELECT INTO, which can be quicker to write (good for ad-hoc querying) and may allow you to deal with changing datatypes over time, since you don't need to define your temp table structure upfront.

    • You can pass table variables back from functions, enabling you to encapsulate and reuse logic much easier (eg make a function to split a string into a table of values on some arbitrary delimiter).

    • Using Table Variables within user-defined functions enables those functions to be used more widely (see CREATE FUNCTION documentation for details). If you're writing a function you should use table variables over temp tables unless there's a compelling need otherwise.

    • Both table variables and temp tables are stored in tempdb. But table variables (since 2005) default to the collation of the current database versus temp tables which take the default collation of tempdb (ref). This means you should be aware of collation issues if using temp tables and your db collation is different to tempdb's, causing problems if you want to compare data in the temp table with data in your database.

    • Global Temp Tables (##tmp) are another type of temp table available to all sessions and users.

    Some further reading:

    JPA: unidirectional many-to-one and cascading delete

    Use this way to delete only one side

        @ManyToOne(cascade=CascadeType.PERSIST, fetch = FetchType.LAZY)
    //  @JoinColumn(name = "qid")
        @JoinColumn(name = "qid", referencedColumnName = "qid", foreignKey = @ForeignKey(name = "qid"), nullable = false)
        // @JsonIgnore
        @JsonBackReference
        private QueueGroup queueGroup;
    

    Block direct access to a file over http but allow php script access

    How about custom module based .htaccess script (like its used in CodeIgniter)? I tried and it worked good in CodeIgniter apps. Any ideas to use it on other apps?

    <IfModule authz_core_module>
        Require all denied
    </IfModule>
    <IfModule !authz_core_module>
        Deny from all
    </IfModule>
    

    How do I get a Cron like scheduler in Python?

    I don't know if something like that already exists. It would be easy to write your own with time, datetime and/or calendar modules, see http://docs.python.org/library/time.html

    The only concern for a python solution is that your job needs to be always running and possibly be automatically "resurrected" after a reboot, something for which you do need to rely on system dependent solutions.

    Python one-line "for" expression

    for item in array: array2.append (item)
    

    Or, in this case:

    array2 += array
    

    Returning value from called function in a shell script

    If it's just a true/false test, have your function return 0 for success, and return 1 for failure. The test would then be:

    if function_name; then
      do something
    else
      error condition
    fi
    

    Max retries exceeded with URL in requests

    It is always good to implement exception handling. It does not only help to avoid unexpected exit of script but can also help to log errors and info notification. When using Python requests I prefer to catch exceptions like this:

        try:
            res = requests.get(adress,timeout=30)
        except requests.ConnectionError as e:
            print("OOPS!! Connection Error. Make sure you are connected to Internet. Technical Details given below.\n")
            print(str(e))            
            renewIPadress()
            continue
        except requests.Timeout as e:
            print("OOPS!! Timeout Error")
            print(str(e))
            renewIPadress()
            continue
        except requests.RequestException as e:
            print("OOPS!! General Error")
            print(str(e))
            renewIPadress()
            continue
        except KeyboardInterrupt:
            print("Someone closed the program")
    

    Here renewIPadress() is a user define function which can change the IP address if it get blocked. You can go without this function.

    How can I get the count of line in a file in an efficient way?

    This solution is about 3.6× faster than the top rated answer when tested on a file with 13.8 million lines. It simply reads the bytes into a buffer and counts the \n characters. You could play with the buffer size, but on my machine, anything above 8KB didn't make the code faster.

    private int countLines(File file) throws IOException {
        int lines = 0;
    
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[BUFFER_SIZE]; // BUFFER_SIZE = 8 * 1024
        int read;
    
        while ((read = fis.read(buffer)) != -1) {
            for (int i = 0; i < read; i++) {
                if (buffer[i] == '\n') lines++;
            }
        }
    
        fis.close();
    
        return lines;
    }
    

    Android how to use Environment.getExternalStorageDirectory()

    As described in Documentation Environment.getExternalStorageDirectory() :

    Environment.getExternalStorageDirectory() Return the primary shared/external storage directory.

    This is an example of how to use it reading an image :

    String fileName = "stored_image.jpg";
     String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
     String pathDir = baseDir + "/Android/data/com.mypackage.myapplication/";
    
     File f = new File(pathDir + File.separator + fileName);
    
            if(f.exists()){
              Log.d("Application", "The file " + file.getName() + " exists!";
             }else{
              Log.d("Application", "The file no longer exists!";
             }
    

    gcc makefile error: "No rule to make target ..."

    There are multiple reasons for this error.

    One of the reason where i encountered this error is while building for linux and windows.

    I have a filename with caps BaseClass.h SubClass.h Unix maintains has case-sensitive filenaming convention and windows is case-insensitive.

    C++ why people don't use uppercase in name of header files?

    Try compiling clean build using gmake clean if you are using gmake

    Some text editors has default settings to ignore case-sensitive filenames. This could also lead to the same error.

    how to add a c++ file in Qt Creator whose name starts with capital letters ? It automatically makes it small letter

    Android: Tabs at the BOTTOM

    For all those of you that try to remove the separating line of the tabWidget, here is an example project (and its respective tutorial), that work great for customizing the tabs and thus removing problems when tabs are at bottom. Eclipse Project: android-custom-tabs ; Original explanation: blog; Hope this helped.

    How to know if two arrays have the same values

    Simple Solution to compare the two arrays:

    var array1 = [2, 4];
    var array2 = [4, 2];
    
    array1.sort();
    array2.sort();
    
    if (array1[0] == array2[0]) {
        console.log("Success");
    }else{
        console.log("Wrong");
    }
    

    How to completely uninstall kubernetes

    If you are clearing the cluster so that you can start again, then, in addition to what @rib47 said, I also do the following to ensure my systems are in a state ready for kubeadm init again:

    kubeadm reset -f
    rm -rf /etc/cni /etc/kubernetes /var/lib/dockershim /var/lib/etcd /var/lib/kubelet /var/run/kubernetes ~/.kube/*
    iptables -F && iptables -X
    iptables -t nat -F && iptables -t nat -X
    iptables -t raw -F && iptables -t raw -X
    iptables -t mangle -F && iptables -t mangle -X
    systemctl restart docker
    

    You then need to re-install docker.io, kubeadm, kubectl, and kubelet to make sure they are at the latest versions for your distribution before you re-initialize the cluster.

    EDIT: Discovered that calico adds firewall rules to the raw table so that needs clearing out as well.

    Can´t run .bat file under windows 10

    There is no inherent reason that a simple batch file would run in XP but not Windows 10. It is possible you are referencing a command or a 3rd party utility that no longer exists. To know more about what is actually happening, you will need to do one of the following:

    • Add a pause to the batch file so that you can see what is happening before it exits.
      1. Right click on one of the .bat files and select "edit". This will open the file in notepad.
      2. Go to the very end of the file and add a new line by pressing "enter".
      3. type pause.
      4. Save the file.
      5. Run the file again using the same method you did before.

    - OR -

    • Run the batch file from a static command prompt so the window does not close.
      1. In the folder where the .bat files are located, hold down the "shift" key and right click in the white space.
      2. Select "Open Command Window Here".
      3. You will now see a new command prompt. Type in the name of the batch file and press enter.

    Once you have done this, I recommend creating a new question with the output you see after using one of the methods above.

    How to Get enum item name from its value

    How can I get the item name "Mon, Tue, etc" when I already have the item value "0, 1, etc."

    On some older C code (quite some time ago), I found code analogous to:

    std::string weekEnumToStr(int n)
    {
       std::string s("unknown");
       switch (n)
       {
       case 0: { s = "Mon"; } break;
       case 1: { s = "Tue"; } break;
       case 2: { s = "Wed"; } break;
       case 3: { s = "Thu"; } break;
       case 4: { s = "Fri"; } break;
       case 5: { s = "Sat"; } break;
       case 6: { s = "Sun"; } break;
       }
       return s;
    }
    

    Con: This establishes a "pathological dependency" between the enumeration values and the function... meaning if you change the enum you must change the function to match. I suppose this is true even for a std::map.

    I vaguely remember we found a utility to generate the function code from the enum code. The enum table length had grown to several hundred ... and at some point it is maybe a sound choice to write code to write code.


    Note -

    in an embedded system enhancement effort, my team replaced many tables (100+?) of null-terminated-strings used to map enum int values to their text strings.

    The problem with the tables was that a value out of range was often not noticed because many of these tables were gathered into one region of code / memory, such that a value out-of-range reached past the named table end(s) and returned a null-terminated-string from some subsequent table.

    Using the function-with-switch statement also allowed us to add an assert in the default clause of the switch. The asserts found several more coding errors during test, and our asserts were tied into a static-ram-system-log our field techs could search.

    Sort a single String in Java

    In Java 8 it can be done with:

    String s = "edcba".chars()
        .sorted()
        .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
        .toString();
    

    A slightly shorter alternative that works with a Stream of Strings of length one (each character in the unsorted String is converted into a String in the Stream) is:

    String sorted =
        Stream.of("edcba".split(""))
            .sorted()
            .collect(Collectors.joining());
    

    CSS: fixed to bottom and centered

    revised code by Daniel Kanis:

    just change the following lines in CSS

    .problem {text-align:center}
    .enclose {position:fixed;bottom:0px;width:100%;}
    

    and in html:

    <p class="enclose problem">
    Your footer text here.
    </p>
    

    Python function pointer

    modname, funcname = myvar.rsplit('.', 1)
    getattr(sys.modules[modname], funcname)(parameter1, parameter2)
    

    How to plot two histograms together in R?

    That image you linked to was for density curves, not histograms.

    If you've been reading on ggplot then maybe the only thing you're missing is combining your two data frames into one long one.

    So, let's start with something like what you have, two separate sets of data and combine them.

    carrots <- data.frame(length = rnorm(100000, 6, 2))
    cukes <- data.frame(length = rnorm(50000, 7, 2.5))
    
    # Now, combine your two dataframes into one.  
    # First make a new column in each that will be 
    # a variable to identify where they came from later.
    carrots$veg <- 'carrot'
    cukes$veg <- 'cuke'
    
    # and combine into your new data frame vegLengths
    vegLengths <- rbind(carrots, cukes)
    

    After that, which is unnecessary if your data is in long format already, you only need one line to make your plot.

    ggplot(vegLengths, aes(length, fill = veg)) + geom_density(alpha = 0.2)
    

    enter image description here

    Now, if you really did want histograms the following will work. Note that you must change position from the default "stack" argument. You might miss that if you don't really have an idea of what your data should look like. A higher alpha looks better there. Also note that I made it density histograms. It's easy to remove the y = ..density.. to get it back to counts.

    ggplot(vegLengths, aes(length, fill = veg)) + 
       geom_histogram(alpha = 0.5, aes(y = ..density..), position = 'identity')
    

    enter image description here

    Java List.add() UnsupportedOperationException

    Not every List implementation supports the add() method.

    One common example is the List returned by Arrays.asList(): it is documented not to support any structural modification (i.e. removing or adding elements) (emphasis mine):

    Returns a fixed-size list backed by the specified array.

    Even if that's not the specific List you're trying to modify, the answer still applies to other List implementations that are either immutable or only allow some selected changes.

    You can find out about this by reading the documentation of UnsupportedOperationException and List.add(), which documents this to be an "(optional operation)". The precise meaning of this phrase is explained at the top of the List documentation.

    As a workaround you can create a copy of the list to a known-modifiable implementation like ArrayList:

    seeAlso = new ArrayList<>(seeAlso);
    

    How to trap on UIViewAlertForUnsatisfiableConstraints?

    This usually appears when you want to use UIActivityViewController in iPad.

    Add below, before you present the controller to mark the arrow.

    activityViewController.popoverPresentationController?.sourceRect = senderView.frame // senderView can be your button/view you tapped to call this VC

    I assume you already have below, if not, add together:

    activityViewController.popoverPresentationController?.sourceView = self.view

    Bloomberg Open API

    This API has been available for a long time and enables to get access to market data (including live) if you are running a Bloomberg Terminal or have access to a Bloomberg Server, which is chargeable.

    The only difference is that the API (not its code) has been open sourced, so it can now be used as a dependency in an open source project for example, without any copyrights issues, which was not the case before.

    How to add an item to a drop down list in ASP.NET?

    Try following code;

    DropDownList1.Items.Add(new ListItem(txt_box1.Text));
    

    Onclick event to remove default value in a text input field

    u can use placeholder and when u write a text on the search box placeholder will hidden. Thanks

    <input placeholder="Search" type="text" />
    

    How to detect my browser version and operating system using JavaScript?

    Detecting browser's details:

    var nVer = navigator.appVersion;
    var nAgt = navigator.userAgent;
    var browserName  = navigator.appName;
    var fullVersion  = ''+parseFloat(navigator.appVersion); 
    var majorVersion = parseInt(navigator.appVersion,10);
    var nameOffset,verOffset,ix;
    
    // In Opera, the true version is after "Opera" or after "Version"
    if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
     browserName = "Opera";
     fullVersion = nAgt.substring(verOffset+6);
     if ((verOffset=nAgt.indexOf("Version"))!=-1) 
       fullVersion = nAgt.substring(verOffset+8);
    }
    // In MSIE, the true version is after "MSIE" in userAgent
    else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
     browserName = "Microsoft Internet Explorer";
     fullVersion = nAgt.substring(verOffset+5);
    }
    // In Chrome, the true version is after "Chrome" 
    else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
     browserName = "Chrome";
     fullVersion = nAgt.substring(verOffset+7);
    }
    // In Safari, the true version is after "Safari" or after "Version" 
    else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
     browserName = "Safari";
     fullVersion = nAgt.substring(verOffset+7);
     if ((verOffset=nAgt.indexOf("Version"))!=-1) 
       fullVersion = nAgt.substring(verOffset+8);
    }
    // In Firefox, the true version is after "Firefox" 
    else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
     browserName = "Firefox";
     fullVersion = nAgt.substring(verOffset+8);
    }
    // In most other browsers, "name/version" is at the end of userAgent 
    else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < 
              (verOffset=nAgt.lastIndexOf('/')) ) 
    {
     browserName = nAgt.substring(nameOffset,verOffset);
     fullVersion = nAgt.substring(verOffset+1);
     if (browserName.toLowerCase()==browserName.toUpperCase()) {
      browserName = navigator.appName;
     }
    }
    // trim the fullVersion string at semicolon/space if present
    if ((ix=fullVersion.indexOf(";"))!=-1)
       fullVersion=fullVersion.substring(0,ix);
    if ((ix=fullVersion.indexOf(" "))!=-1)
       fullVersion=fullVersion.substring(0,ix);
    
    majorVersion = parseInt(''+fullVersion,10);
    if (isNaN(majorVersion)) {
     fullVersion  = ''+parseFloat(navigator.appVersion); 
     majorVersion = parseInt(navigator.appVersion,10);
    }
    
    document.write(''
     +'Browser name  = '+browserName+'<br>'
     +'Full version  = '+fullVersion+'<br>'
     +'Major version = '+majorVersion+'<br>'
     +'navigator.appName = '+navigator.appName+'<br>'
     +'navigator.userAgent = '+navigator.userAgent+'<br>'
    )
    

    Source JavaScript: browser name.
    See JSFiddle to detect Browser Details.

    Detecting OS:

    // This script sets OSName variable as follows:
    // "Windows"    for all versions of Windows
    // "MacOS"      for all versions of Macintosh OS
    // "Linux"      for all versions of Linux
    // "UNIX"       for all other UNIX flavors 
    // "Unknown OS" indicates failure to detect the OS
    
    var OSName="Unknown OS";
    if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
    if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
    if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
    if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";
    
    document.write('Your OS: '+OSName);
    

    source JavaScript: OS detection.
    See JSFiddle to detect OS Details.

    _x000D_
    _x000D_
        var nVer = navigator.appVersion;_x000D_
        var nAgt = navigator.userAgent;_x000D_
        var browserName  = navigator.appName;_x000D_
        var fullVersion  = ''+parseFloat(navigator.appVersion); _x000D_
        var majorVersion = parseInt(navigator.appVersion,10);_x000D_
        var nameOffset,verOffset,ix;_x000D_
        _x000D_
        // In Opera, the true version is after "Opera" or after "Version"_x000D_
        if ((verOffset=nAgt.indexOf("Opera"))!=-1) {_x000D_
         browserName = "Opera";_x000D_
         fullVersion = nAgt.substring(verOffset+6);_x000D_
         if ((verOffset=nAgt.indexOf("Version"))!=-1) _x000D_
           fullVersion = nAgt.substring(verOffset+8);_x000D_
        }_x000D_
        // In MSIE, the true version is after "MSIE" in userAgent_x000D_
        else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {_x000D_
         browserName = "Microsoft Internet Explorer";_x000D_
         fullVersion = nAgt.substring(verOffset+5);_x000D_
        }_x000D_
        // In Chrome, the true version is after "Chrome" _x000D_
        else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {_x000D_
         browserName = "Chrome";_x000D_
         fullVersion = nAgt.substring(verOffset+7);_x000D_
        }_x000D_
        // In Safari, the true version is after "Safari" or after "Version" _x000D_
        else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {_x000D_
         browserName = "Safari";_x000D_
         fullVersion = nAgt.substring(verOffset+7);_x000D_
         if ((verOffset=nAgt.indexOf("Version"))!=-1) _x000D_
           fullVersion = nAgt.substring(verOffset+8);_x000D_
        }_x000D_
        // In Firefox, the true version is after "Firefox" _x000D_
        else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {_x000D_
         browserName = "Firefox";_x000D_
         fullVersion = nAgt.substring(verOffset+8);_x000D_
        }_x000D_
        // In most other browsers, "name/version" is at the end of userAgent _x000D_
        else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < _x000D_
                  (verOffset=nAgt.lastIndexOf('/')) ) _x000D_
        {_x000D_
         browserName = nAgt.substring(nameOffset,verOffset);_x000D_
         fullVersion = nAgt.substring(verOffset+1);_x000D_
         if (browserName.toLowerCase()==browserName.toUpperCase()) {_x000D_
          browserName = navigator.appName;_x000D_
         }_x000D_
        }_x000D_
        // trim the fullVersion string at semicolon/space if present_x000D_
        if ((ix=fullVersion.indexOf(";"))!=-1)_x000D_
           fullVersion=fullVersion.substring(0,ix);_x000D_
        if ((ix=fullVersion.indexOf(" "))!=-1)_x000D_
           fullVersion=fullVersion.substring(0,ix);_x000D_
        _x000D_
        majorVersion = parseInt(''+fullVersion,10);_x000D_
        if (isNaN(majorVersion)) {_x000D_
         fullVersion  = ''+parseFloat(navigator.appVersion); _x000D_
         majorVersion = parseInt(navigator.appVersion,10);_x000D_
        }_x000D_
        _x000D_
        document.write(''_x000D_
         +'Browser name  = '+browserName+'<br>'_x000D_
         +'Full version  = '+fullVersion+'<br>'_x000D_
         +'Major version = '+majorVersion+'<br>'_x000D_
         +'navigator.appName = '+navigator.appName+'<br>'_x000D_
         +'navigator.userAgent = '+navigator.userAgent+'<br>'_x000D_
        )_x000D_
    _x000D_
        // This script sets OSName variable as follows:_x000D_
        // "Windows"    for all versions of Windows_x000D_
        // "MacOS"      for all versions of Macintosh OS_x000D_
        // "Linux"      for all versions of Linux_x000D_
        // "UNIX"       for all other UNIX flavors _x000D_
        // "Unknown OS" indicates failure to detect the OS_x000D_
        _x000D_
        var OSName="Unknown OS";_x000D_
        if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";_x000D_
        if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";_x000D_
        if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";_x000D_
        if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";_x000D_
        _x000D_
        document.write('Your OS: '+OSName);
    _x000D_
    _x000D_
    _x000D_

    SQL "select where not in subquery" returns no results

    Just off the top of my head...

    select c.commonID, t1.commonID, t2.commonID
    from Common c
         left outer join Table1 t1 on t1.commonID = c.commonID
         left outer join Table2 t2 on t2.commonID = c.commonID
    where t1.commonID is null 
         and t2.commonID is null
    

    I ran a few tests and here were my results w.r.t. @patmortech's answer and @rexem's comments.

    If either Table1 or Table2 is not indexed on commonID, you get a table scan but @patmortech's query is still twice as fast (for a 100K row master table).

    If neither are indexed on commonID, you get two table scans and the difference is negligible.

    If both are indexed on commonID, the "not exists" query runs in 1/3 the time.

    console.log(result) returns [object Object]. How do I get result.name?

    Try adding JSON.stringify(result) to convert the JS Object into a JSON string.

    From your code I can see you are logging the result in error which is called if the AJAX request fails, so I'm not sure how you'd go about accessing the id/name/etc. then (you are checking for success inside the error condition!).

    Note that if you use Chrome's console you should be able to browse through the object without having to stringify the JSON, which makes it easier to debug.

    Detecting attribute change of value of an attribute I made

    You would have to watch the DOM node changes. There is an API called MutationObserver, but it looks like the support for it is very limited. This SO answer has a link to the status of the API, but it seems like there is no support for it in IE or Opera so far.

    One way you could get around this problem is to have the part of the code that modifies the data-select-content-val attribute dispatch an event that you can listen to.

    For example, see: http://jsbin.com/arucuc/3/edit on how to tie it together.

    The code here is

    $(function() {  
      // Here you register for the event and do whatever you need to do.
      $(document).on('data-attribute-changed', function() {
        var data = $('#contains-data').data('mydata');
        alert('Data changed to: ' + data);
      });
    
      $('#button').click(function() {
        $('#contains-data').data('mydata', 'foo');
        // Whenever you change the attribute you will user the .trigger
        // method. The name of the event is arbitrary
        $(document).trigger('data-attribute-changed');
      });
    
       $('#getbutton').click(function() {
        var data = $('#contains-data').data('mydata');
        alert('Data is: ' + data);
      });
    });
    

    Is there any difference between a GUID and a UUID?

    GUID is Microsoft's implementation of the UUID standard.

    Per Wikipedia:

    The term GUID usually refers to Microsoft's implementation of the Universally Unique Identifier (UUID) standard.

    An updated quote from that same Wikipedia article:

    RFC 4122 itself states that UUIDs "are also known as GUIDs". All this suggests that "GUID", while originally referring to a variant of UUID used by Microsoft, has become simply an alternative name for UUID…

    Escape double quote in grep

    The problem is that you aren't correctly escaping the input string, try:

    echo "\"member\":\"time\"" | grep -e "member\""
    

    Alternatively, you can use unescaped double quotes within single quotes:

    echo '"member":"time"' | grep -e 'member"'
    

    It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd').

    What is the Java equivalent for LINQ?

    Shameless self plug: you could always use https://github.com/amoerie/jstreams

    Works on Java 6 and up, a perfect fit for Android development.

    It looks a lot like Scala operators, lodash, C# LINQ, etc.

    Open application after clicking on Notification

    Here's example using NotificationCompact.Builder class which is the recent version to build notification.

    private void startNotification() {
        Log.i("NextActivity", "startNotification");
    
     // Sets an ID for the notification
          int mNotificationId = 001;
    
        // Build Notification , setOngoing keeps the notification always in status bar
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ldb)
                        .setContentTitle("Stop LDB")
                        .setContentText("Click to stop LDB")
                        .setOngoing(true);
    
        // Create pending intent, mention the Activity which needs to be 
        //triggered when user clicks on notification(StopScript.class in this case)
    
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, StopScript.class), PendingIntent.FLAG_UPDATE_CURRENT);
    
    
        mBuilder.setContentIntent(contentIntent);
    
    
        // Gets an instance of the NotificationManager service
       NotificationManager mNotificationManager =
                (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
    
    
        // Builds the notification and issues it.
        mNotificationManager.notify(mNotificationId, mBuilder.build());
    
    
    }
    

    How do I return the response from an asynchronous call?

    If you're using promises, this answer is for you.

    This means AngularJS, jQuery (with deferred), native XHR's replacement (fetch), EmberJS, BackboneJS's save or any node library that returns promises.

    Your code should be something along the lines of this:

    function foo() {
        var data;
        // or $.get(...).then, or request(...).then, or query(...).then
        fetch("/echo/json").then(function(response){
            data = response.json();
        });
        return data;
    }
    
    var result = foo(); // result is always undefined no matter what.
    

    Felix Kling did a fine job writing an answer for people using jQuery with callbacks for AJAX. I have an answer for native XHR. This answer is for generic usage of promises either on the frontend or backend.


    The core issue

    The JavaScript concurrency model in the browser and on the server with NodeJS/io.js is asynchronous and reactive.

    Whenever you call a method that returns a promise, the then handlers are always executed asynchronously - that is, after the code below them that is not in a .then handler.

    This means when you're returning data the then handler you've defined did not execute yet. This in turn means that the value you're returning has not been set to the correct value in time.

    Here is a simple analogy for the issue:

    _x000D_
    _x000D_
        function getFive(){_x000D_
            var data;_x000D_
            setTimeout(function(){ // set a timer for one second in the future_x000D_
               data = 5; // after a second, do this_x000D_
            }, 1000);_x000D_
            return data;_x000D_
        }_x000D_
        document.body.innerHTML = getFive(); // `undefined` here and not 5
    _x000D_
    _x000D_
    _x000D_

    The value of data is undefined since the data = 5 part has not executed yet. It will likely execute in a second but by that time it is irrelevant to the returned value.

    Since the operation did not happen yet (AJAX, server call, IO, timer) you're returning the value before the request got the chance to tell your code what that value is.

    One possible solution to this problem is to code re-actively , telling your program what to do when the calculation completed. Promises actively enable this by being temporal (time-sensitive) in nature.

    Quick recap on promises

    A Promise is a value over time. Promises have state, they start as pending with no value and can settle to:

    • fulfilled meaning that the computation completed successfully.
    • rejected meaning that the computation failed.

    A promise can only change states once after which it will always stay at the same state forever. You can attach then handlers to promises to extract their value and handle errors. then handlers allow chaining of calls. Promises are created by using APIs that return them. For example, the more modern AJAX replacement fetch or jQuery's $.get return promises.

    When we call .then on a promise and return something from it - we get a promise for the processed value. If we return another promise we'll get amazing things, but let's hold our horses.

    With promises

    Let's see how we can solve the above issue with promises. First, let's demonstrate our understanding of promise states from above by using the Promise constructor for creating a delay function:

    function delay(ms){ // takes amount of milliseconds
        // returns a new promise
        return new Promise(function(resolve, reject){
            setTimeout(function(){ // when the time is up
                resolve(); // change the promise to the fulfilled state
            }, ms);
        });
    }
    

    Now, after we converted setTimeout to use promises, we can use then to make it count:

    _x000D_
    _x000D_
    function delay(ms){ // takes amount of milliseconds_x000D_
      // returns a new promise_x000D_
      return new Promise(function(resolve, reject){_x000D_
        setTimeout(function(){ // when the time is up_x000D_
          resolve(); // change the promise to the fulfilled state_x000D_
        }, ms);_x000D_
      });_x000D_
    }_x000D_
    _x000D_
    function getFive(){_x000D_
      // we're RETURNING the promise, remember, a promise is a wrapper over our value_x000D_
      return delay(100).then(function(){ // when the promise is ready_x000D_
          return 5; // return the value 5, promises are all about return values_x000D_
      })_x000D_
    }_x000D_
    // we _have_ to wrap it like this in the call site, we can't access the plain value_x000D_
    getFive().then(function(five){ _x000D_
       document.body.innerHTML = five;_x000D_
    });
    _x000D_
    _x000D_
    _x000D_

    Basically, instead of returning a value which we can't do because of the concurrency model - we're returning a wrapper for a value that we can unwrap with then. It's like a box you can open with then.

    Applying this

    This stands the same for your original API call, you can:

    function foo() {
        // RETURN the promise
        return fetch("/echo/json").then(function(response){
            return response.json(); // process it inside the `then`
        });
    }
    
    foo().then(function(response){
        // access the value inside the `then`
    })
    

    So this works just as well. We've learned we can't return values from already asynchronous calls but we can use promises and chain them to perform processing. We now know how to return the response from an asynchronous call.

    ES2015 (ES6)

    ES6 introduces generators which are functions that can return in the middle and then resume the point they were at. This is typically useful for sequences, for example:

    function* foo(){ // notice the star, this is ES6 so new browsers/node/io only
        yield 1;
        yield 2;
        while(true) yield 3;
    }
    

    Is a function that returns an iterator over the sequence 1,2,3,3,3,3,.... which can be iterated. While this is interesting on its own and opens room for a lot of possibility there is one particular interesting case.

    If the sequence we're producing is a sequence of actions rather than numbers - we can pause the function whenever an action is yielded and wait for it before we resume the function. So instead of a sequence of numbers, we need a sequence of future values - that is: promises.

    This somewhat tricky but very powerful trick lets us write asynchronous code in a synchronous manner. There are several "runners" that do this for you, writing one is a short few lines of code but is beyond the scope of this answer. I'll be using Bluebird's Promise.coroutine here, but there are other wrappers like co or Q.async.

    var foo = coroutine(function*(){
        var data = yield fetch("/echo/json"); // notice the yield
        // code here only executes _after_ the request is done
        return data.json(); // data is defined
    });
    

    This method returns a promise itself, which we can consume from other coroutines. For example:

    var main = coroutine(function*(){
       var bar = yield foo(); // wait our earlier coroutine, it returns a promise
       // server call done here, code below executes when done
       var baz = yield fetch("/api/users/"+bar.userid); // depends on foo's result
       console.log(baz); // runs after both requests done
    });
    main();
    

    ES2016 (ES7)

    In ES7, this is further standardized, there are several proposals right now but in all of them you can await promise. This is just "sugar" (nicer syntax) for the ES6 proposal above by adding the async and await keywords. Making the above example:

    async function foo(){
        var data = await fetch("/echo/json"); // notice the await
        // code here only executes _after_ the request is done
        return data.json(); // data is defined
    }
    

    It still returns a promise just the same :)

    What is the purpose of a self executing function in javascript?

    (function(){
        var foo = {
            name: 'bob'
        };
        console.log(foo.name); // bob
    })();
    console.log(foo.name); // Reference error
    

    Actually, the above function will be treated as function expression without a name.

    The main purpose of wrapping a function with close and open parenthesis is to avoid polluting the global space.

    The variables and functions inside the function expression became private (i.e) they will not be available outside of the function.

    React - uncaught TypeError: Cannot read property 'setState' of undefined

    There are two solutions of this issue:

    The first solution is add a constructor to your component and bind your function like bellow:

    constructor(props) {
            super(props);
    
            ...
    
            this.delta = this.delta.bind(this);
        }
    

    So do this:

    this.delta = this.delta.bind(this); 
    

    Instead of this:

    this.delta.bind(this);
    

    The second solution is to use an arrow function instead:

    delta = () => {
           this.setState({
               count : this.state.count++
          });
       }
    

    Actually arrow function DOES NOT bind it’s own this. Arrow Functions lexically bind their context so this actually refers to the originating context.

    For more information about bind function:

    Bind function Understanding JavaScript Bind ()

    For more information about arrow function:

    Javascript ES6 — Arrow Functions and Lexical this

    What is time_t ultimately a typedef to?

    The time_t Wikipedia article article sheds some light on this. The bottom line is that the type of time_t is not guaranteed in the C specification.

    The time_t datatype is a data type in the ISO C library defined for storing system time values. Such values are returned from the standard time() library function. This type is a typedef defined in the standard header. ISO C defines time_t as an arithmetic type, but does not specify any particular type, range, resolution, or encoding for it. Also unspecified are the meanings of arithmetic operations applied to time values.

    Unix and POSIX-compliant systems implement the time_t type as a signed integer (typically 32 or 64 bits wide) which represents the number of seconds since the start of the Unix epoch: midnight UTC of January 1, 1970 (not counting leap seconds). Some systems correctly handle negative time values, while others do not. Systems using a 32-bit time_t type are susceptible to the Year 2038 problem.

    nodejs module.js:340 error: cannot find module

    EDIT: This answer is outdated. With things like Yarn and NPM 5's lockfiles it is now easier to ensure you're dependencies are correct on platforms like Heroku

    I had a similar issue related to node_modules being modified somehow locally but the change was not reflect on Heroku, causing my app to crash. It's relatively easy fix if this is your issue:

    # Remove node_modules
    rm -fr node_modules
    
    # Reinstall packages
    npm i
    
    # Commit changes
    git add node_modules
    git commit -m 'Fix node_modules dependencies.'
    git push heroku master
    

    Hope that helps for others with a similar issue.

    Google Chrome redirecting localhost to https

    I also have been struggling with this issue. Seems that HSTS is intended for only domain names. So if you are developing in local machine, it much easier to use IP address. So I switched from localhost to 127.0.0.1

    An existing connection was forcibly closed by the remote host

    I had the same issue and managed to resolve it eventually. In my case, the port that the client sends the request to did not have a SSL cert binding to it. So I fixed the issue by binding a SSL cert to the port on the server side. Once that was done, this exception went away.

    How to test if a string is basically an integer in quotes using Ruby

    I like the following, straight forward:

    def is_integer?(str)
      str.to_i != 0 || str == '0' || str == '-0'
    end
    
    is_integer?('123')
    => true
    
    is_integer?('sdf')
    => false
    
    is_integer?('-123')
    => true
    
    is_integer?('0')
    => true
    
    is_integer?('-0')
    => true
    

    Careful though:

    is_integer?('123sdfsdf')
    => true
    

    Is there a maximum number you can set Xmx to when trying to increase jvm memory?

    Have a look at this for some common errors in setting the java heap. You've probably set the heap size to a larger value than your computer's physical memory.

    You should avoid solving this problem by increasing the heap size. Instead, you should profile your application to see where you spend such a large amount of memory.

    Run Batch File On Start-up

    There are a few ways to run a batch file on start up. The one I usually use is through task scheduler. If you press the windows key then type task scheduler it will come up as an option (or find through administerative tools).

    When you create a new task you can chose from trigger options such as 'At log on' for a specific user, on workstation unlock etc. Then in actions you select start a program and put the full path to your batch script (there is also an option to put any command line args required).

    Here is a an example script to launch Stack Overflow in Firefox:

    @echo off
    
    title Auto launch Stack Overflow
    
    
    start firefox http://stackoverflow.com/questions/tagged/python+or+sql+or+sqlite+or+plsql+or+oracle+or+windows-7+or+cmd+or+excel+or+access+or+vba+or+excel-vba+or+access-vba?sort=newest
    
    REM Optional - I tend to log these sorts of events so that you can see what has happened afterwards
    echo %date% %time%, %computername% >> %logs%\StackOverflowAuto.csv
    
    exit
    

    How to restart a rails server on Heroku?

    Just type the following commands from console.

    cd /your_project
    heroku restart
    

    Inline instantiation of a constant List

    const is for compile-time constants. You could just make it static readonly, but that would only apply to the METRICS variable itself (which should typically be Metrics instead, by .NET naming conventions). It wouldn't make the list immutable - so someone could call METRICS.Add("shouldn't be here");

    You may want to use a ReadOnlyCollection<T> to wrap it. For example:

    public static readonly IList<String> Metrics = new ReadOnlyCollection<string>
        (new List<String> { 
             SourceFile.LoC, SourceFile.McCabe, SourceFile.NoM,
             SourceFile.NoA, SourceFile.FanOut, SourceFile.FanIn, 
             SourceFile.Par, SourceFile.Ndc, SourceFile.Calls });
    

    ReadOnlyCollection<T> just wraps a potentially-mutable collection, but as nothing else will have access to the List<T> afterwards, you can regard the overall collection as immutable.

    (The capitalization here is mostly guesswork - using fuller names would make them clearer, IMO.)

    Whether you declare it as IList<string>, IEnumerable<string>, ReadOnlyCollection<string> or something else is up to you... if you expect that it should only be treated as a sequence, then IEnumerable<string> would probably be most appropriate. If the order matters and you want people to be able to access it by index, IList<T> may be appropriate. If you want to make the immutability apparent, declaring it as ReadOnlyCollection<T> could be handy - but inflexible.

    Search for an item in a Lua list

    Use the following representation instead:

    local items = { apple=true, orange=true, pear=true, banana=true }
    if items.apple then
        ...
    end
    

    Setting an HTML text input box's "default" value. Revert the value when clicking ESC

    See the defaultValue property of a text input, it's also used when you reset the form by clicking an <input type="reset"/> button (http://www.w3schools.com/jsref/prop_text_defaultvalue.asp )

    btw, defaultValue and placeholder text are different concepts, you need to see which one better fits your needs

    How to serialize SqlAlchemy result to JSON?

    Custom serialization and deserialization.

    "from_json" (class method) builds a Model object based on json data.

    "deserialize" could be called only on instance, and merge all data from json into Model instance.

    "serialize" - recursive serialization

    __write_only__ property is needed to define write only properties ("password_hash" for example).

    class Serializable(object):
        __exclude__ = ('id',)
        __include__ = ()
        __write_only__ = ()
    
        @classmethod
        def from_json(cls, json, selfObj=None):
            if selfObj is None:
                self = cls()
            else:
                self = selfObj
            exclude = (cls.__exclude__ or ()) + Serializable.__exclude__
            include = cls.__include__ or ()
            if json:
                for prop, value in json.iteritems():
                    # ignore all non user data, e.g. only
                    if (not (prop in exclude) | (prop in include)) and isinstance(
                            getattr(cls, prop, None), QueryableAttribute):
                        setattr(self, prop, value)
            return self
    
        def deserialize(self, json):
            if not json:
                return None
            return self.__class__.from_json(json, selfObj=self)
    
        @classmethod
        def serialize_list(cls, object_list=[]):
            output = []
            for li in object_list:
                if isinstance(li, Serializable):
                    output.append(li.serialize())
                else:
                    output.append(li)
            return output
    
        def serialize(self, **kwargs):
    
            # init write only props
            if len(getattr(self.__class__, '__write_only__', ())) == 0:
                self.__class__.__write_only__ = ()
            dictionary = {}
            expand = kwargs.get('expand', ()) or ()
            prop = 'props'
            if expand:
                # expand all the fields
                for key in expand:
                    getattr(self, key)
            iterable = self.__dict__.items()
            is_custom_property_set = False
            # include only properties passed as parameter
            if (prop in kwargs) and (kwargs.get(prop, None) is not None):
                is_custom_property_set = True
                iterable = kwargs.get(prop, None)
            # loop trough all accessible properties
            for key in iterable:
                accessor = key
                if isinstance(key, tuple):
                    accessor = key[0]
                if not (accessor in self.__class__.__write_only__) and not accessor.startswith('_'):
                    # force select from db to be able get relationships
                    if is_custom_property_set:
                        getattr(self, accessor, None)
                    if isinstance(self.__dict__.get(accessor), list):
                        dictionary[accessor] = self.__class__.serialize_list(object_list=self.__dict__.get(accessor))
                    # check if those properties are read only
                    elif isinstance(self.__dict__.get(accessor), Serializable):
                        dictionary[accessor] = self.__dict__.get(accessor).serialize()
                    else:
                        dictionary[accessor] = self.__dict__.get(accessor)
            return dictionary
    

    Vue.js get selected option on @change

    The changed value will be in event.target.value

    _x000D_
    _x000D_
    const app = new Vue({_x000D_
      el: "#app",_x000D_
      data: function() {_x000D_
        return {_x000D_
          message: "Vue"_x000D_
        }_x000D_
      },_x000D_
      methods: {_x000D_
        onChange(event) {_x000D_
          console.log(event.target.value);_x000D_
        }_x000D_
      }_x000D_
    })
    _x000D_
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>_x000D_
    <div id="app">_x000D_
      <select name="LeaveType" @change="onChange" class="form-control">_x000D_
       <option value="1">Annual Leave/ Off-Day</option>_x000D_
       <option value="2">On Demand Leave</option>_x000D_
    </select>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    codeigniter, result() vs. result_array()

    result_array() is faster, result() is easier

    Quotation marks inside a string

    String name = "\"john\"";
    

    You have to escape the second pair of quotation marks using the \ character in front. It might be worth looking at this link, which explains in some detail.

    Other scenario where you set variable:

    String name2 = "\""+name+"\"";
    

    Sequence in console:

    > String name = "\"john\"";
    > name
    ""john""
    > String name2 = "\""+name+"\"";
    > name2
    """john"""
    

    PostgreSQL JOIN data from 3 tables

    Something like:

    select t1.name, t2.image_id, t3.path
    from table1 t1 inner join table2 t2 on t1.person_id = t2.person_id
    inner join table3 t3 on t2.image_id=t3.image_id
    

    Flask Python Buttons

    In case anyone was still looking and came across this SO post like I did.

    <input type="submit" name="open" value="Open">
    <input type="submit" name="close" value="Close">
    

    def contact():
        if "open" in request.form:
            pass
        elif "close" in request.form:
            pass
        return render_template('contact.html')
    

    Simple, concise, and it works. Don't even need to instantiate a form object.

    How to enable CORS on Firefox?

    It's only possible when the server sends this header: Access-Control-Allow-Origin: *

    If this is your code then you can setup it like this (PHP):

    header('Access-Control-Allow-Origin: *');
    

    Div Scrollbar - Any way to style it?

    Looking at the web I find some simple way to style scrollbars.

    This is THE guy! http://almaer.com/blog/creating-custom-scrollbars-with-css-how-css-isnt-great-for-every-task

    And here my implementation! https://dl.dropbox.com/u/1471066/cloudBI/cssScrollbars.png

    /* Turn on a 13x13 scrollbar */
    ::-webkit-scrollbar {
        width: 10px;
        height: 13px;
    }
    
    ::-webkit-scrollbar-button:vertical {
        background-color: silver;
        border: 1px solid gray;
    }
    
    /* Turn on single button up on top, and down on bottom */
    ::-webkit-scrollbar-button:start:decrement,
    ::-webkit-scrollbar-button:end:increment {
        display: block;
    }
    
    /* Turn off the down area up on top, and up area on bottom */
    ::-webkit-scrollbar-button:vertical:start:increment,
    ::-webkit-scrollbar-button:vertical:end:decrement {
        display: none;
    }
    
    /* Place The scroll down button at the bottom */
    ::-webkit-scrollbar-button:vertical:increment {
        display: none;
    }
    
    /* Place The scroll up button at the up */
    ::-webkit-scrollbar-button:vertical:decrement {
        display: none;
    }
    
    /* Place The scroll down button at the bottom */
    ::-webkit-scrollbar-button:horizontal:increment {
        display: none;
    }
    
    /* Place The scroll up button at the up */
    ::-webkit-scrollbar-button:horizontal:decrement {
        display: none;
    }
    
    ::-webkit-scrollbar-track:vertical {
        background-color: blue;
        border: 1px dashed pink;
    }
    
    /* Top area above thumb and below up button */
    ::-webkit-scrollbar-track-piece:vertical:start {
        border: 0px;
    }
    
    /* Bottom area below thumb and down button */
    ::-webkit-scrollbar-track-piece:vertical:end {
        border: 0px;
    }
    
    /* Track below and above */
    ::-webkit-scrollbar-track-piece {
        background-color: silver;
    }
    
    /* The thumb itself */
    ::-webkit-scrollbar-thumb:vertical {
        height: 50px;
        background-color: gray;
    }
    
    /* The thumb itself */
    ::-webkit-scrollbar-thumb:horizontal {
        height: 50px;
        background-color: gray;
    }
    
    /* Corner */
    ::-webkit-scrollbar-corner:vertical {
        background-color: black;
    }
    
    /* Resizer */
    ::-webkit-scrollbar-resizer:vertical {
        background-color: gray;
    }
    

    Dropdownlist validation in Asp.net Using Required field validator

    I was struggling with this for a few days until I chanced on the issue when I had to build a new Dropdown. I had several DropDownList controls and attempted to get validation working with no luck. One was databound and the other was filled from the aspx page. I needed to drop the databound one and add a second manual list. In my case Validators failed if you built a dropdown like this and looked at any value (0 or -1) for either a required or compare validator:

    <asp:DropDownList ID="DDL_Reason" CssClass="inputDropDown" runat="server">
    <asp:ListItem>--Select--</asp:ListItem>                                                                                                
    <asp:ListItem>Expired</asp:ListItem>                                                                                                
    <asp:ListItem>Lost/Stolen</asp:ListItem>                                                                                                
    <asp:ListItem>Location Change</asp:ListItem>                                                                                            
    </asp:DropDownList>
    

    However adding the InitialValue like this worked instantly for a compare Validator.

    <asp:ListItem Text="-- Select --" Value="-1"></asp:ListItem>
    

    How to get current local date and time in Kotlin

    checkout these easy to use Kotlin extensions for date format

    fun String.getStringDate(initialFormat: String, requiredFormat: String, locale: Locale = Locale.getDefault()): String {
        return this.toDate(initialFormat, locale).toString(requiredFormat, locale)
    }
    
    fun String.toDate(format: String, locale: Locale = Locale.getDefault()): Date = SimpleDateFormat(format, locale).parse(this)
    
    fun Date.toString(format: String, locale: Locale = Locale.getDefault()): String {
        val formatter = SimpleDateFormat(format, locale)
        return formatter.format(this)
    }
    

    How to scan a folder in Java?

    Not sure how you want to represent the tree? Anyway here's an example which scans the entire subtree using recursion. Files and directories are treated alike. Note that File.listFiles() returns null for non-directories.

    public static void main(String[] args) {
        Collection<File> all = new ArrayList<File>();
        addTree(new File("."), all);
        System.out.println(all);
    }
    
    static void addTree(File file, Collection<File> all) {
        File[] children = file.listFiles();
        if (children != null) {
            for (File child : children) {
                all.add(child);
                addTree(child, all);
            }
        }
    }
    

    Java 7 offers a couple of improvements. For example, DirectoryStream provides one result at a time - the caller no longer has to wait for all I/O operations to complete before acting. This allows incremental GUI updates, early cancellation, etc.

    static void addTree(Path directory, Collection<Path> all)
            throws IOException {
        try (DirectoryStream<Path> ds = Files.newDirectoryStream(directory)) {
            for (Path child : ds) {
                all.add(child);
                if (Files.isDirectory(child)) {
                    addTree(child, all);
                }
            }
        }
    }
    

    Note that the dreaded null return value has been replaced by IOException.

    Java 7 also offers a tree walker:

    static void addTree(Path directory, final Collection<Path> all)
            throws IOException {
        Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                    throws IOException {
                all.add(file);
                return FileVisitResult.CONTINUE;
            }
        });
    }
    

    Increasing Heap Size on Linux Machines

    You can use the following code snippet :

    java -XX:+PrintFlagsFinal -Xms512m -Xmx1024m -Xss512k -XX:PermSize=64m -XX:MaxPermSize=128m
        -version | grep -iE 'HeapSize|PermSize|ThreadStackSize'
    

    In my pc I am getting following output :

        uintx InitialHeapSize                          := 536870912       {product}
        uintx MaxHeapSize                              := 1073741824      {product}
        uintx PermSize                                 := 67108864        {pd product}
        uintx MaxPermSize                              := 134217728       {pd product}
         intx ThreadStackSize                          := 512             {pd product}
    

    How do I get the different parts of a Flask request's url?

    another example:

    request:

    curl -XGET http://127.0.0.1:5000/alert/dingding/test?x=y
    

    then:

    request.method:              GET
    request.url:                 http://127.0.0.1:5000/alert/dingding/test?x=y
    request.base_url:            http://127.0.0.1:5000/alert/dingding/test
    request.url_charset:         utf-8
    request.url_root:            http://127.0.0.1:5000/
    str(request.url_rule):       /alert/dingding/test
    request.host_url:            http://127.0.0.1:5000/
    request.host:                127.0.0.1:5000
    request.script_root:
    request.path:                /alert/dingding/test
    request.full_path:           /alert/dingding/test?x=y
    
    request.args:                ImmutableMultiDict([('x', 'y')])
    request.args.get('x'):       y
    

    'Conda' is not recognized as internal or external command

    In addition to adding C:\Users\yourusername\Anaconda3 and C:\Users\yourusername\Anaconda3\Scripts, as recommended by Raja (above), also add C:\Users\yourusername\Anaconda3\Library\bin to your path variable. This will prevent an SSL error that is bound to happen if you're performing this on a fresh install of Anaconda.

    How can I make a TextArea 100% width without overflowing when padding is present in CSS?

    _x000D_
    _x000D_
    * {_x000D_
        box-sizing: border-box;_x000D_
    }_x000D_
    _x000D_
    .container {_x000D_
        border-radius: 5px;_x000D_
        background-color: #f2f2f2;_x000D_
        padding: 20px;_x000D_
    }_x000D_
    _x000D_
    /* Clear floats after the columns */_x000D_
    .row:after {_x000D_
        content: "";_x000D_
        display: table;_x000D_
        clear: both;_x000D_
    }_x000D_
    _x000D_
    input[type=text], select, textarea{_x000D_
        width: 100%;_x000D_
        padding: 12px;_x000D_
        border: 1px solid #ccc;_x000D_
        border-radius: 4px;_x000D_
        box-sizing: border-box;_x000D_
        resize: vertical;_x000D_
    }
    _x000D_
    <div class="container">_x000D_
      <div class="row">_x000D_
        <label for="name">Name</label>_x000D_
        <input type="text" id="name" name="name" placeholder="Your name..">_x000D_
      </div>_x000D_
      <div class="row">_x000D_
        <label for="country">Country</label>_x000D_
        <select id="country" name="country">_x000D_
          <option value="australia">UK</option>_x000D_
          <option value="canada">USA</option>_x000D_
          <option value="usa">RU</option>_x000D_
        </select>_x000D_
      </div>    _x000D_
      <div class="row">_x000D_
        <label for="subject">Subject</label>_x000D_
        <textarea id="subject" name="subject" placeholder="Write something.." style="height:200px"></textarea>_x000D_
      </div>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    How do I do an OR filter in a Django query?

    It is worth to note that it's possible to add Q expressions.

    For example:

    from django.db.models import Q
    
    query = Q(first_name='mark')
    query.add(Q(email='[email protected]'), Q.OR)
    query.add(Q(last_name='doe'), Q.AND)
    
    queryset = User.objects.filter(query)
    

    This ends up with a query like :

    (first_name = 'mark' or email = '[email protected]') and last_name = 'doe'
    

    This way there is no need to deal with or operators, reduce's etc.

    Is there a way to cast float as a decimal without rounding and preserving its precision?

    cast (field1 as decimal(53,8)
    ) field 1
    

    The default is: decimal(18,0)

    What does .pack() do?

    The pack method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize or setBounds (which also sets the frame location). In general, using pack is preferable to calling setSize, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.

    From Java tutorial

    You should also refer to Javadocs any time you need additional information on any Java API

    PG COPY error: invalid input syntax for integer

    All in python (using psycopg2), create the empty table first then use copy_expert to load the csv into it. It should handle for empty values.

    import psycopg2
    conn = psycopg2.connect(host="hosturl", database="db_name", user="username", password="password")
    cur = conn.cursor()
    cur.execute("CREATE TABLE schema.destination_table ("
                "age integer, "
                "first_name varchar(20), "
                "last_name varchar(20)"
                ");")
    
    with open(r'C:/tmp/people.csv', 'r') as f:
        next(f)  # Skip the header row. Or remove this line if csv has no header.
        conn.cursor.copy_expert("""COPY schema.destination_table FROM STDIN WITH (FORMAT CSV)""", f)
    

    python tuple to dict

    Here are couple ways of doing it:

    >>> t = ((1, 'a'), (2, 'b'))
    
    >>> # using reversed function
    >>> dict(reversed(i) for i in t)
    {'a': 1, 'b': 2}
    
    >>> # using slice operator
    >>> dict(i[::-1] for i in t)
    {'a': 1, 'b': 2}
    

    Stop MySQL service windows

    I got the same problem and here my solution:

    1. go to service.msc and find mysql service. set it as start manually.
    2. go to task manager - processes tab and find mysqld. stop it
    3. go to task manager - services tab find mysql service and stop it

    Catch checked change event of a checkbox

    $(document).ready(function(){
        checkUncheckAll("#select_all","[name='check_boxes[]']");
    });
    
    var NUM_BOXES = 10;
    // last checkbox the user clicked
    var last = -1;
    function check(event) {
      // in IE, the event object is a property of the window object
      // in Mozilla, event object is passed to event handlers as a parameter
      event = event || window.event;
    
      var num = parseInt(/box\[(\d+)\]/.exec(this.name)[1]);
      if (event.shiftKey && last != -1) {
        var di = num > last ? 1 : -1;
        for (var i = last; i != num; i += di)
          document.forms.boxes['box[' + i + ']'].checked = true;
      }
      last = num;
    }
    function init() {
      for (var i = 0; i < NUM_BOXES; i++)
        document.forms.boxes['box[' + i + ']'].onclick = check;
    }
    

    HTML:

    <body onload="init()">
      <form name="boxes">
        <input name="box[0]" type="checkbox">
        <input name="box[1]" type="checkbox">
        <input name="box[2]" type="checkbox">
        <input name="box[3]" type="checkbox">
        <input name="box[4]" type="checkbox">
        <input name="box[5]" type="checkbox">
        <input name="box[6]" type="checkbox">
        <input name="box[7]" type="checkbox">
        <input name="box[8]" type="checkbox">
        <input name="box[9]" type="checkbox">
      </form>
    </body>
    

    How can I change from SQL Server Windows mode to mixed mode (SQL Server 2008)?

    From MSDN:

    To change security authentication mode:

    In SQL Server Management Studio Object Explorer, right-click the server, and then click Properties.

    On the Security page, under Server authentication, select the new server authentication mode, and then click OK.

    In the SQL Server Management Studio dialog box, click OK to acknowledge the requirement to restart SQL Server.

    In Object Explorer, right-click your server, and then click Restart. If SQL Server Agent is running, it must also be restarted.

    To enable the SA login:

    In Object Explorer, expand Security, expand Logins, right-click SA, and then click Properties.

    On the General page, you might have to create and confirm a password for the login.

    On the Status page, in the Login section, click Enabled, and then click OK.

    How to read a file from jar in Java?

    Check first your class loader.

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    
    if (classLoader == null) {
        classLoader = Class.class.getClassLoader();
    }
    
    classLoader.getResourceAsStream("xmlFileNameInJarFile.xml");
    
    // xml file location at xxx.jar
    // + folder
    // + folder
    // xmlFileNameInJarFile.xml
    

    git pull from master into the development branch

    git pull origin master --allow-unrelated-histories

    You might want to use this if your histories doesnt match and want to merge it anyway..

    refer here

    How to disable mouse right click on a web page?

    You can do so with Javascript and/or an HTML attribute (which is really a Javascript event handler anyway) as described here: http://www.codeproject.com/KB/aspnet/Disabling_the_right_click.aspx

    <script language="javascript">
    document.onmousedown=disableclick;
    status="Right Click Disabled";
    Function disableclick(event)
    {
      if(event.button==2)
       {
         alert(status);
         return false;    
       }
    }
    </script>
    

    and

    <body oncontextmenu="return false">
    ...
    </body>
    

    Angular IE Caching issue for $http

    meta http-equiv="Cache-Control" content="no-cache"
    

    I just added this to View and it started working on IE. Confirmed to work on Angular 2.

    Maximum number of threads per process in Linux?

    In practical terms, the limit is usually determined by stack space. If each thread gets a 1MB stack (I can't remember if that is the default on Linux), then you a 32-bit system will run out of address space after 3000 threads (assuming that the last gb is reserved to the kernel).

    However, you'll most likely experience terrible performance if you use more than a few dozen threads. Sooner or later, you get too much context-switching overhead, too much overhead in the scheduler, and so on. (Creating a large number of threads does little more than eat a lot of memory. But a lot of threads with actual work to do is going to slow you down as they're fighting for the available CPU time)

    What are you doing where this limit is even relevant?

    What is the difference between <jsp:include page = ... > and <%@ include file = ... >?

    One is a static import (<%=@ include...>"), the other is a dynamic one (jsp:include). It will affect for example the path you gonna have to specify for your included file. A little research on Google will tell you more.

    Android SDK Manager gives "Failed to fetch URL https://dl-ssl.google.com/android/repository/repository.xml" error when selecting repository

    Try this solution and it worked. this problem is caused because ADB is unable to connect to the android servers to fetch updates. (If at home try turning off firewall)

    • Goto Android SDK Manager c://android-sdk-windows/ open SDK-Manager
    • Click Settings - Will be asked for a proxy.
    • If have one enter the IP address and the port number. If not turn off your firewall.
    • Check "Force https://... " (to force SDK Manager to use http, not https)

    This should work immediately.

    Call removeView() on the child's parent first

    You can also do it by checking if View's indexOfView method if indexOfView method returns -1 then we can use.

    ViewGroup's detachViewFromParent(v); followed by ViewGroup's removeDetachedView(v, true/false);

    Why do I have to define LD_LIBRARY_PATH with an export every time I run my application?

    You can just put this all on one line:

    LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/path/to/library" ./sync_test
    

    Should make things a little easier, even if it doesn't change anything fundamental

    Ruby - test for array

    Are you sure it needs to be an array? You may be able to use respond_to?(method) so your code would work for similar things that aren't necessarily arrays (maybe some other enumberable thing). If you do actually need an array, then the post describing the Array#kind\_of? method is best.

    ['hello'].respond_to?('each')
    

    Get file size, image width and height before upload

    Multiple images upload with info data preview

    Using HTML5 and the File API

    Example using URL API

    The images sources will be a URL representing the Blob object
    <img src="blob:null/026cceb9-edr4-4281-babb-b56cbf759a3d">

    _x000D_
    _x000D_
    const EL_browse  = document.getElementById('browse');_x000D_
    const EL_preview = document.getElementById('preview');_x000D_
    _x000D_
    const readImage  = file => {_x000D_
      if ( !(/^image\/(png|jpe?g|gif)$/).test(file.type) )_x000D_
        return EL_preview.insertAdjacentHTML('beforeend', `Unsupported format ${file.type}: ${file.name}<br>`);_x000D_
    _x000D_
      const img = new Image();_x000D_
      img.addEventListener('load', () => {_x000D_
        EL_preview.appendChild(img);_x000D_
        EL_preview.insertAdjacentHTML('beforeend', `<div>${file.name} ${img.width}×${img.height} ${file.type} ${Math.round(file.size/1024)}KB<div>`);_x000D_
        window.URL.revokeObjectURL(img.src); // Free some memory_x000D_
      });_x000D_
      img.src = window.URL.createObjectURL(file);_x000D_
    }_x000D_
    _x000D_
    EL_browse.addEventListener('change', ev => {_x000D_
      EL_preview.innerHTML = ''; // Remove old images and data_x000D_
      const files = ev.target.files;_x000D_
      if (!files || !files[0]) return alert('File upload not supported');_x000D_
      [...files].forEach( readImage );_x000D_
    });
    _x000D_
    #preview img { max-height: 100px; }
    _x000D_
    <input id="browse" type="file" multiple>_x000D_
    <div id="preview"></div>
    _x000D_
    _x000D_
    _x000D_

    Example using FileReader API

    In case you need images sources as long Base64 encoded data strings
    <img src="data:image/png;base64,iVBORw0KGg... ...lF/++TkSuQmCC=">

    _x000D_
    _x000D_
    const EL_browse  = document.getElementById('browse');_x000D_
    const EL_preview = document.getElementById('preview');_x000D_
    _x000D_
    const readImage = file => {_x000D_
      if ( !(/^image\/(png|jpe?g|gif)$/).test(file.type) )_x000D_
        return EL_preview.insertAdjacentHTML('beforeend', `<div>Unsupported format ${file.type}: ${file.name}</div>`);_x000D_
    _x000D_
      const reader = new FileReader();_x000D_
      reader.addEventListener('load', () => {_x000D_
        const img  = new Image();_x000D_
        img.addEventListener('load', () => {_x000D_
          EL_preview.appendChild(img);_x000D_
          EL_preview.insertAdjacentHTML('beforeend', `<div>${file.name} ${img.width}×${img.height} ${file.type} ${Math.round(file.size/1024)}KB</div>`);_x000D_
        });_x000D_
        img.src = reader.result;_x000D_
      });_x000D_
      reader.readAsDataURL(file);  _x000D_
    };_x000D_
    _x000D_
    EL_browse.addEventListener('change', ev => {_x000D_
      EL_preview.innerHTML = ''; // Clear Preview_x000D_
      const files = ev.target.files;_x000D_
      if (!files || !files[0]) return alert('File upload not supported');_x000D_
      [...files].forEach( readImage );_x000D_
    });
    _x000D_
    #preview img { max-height: 100px; }
    _x000D_
    <input id="browse" type="file"  multiple>_x000D_
    <div id="preview"></div>_x000D_
      
    _x000D_
    _x000D_
    _x000D_

    How to prevent going back to the previous activity?

    Put finish() just after

    Intent i = new Intent(Summary1.this,MainActivity.class);
                startActivity(i);
    finish();
    

    Hash function for a string

    Java's String implements hashCode like this:

    public int hashCode()
    
    Returns a hash code for this string. The hash code for a String object is computed as
    
         s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
    
    using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.) 
    

    So something like this:

    int HashTable::hash (string word) {
        int result = 0;
        for(size_t i = 0; i < word.length(); ++i) {
            result += word[i] * pow(31, i);
        }
        return result;
    }
    

    Does Python have “private” variables in classes?

    As correctly mentioned by many of the comments above, let's not forget the main goal of Access Modifiers: To help users of code understand what is supposed to change and what is supposed not to. When you see a private field you don't mess around with it. So it's mostly syntactic sugar which is easily achieved in Python by the _ and __.

    Java Array Sort descending?

    It's good sometimes we practice over an example, here is a full one:

    sortdesc.java

    import java.util.Arrays;
    import java.util.Collections;
    class sortdesc{
    public static void main(String[] args){
           // int Array
           Integer[] intArray=new Integer[]{
                     new Integer(15),
                     new Integer(9),
                     new Integer(16),
                     new Integer(2),
                     new Integer(30)};
    
           // Sorting int Array in descending order
           Arrays.sort(intArray,Collections.reverseOrder());
    
           // Displaying elements of int Array
           System.out.println("Int Array Elements in reverse order:");
           for(int i=0;i<intArray.length;i++)
              System.out.println(intArray[i]);
    
           // String Array
           String[] stringArray=new String[]{"FF","PP","AA","OO","DD"};
    
           // Sorting String Array in descending order
           Arrays.sort(stringArray,Collections.reverseOrder());
    
           // Displaying elements of String Array
           System.out.println("String Array Elements in reverse order:");
           for(int i=0;i<stringArray.length;i++)
              System.out.println(stringArray[i]);}}
    

    compiling it...

    javac sortdec.java
    

    calling it...

    java sortdesc
    

    OUTPUT

    Int Array Elements in reverse order:
    30
    16
    15
    9
    2
    String Array Elements in reverse order:
    PP
    OO
    FF
    DD
    AA
    

    If you want to try an alphanumeric array...

    //replace this line:
    String[] stringArray=new String[]{"FF","PP","AA","OO","DD"};
    
    //with this:
    String[] stringArray=new String[]{"10FF","20AA","50AA"};
    

    you gonna get the OUTPUT as follow:

    50AA
    20AA
    10FF
    

    source

    npm install hangs

    *Try doing sudo npm install.

    *If you're using github then it could be you don't have permission and need to generated a public SSH key and add it to your settings account: (https://help.github.com/articles/generating-ssh-keys/)

    PHP function ssh2_connect is not working

    I have solved this on ubuntu 16.4 PHP 7.0.27-0+deb9u and nginx

    sudo apt install php-ssh2 
    

    How to delete a folder and all contents using a bat file in windows?

    1. del /s /q c:\where ever the file is\*
    2. rmdir /s /q c:\where ever the file is\
    3. mkdir c:\where ever the file is\

    Why is conversion from string constant to 'char*' valid in C but invalid in C++

    Up through C++03, your first example was valid, but used a deprecated implicit conversion--a string literal should be treated as being of type char const *, since you can't modify its contents (without causing undefined behavior).

    As of C++11, the implicit conversion that had been deprecated was officially removed, so code that depends on it (like your first example) should no longer compile.

    You've noted one way to allow the code to compile: although the implicit conversion has been removed, an explicit conversion still works, so you can add a cast. I would not, however, consider this "fixing" the code.

    Truly fixing the code requires changing the type of the pointer to the correct type:

    char const *p = "abc"; // valid and safe in either C or C++.
    

    As to why it was allowed in C++ (and still is in C): simply because there's a lot of existing code that depends on that implicit conversion, and breaking that code (at least without some official warning) apparently seemed to the standard committees like a bad idea.

    Why can't I call a public method in another class?

    You have to create a variable of the type of the class, and set it equal to a new instance of the object first.

    GradeBook myGradeBook = new GradeBook();
    

    Then call the method on the obect you just created.

    myGradeBook.[method you want called]
    

    Connecting to remote URL which requires authentication using Java

    Since Java 9, you can do this

    URL url = new URL("http://www.example.com");
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    connection.setAuthenticator(new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication ("USER", "PASS".toCharArray());
        }
    });
    

    python: How do I know what type of exception occurred?

    To add to Lauritz's answer, I created a decorator/wrapper for exception handling and the wrapper logs which type of exception occurred.

    class general_function_handler(object):
        def __init__(self, func):
            self.func = func
        def __get__(self, obj, type=None):
            return self.__class__(self.func.__get__(obj, type))
        def __call__(self, *args, **kwargs):
            try:
                retval = self.func(*args, **kwargs)
            except Exception, e :
                logging.warning('Exception in %s' % self.func)
                template = "An exception of type {0} occured. Arguments:\n{1!r}"
                message = template.format(type(e).__name__, e.args)
                logging.exception(message)
                sys.exit(1) # exit on all exceptions for now
            return retval
    

    This can be called on a class method or a standalone function with the decorator:

    @general_function_handler

    See my blog about for the full example: http://ryaneirwin.wordpress.com/2014/05/31/python-decorators-and-exception-handling/

    How can I build a recursive function in python?

    Recursion in Python works just as recursion in an other language, with the recursive construct defined in terms of itself:

    For example a recursive class could be a binary tree (or any tree):

    class tree():
        def __init__(self):
            '''Initialise the tree'''
            self.Data = None
            self.Count = 0
            self.LeftSubtree = None
            self.RightSubtree = None
    
        def Insert(self, data):
            '''Add an item of data to the tree'''
            if self.Data == None:
                self.Data = data
                self.Count += 1
            elif data < self.Data:
                if self.LeftSubtree == None:
                    # tree is a recurive class definition
                    self.LeftSubtree = tree()
                # Insert is a recursive function
                self.LeftSubtree.Insert(data)
            elif data == self.Data:
                self.Count += 1
            elif data > self.Data:
                if self.RightSubtree == None:
                    self.RightSubtree = tree()
                self.RightSubtree.Insert(data)
    
    if __name__ == '__main__':
        T = tree()
        # The root node
        T.Insert('b')
        # Will be put into the left subtree
        T.Insert('a')
        # Will be put into the right subtree
        T.Insert('c')
    

    As already mentioned a recursive structure must have a termination condition. In this class, it is not so obvious because it only recurses if new elements are added, and only does it a single time extra.

    Also worth noting, python by default has a limit to the depth of recursion available, to avoid absorbing all of the computer's memory. On my computer this is 1000. I don't know if this changes depending on hardware, etc. To see yours :

    import sys
    sys.getrecursionlimit()
    

    and to set it :

    import sys #(if you haven't already)
    sys.setrecursionlimit()
    

    edit: I can't guarentee that my binary tree is the most efficient design ever. If anyone can improve it, I'd be happy to hear how

    Check if bash variable equals 0

    Double parenthesis (( ... )) is used for arithmetic operations.

    Double square brackets [[ ... ]] can be used to compare and examine numbers (only integers are supported), with the following operators:

    · NUM1 -eq NUM2 returns true if NUM1 and NUM2 are numerically equal.
    
    · NUM1 -ne NUM2 returns true if NUM1 and NUM2 are not numerically equal.
    
    · NUM1 -gt NUM2 returns true if NUM1 is greater than NUM2.
    
    · NUM1 -ge NUM2 returns true if NUM1 is greater than or equal to NUM2.
    
    · NUM1 -lt NUM2 returns true if NUM1 is less than NUM2.
    
    · NUM1 -le NUM2 returns true if NUM1 is less than or equal to NUM2.
    

    For example

    if [[ $age > 21 ]] # bad, > is a string comparison operator
    
    if [ $age > 21 ] # bad, > is a redirection operator
    
    if [[ $age -gt 21 ]] # okay, but fails if $age is not numeric
    
    if (( $age > 21 )) # best, $ on age is optional
    

    How to configure Visual Studio to use Beyond Compare

    I use BC3 for my git diff, but I'd also add vscode to the list of useful git diff tools. Some users prefer vscode over vs ide experience.

    Using VS Code for Git Diff

    git config --global diff.tool vscode
    git config --global difftool.vscode.cmd "code --wait --diff $LOCAL $REMOTE"
    

    Google Maps API V3 : How show the direction from a point A to point B (Blue line)?

      // First Initiate your map. Tie it to some ID in the HTML eg. 'MyMapID'
      var map = new google.maps.Map(
        document.getElementById('MyMapID'),
        {
          center: {
            lat: Some.latitude,
            lng: Some.longitude
          }
        }
      );
      // Create a new directionsService object.
      var directionsService = new google.maps.DirectionsService;
        directionsService.route({
          origin: origin.latitude +','+ origin.longitude,
          destination: destination.latitude +','+ destination.longitude,
          travelMode: 'DRIVING',
        }, function(response, status) {
          if (status === google.maps.DirectionsStatus.OK) {
            var directionsDisplay = new google.maps.DirectionsRenderer({
              suppressMarkers: true,
              map: map,
              directions: response,
              draggable: false,
              suppressPolylines: true, 
              // IF YOU SET `suppressPolylines` TO FALSE, THE LINE WILL BE
              // AUTOMATICALLY DRAWN FOR YOU.
            });
    
            // IF YOU WISH TO APPLY USER ACTIONS TO YOUR LINE YOU NEED TO CREATE A 
            // `polyLine` OBJECT BY LOOPING THROUGH THE RESPONSE ROUTES AND CREATING A 
            // LIST
            pathPoints = response.routes[0].overview_path.map(function (location) {
              return {lat: location.lat(), lng: location.lng()};
            });
    
            var assumedPath = new google.maps.Polyline({
             path: pathPoints, //APPLY LIST TO PATH
             geodesic: true,
             strokeColor: '#708090',
             strokeOpacity: 0.7,
             strokeWeight: 2.5
           });
    
           assumedPath.setMap(map); // Set the path object to the map
    

    Finding duplicate integers in an array and display how many times they occurred

    Use Group by:

    int[] values = new []{1,2,3,4,5,4,4,3};
    
    var groups = values.GroupBy(v => v);
    foreach(var group in groups)
        Console.WriteLine("Value {0} has {1} items", group.Key, group.Count());
    

    What are intent-filters in Android?

    If possible try this one instant solution:

    Intent intent =new Intent(getApplicationBaseContext,second_Act.class);
    StartActivity(intent);
    

    Read MS Exchange email in C#

    1. The currently preferred (Exchange 2013 and 2016) API is EWS. It is purely HTTP based and can be accessed from any language, but there are .Net and Java specific libraries.

      You can use EWSEditor to play with the API.

    2. Extended MAPI. This is the native API used by Outlook. It ends up using the MSEMS Exchange MAPI provider, which can talk to Exchange using RPC (Exchange 2013 no longer supports it) or RPC-over-HTTP (Exchange 2007 or newer) or MAPI-over-HTTP (Exchange 2013 and newer).

      The API itself can only be accessed from unmanaged C++ or Delphi. You can also use Redemption (any language) - its RDO family of objects is an Extended MAPI wrapper. To use Extended MAPI, you need to install either Outlook or the standalone (Exchange) version of MAPI (on extended support, and it does not support Unicode PST and MSG files and cannot access Exchange 2016). Extended MAPI can be used in a service.

      You can play with the API using OutlookSpy or MFCMAPI.

    3. Outlook Object Model - not Exchange specific, but it allows access to all data available in Outlook on the machine where the code runs. Cannot be used in a service.

    4. Exchange Active Sync. Microsoft no longer invests any significant resources into this protocol.

    5. Outlook used to install CDO 1.21 library (it wraps Extended MAPI), but it had been deprecated by Microsoft and no longer receives any updates.

    6. There used to be a third-party .Net MAPI wrapper called MAPI33, but it is no longer being developed or supported.

    7. WebDAV - deprecated.

    8. Collaborative Data Objects for Exchange (CDOEX) - deprecated.

    9. Exchange OLE DB Provider (EXOLEDB) - deprecated.

    What is the garbage collector in Java?

    Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. An in use object, or a referenced object, means that some part of your program still maintains a pointer to that object. An unused object, or unreferenced object, is no longer referenced by any part of your program. So the memory used by an unreferenced object can be reclaimed.

    In a programming language like C, allocating and deallocating memory is a manual process. In Java, process of deallocating memory is handled automatically by the garbage collector. Please check the link for a better understanding. http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html

    Picking a random element from a set

    Clojure solution:

    (defn pick-random [set] (let [sq (seq set)] (nth sq (rand-int (count sq)))))
    

    How can I determine browser window size on server side C#

    There is a solution to solve page_onload problem (can't get size until page load complete) : Create a userControl :

    <%@ Control Language="VB" AutoEventWireup="false" CodeFile="ClientSizeDetector.ascx.vb"    Inherits="Project_UserControls_ClientSizeDetector" %>
    <%If (IsFirstTime) Then%>
    <script type="text/javascript">
    var pageURL = window.location.href.search(/\?/) > 0 ? "&" : "?";
    window.location.href = window.location.href + pageURL + "clientHeight=" + window.innerHeight + "&clientWidth=" + window.innerWidth;
    </script>
    <%End If%>
    

    Code behind :

     Private _isFirstTime As Boolean = False
     Private _clientWidth As Integer = 0
     Private _clientHeight As Integer = 0
    
     Public Property ClientWidth() As Integer
        Get
            Return _clientWidth
        End Get
        Set(value As Integer)
            _clientWidth = value
        End Set
    End Property
    
    Public Property ClientHeight() As Integer
        Get
            Return _clientHeight
        End Get
        Set(value As Integer)
            _clientHeight = value
        End Set
    End Property
    
    public Property IsFirstTime() As Boolean 
        Get
            Return _isFirstTime
        End Get
        Set(value As Boolean)
            _isFirstTime = value
        End Set
    End Property
    
    
    
    Protected Overrides Sub OnInit(e As EventArgs)
    
        If (String.IsNullOrEmpty(Request.QueryString("clientHeight")) Or String.IsNullOrEmpty(Request.QueryString("clientWidth"))) Then
            Me._isFirstTime = True
        Else
            Integer.TryParse(Request.QueryString("clientHeight").ToString(), ClientHeight)
            Integer.TryParse(Request.QueryString("clientWidth").ToString(), ClientWidth)
            Me._isFirstTime = False
        End If
    End Sub
    

    So after, you can call your control properties

    Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine

    Eureka ! Finally I found a solution on this.

    This is caused by Windows update that stops any 32-bit processes from consuming more than 1200 MB on a 64-bit machine. The only way you can repair this is by using the System Restore option on Win 7.

    Start >> All Programs >> Accessories >> System Tools >> System Restore.

    And then restore to a date on which your Java worked fine. This worked for me. What is surprising here is Windows still pushes system updates under the name of "Critical Updates" even when you disable all windows updates. ^&%)#* Windows :-)

    How to access html form input from asp.net code behind

    If you are accessing a plain HTML form, it has to be submitted to the server via a submit button (or via javascript post). This usually means that your form definition will look like this (I'm going off of memory, make sure you check the html elements are correct):

    <form method="POST" action="page.aspx">
    
    <input id="customerName" name="customerName" type="Text" />
    <input id="customerPhone" name="customerPhone" type="Text" />
    <input value="Save" type="Submit" />
    
    </form>
    

    You should be able to access the customerName and customerPhone data like this:

    string n = String.Format("{0}", Request.Form["customerName"]);
    

    If you have method="GET" in the form (not recommended, it messes up your URL space), you will have to access the form data like this:

    string n = String.Format("{0}", Request.QueryString["customerName"]);
    

    This of course will only work if the form was 'Posted', 'Submitted', or done via a 'Postback'. (i.e. somebody clicked the 'Save' button, or this was done programatically via javascript.)

    Also, keep in mind that accessing these elements in this manner can only be done when you are not using server controls (i.e. runat="server"), with server controls the id and name are different.

    Align text in JLabel to the right

    To me, it seems as if your actual intention is to put different words on different lines. But let me answer your first question:

    JLabel lab=new JLabel("text");
    lab.setHorizontalAlignment(SwingConstants.LEFT);     
    

    And if you have an image:

    JLabel lab=new Jlabel("text");
    lab.setIcon(new ImageIcon("path//img.png"));
    lab.setHorizontalTextPosition(SwingConstants.LEFT);
    

    But, I believe you want to make the label such that there are only 2 words on 1 line.

    In that case try this:

    String urText="<html>You can<br>use basic HTML<br>in Swing<br> components," 
       +"Hope<br> I helped!";
    JLabel lac=new JLabel(urText);
    lac.setAlignmentX(Component.RIGHT_ALIGNMENT);
    

    Will iOS launch my app into the background if it was force-quit by the user?

    You can change your target's launch settings in "Manage Scheme" to Wait for <app>.app to be launched manually, which allows you debug by setting a breakpoint in application: didReceiveRemoteNotification: fetchCompletionHandler: and sending the push notification to trigger the background launch.

    I'm not sure it'll solve the issue, but it may assist you with debugging for now.

    screenshot

    rbind error: "names do not match previous names"

    check all the variables names in both of the combined files. Name of variables of both files to be combines should be exact same or else it will produce the above mentioned errors. I was facing the same problem as well, and after making all names same in both the file, rbind works accurately.

    Thanks

    An internal error occurred during: "Updating Maven Project". java.lang.NullPointerException

    Above solutions did not work for me as the issue with open JDK 13 version https://github.com/spotify/dockerfile-maven/issues/163 So I degraded to open JDK8 and it works for me

    How to access single elements in a table in R

    ?"[" pretty much covers the various ways of accessing elements of things.

    Under usage it lists these:

    x[i]
    x[i, j, ... , drop = TRUE]
    x[[i, exact = TRUE]]
    x[[i, j, ..., exact = TRUE]]
    x$name
    getElement(object, name)
    
    x[i] <- value
    x[i, j, ...] <- value
    x[[i]] <- value
    x$i <- value
    

    The second item is sufficient for your purpose

    Under Arguments it points out that with [ the arguments i and j can be numeric, character or logical

    So these work:

    data[1,1]
    data[1,"V1"]
    

    As does this:

    data$V1[1]
    

    and keeping in mind a data frame is a list of vectors:

    data[[1]][1]
    data[["V1"]][1]
    

    will also both work.

    So that's a few things to be going on with. I suggest you type in the examples at the bottom of the help page one line at a time (yes, actually type the whole thing in one line at a time and see what they all do, you'll pick up stuff very quickly and the typing rather than copypasting is an important part of helping to commit it to memory.)

    Exit while loop by user hitting ENTER key

    user_input=input("ENTER SOME POSITIVE INTEGER : ")
    if((not user_input) or (int(user_input)<=0)):    
       print("ENTER SOME POSITIVE INTEGER GREATER THAN ZERO") #print some info
       import sys        #import
       sys.exit(0)       #exit program 
    '''
    #(not user_input) checks if user has pressed enter key without entering  
    # number.
    #(int(user_input)<=0) checks if user has entered any number less than or 
    #equal to zero.
    '''
    

    Application Loader stuck at "Authenticating with the iTunes store" when uploading an iOS app

    Go to Preferences -> Accounts, remove your account and add it again. Then try uploading again and wait a few minutes.

    How to get all selected values from <select multiple=multiple>?

    Try this:

    $('#select-meal-type').change(function(){
        var arr = $(this).val()
    });
    

    Demo

    _x000D_
    _x000D_
    $('#select-meal-type').change(function(){_x000D_
      var arr = $(this).val();_x000D_
      console.log(arr)_x000D_
    })
    _x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
    <select id="select-meal-type" multiple="multiple">_x000D_
      <option value="1">Breakfast</option>_x000D_
      <option value="2">Lunch</option>_x000D_
      <option value="3">Dinner</option>_x000D_
      <option value="4">Snacks</option>_x000D_
      <option value="5">Dessert</option>_x000D_
    </select>
    _x000D_
    _x000D_
    _x000D_

    fiddle

    Rails and PostgreSQL: Role postgres does not exist

    In Ubuntu local user command prompt, but not root user, type

    sudo -u postgres createuser username

    username above should match the name indicated in the message "FATAL: role 'username' does not exist."

    Enter password for username.

    Then re-enter the command that generated role does not exist message.

    How can I use a C++ library from node.js?

    You could use emscripten to compile C++ code into js.

    Settings to Windows Firewall to allow Docker for Windows to share drive

    My G drive stopped being shared with Docker after a recent Windows 10 update. I was getting the same problem saying it was blocked by the Windows firewall when attempting to reshare it.

    Then I had tried to solve this issues by couple of suggestion but i cant resolve that issue after that I have tried to Reset credentials below of Shared Drives and my issue was solved.

    So If you want then you can try to do this-

    enter image description here

    How do I automatically resize an image for a mobile site?

    if you use bootstrap 3 , just add img-responsive class in your img tag

    <img class="img-responsive"  src="...">
    

    if you use bootstrap 4, add img-fluid class in your img tag

    <img class="img-fluid"  src="...">
    

    which does the staff: max-width: 100%, height: auto, and display:block to the image

    How to work with progress indicator in flutter?

    {
    isloading? progressIos:Container()
    
    progressIos(int i) {
        return Container(
            color: i == 1
                ? AppColors.liteBlack
                : i == 2 ? AppColors.darkBlack : i == 3 ? AppColors.pinkBtn : '',
            child: Center(child: CupertinoActivityIndicator()));
      }
    }
    

    Styling an anchor tag to look like a submit button

    Why not just use a button and call the url with JavaScript?

    <input type="button" value="Cancel" onclick="location.href='url.html';return false;" />
    

    Could not find or load main class

    i guess that you have a different class name in p1.java