Programs & Examples On #Mysql num rows

Retrieves the number of rows from a result set.

if var == False

Python uses not instead of ! for negation.

Try

if not var: 
    print "learnt stuff"

instead

PHP sessions that have already been started

None of the above was suitable, without calling session_start() in all php files that depend on $Session variables they will not be included. The Notice is so annoying and quickly fill up the Error_log. The only solution that I can find that works is this....

    error_reporting(E_ALL ^ E_NOTICE);
    session_start();

A Bad fix , but it works.

how to delete all cookies of my website in php

The provided Answers did not solve my problem,

It did not:

  1. Remove parent domain cookies (from a.b.c; remove b.c; cookies),
  2. Remove cookies from a higher path other then root.

My script does, see.

<?php function unset_cookie($name)
{
    $host = $_SERVER['HTTP_HOST'];
    $domain = explode(':', $host)[0];

    $uri = $_SERVER['REQUEST_URI'];
    $uri = rtrim(explode('?', $uri)[0], '/');

    if ($uri && !filter_var('file://' . $uri, FILTER_VALIDATE_URL)) {
        throw new Exception('invalid uri: ' . $uri);
    }

    $parts = explode('/', $uri);

    $cookiePath = '';
    foreach ($parts as $part) {
        $cookiePath = '/'.ltrim($cookiePath.'/'.$part, '//');

        setcookie($name, '', 1, $cookiePath);

        $_domain = $domain;
        do {
            setcookie($name, '', 1, $cookiePath, $_domain);
        } while (strpos($_domain, '.') !== false && $_domain = substr($_domain, 1 + strpos($_domain, '.')));
    }
}

It is not the most pretty/safe/optimal solution, so use this only if you do not known the cookie-path and/or cookie-domain's. Or use the idea in order to create your version.

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

Here is a list of examples for sending cookies - https://github.com/andriichuk/php-curl-cookbook#cookies

$curlHandler = curl_init();

curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://httpbin.org/cookies',
CURLOPT_RETURNTRANSFER => true,

CURLOPT_COOKIEFILE  => $cookieFile,
CURLOPT_COOKIE => 'foo=bar;baz=foo',

/**
 * Or set header
 * CURLOPT_HTTPHEADER => [
       'Cookie: foo=bar;baz=foo',
   ]
 */
]);

$response = curl_exec($curlHandler);
curl_close($curlHandler);

echo $response;

MySQL : transaction within a stored procedure

Here's an example of a transaction that will rollback on error and return the error code.

DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `SP_CREATE_SERVER_USER`(
    IN P_server_id VARCHAR(100),
    IN P_db_user_pw_creds VARCHAR(32),
    IN p_premium_status_name VARCHAR(100),
    IN P_premium_status_limit INT,
    IN P_user_tag VARCHAR(255),
    IN P_first_name VARCHAR(50),
    IN P_last_name VARCHAR(50)
)
BEGIN

    DECLARE errno INT;
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
    GET CURRENT DIAGNOSTICS CONDITION 1 errno = MYSQL_ERRNO;
    SELECT errno AS MYSQL_ERROR;
    ROLLBACK;
    END;

    START TRANSACTION;

    INSERT INTO server_users(server_id, db_user_pw_creds, premium_status_name, premium_status_limit)
    VALUES(P_server_id, P_db_user_pw_creds, P_premium_status_name, P_premium_status_limit);

    INSERT INTO client_users(user_id, server_id, user_tag, first_name, last_name, lat, lng)
    VALUES(P_server_id, P_server_id, P_user_tag, P_first_name, P_last_name, 0, 0);

    COMMIT WORK;

END$$
DELIMITER ;

This is assuming that autocommit is set to 0. Hope this helps.

How to read large text file on windows?

I just used less on top of Cygwin to read a 3GB file, though I ended up using grep to find what I needed in it.

(less is more, but better.)

See this answer for more details on less: https://stackoverflow.com/a/1343576/1005039

Get Row Index on Asp.net Rowcommand event

ImageButton \ Button etc.

CommandArgument='<%# Container.DataItemIndex%>' 

code-behind

protected void gvProductsList_RowCommand(object sender, GridViewCommandEventArgs e)
{
    int index = e.CommandArgument;
}

efficient way to implement paging

The approach that I am giving is the fastest pagination that SQL server can achieve. I have tested this on 5 million records. This approach is far better than "OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY" provided by SQL Server.

-- The below given code computes the page numbers and the max row of previous page
-- Replace <<>> with the correct table data.
-- Eg. <<IdentityColumn of Table>> can be EmployeeId and <<Table>> will be dbo.Employees

DECLARE @PageNumber int=1; --1st/2nd/nth page. In stored proc take this as input param.
DECLARE @NoOfRecordsPerPage int=1000;

 DECLARE @PageDetails TABLE
       (
        <<IdentityColumn of Table>> int,
        rownum int,
        [PageNumber] int
       )           
       INSERT INTO @PageDetails values(0, 0, 0)
       ;WITH CTE AS
       (
       SELECT <<IdentityColumn of Table>>, ROW_NUMBER() OVER(ORDER BY <<IdentityColumn of Table>>) rownum FROM <<Table>>
       )
       Insert into @PageDetails 
       SELECT <<IdentityColumn of Table>>, CTE.rownum, ROW_NUMBER() OVER (ORDER BY rownum) as [PageNumber] FROM CTE WHERE CTE.rownum%@NoOfRecordsPerPage=0


--SELECT * FROM @PageDetails 

-- Actual pagination
SELECT TOP (@NoOfRecordsPerPage)
FROM <<Table>> AS <<Table>>
WHERE <<IdentityColumn of Table>> > (SELECT <<IdentityColumn of Table>> FROM 
@PageDetails WHERE PageNumber=@PageNumber)
ORDER BY <<Identity Column of Table>>

How can I run Tensorboard on a remote server?

For anyone who must use the ssh keys (for a corporate server).

Just add -i /.ssh/id_rsa at the end.

$ ssh -N -f -L localhost:8211:localhost:6007 myname@servername -i /.ssh/id_rsa

Jquery/Ajax Form Submission (enctype="multipart/form-data" ). Why does 'contentType:False' cause undefined index in PHP?

Please set your form action attribute as below it will solve your problem.

<form name="addProductForm" id="addProductForm" action="javascript:;" enctype="multipart/form-data" method="post" accept-charset="utf-8">

jQuery code:

$(document).ready(function () {
    $("#addProductForm").submit(function (event) {

        //disable the default form submission
        event.preventDefault();
        //grab all form data  
        var formData = $(this).serialize();

        $.ajax({
            url: 'addProduct.php',
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function () {
                alert('Form Submitted!');
            },
            error: function(){
                alert("error in ajax form submission");
            }
        });

        return false;
    });
});

AngularJS: How can I pass variables between controllers?

Ah, have a bit of this new stuff as another alternative. It's localstorage, and works where angular works. You're welcome. (But really, thank the guy)

https://github.com/gsklee/ngStorage

Define your defaults:

$scope.$storage = $localStorage.$default({
    prop1: 'First',
    prop2: 'Second'
});

Access the values:

$scope.prop1 = $localStorage.prop1;
$scope.prop2 = $localStorage.prop2;

Store the values

$localStorage.prop1 = $scope.prop1;
$localStorage.prop2 = $scope.prop2;

Remember to inject ngStorage in your app and $localStorage in your controller.

how to run a command at terminal from java program?

I don't know why, but for some reason, the "/bin/bash" version didn't work for me. Instead, the simpler version worked, following the example given here at Oracle Docs.

String[] args = new String[] {"ping", "www.google.com"};
Process proc = new ProcessBuilder(args).start();

Make the current commit the only (initial) commit in a Git repository?

This deletes the history on the master branch (you might want to make a backup before running the commands):

git branch tmp_branch $(echo "commit message" | git commit-tree HEAD^{tree})
git checkout tmp_branch
git branch -D master
git branch -m master
git push -f --set-upstream origin master

This is based on the answer from @dan_waterworth.

What's the Use of '\r' escape sequence?

The '\r' stands for "Carriage Return" - it's a holdover from the days of typewriters and really old printers. The best example is in Windows and other DOSsy OSes, where a newline is given as "\r\n". These are the instructions sent to an old printer to start a new line: first move the print head back to the beginning, then go down one.

Different OSes will use other newline sequences. Linux and OSX just use '\n'. Older Mac OSes just use '\r'. Wikipedia has a more complete list, but those are the important ones.

Hope this helps!

PS: As for why you get that weird output... Perhaps the console is moving the "cursor" back to the beginning of the line, and then overwriting the first bit with spaces or summat.

Single Line Nested For Loops

The best source of information is the official Python tutorial on list comprehensions. List comprehensions are nearly the same as for loops (certainly any list comprehension can be written as a for-loop) but they are often faster than using a for loop.

Look at this longer list comprehension from the tutorial (the if part filters the comprehension, only parts that pass the if statement are passed into the final part of the list comprehension (here (x,y)):

>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

It's exactly the same as this nested for loop (and, as the tutorial says, note how the order of for and if are the same).

>>> combs = []
>>> for x in [1,2,3]:
...     for y in [3,1,4]:
...         if x != y:
...             combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

The major difference between a list comprehension and a for loop is that the final part of the for loop (where you do something) comes at the beginning rather than at the end.

On to your questions:

What type must object be in order to use this for loop structure?

An iterable. Any object that can generate a (finite) set of elements. These include any container, lists, sets, generators, etc.

What is the order in which i and j are assigned to elements in object?

They are assigned in exactly the same order as they are generated from each list, as if they were in a nested for loop (for your first comprehension you'd get 1 element for i, then every value from j, 2nd element into i, then every value from j, etc.)

Can it be simulated by a different for loop structure?

Yes, already shown above.

Can this for loop be nested with a similar or different structure for loop? And how would it look?

Sure, but it's not a great idea. Here, for example, gives you a list of lists of characters:

[[ch for ch in word] for word in ("apple", "banana", "pear", "the", "hello")]

Calculating distance between two geographic locations

    private static Double _MilesToKilometers = 1.609344;
    private static Double _MilesToNautical = 0.8684;


    /// <summary>
    /// Calculates the distance between two points of latitude and longitude.
    /// Great Link - http://www.movable-type.co.uk/scripts/latlong.html
    /// </summary>
    /// <param name="coordinate1">First coordinate.</param>
    /// <param name="coordinate2">Second coordinate.</param>
    /// <param name="unitsOfLength">Sets the return value unit of length.</param>
    public static Double Distance(Coordinate coordinate1, Coordinate coordinate2, UnitsOfLength unitsOfLength)
    {

        double theta = coordinate1.getLongitude() - coordinate2.getLongitude();
        double distance = Math.sin(ToRadian(coordinate1.getLatitude())) * Math.sin(ToRadian(coordinate2.getLatitude())) +
                       Math.cos(ToRadian(coordinate1.getLatitude())) * Math.cos(ToRadian(coordinate2.getLatitude())) *
                       Math.cos(ToRadian(theta));

        distance = Math.acos(distance);
        distance = ToDegree(distance);
        distance = distance * 60 * 1.1515;

        if (unitsOfLength == UnitsOfLength.Kilometer)
            distance = distance * _MilesToKilometers;
        else if (unitsOfLength == UnitsOfLength.NauticalMiles)
            distance = distance * _MilesToNautical;

        return (distance);

    }

The filename, directory name, or volume label syntax is incorrect inside batch

set myPATH="C:\Users\DEB\Downloads\10.1.1.0.4"
cd %myPATH%
  • The single quotes do not indicate a string, they make it starts: 'C:\ instead of C:\ so

  • %name% is the usual syntax for expanding a variable, the !name! syntax needs to be enabled using the command setlocal ENABLEDELAYEDEXPANSION first, or by running the command prompt with CMD /V:ON.

  • Don't use PATH as your name, it is a system name that contains all the locations of executable programs. If you overwrite it, random bits of your script will stop working. If you intend to change it, you need to do set PATH=%PATH%;C:\Users\DEB\Downloads\10.1.1.0.4 to keep the current PATH content, and add something to the end.

Explain __dict__ attribute

Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes. Quoting from the documentation for __dict__

A dictionary or other mapping object used to store an object's (writable) attributes.

Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:

def func():
    pass

func.temp = 1

print(func.__dict__)

class TempClass:
    a = 1
    def temp_function(self):
        pass

print(TempClass.__dict__)

will output

{'temp': 1}
{'__module__': '__main__', 
 'a': 1, 
 'temp_function': <function TempClass.temp_function at 0x10a3a2950>, 
 '__dict__': <attribute '__dict__' of 'TempClass' objects>, 
 '__weakref__': <attribute '__weakref__' of 'TempClass' objects>, 
 '__doc__': None}

Call child component method from parent class - Angular

This Worked for me ! For Angular 2 , Call child component method in parent component

Parent.component.ts

    import { Component, OnInit, ViewChild } from '@angular/core';
    import { ChildComponent } from '../child/child'; 
    @Component({ 
               selector: 'parent-app', 
               template: `<child-cmp></child-cmp>` 
              }) 
    export class parentComponent implements OnInit{ 
        @ViewChild(ChildComponent ) child: ChildComponent ; 

        ngOnInit() { 
           this.child.ChildTestCmp(); } 
}

Child.component.ts

import { Component } from '@angular/core';
@Component({ 
  selector: 'child-cmp', 
  template: `<h2> Show Child Component</h2><br/><p> {{test }}</p> ` 
})
export class ChildComponent {
  test: string;
  ChildTestCmp() 
  { 
    this.test = "I am child component!"; 
  }
 }

how to force maven to update local repo

Click settings and search for "Repositories", then select the local repo and click "Update". That's all. This action meets my need.

getting the table row values with jquery

All Elements

$('#tabla > tbody  > tr').each(function() {
    $(this).find("td:gt(0)").each(function(){
       alert($(this).html());
       });
});

How do I "decompile" Java class files?

There are a few programs you can use. You will get the actual Java code, but sometimes the code will have been obfuscated so methods are named by one letter or number or a random mix of letters and numbers.

DJ Decompiler Mocha

pandas: to_numeric for multiple columns

df.loc[:,'col':] = df.loc[:,'col':].apply(pd.to_numeric, errors = 'coerce')

How can I clear the input text after clicking

If you need placeholder like behavior. you can use this.

$("selector").data("DefaultText", SetYourDefaultTextHere);
// You can also define the DefaultText as attribute and access that using attr() function

$("selector").focus(function(){
if($(this).val() == $(this).data("DefaultText"))
   $(this).val('');
});

How do you make an array of structs in C?

Another way of initializing an array of structs is to initialize the array members explicitly. This approach is useful and simple if there aren't too many struct and array members.

Use the typedef specifier to avoid re-using the struct statement everytime you declare a struct variable:

typedef struct
{
    double p[3];//position
    double v[3];//velocity
    double a[3];//acceleration
    double radius;
    double mass;
}Body;

Then declare your array of structs. Initialization of each element goes along with the declaration:

Body bodies[n] = {{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}, 
                  {{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}, 
                  {{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}};

To repeat, this is a rather simple and straightforward solution if you don't have too many array elements and large struct members and if you, as you stated, are not interested in a more dynamic approach. This approach can also be useful if the struct members are initialized with named enum-variables (and not just numbers like the example above) whereby it gives the code-reader a better overview of the purpose and function of a structure and its members in certain applications.

"cannot resolve symbol R" in Android Studio

This problem is caused because of the naming of files in "res" or "drawable" folder. You can't use any capital letter for naming a resource file. So, check if there is any such file and rename it with small letters.

And, also, you can try this: Go to: File > Invalidate cache/restart

These options have worked for me.

How can I create and style a div using JavaScript?

_x000D_
_x000D_
var div = document.createElement("div");_x000D_
div.style.width = "100px";_x000D_
div.style.height = "100px";_x000D_
div.style.background = "red";_x000D_
div.style.color = "white";_x000D_
div.innerHTML = "Hello";_x000D_
_x000D_
document.getElementById("main").appendChild(div);
_x000D_
<body>_x000D_
<div id="main"></div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

var div = document.createElement("div");
div.style.width = "100px";
div.style.height = "100px";
div.style.background = "red";
div.style.color = "white";
div.innerHTML = "Hello";

document.getElementById("main").appendChild(div);
OR
document.body.appendChild(div);

Use parent reference instead of document.body.

How to make String.Contains case insensitive?

You can use:

if (myString1.IndexOf("AbC", StringComparison.OrdinalIgnoreCase) >=0) {
    //...
}

This works with any .NET version.

How to use Collections.sort() in Java?

Create a comparator which accepts the compare mode in its constructor and pass different modes for different scenarios based on your requirement

public class RecipeComparator implements Comparator<Recipe> {

public static final int COMPARE_BY_ID = 0;
public static final int COMPARE_BY_NAME = 1;

private int compare_mode = COMPARE_BY_NAME;

public RecipeComparator() {
}

public RecipeComparator(int compare_mode) {
    this.compare_mode = compare_mode;
}

@Override
public int compare(Recipe o1, Recipe o2) {
    switch (compare_mode) {
    case COMPARE_BY_ID:
        return o1.getId().compareTo(o2.getId());
    default:
        return o1.getInputRecipeName().compareTo(o2.getInputRecipeName());
    }
}

}

Actually for numbers you need to handle them separately check below

public static void main(String[] args) {
    String string1 = "1";
    String string2 = "2";
    String string11 = "11";

    System.out.println(string1.compareTo(string2)); 
    System.out.println(string2.compareTo(string11));// expected -1 returns 1
   // to compare numbers you actually need to do something like this

    int number2 = Integer.valueOf(string1);
    int number11 = Integer.valueOf(string11);

    int compareTo = number2 > number11 ? 1 : (number2 < number11 ? -1 : 0) ;
    System.out.println(compareTo);// prints -1
}

Does JavaScript guarantee object property order?

Just found this out the hard way.

Using React with Redux, the state container of which's keys I want to traverse in order to generate children is refreshed everytime the store is changed (as per Redux's immutability concepts).

Thus, in order to take Object.keys(valueFromStore) I used Object.keys(valueFromStore).sort(), so that I at least now have an alphabetical order for the keys.

How can I disable all views inside the layout?

If you want to disable a set of, or say a particular kind of view.Let's say you want to disable a fixed number of buttons with some particular text of or no text then you can use array of that type and loop through the array elements while disabling the buttons using setEnabled(false) property You can do it on a function call like this:

public void disable(){
        for(int i=0;i<9;i++){
                if(bt[i].getText().equals("")){//Button Text condition
                    bt[i].setEnabled(false);
            }
        }
}

Selenium -- How to wait until page is completely loaded

You can do this in many ways before clicking on add items:

WebDriverWait wait = new WebDriverWait(driver, 40);
wait.until(ExpectedConditions.elementToBeClickable(By.id("urelementid")));// instead of id u can use cssSelector or xpath of ur element.


or

wait.until(ExpectedConditions.visibilityOfElementLocated("urelement"));

You can also wait like this. If you want to wait until invisible of previous page element:

wait.until(ExpectedConditions.invisibilityOfElementLocated("urelement"));

Here is the link where you can find all the Selenium WebDriver APIs that can be used for wait and its documentation.

https://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html

How to read a line from the console in C?

You might need to use a character by character (getc()) loop to ensure you have no buffer overflows and don't truncate the input.

TypeScript: correct way to do string equality?

If you know x and y are both strings, using === is not strictly necessary, but is still good practice.

Assuming both variables actually are strings, both operators will function identically. However, TS often allows you to pass an object that meets all the requirements of string rather than an actual string, which may complicate things.

Given the possibility of confusion or changes in the future, your linter is probably correct in demanding ===. Just go with that.

transform object to array with lodash

var arr = _.map(obj)

You can use _.map function (of both lodash and underscore) with object as well, it will internally handle that case, iterate over each value and key with your iteratee, and finally return an array. Infact, you can use it without any iteratee (just _.map(obj)) if you just want a array of values. The good part is that, if you need any transformation in between, you can do it in one go.

Example:

_x000D_
_x000D_
var obj = {_x000D_
    key1: {id: 1, name: 'A'},_x000D_
    key2: {id: 2, name: 'B'},_x000D_
    key3: {id: 3, name: 'C'}_x000D_
};_x000D_
_x000D_
var array1 = _.map(obj, v=>v);_x000D_
console.log('Array 1: ', array1);_x000D_
_x000D_
/*Actually you don't need the callback v=>v if you_x000D_
are not transforming anything in between, v=>v is default*/_x000D_
_x000D_
//SO simply you can use_x000D_
var array2 = _.map(obj);_x000D_
console.log('Array 2: ', array2);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
_x000D_
_x000D_
_x000D_

However, if you want to transform your object you can do so, even if you need to preserve the key, you can do that ( _.map(obj, (v, k) => {...}) with additional argument in map and then use it how you want.

However there are other Vanilla JS solution to this (as every lodash solution there should pure JS version of it) like:

  • Object.keys and then map them to values
  • Object.values (in ES-2017)
  • Object.entries and then map each key/value pairs (in ES-2017)
  • for...in loop and use each keys for feting values

And a lot more. But since this question is for lodash (and assuming someone already using it) then you don't need to think a lot about version, support of methods and error handling if those are not found.

There are other lodash solutions like _.values (more readable for specific perpose), or getting pairs and then map and so on. but in the case your code need flexibility that you can update it in future as you need to preserve keys or transforming values a bit, then the best solution is to use a single _.map as addresed in this answer. That will bt not that difficult as per readability also.

jQuery get value of select onChange

jQuery(document).ready(function(){

    jQuery("#id").change(function() {
      var value = jQuery(this).children(":selected").attr("value");
     alert(value);

    });
})

Using Javascript can you get the value from a session attribute set by servlet in the HTML page

<%
String session_val = (String)session.getAttribute("sessionval"); 
System.out.println("session_val"+session_val);
%>
<html>
<head>
<script type="text/javascript">
var session_obj= '<%=session_val%>';
alert("session_obj"+session_obj);
</script>
</head>
</html>

How to do exponential and logarithmic curve fitting in Python? I found only polynomial fitting

We demonstrate features of lmfit while solving both problems.

Given

import lmfit

import numpy as np

import matplotlib.pyplot as plt


%matplotlib inline
np.random.seed(123)
# General Functions
def func_log(x, a, b, c):
    """Return values from a general log function."""
    return a * np.log(b * x) + c


# Data
x_samp = np.linspace(1, 5, 50)
_noise = np.random.normal(size=len(x_samp), scale=0.06)
y_samp = 2.5 * np.exp(1.2 * x_samp) + 0.7 + _noise
y_samp2 = 2.5 * np.log(1.2 * x_samp) + 0.7 + _noise

Code

Approach 1 - lmfit Model

Fit exponential data

regressor = lmfit.models.ExponentialModel()                # 1    
initial_guess = dict(amplitude=1, decay=-1)                # 2
results = regressor.fit(y_samp, x=x_samp, **initial_guess)
y_fit = results.best_fit    

plt.plot(x_samp, y_samp, "o", label="Data")
plt.plot(x_samp, y_fit, "k--", label="Fit")
plt.legend()

enter image description here

Approach 2 - Custom Model

Fit log data

regressor = lmfit.Model(func_log)                          # 1
initial_guess = dict(a=1, b=.1, c=.1)                      # 2
results = regressor.fit(y_samp2, x=x_samp, **initial_guess)
y_fit = results.best_fit

plt.plot(x_samp, y_samp2, "o", label="Data")
plt.plot(x_samp, y_fit, "k--", label="Fit")
plt.legend()

enter image description here


Details

  1. Choose a regression class
  2. Supply named, initial guesses that respect the function's domain

You can determine the inferred parameters from the regressor object. Example:

regressor.param_names
# ['decay', 'amplitude']

To make predictions, use the ModelResult.eval() method.

model = results.eval
y_pred = model(x=np.array([1.5]))

Note: the ExponentialModel() follows a decay function, which accepts two parameters, one of which is negative.

enter image description here

See also ExponentialGaussianModel(), which accepts more parameters.

Install the library via > pip install lmfit.

Execution time of C program

If you are using the Unix shell for running, you can use the time command.

doing

$ time ./a.out

assuming a.out as the executable will give u the time taken to run this

Assign variable value inside if-statement

I believe that your problem is due to the fact that you are defining the variable v inside the test. As explained by @rmalchow, it will work you change it into

int v;
if((v = someMethod()) != 0) return true;

There is also another issue of variable scope. Even if what you tried were to work, what would be the point? Assuming you could define the variable scope inside the test, your variable v would not exist outside that scope. Hence, creating the variable and assigning the value would be pointless, for you would not be able to use it.

Variables exist only in the scope they were created. Since you are assigning the value to use it afterwards, consider the scope where you are creating the varible so that it may be used where needed.

Where does forever store console.log output?

It is a old question but i ran across the same issues. If you wanna see live output you can run

forever logs

This would show the path of the logs file as well as the number of the script. You can then use

forever logs 0 -f

0 should be replaced by the number of the script you wanna see the output for.

Initializing an Array of Structs in C#

You cannot initialize reference types by default other than null. You have to make them readonly. So this could work;

    readonly MyStruct[] MyArray = new MyStruct[]{
      new MyStruct{ label = "a", id = 1},
      new MyStruct{ label = "b", id = 5},
      new MyStruct{ label = "c", id = 1}
    };

Can you overload controller methods in ASP.NET MVC?

As far as I know you can only have the same method when using different http methods.

i.e.

[AcceptVerbs("GET")]
public ActionResult MyAction()
{

}

[AcceptVerbs("POST")]
public ActionResult MyAction(FormResult fm)
{

}

Replace specific text with a redacted version using Python

You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.

NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.

Example:

Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.

Returns:

NER with spacy

Just be aware that this is not 100%!

Here are a little snippet for you to try out:

import spacy

phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
   doc = nlp(phrase)
   replaced = ""
   for token in doc:
      if token in doc.ents:
         replaced+="XXXX "
      else:
         replaced+=token.text+" "

Read more here: https://spacy.io/usage/linguistic-features#named-entities

You could, instead of replacing with XXXX, replace based on the entity type, like:

if ent.label_ == "PERSON":
   replaced += "<PERSON> "

Then:

import re, random

personames = ["Jack", "Mike", "Bob", "Dylan"]

phrase = re.replace("<PERSON>", random.choice(personames), phrase)

How to push a docker image to a private repository

There are two options:

  1. Go into the hub, and create the repository first, and mark it as private. Then when you push to that repo, it will be private. This is the most common approach.

  2. log into your docker hub account, and go to your global settings. There is a setting that allows you to set what your default visability is for the repositories that you push. By default it is set to public, but if you change it to private, all of your repositories that you push will be marked as private by default. It is important to note that you will need to have enough private repos available on your account, or else the repo will be locked until you upgrade your plan.

How to use jQuery in chrome extension?

Its very easy just do the following:

add the following line in your manifest.json

"content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'",

Now you are free to load jQuery directly from url

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

Source: google doc

How to access local files of the filesystem in the Android emulator?

In Android Studio 3.0 and later do this:

View > Tool Windows > Device File Explorer

Parsing Query String in node.js

There's also the QueryString module's parse() method:

var http = require('http'),
    queryString = require('querystring');

http.createServer(function (oRequest, oResponse) {

    var oQueryParams;

    // get query params as object
    if (oRequest.url.indexOf('?') >= 0) {
        oQueryParams = queryString.parse(oRequest.url.replace(/^.*\?/, ''));

        // do stuff
        console.log(oQueryParams);
    }

    oResponse.writeHead(200, {'Content-Type': 'text/plain'});
    oResponse.end('Hello world.');

}).listen(1337, '127.0.0.1');

Multiple try codes in one block

If you don't want to chain (a huge number of) try-except clauses, you may try your codes in a loop and break upon 1st success.

Example with codes which can be put into functions:

for code in (
    lambda: a / b,
    lambda: a / (b + 1),
    lambda: a / (b + 2),
    ):
    try: print(code())
    except Exception as ev: continue
    break
else:
    print("it failed: %s" % ev)

Example with arbitrary codes (statements) directly in the current scope:

for i in 2, 1, 0:
    try:
        if   i == 2: print(a / b)
        elif i == 1: print(a / (b + 1))
        elif i == 0: print(a / (b + 2))
        break        
    except Exception as ev:
        if i:
            continue
        print("it failed: %s" % ev)

Position buttons next to each other in the center of page

you can add this style to your buttons:

#button1 , #button2 {
display:inline-block;
/* additional code */
}

this aligns your buttons inline. ('side by side') :)

String concatenation with Groovy

I always go for the second method (using the GString template), though when there are more than a couple of parameters like you have, I tend to wrap them in ${X} as I find it makes it more readable.

Running some benchmarks (using Nagai Masato's excellent GBench module) on these methods also shows templating is faster than the other methods:

@Grab( 'com.googlecode.gbench:gbench:0.3.0-groovy-2.0' )
import gbench.*

def (foo,bar,baz) = [ 'foo', 'bar', 'baz' ]
new BenchmarkBuilder().run( measureCpuTime:false ) {
  // Just add the strings
  'String adder' {
    foo + bar + baz
  }
  // Templating
  'GString template' {
    "$foo$bar$baz"
  }
  // I find this more readable
  'Readable GString template' {
    "${foo}${bar}${baz}"
  }
  // StringBuilder
  'StringBuilder' {
    new StringBuilder().append( foo )
                       .append( bar )
                       .append( baz )
                       .toString()
  }
  'StringBuffer' {
    new StringBuffer().append( foo )
                      .append( bar )
                      .append( baz )
                      .toString()
  }
}.prettyPrint()

That gives me the following output on my machine:

Environment
===========
* Groovy: 2.0.0
* JVM: Java HotSpot(TM) 64-Bit Server VM (20.6-b01-415, Apple Inc.)
    * JRE: 1.6.0_31
    * Total Memory: 81.0625 MB
    * Maximum Memory: 123.9375 MB
* OS: Mac OS X (10.6.8, x86_64) 

Options
=======
* Warm Up: Auto 
* CPU Time Measurement: Off

String adder               539
GString template           245
Readable GString template  244
StringBuilder              318
StringBuffer               370

So with readability and speed in it's favour, I'd recommend templating ;-)

NB: If you add toString() to the end of the GString methods to make the output type the same as the other metrics, and make it a fairer test, StringBuilder and StringBuffer beat the GString methods for speed. However as GString can be used in place of String for most things (you just need to exercise caution with Map keys and SQL statements), it can mostly be left without this final conversion

Adding these tests (as it has been asked in the comments)

  'GString template toString' {
    "$foo$bar$baz".toString()
  }
  'Readable GString template toString' {
    "${foo}${bar}${baz}".toString()
  }

Now we get the results:

String adder                        514
GString template                    267
Readable GString template           269
GString template toString           478
Readable GString template toString  480
StringBuilder                       321
StringBuffer                        369

So as you can see (as I said), it is slower than StringBuilder or StringBuffer, but still a bit faster than adding Strings...

But still lots more readable.

Edit after comment by ruralcoder below

Updated to latest gbench, larger strings for concatenation and a test with a StringBuilder initialised to a good size:

@Grab( 'org.gperfutils:gbench:0.4.2-groovy-2.1' )

def (foo,bar,baz) = [ 'foo' * 50, 'bar' * 50, 'baz' * 50 ]
benchmark {
  // Just add the strings
  'String adder' {
    foo + bar + baz
  }
  // Templating
  'GString template' {
    "$foo$bar$baz"
  }
  // I find this more readable
  'Readable GString template' {
    "${foo}${bar}${baz}"
  }
  'GString template toString' {
    "$foo$bar$baz".toString()
  }
  'Readable GString template toString' {
    "${foo}${bar}${baz}".toString()
  }
  // StringBuilder
  'StringBuilder' {
    new StringBuilder().append( foo )
                       .append( bar )
                       .append( baz )
                       .toString()
  }
  'StringBuffer' {
    new StringBuffer().append( foo )
                      .append( bar )
                      .append( baz )
                      .toString()
  }
  'StringBuffer with Allocation' {
    new StringBuffer( 512 ).append( foo )
                      .append( bar )
                      .append( baz )
                      .toString()
  }
}.prettyPrint()

gives

Environment
===========
* Groovy: 2.1.6
* JVM: Java HotSpot(TM) 64-Bit Server VM (23.21-b01, Oracle Corporation)
    * JRE: 1.7.0_21
    * Total Memory: 467.375 MB
    * Maximum Memory: 1077.375 MB
* OS: Mac OS X (10.8.4, x86_64)

Options
=======
* Warm Up: Auto (- 60 sec)
* CPU Time Measurement: On

                                    user  system  cpu  real

String adder                         630       0  630   647
GString template                      29       0   29    31
Readable GString template             32       0   32    33
GString template toString            429       0  429   443
Readable GString template toString   428       1  429   441
StringBuilder                        383       1  384   396
StringBuffer                         395       1  396   409
StringBuffer with Allocation         277       0  277   286

How do I get class name in PHP?

I think it's important to mention little difference between 'self' and 'static' in PHP as 'best answer' uses 'static' which can give confusing result to some people.

<?php
class X {
    function getStatic() {
        // gets THIS class of instance of object
        // that extends class in which is definied function
        return static::class;
    }
    function getSelf() {
        // gets THIS class of class in which function is declared
        return self::class;
    }
}

class Y extends X {
}
class Z extends Y {
}

$x = new X();
$y = new Y();
$z = new Z();

echo 'X:' . $x->getStatic() . ', ' . $x->getSelf() . 
    ', Y: ' . $y->getStatic() . ', ' . $y->getSelf() . 
    ', Z: ' . $z->getStatic() . ', ' . $z->getSelf();

Results:

X: X, X
Y: Y, X
Z: Z, X

How to append the output to a file?

Use >> to append:

command >> file

How can I get the behavior of GNU's readlink -f on a Mac?

Here is a portable shell function that should work in ANY Bourne comparable shell. It will resolve the relative path punctuation ".. or ." and dereference symbolic links.

If for some reason you do not have a realpath(1) command, or readlink(1) this can be aliased.

which realpath || alias realpath='real_path'

Enjoy:

real_path () {
  OIFS=$IFS
  IFS='/'
  for I in $1
  do
    # Resolve relative path punctuation.
    if [ "$I" = "." ] || [ -z "$I" ]
      then continue
    elif [ "$I" = ".." ]
      then FOO="${FOO%%/${FOO##*/}}"
           continue
      else FOO="${FOO}/${I}"
    fi

    ## Resolve symbolic links
    if [ -h "$FOO" ]
    then
    IFS=$OIFS
    set `ls -l "$FOO"`
    while shift ;
    do
      if [ "$1" = "->" ]
        then FOO=$2
             shift $#
             break
      fi
    done
    IFS='/'
    fi
  done
  IFS=$OIFS
  echo "$FOO"
}

also, just in case anybody is interested here is how to implement basename and dirname in 100% pure shell code:

## http://www.opengroup.org/onlinepubs/000095399/functions/dirname.html
# the dir name excludes the least portion behind the last slash.
dir_name () {
  echo "${1%/*}"
}

## http://www.opengroup.org/onlinepubs/000095399/functions/basename.html
# the base name excludes the greatest portion in front of the last slash.
base_name () {
  echo "${1##*/}"
}

You can find updated version of this shell code at my google site: http://sites.google.com/site/jdisnard/realpath

EDIT: This code is licensed under the terms of the 2-clause (freeBSD style) license. A copy of the license may be found by following the above hyperlink to my site.

Retrofit 2 - Dynamic URL

You can use the encoded flag on the @Path annotation:

public interface APIService {
  @GET("{fullUrl}")
  Call<Users> getUsers(@Path(value = "fullUrl", encoded = true) String fullUrl);
}
  • This will prevent the replacement of / with %2F.
  • It will not save you from ? being replaced by %3F, however, so you still can't pass in dynamic query strings.

Truncate/round whole number in JavaScript?

Math.trunc() function removes all the fractional digits.

For positive number it behaves exactly the same as Math.floor():

console.log(Math.trunc(89.13349)); // output is 89

For negative numbers it behaves same as Math.ceil():

console.log(Math.trunc(-89.13349)); //output is -89

Adding Jar files to IntellijIdea classpath

On the Mac version I was getting the error when trying to run JSON-Clojure.json.clj, which is the script to export a database table to JSON. To get it to work I had to download the latest Clojure JAR from http://clojure.org/ and then right-click on PHPStorm app in the Finder and "Show Package Contents". Then go to Contents in there. Then open the lib folder, and see a bunch of .jar files. Copy the clojure-1.8.0.jar file from the unzipped archive I downloaded from clojure.org into the aforementioned lib folder inside the PHPStorm.app/Contents/lib. Restart the app. Now it freaking works.

EDIT: You also have to put the JSR-223 script engine into PHPStorm.app/Contents/lib. It can be built from https://github.com/ato/clojure-jsr223 or downloaded from https://www.dropbox.com/s/jg7s0c41t5ceu7o/clojure-jsr223-1.5.1.jar?dl=0 .

How do I fix the error 'Named Pipes Provider, error 40 - Could not open a connection to' SQL Server'?

Did have the same problem. Spent like 6 hours when had to migrate some servers. Tried all suggestions available on this topic and others.

Solution was as simple as server restart!

Multiple arguments to function called by pthread_create()?

The args of print_the_arguments is arguments, so you should use:

struct arg_struct *args = (struct arg_struct *)arguments. 

Django REST Framework: adding additional field to ModelSerializer

This worked for me. If we want to just add an additional field in ModelSerializer, we can do it like below, and also the field can be assigned some val after some calculations of lookup. Or in some cases, if we want to send the parameters in API response.

In model.py

class Foo(models.Model):
    """Model Foo"""
    name = models.CharField(max_length=30, help_text="Customer Name")

In serializer.py

class FooSerializer(serializers.ModelSerializer):
    retrieved_time = serializers.SerializerMethodField()
    
    @classmethod
    def get_retrieved_time(self, object):
        """getter method to add field retrieved_time"""
        return None

  class Meta:
        model = Foo
        fields = ('id', 'name', 'retrieved_time ')

Hope this could help someone.

Calculate average in java

This

for (int i = 0; i<args.length -1; ++i)
    count++;

basically computes args.length again, just incorrectly (loop condition should be i<args.length). Why not just use args.length (or nums.length) directly instead?

Otherwise your code seems OK. Although it looks as though you wanted to read the input from the command line, but don't know how to convert that into an array of numbers - is this your real problem?

PHP using Gettext inside <<<EOF string

As far as I can see in the manual, it is not possible to call functions inside HEREDOC strings. A cumbersome way would be to prepare the words beforehand:

<?php

    $world = _("World");

    $str = <<<EOF
    <p>Hello</p>
    <p>$world</p>
EOF;
    echo $str;
?>

a workaround idea that comes to mind is building a class with a magic getter method.

You would declare a class like this:

class Translator
{
 public function __get($name) {
  return _($name); // Does the gettext lookup
  }
 }

Initialize an object of the class at some point:

  $translate = new Translator();

You can then use the following syntax to do a gettext lookup inside a HEREDOC block:

    $str = <<<EOF
    <p>Hello</p>
    <p>{$translate->World}</p>
EOF;
    echo $str;
?>

$translate->World will automatically be translated to the gettext lookup thanks to the magic getter method.

To use this method for words with spaces or special characters (e.g. a gettext entry named Hello World!!!!!!, you will have to use the following notation:

 $translate->{"Hello World!!!!!!"}

This is all untested but should work.

Update: As @mario found out, it is possible to call functions from HEREDOC strings after all. I think using getters like this is a sleek solution, but using a direct function call may be easier. See the comments on how to do this.

Could not load the Tomcat server configuration

In the Servers tab of eclipse, go to the properties of the server and Switch location to latest downloaded tomcat version.

This resolved the issue for me.

Tomcat Server Properties

What is the most efficient way to check if a value exists in a NumPy array?

The most obvious to me would be:

np.any(my_array[:, 0] == value)

forward declaration of a struct in C?

A struct (without a typedef) often needs to (or should) be with the keyword struct when used.

struct A;                      // forward declaration
void function( struct A *a );  // using the 'incomplete' type only as pointer

If you typedef your struct you can leave out the struct keyword.

typedef struct A A;          // forward declaration *and* typedef
void function( A *a );

Note that it is legal to reuse the struct name

Try changing the forward declaration to this in your code:

typedef struct context context;

It might be more readable to do add a suffix to indicate struct name and type name:

typedef struct context_s context_t;

Read lines from a text file but skip the first two lines

May be I am oversimplifying?

Just add the following code:

Open sFileName For Input as iFileNum
Line Input #iFileNum, dummy1
Line Input #iFileNum, dummy2
........

Sundar

Getting the source of a specific image element with jQuery

$('img.conversation_img[alt="example"]')
    .each(function(){
         alert($(this).attr('src'))
    });

This will display src attributes of all images of class 'conversation_img' with alt='example'

The model backing the <Database> context has changed since the database was created

Here's some information from Scott Gu's Blog posted by Jeff on what's actually taking place:

For those who are seeing this exception:

"The model backing the 'Production' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance."

Here is what is going on and what to do about it:

When a model is first created, we run a DatabaseInitializer to do things like create the database if it's not there or add seed data. The default DatabaseInitializer tries to compare the database schema needed to use the model with a hash of the schema stored in an EdmMetadata table that is created with a database (when Code First is the one creating the database). Existing databases won’t have the EdmMetadata table and so won’t have the hash…and the implementation today will throw if that table is missing. We'll work on changing this behavior before we ship the fial version since it is the default. Until then, existing databases do not generally need any database initializer so it can be turned off for your context type by calling:

Database.SetInitializer<YourDbContext>(null);

Jeff

How to get anchor text/href on click using jQuery?

Edited to reflect update to question

$(document).ready(function() {
    $(".res a").click(function() {
        alert($(this).attr("href"));
    });
});

How to update values in a specific row in a Python Pandas DataFrame?

If you have one large dataframe and only a few update values I would use apply like this:

import pandas as pd

df = pd.DataFrame({'filename' :  ['test0.dat', 'test2.dat'], 
                                  'm': [12, 13], 'n' : [None, None]})

data = {'filename' :  'test2.dat', 'n':16}

def update_vals(row, data=data):
    if row.filename == data['filename']:
        row.n = data['n']
    return row

df.apply(update_vals, axis=1)

Creating SVG graphics using Javascript?

So if you want to build your SVG stuff piece by piece in JS, then don't just use createElement(), those won't draw, use this instead:

var ci = document.createElementNS("http://www.w3.org/2000/svg", "circle");

How to initialize a nested struct?

You need to redefine the unnamed struct during &Configuration{}

package main

import "fmt"

type Configuration struct {
    Val   string
    Proxy struct {
        Address string
        Port    string
    }
}

func main() {

    c := &Configuration{
        Val: "test",
        Proxy: struct {
            Address string
            Port    string
        }{
            Address: "127.0.0.1",
            Port:    "8080",
        },
    }
    fmt.Println(c)
}

https://play.golang.org/p/Fv5QYylFGAY

How to set a value to a file input in HTML?

Not an answer to your question (which others have answered), but if you want to have some edit functionality of an uploaded file field, what you probably want to do is:

  • show the current value of this field by just printing the filename or URL, a clickable link to download it, or if it's an image: just show it, possibly as thumbnail
  • the <input> tag to upload a new file
  • a checkbox that, when checked, deletes the currently uploaded file. note that there's no way to upload an 'empty' file, so you need something like this to clear out the field's value

Replacing instances of a character in a string

names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]

usernames = []

for i in names:
    if " " in i:
        i = i.replace(" ", "_")
    print(i)

Output: Joey_Tribbiani Monica_Geller Chandler_Bing Phoebe_Buffay

How do I make a redirect in PHP?

Use:

<?php
    $url = "targetpage"
    function redirect$url(){
        if (headers_sent()) == false{
            echo '<script>window.location.href="' . $url . '";</script>';
        }
    }
?>

finding the type of an element using jQuery

The following will return true if the element is an input:

$("#elementId").is("input") 

or you can use the following to get the name of the tag:

$("#elementId").get(0).tagName

How to read a single character at a time from a file in Python?

os.system("stty -icanon -echo")
while True:
    raw_c = sys.stdin.buffer.peek()
    c = sys.stdin.read(1)
    print(f"Char: {c}")

How do you log all events fired by an element in jQuery?

Here is a non-jquery way to monitor events in the console with your code and without the use of monitorEvents() because that only works in Chrome Developer Console. You can also choose to not monitor certain events by editing the no_watch array.

    function getEvents(obj) {
    window["events_list"] = [];
    var no_watch = ['mouse', 'pointer']; // Array of event types not to watch
    var no_watch_reg = new RegExp(no_watch.join("|"));

    for (var prop in obj) {
        if (prop.indexOf("on") === 0) {
            prop = prop.substring(2); // remove "on" from beginning
            if (!prop.match(no_watch_reg)) {
                window["events_list"].push(prop);
                window.addEventListener(prop, function() {
                    console.log(this.event); // Display fired event in console
                } , false);
            }
        }
    }
    window["events_list"].sort(); // Alphabetical order 

}

getEvents(document); // Put window, document or any html element here
console.log(events_list); // List every event on element

What is the use of the @ symbol in PHP?

Like already some answered before: The @ operator suppresses all errors in PHP, including notices, warnings and even critical errors.

BUT: Please, really do not use the @ operator at all.

Why?

Well, because when you use the @ operator for error supression, you have no clue at all where to start when an error occurs. I already had some "fun" with legacy code where some developers used the @ operator quite often. Especially in cases like file operations, network calls, etc. Those are all cases where lots of developers recommend the usage of the @ operator as this sometimes is out of scope when an error occurs here (for example a 3rdparty API could be unreachable, etc.).

But what's the point to still not use it? Let's have a look from two perspectives:

As a developer: When @ is used, I have absolutely no idea where to start. If there are hundreds or even thousands of function calls with @ the error could be like everyhwere. No reasonable debugging possible in this case. And even if it is just a 3rdparty error - then it's just fine and you're done fast. ;-) Moreover, it's better to add enough details to the error log, so developers are able to decide easily if a log entry is something that must be checked further or if it's just a 3rdparty failure that is out of the developer's scope.

As a user: Users don't care at all what the reason for an error is or not. Software is there for them to work, to finish a specific task, etc. They don't care if it's the developer's fault or a 3rdparty problem. Especially for the users, I strongly recommend to log all errors, even if they're out of scope. Maybe you'll notice that a specific API is offline frequently. What can you do? You can talk to your API partner and if they're not able to keep it stable, you should probably look for another partner.

In short: You should know that there exists something like @ (knowledge is always good), but just do not use it. Many developers (especially those debugging code from others) will be very thankful.

adding 1 day to a DATETIME format value

There is a more concise and intuitive way to add days to php date. Don't get me wrong, those php expressions are great, but you always have to google how to treat them. I miss auto-completion facility for that.

Here is how I like to handle those cases:

(new Future(
    new DateTimeFromISO8601String('2014-11-21T06:04:31.321987+00:00'),
    new OneDay()
))
    ->value();

For me, it's way more intuitive and autocompletion works out of the box. No need to google for the solution each time.

As a nice bonus, you don't have to worry about formatting the resulting value, it's already is ISO8601 format.

This is meringue library, there are more examples here.

Combining a class selector and an attribute selector with jQuery

I think you just need to remove the space. i.e.

$(".myclass[reference=12345]").css('border', '#000 solid 1px');

There is a fiddle here http://jsfiddle.net/xXEHY/

Does Python's time.time() return the local or UTC timestamp?

This is for the text form of a timestamp that can be used in your text files. (The title of the question was different in the past, so the introduction to this answer was changed to clarify how it could be interpreted as the time. [updated 2016-01-14])

You can get the timestamp as a string using the .now() or .utcnow() of the datetime.datetime:

>>> import datetime
>>> print datetime.datetime.utcnow()
2012-12-15 10:14:51.898000

The now differs from utcnow as expected -- otherwise they work the same way:

>>> print datetime.datetime.now()
2012-12-15 11:15:09.205000

You can render the timestamp to the string explicitly:

>>> str(datetime.datetime.now())
'2012-12-15 11:15:24.984000'

Or you can be even more explicit to format the timestamp the way you like:

>>> datetime.datetime.now().strftime("%A, %d. %B %Y %I:%M%p")
'Saturday, 15. December 2012 11:19AM'

If you want the ISO format, use the .isoformat() method of the object:

>>> datetime.datetime.now().isoformat()
'2013-11-18T08:18:31.809000'

You can use these in variables for calculations and printing without conversions.

>>> ts = datetime.datetime.now()
>>> tf = datetime.datetime.now()
>>> te = tf - ts
>>> print ts
2015-04-21 12:02:19.209915
>>> print tf
2015-04-21 12:02:30.449895
>>> print te
0:00:11.239980

Ctrl+click doesn't work in Eclipse Juno

If your build path is correct, the ctrl + click will work

How do I zip two arrays in JavaScript?

Use the map method:

_x000D_
_x000D_
var a = [1, 2, 3]_x000D_
var b = ['a', 'b', 'c']_x000D_
_x000D_
var c = a.map(function(e, i) {_x000D_
  return [e, b[i]];_x000D_
});_x000D_
_x000D_
console.log(c)
_x000D_
_x000D_
_x000D_

DEMO

What is "export default" in JavaScript?

It's part of the ES6 module system, described here. There is a helpful example in that documentation, also:

If a module defines a default export:

export default function() { console.log("hello!") }

then you can import that default export by omitting the curly braces:

import foo from "foo";
foo(); // hello!

Update: As of June 2015, the module system is defined in §15.2 and the export syntax in particular is defined in §15.2.3 of the ECMAScript 2015 specification.

Display number always with 2 decimal places in <input>

If you are using Angular 2 (apparently it also works for Angular 4 too), you can use the following to round to two decimal places{{ exampleNumber | number : '1.2-2' }}, as in:

<ion-input value="{{ exampleNumber | number : '1.2-2' }}"></ion-input>

BREAKDOWN

'1.2-2' means {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}:

  • A minimum of 1 digit will be shown before decimal point
  • It will show at least 2 digits after decimal point
  • But not more than 2 digits

Credit due here and here

CSS get height of screen resolution

It is not possible to get the height of the screen from CSS. However, using since CSS3 you can use media queries to control the display of the template as per the resolution.

If you want to code on the basis of height using media queries, you can define style-sheet and call it like this.

<link rel="stylesheet" media="screen and (device-height: 600px)" />

End-line characters from lines read from text file, using Python

Simple. Use splitlines()

L = open("myFile.txt", "r").read().splitlines();
for line in L: 
    process(line) # this 'line' will not have '\n' character at the end

jQuery CSS Opacity

Try with this :

jQuery('#main').css({ opacity: 0.6 });

Sass and combined child selector

For that single rule you have, there isn't any shorter way to do it. The child combinator is the same in CSS and in Sass/SCSS and there's no alternative to it.

However, if you had multiple rules like this:

#foo > ul > li > ul > li > a:nth-child(3n+1) {
    color: red;
}

#foo > ul > li > ul > li > a:nth-child(3n+2) {
    color: green;
}

#foo > ul > li > ul > li > a:nth-child(3n+3) {
    color: blue;
}

You could condense them to one of the following:

/* Sass */
#foo > ul > li > ul > li
    > a:nth-child(3n+1)
        color: red
    > a:nth-child(3n+2)
        color: green
    > a:nth-child(3n+3)
        color: blue

/* SCSS */
#foo > ul > li > ul > li {
    > a:nth-child(3n+1) { color: red; }
    > a:nth-child(3n+2) { color: green; }
    > a:nth-child(3n+3) { color: blue; }
}

MySQL Sum() multiple columns

If any of your markn columns are "AllowNull" then you will need to do a little extra to insure the correct result is returned, this is because 1 NULL value will result in a NULL total.

This is what i would consider to be the correct answer.

SUM(IFNULL(`mark1`, 0) + IFNULL(`mark2`, 0) + IFNULL(`mark3`, 0)) AS `total_marks` 

IFNULL will return the 2nd parameter if the 1st is NULL. COALESCE could be used but i prefer to only use it if it is required. See What is the difference bewteen ifnull and coalesce in mysql?

SUM-ing the entire calculation is tidier than SUM-ing each column individually.

SELECT `student`, SUM(IFNULL(`mark1`, 0) + IFNULL(`mark2`, 0) + IFNULL(`mark3`, 0)) AS `total_marks` 
FROM student_scorecard
GROUP BY `student`

What is ToString("N0") format?

You can find the list of formats here (in the Double.ToString()-MSDN-Article) as comments in the example section.

Best way to select random rows PostgreSQL

Starting with PostgreSQL 9.5, there's a new syntax dedicated to getting random elements from a table :

SELECT * FROM mytable TABLESAMPLE SYSTEM (5);

This example will give you 5% of elements from mytable.

See more explanation on the documentation: http://www.postgresql.org/docs/current/static/sql-select.html

Using ResourceManager

According to the MSDN documentation here, The basename argument specifies "The root name of the resource file without its extension but including any fully qualified namespace name. For example, the root name for the resource file named "MyApplication.MyResource.en-US.resources" is "MyApplication.MyResource"."

The ResourceManager will automatically try to retrieve the values for the current UI culture. If you want to use a specific language, you'll need to set the current UI culture to the language you wish to use.

Add jars to a Spark Job - spark-submit

Another approach in spark 2.1.0 is to use --conf spark.driver.userClassPathFirst=true during spark-submit which changes the priority of dependency load, and thus the behavior of the spark-job, by giving priority to the jars the user is adding to the class-path with the --jars option.

Adding event listeners to dynamically added elements using jQuery

You are dynamically generating those elements so any listener applied on page load wont be available. I have edited your fiddle with the correct solution. Basically jQuery holds the event for later binding by attaching it to the parent Element and propagating it downward to the correct dynamically created element.

$('#musics').on('change', '#want',function(e) {
    $(this).closest('.from-group').val(($('#want').is(':checked')) ? "yes" : "no");
    var ans=$(this).val();
    console.log(($('#want').is(':checked')));
});

http://jsfiddle.net/swoogie/1rkhn7ek/39/

How to download file in swift?

Use URLSessionDownloadTask to download files in background so that they can completed even if the app is terminated.

For more information see:

https://www.ralfebert.de/snippets/ios/urlsession-background-downloads/

It also shows how to implement progress monitoring for multiple tasks running in parallel:

Parsing JSON string in Java

See my comment. You need to include the full org.json library when running as android.jar only contains stubs to compile against.

In addition, you must remove the two instances of extra } in your JSON data following longitude.

   private final static String JSON_DATA =
     "{" 
   + "  \"geodata\": [" 
   + "    {" 
   + "      \"id\": \"1\"," 
   + "      \"name\": \"Julie Sherman\","                  
   + "      \"gender\" : \"female\"," 
   + "      \"latitude\" : \"37.33774833333334\"," 
   + "      \"longitude\" : \"-121.88670166666667\""
   + "    }," 
   + "    {" 
   + "      \"id\": \"2\"," 
   + "      \"name\": \"Johnny Depp\","          
   + "      \"gender\" : \"male\"," 
   + "      \"latitude\" : \"37.336453\"," 
   + "      \"longitude\" : \"-121.884985\""
   + "    }" 
   + "  ]" 
   + "}"; 

Apart from that, geodata is in fact not a JSONObject but a JSONArray.

Here is the fully working and tested corrected code:

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ShowActivity {


  private final static String JSON_DATA =
     "{" 
   + "  \"geodata\": [" 
   + "    {" 
   + "      \"id\": \"1\"," 
   + "      \"name\": \"Julie Sherman\","                  
   + "      \"gender\" : \"female\"," 
   + "      \"latitude\" : \"37.33774833333334\"," 
   + "      \"longitude\" : \"-121.88670166666667\""
   + "    }," 
   + "    {" 
   + "      \"id\": \"2\"," 
   + "      \"name\": \"Johnny Depp\","          
   + "      \"gender\" : \"male\"," 
   + "      \"latitude\" : \"37.336453\"," 
   + "      \"longitude\" : \"-121.884985\""
   + "    }" 
   + "  ]" 
   + "}"; 

  public static void main(final String[] argv) throws JSONException {
    final JSONObject obj = new JSONObject(JSON_DATA);
    final JSONArray geodata = obj.getJSONArray("geodata");
    final int n = geodata.length();
    for (int i = 0; i < n; ++i) {
      final JSONObject person = geodata.getJSONObject(i);
      System.out.println(person.getInt("id"));
      System.out.println(person.getString("name"));
      System.out.println(person.getString("gender"));
      System.out.println(person.getDouble("latitude"));
      System.out.println(person.getDouble("longitude"));
    }
  }
}

Here's the output:

C:\dev\scrap>java -cp json.jar;. ShowActivity
1
Julie Sherman
female
37.33774833333334
-121.88670166666667
2
Johnny Depp
male
37.336453
-121.884985

Find the item with maximum occurrences in a list

A simple way without any libraries or sets

def mcount(l):
  n = []                  #To store count of each elements
  for x in l:
      count = 0
      for i in range(len(l)):
          if x == l[i]:
              count+=1
      n.append(count)
  a = max(n)              #largest in counts list
  for i in range(len(n)):
      if n[i] == a:
          return(l[i],a)  #element,frequency
  return                  #if something goes wrong

android - setting LayoutParams programmatically

int dp1 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1,
            context.getResources().getDisplayMetrics());

tv.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
dp1 * 100)); // if you want to set layout height to 100dp

llview.addView(tv);

Junit test case for database insert method with DAO and web service

/*

public class UserDAO {

public boolean insertUser(UserBean u) {
    boolean flag = false;
    MySqlConnection msq = new MySqlConnection();
    try {

        String sql = "insert into regis values(?,?,?,?,?)";

        Connection connection = msq.getConnection();
        PreparedStatement statement = null;
        statement = (PreparedStatement) connection.prepareStatement(sql);
        statement.setString(1, u.getname());
        statement.setString(2, u.getlname());
        statement.setString(3, u.getemail());
        statement.setString(4, u.getusername());
        statement.setString(5, u.getpasswords());
        statement.executeUpdate();

        flag = true;
    } catch (Exception e) {
    } finally {
        return flag;
    }

}

public String userValidate(UserBean u) {
    String login = "";
    MySqlConnection msq = new MySqlConnection();
    try {
        String email = u.getemail();
        String Pass = u.getpasswords();

        String sql = "SELECT name FROM regis WHERE email=? and passwords=?";
        com.mysql.jdbc.Connection connection = msq.getConnection();
        com.mysql.jdbc.PreparedStatement statement = null;
        ResultSet rs = null;
        statement = (com.mysql.jdbc.PreparedStatement) connection.prepareStatement(sql);
        statement.setString(1, email);
        statement.setString(2, Pass);
        rs = statement.executeQuery();
        if (rs.next()) {
            login = rs.getString("name");
        } else {
            login = "false";
        }

    } catch (Exception e) {
    } finally {
        return login;
    }
}

public boolean getmessage(UserBean u) {
    boolean flag = false;
    MySqlConnection msq = new MySqlConnection();
    try {


        String sql = "insert into feedback values(?,?)";

        Connection connection = msq.getConnection();
        PreparedStatement statement = null;
        statement = (PreparedStatement) connection.prepareStatement(sql);
        statement.setString(1, u.getemail());
        statement.setString(2, u.getfeedback());
        statement.executeUpdate();

        flag = true;
    } catch (Exception e) {
    } finally {
        return flag;
    }

}

public boolean insertOrder(cartbean u) {
    boolean flag = false;
    MySqlConnection msq = new MySqlConnection();
    try {

        String sql = "insert into cart (product_id, email, Tprice, quantity) values (?,?,2000,?)";

        Connection connection = msq.getConnection();
        PreparedStatement statement = null;
        statement = (PreparedStatement) connection.prepareStatement(sql);
        statement.setString(1, u.getpid());
        statement.setString(2, u.getemail());
        statement.setString(3, u.getquantity());

        statement.executeUpdate();

        flag = true;
    } catch (Exception e) {
        System.out.print("hi");
    } finally {
        return flag;
    }

}

}

wkhtmltopdf: cannot connect to X server

For 64-bit Use:

wget http://wkhtmltopdf.googlecode.com/files/wkhtmltopdf-0.9.9-static-amd64.tar.bz2

tar xvjf wkhtmltopdf-0.9.9-static-amd64.tar.bz2

sudo mv wkhtmltopdf-amd64 /usr/bin/wkhtmltopdf

sudo chmod +x /usr/bin/wkhtmltopdf

Null pointer Exception on .setOnClickListener

android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Because Submit button is inside login_modal so you need to use loginDialog view to access button:

Submit = (Button)loginDialog.findViewById(R.id.Submit);

How to change column datatype in SQL database without losing data

Go to Tool-Option-designers-Table and Database designers and Uncheck Prevent saving optionenter image description here

Add alternating row color to SQL Server Reporting services report

When using row and column groups both, I had an issue where the colors would alternate between the columns even though it was the same row. I resolved this by using a global variable that alternates only when the row changes:

Public Dim BGColor As String = "#ffffff"

Function AlternateColor() As String
  If BGColor = "#cccccc" Then
    BGColor = "#ffffff"
    Return "#cccccc"
  Else
    BGColor = "#cccccc"
    Return "#ffffff"
  End  If
End Function

Now, in the first column of the row you want to alternate, set the color expression to:

=Code.AlternateColor()

-

In the remaining columns, set them all to:

=Code.BGColor

This should make the colors alternate only after the first column is drawn.

This may (unverifiably) improve performance, too, since it does not need to do a math computation for each column.

How can I declare a two dimensional string array?

I assume you're looking for this:

        string[,] Tablero = new string[3,3];

The syntax for a jagged array is:

        string[][] Tablero = new string[3][];
        for (int ix = 0; ix < 3; ++ix) {
            Tablero[ix] = new string[3];
        }

How can I open a .tex file?

A .tex file should be a LaTeX source file.

If this is the case, that file contains the source code for a LaTeX document. You can open it with any text editor (notepad, notepad++ should work) and you can view the source code. But if you want to view the final formatted document, you need to install a LaTeX distribution and compile the .tex file.

Of course, any program can write any file with any extension, so if this is not a LaTeX document, then we can't know what software you need to install to open it. Maybe if you upload the file somewhere and link it in your question we can see the file and provide more help to you.


Yes, this is the source code of a LaTeX document. If you were able to paste it here, then you are already viewing it. If you want to view the compiled document, you need to install a LaTeX distribution. You can try to install MiKTeX then you can use that to compile the document to a .pdf file.

You can also check out this question and answer for how to do it: How to compile a LaTeX document?

Also, there's an online LaTeX editor and you can paste your code in there to preview the document: https://www.overleaf.com/.

When to use dynamic vs. static libraries

Ulrich Drepper's paper on "How to Write Shared Libraries" is also good resource that details how best to take advantage of shared libraries, or what he refers to as "Dynamic Shared Objects" (DSOs). It focuses more on shared libraries in the ELF binary format, but some discussions are suitable for Windows DLLs as well.

Xcode/Simulator: How to run older iOS version?

To anyone else who finds this older question, you can now download all old versions.

Xcode -> Preferences -> Components (Click on Simulators tab).

Install all the versions you want/need.

To show all installed simulators:

Target -> In dropdown "deployment target" choose the installed version with lowest version nr.

You should now see all your available simulators in the dropdown.

What is the difference between an expression and a statement in Python?

Expressions:

  • Expressions are formed by combining objects and operators.
  • An expression has a value, which has a type.
  • Syntax for a simple expression:<object><operator><object>

2.0 + 3 is an expression which evaluates to 5.0 and has a type float associated with it.

Statements

Statements are composed of expression(s). It can span multiple lines.

Is there an XSLT name-of element?

This will give you the current element name (tag name)

<xsl:value-of select ="name(.)"/>

OP-Edit: This will also do the trick:

<xsl:value-of select ="local-name()"/>

Elasticsearch query to return all records

The best way to adjust the size is using size=number in front of the URL

Curl -XGET "http://localhost:9200/logstash-*/_search?size=50&pretty"

Note: maximum value which can be defined in this size is 10000. For any value above ten thousand it expects you to use scroll function which would minimise any chances of impacts to performance.

Java ArrayList of Arrays?

  1. Create the ArrayList like ArrayList action.

    In JDK 1.5 or higher use ArrayList <string[]> reference name.

    In JDK 1.4 or lower use ArrayList reference name.

  2. Specify the access specifiers:

    • public, can be accessed anywhere
    • private, accessed within the class
    • protected, accessed within the class and different package subclasses
  3. Then specify the reference it will be assigned in

    action = new ArrayList<String[]>();
    
  4. In JVM new keyword will allocate memory in runtime for the object.

    You should not assigned the value where declared, because you are asking without fixed size.

  5. Finally you can be use the add() method in ArrayList. Use like

    action.add(new string[how much you need])
    

    It will allocate the specific memory area in heap.

Converting from a string to boolean in Python?

Use:

bool(distutils.util.strtobool(some_string))

True values are y, yes, t, true, on and 1; false values are n, no, f, false, off and 0. Raises ValueError if val is anything else.

Be aware that distutils.util.strtobool() returns integer representations and thus it needs to be wrapped with bool() to get Boolean values.

What is the purpose of the word 'self'?

Let's say you have a class ClassA which contains a method methodA defined as:

def methodA(self, arg1, arg2):
    # do something

and ObjectA is an instance of this class.

Now when ObjectA.methodA(arg1, arg2) is called, python internally converts it for you as:

ClassA.methodA(ObjectA, arg1, arg2)

The self variable refers to the object itself.

Show image using file_get_contents

Do i need to modify the headers and just echo it or something?

exactly.

Send a header("content-type: image/your_image_type"); and the data afterwards.

ORA-03113: end-of-file on communication channel after long inactivity in ASP.Net app

Add Validate Connection=true to your connection string.

Look at this blog to find more about.

DETAILS: After OracleConnection.Close() the real database connection does not terminate. The connection object is put back in connection pool. The use of connection pool is implicit by ODP.NET. If you create a new connection you get one of the pool. If this connection is "yet open" the OracleConnection.Open() method does not really creates a new connection. If the real connection is broken (for any reason) you get a failure on first select, update, insert or delete.

With Validate Connection the real connection is validated in Open() method.

How to configure Git post commit hook

As mentioned in "Polling must die: triggering Jenkins builds from a git hook", you can notify Jenkins of a new commit:

With the latest Git plugin 1.1.14 (that I just release now), you can now do this more >easily by simply executing the following command:

curl http://yourserver/jenkins/git/notifyCommit?url=<URL of the Git repository>

This will scan all the jobs that’s configured to check out the specified URL, and if they are also configured with polling, it’ll immediately trigger the polling (and if that finds a change worth a build, a build will be triggered in turn.)

This allows a script to remain the same when jobs come and go in Jenkins.
Or if you have multiple repositories under a single repository host application (such as Gitosis), you can share a single post-receive hook script with all the repositories. Finally, this URL doesn’t require authentication even for secured Jenkins, because the server doesn’t directly use anything that the client is sending. It runs polling to verify that there is a change, before it actually starts a build.

As mentioned here, make sure to use the right address for your Jenkins server:

since we're running Jenkins as standalone Webserver on port 8080 the URL should have been without the /jenkins, like this:

http://jenkins:8080/git/notifyCommit?url=git@gitserver:tools/common.git

To reinforce that last point, ptha adds in the comments:

It may be obvious, but I had issues with:

curl http://yourserver/jenkins/git/notifyCommit?url=<URL of the Git repository>. 

The url parameter should match exactly what you have in Repository URL of your Jenkins job.
When copying examples I left out the protocol, in our case ssh://, and it didn't work.


You can also use a simple post-receive hook like in "Push based builds using Jenkins and GIT"

#!/bin/bash
/usr/bin/curl --user USERNAME:PASS -s \

http://jenkinsci/job/PROJECTNAME/build?token=1qaz2wsx

Configure your Jenkins job to be able to “Trigger builds remotely” and use an authentication token (1qaz2wsx in this example).

However, this is a project-specific script, and the author mentions a way to generalize it.
The first solution is easier as it doesn't depend on authentication or a specific project.


I want to check in change set whether at least one java file is there the build should start.
Suppose the developers changed only XML files or property files, then the build should not start.

Basically, your build script can:

  • put a 'build' notes (see git notes) on the first call
  • on the subsequent calls, grab the list of commits between HEAD of your branch candidate for build and the commit referenced by the git notes 'build' (git show refs/notes/build): git diff --name-only SHA_build HEAD.
  • your script can parse that list and decide if it needs to go on with the build.
  • in any case, create/move your git notes 'build' to HEAD.

May 2016: cwhsu points out in the comments the following possible url:

you could just use curl --user USER:PWD http://JENKINS_SERVER/job/JOB_NAME/build?token=YOUR_TOKEN if you set trigger config in your item

http://i.imgur.com/IolrOOj.png


June 2016, polaretto points out in the comments:

I wanted to add that with just a little of shell scripting you can avoid manual url configuration, especially if you have many repositories under a common directory.
For example I used these parameter expansions to get the repo name

repository=${PWD%/hooks}; 
repository=${repository##*/} 

and then use it like:

curl $JENKINS_URL/git/notifyCommit?url=$GIT_URL/$repository

Why does Git treat this text file as a binary file?

If you have not set the type of a file, Git tries to determine it automatically and a file with really long lines and maybe some wide characters (e.g. Unicode) is treated as binary. With the .gitattributes file you can define how Git interpretes the file. Setting the diff attribute manually lets Git interprete the file content as text and will do an usual diff.

Just add a .gitattributes to your repository root folder and set the diff attribute to the paths or files. Here's an example:

src/Acme/DemoBundle/Resources/public/js/i18n/* diff
doc/Help/NothingToSay.yml                      diff
*.css                                          diff

If you want to check if there are attributes set on a file, you can do that with the help of git check-attr

git check-attr --all -- src/my_file.txt

Another nice reference about Git attributes could be found here.

Android ListView Selector Color

TO ADD: @Christopher's answer does not work on API 7/8 (as per @Jonny's correct comment) IF you are using colours, instead of drawables. (In my testing, using drawables as per Christopher works fine)

Here is the FIX for 2.3 and below when using colours:

As per @Charles Harley, there is a bug in 2.3 and below where filling the list item with a colour causes the colour to flow out over the whole list. His fix is to define a shape drawable containing the colour you want, and to use that instead of the colour.

I suggest looking at this link if you want to just use a colour as selector, and are targeting Android 2 (or at least allow for Android 2).

How can I populate a select dropdown list from a JSON feed with AngularJS?

<select name="selectedFacilityId" ng-model="selectedFacilityId">
         <option ng-repeat="facility in facilities" value="{{facility.id}}">{{facility.name}}</option>
     </select>  

This is an example on how to use it.

Use of "global" keyword in Python

It means that you should not do the following:

x = 1

def myfunc():
  global x

  # formal parameter
  def localfunction(x):
    return x+1

  # import statement
  import os.path as x

  # for loop control target
  for x in range(10):
    print x

  # class definition
  class x(object):
    def __init__(self):
      pass

  #function definition
  def x():
    print "I'm bad"

Maximum execution time in phpMyadmin

Your change should work. However, there are potentially few php.ini configuration files with the 'xampp' stack. Try to identify whether or not there's an 'apache' specific php.ini. One potential location is:

C:\xampp\apache\bin\php.ini

How to add a bot to a Telegram Group?

Edit: now there is yet an easier way to do this - when creating your group, just mention the full bot name (eg. @UniversalAgent1Bot) and it will list it as you type. Then you can just tap on it to add it.

Old answer:

  1. Create a new group from the menu. Don't add any bots yet
  2. Find the bot (for instance you can go to Contacts and search for it)
  3. Tap to open
  4. Tap the bot name on the top bar. Your page becomes like this: Telegram bot settings
  5. Now, tap the triple ... and you will get the Add to Group button: Adding the bot
  6. Now select your group and add the bot - and confirm the addition

Why is visible="false" not working for a plain html table?

If you want use it, use runat="server" for that table. After that use tablename.visible=False in server side code.

string to string array conversion in java

An additional method:

As was already mentioned, you could convert the original String "name" to a char array quite easily:

String originalString = "name";
char[] charArray = originalString.toCharArray();

To continue this train of thought, you could then convert the char array to a String array:

String[] stringArray = new String[charArray.length];
for (int i = 0; i < charArray.length; i++){
    stringArray[i] = String.valueOf(charArray[i]);
}

At this point, your stringArray will be filled with the original values from your original string "name". For example, now calling

System.out.println(stringArray[0]);

Will return the value "n" (as a String) in this case.

Accessing an SQLite Database in Swift

Configure your Swift project to handle SQLite C calls:

Create bridging header file to the project. See the Importing Objective-C into Swift section of the Using Swift with Cocoa and Objective-C. This bridging header should import sqlite3.h:

Add the libsqlite3.0.dylib to your project. See Apple's documentation regarding adding library/framework to one's project.

and used following code

    func executeQuery(query: NSString ) -> Int
    {
        if  sqlite3_open(databasePath! as String, &database) != SQLITE_OK
        {
            println("Databse is not open")
            return 0
        }
        else
        {
            query.stringByReplacingOccurrencesOfString("null", withString: "")
            var cStatement:COpaquePointer = nil
            var executeSql = query as NSString
            var lastId : Int?
            var sqlStatement = executeSql.cStringUsingEncoding(NSUTF8StringEncoding)
            sqlite3_prepare_v2(database, sqlStatement, -1, &cStatement, nil)
            var execute = sqlite3_step(cStatement)
            println("\(execute)")
            if execute == SQLITE_DONE
            {
                lastId = Int(sqlite3_last_insert_rowid(database))
            }
            else
            {
                println("Error in Run Statement :- \(sqlite3_errmsg16(database))")
            }
            sqlite3_finalize(cStatement)
            return lastId!
        }
    }
    func ViewAllData(query: NSString, error: NSError) -> NSArray
    {
        var cStatement = COpaquePointer()
        var result : AnyObject = NSNull()
        var thisArray : NSMutableArray = NSMutableArray(capacity: 4)
        cStatement = prepare(query)
        if cStatement != nil
        {
            while sqlite3_step(cStatement) == SQLITE_ROW
            {
                result = NSNull()
                var thisDict : NSMutableDictionary = NSMutableDictionary(capacity: 4)
                for var i = 0 ; i < Int(sqlite3_column_count(cStatement)) ; i++
                {
                    if sqlite3_column_type(cStatement, Int32(i)) == 0
                    {
                        continue
                    }
                    if sqlite3_column_decltype(cStatement, Int32(i)) != nil && strcasecmp(sqlite3_column_decltype(cStatement, Int32(i)), "Boolean") == 0
                    {
                        var temp = sqlite3_column_int(cStatement, Int32(i))
                        if temp == 0
                        {
                            result = NSNumber(bool : false)
                        }
                        else
                        {
                            result = NSNumber(bool : true)
                        }
                    }
                    else if sqlite3_column_type(cStatement,Int32(i)) == SQLITE_INTEGER
                    {
                        var temp = sqlite3_column_int(cStatement,Int32(i))
                        result = NSNumber(int : temp)
                    }
                    else if sqlite3_column_type(cStatement,Int32(i)) == SQLITE_FLOAT
                    {
                        var temp = sqlite3_column_double(cStatement,Int32(i))
                        result = NSNumber(double: temp)
                    }
                    else
                    {
                        if sqlite3_column_text(cStatement, Int32(i)) != nil
                        {
                            var temp = sqlite3_column_text(cStatement,Int32(i))
                            result = String.fromCString(UnsafePointer<CChar>(temp))!
                            
                            var keyString = sqlite3_column_name(cStatement,Int32(i))
                            thisDict.setObject(result, forKey: String.fromCString(UnsafePointer<CChar>(keyString))!)
                        }
                        result = NSNull()

                    }
                    if result as! NSObject != NSNull()
                    {
                        var keyString = sqlite3_column_name(cStatement,Int32(i))
                        thisDict.setObject(result, forKey: String.fromCString(UnsafePointer<CChar>(keyString))!)
                    }
                }
                thisArray.addObject(NSMutableDictionary(dictionary: thisDict))
            }
            sqlite3_finalize(cStatement)
        }
        return thisArray
    }
    func prepare(sql : NSString) -> COpaquePointer
    {
        var cStatement:COpaquePointer = nil
        sqlite3_open(databasePath! as String, &database)
        var utfSql = sql.UTF8String
        if sqlite3_prepare(database, utfSql, -1, &cStatement, nil) == 0
        {
            sqlite3_close(database)
            return cStatement
        }
        else
        {
            sqlite3_close(database)
            return nil
        }
    }
}

How to debug heap corruption errors?

You can detect a lot of heap corruption problems by enabling Page Heap for your application . To do this you need to use gflags.exe that comes as a part of Debugging Tools For Windows

Run Gflags.exe and in the Image file options for your executable, check "Enable Page Heap" option.

Now restart your exe and attach to a debugger. With Page Heap enabled, the application will break into debugger whenever any heap corruption occurs.

youtube: link to display HD video by default

via Is there a way to link someone to a YouTube Video in HD 1080p quality?

Yes there is:

https://www.youtube.com/embed/Susj4jVWs0s?version=3&vq=hd720

options are:

default|none: vq=auto;
Code for auto: vq=auto;
Code for 2160p: vq=hd2160;
Code for 1440p: vq=hd1440;
Code for 1080p: vq=hd1080;
Code for 720p: vq=hd720;
Code for 480p: vq=large;
Code for 360p: vq=medium;
Code for 240p: vq=small;

As mentioned, you have to use the /embed/ or /v/ URL.

Note: Some copyrighted content doesn't support be played in this way

Retrieving the text of the selected <option> in <select> element

Easy, simple way:

const select = document.getElementById('selectID');
const selectedOption = [...select.options].find(option => option.selected).text;

How to add an auto-incrementing primary key to an existing table, in PostgreSQL?

To use an identity column in v10,

ALTER TABLE test 
ADD COLUMN id { int | bigint | smallint}
GENERATED { BY DEFAULT | ALWAYS } AS IDENTITY PRIMARY KEY;

For an explanation of identity columns, see https://blog.2ndquadrant.com/postgresql-10-identity-columns/.

For the difference between GENERATED BY DEFAULT and GENERATED ALWAYS, see https://www.cybertec-postgresql.com/en/sequences-gains-and-pitfalls/.

For altering the sequence, see https://popsql.io/learn-sql/postgresql/how-to-alter-sequence-in-postgresql/.

Jquery button click() function is not working

You need to use the event delegation syntax of .on() here. Change:

$("#add").click(function() {

to

$("#buildyourform").on('click', '#add', function () {

jsFiddle example

Access denied for user 'root'@'localhost' (using password: Yes) after password reset LINUX

Actually I took a closer look at the user table in mysql database, turns out someone prior to me edited the ssl_type field for user root to SSL.

I edited that field and restarted mysql and it worked like a charm.

Thanks.

Maven build failed: "Unable to locate the Javac Compiler in: jre or jdk issue"

The solution to this problem is very simple...

If you don't have Ant build file then generate it. In Eclipse you can easily create a Ant file.

Refer to the link to create Ant build file [http://www.codejava.net/ides/eclipse/how-to-create-ant-build-file-for-existing-java-project-in-eclipse].

Now follow the given steps:

1) Add your Ant build file in Ant view that is in view window.

2) right click on your Ant build file and select Run As and the second option in that "Ant Build".

3) Now a dialog box will open with various options and tabs.

4) Select the JRE tab.

5) You will see three radio buttons and they will be having JRE or JDK selected as an option.

6) Look carefully if the radio button options are having JRE as selected then change it to JDK.

7) Click apply.

That's it...!!!

Read String line by line

You can also use:

String[] lines = someString.split("\n");

If that doesn't work try replacing \n with \r\n.

Autonumber value of last inserted row - MS Access / VBA

If DAO use

RS.Move 0, RS.LastModified
lngID = RS!AutoNumberFieldName

If ADO use

cn.Execute "INSERT INTO TheTable.....", , adCmdText + adExecuteNoRecords
Set rs = cn.Execute("SELECT @@Identity", , adCmdText)
Debug.Print rs.Fields(0).Value

cn being a valid ADO connection, @@Identity will return the last Identity (Autonumber) inserted on this connection.

Note that @@Identity might be troublesome because the last generated value may not be the one you are interested in. For the Access database engine, consider a VIEW that joins two tables, both of which have the IDENTITY property, and you INSERT INTO the VIEW. For SQL Server, consider if there are triggers that in turn insert records into another table that also has the IDENTITY property.

BTW DMax would not work as if someone else inserts a record just after you've inserted one but before your Dmax function finishes excecuting, then you would get their record.

Global Variable from a different file Python

from file2 import * is making copies. You want to do this:

import file2
print file2.foo
print file2.SomeClass()

HSL to RGB color conversion

PHP - shortest but precise

Here I rewrite my JS answer (math details are there) to PHP - you can run it here

function hsl2rgb($h,$s,$l) 
{
  $a = $s * min($l, 1-$l);
  $k = function($n,$h) { return ($n+$h/30)%12;};
  $f = function($n) use ($h,$s,$l,$a,$k) { 
      return $l - $a * max( min($k($n,$h)-3, 9-$k($n,$h), 1),-1);
  };
  return [ $f(0), $f(8), $f(4) ];
}   

How to provide a file download from a JSF backing bean?

Introduction

You can get everything through ExternalContext. In JSF 1.x, you can get the raw HttpServletResponse object by ExternalContext#getResponse(). In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream() without the need to grab the HttpServletResponse from under the JSF hoods.

On the response, you should set the Content-Type header so that the client knows which application to associate with the provided file. And, you should set the Content-Length header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition header to attachment if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.

Most important part is to call FacesContext#responseComplete() to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException with a message like getoutputstream() has already been called for this response when the JSF implementation calls getWriter() to render HTML.

Turn off ajax / don't use remote command!

You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink> and <h:commandButton>. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.

In case you're using e.g. PrimeFaces <p:commandXxx>, then you need to make sure that you explicitly turn off ajax via ajax="false" attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" /> in the command component.

Generic JSF 2.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();

    ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
    ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = ec.getResponseOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Generic JSF 1.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

    response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
    response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = response.getOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Common static file example

In case you need to stream a static file from the local disk file system, substitute the code as below:

File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();

// ...

Files.copy(file.toPath(), output);

Common dynamic file example

In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output there where the API being used expects an OutputStream.

E.g. iText PDF:

String fileName = "dynamic.pdf";
String contentType = "application/pdf";

// ...

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();

E.g. Apache POI HSSF:

String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";

// ...

HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();

Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.

Utility method

If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile() methods taking either a File, or an InputStream, or a byte[], and specifying whether the file should be downloaded as an attachment (true) or inline (false).

public void download() throws IOException {
    Faces.sendFile(file, true);
}

Yes, this code is complete as-is. You don't need to invoke responseComplete() and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.

Error in Eclipse: "The project cannot be built until build path errors are resolved"

  1. Open the Problems view. You can open this view by clicking on the small + sign at the left hand bottom corner of eclipse. It's a very tiny plus with a rectangle around it. Click on it and select problems.

  2. The problem view will show you the problems that need to be resolved.

    • If the message says "the project is missing the required libraries...", you need to configure your build path by right clicking on your project, selecting properties, then build path. Add the required jar files using the libraries tab. -If there are other problems other than missing libraries, you need to post the exact problems here to get a precise solution.

How to check if directory exists in %PATH%?

This is a variation to Kevin Edwards's answer using string replacement. The basic pattern is:

IF "%PATH:new_path=%" == "%PATH%" PATH=%PATH%;new_path

For example:

IF "%PATH:C:\Scripts=%" == "%PATH%" PATH=%PATH%;C:\Scripts

In a nutshell, we make a conditional test where we attempt to remove/replace new_path from our PATH environment variable. If new_path doesn't exist the condition succeeds and the new_path will be appended to PATH for the first time. If new_path already exists then the condition fails and we will not add new_path a second time.

Convert a bitmap into a byte array

A MemoryStream can be helpful for this. You could put it in an extension method:

public static class ImageExtensions
{
    public static byte[] ToByteArray(this Image image, ImageFormat format)
    {
        using(MemoryStream ms = new MemoryStream())
        {
            image.Save(ms, format);
            return ms.ToArray();
        }
    }
}

You could just use it like:

var image = new Bitmap(10, 10);
// Draw your image
byte[] arr = image.ToByteArray(ImageFormat.Bmp);

I partially disagree with prestomanifto's answer in regards to the ImageConverter. Do not use ImageConverter. There's nothing technically wrong with it, but simply the fact that it uses boxing/unboxing from object tells me it's code from the old dark places of the .NET framework and its not ideal to use with image processing (it's overkill for converting to a byte[] at least), especially when you consider the following.

I took a look at the ImageConverter code used by the .Net framework, and internally it uses code almost identical to the one I provided above. It creates a new MemoryStream, saves the Bitmap in whatever format it was in when you provided it, and returns the array. Skip the extra overhead of creating an ImageConverter class by using MemoryStream

How to clear the entire array?

[your Array name] = Empty

Then the array will be without content and can be filled again.

How do I use HTML as the view engine in Express?

No view engine is necessary, if you want to use angular with simple plain html file. Here's how to do it: In your route.js file:

router.get('/', (req, res) => {
   res.sendFile('index.html', {
     root: 'yourPathToIndexDirectory'
   });
});

Set icon for Android application

Define the icon for android application

<application android:icon="drawable resource">
.... 
</application> 

https://developer.android.com/guide/topics/manifest/application-element.html


If your app available across large range of devices

You should create separate icons for all generalized screen densities, including low-, medium-, high-, and extra-high-density screens. This ensures that your icons will display properly across the range of devices on which your application can be installed...

enter image description here


Size & Format

Launcher icons should be 32-bit PNGs with an alpha channel for transparency. The finished launcher icon dimensions corresponding to a given generalized screen density are shown in the table below.

enter image description here


Place icon in mipmap or drawable folder

android:icon="@drawable/icon_name" or android:icon="@mipmap/icon_name"

developer.android.com/guide says,

This attribute must be set as a reference to a drawable resource containing the image (for example "@drawable/icon").

about launcher icons android-developers.googleblog.com says,

It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density. For example, an xxxhdpi app icon can be used on the launcher for an xxhdpi device.

Dianne Hackborn from Google (Android Framework) says,

If you are building different versions of your app for different densities, you should know about the "mipmap" resource directory. This is exactly like "drawable" resources, except it does not participate in density stripping when creating the different apk targets.

For launcher icons, the AndroidManifest.xml file must reference the mipmap/ location

<application android:name="ApplicationTitle"
         android:label="@string/app_label"
         android:icon="@mipmap/ic_launcher" >

Little bit more quoting this

  1. You want to load an image for your device density and you are going to use it "as is", without changing its actual size. In this case you should work with drawables and Android will give you the best fitting image.

  2. You want to load an image for your device density, but this image is going to be scaled up or down. For instance this is needed when you want to show a bigger launcher icon, or you have an animation, which increases image's size. In such cases, to ensure best image quality, you should put your image into mipmap folder. What Android will do is, it will try to pick up the image from a higher density bucket instead of scaling it up. This will increase sharpness (quality) of the image.

Fore more you can read mipmap vs drawable folders


Tools to easily generate assets

  1. Android Asset Studio by romannurik.github
  2. Android Asset Studio by jgilfelt.github
  3. Image Asset Studio(from Android Studio)
  4. Material Icon Generator.bitdroid.de
  5. Android Material Design Icon Generator Plugin by github.com/konifar
  6. A script to generate android assets from a SVG file

Read more : https://developer.android.com/guide/practices/ui_guidelines/icon_design_launcher.html

Executing a shell script from a PHP script

I was struggling with this exact issue for three days. I had set permissions on the script to 755. I had been calling my script as follows.

<?php
   $outcome = shell_exec('/tmp/clearUp.sh');
   echo $outcome;
?>

My script was as follows.

#!bin/bash
find . -maxdepth 1 -name "search*.csv" -mmin +0 -exec rm {} \;

I was getting no output or feedback. The change I made to get the script to run was to add a cd to tmp inside the script:

#!bin/bash
cd /tmp;
find . -maxdepth 1 -name "search*.csv" -mmin +0 -exec rm {} \;

This was more by luck than judgement but it is now working perfectly. I hope this helps.

How to use a variable inside a regular expression?

I needed to search for usernames that are similar to each other, and what Ned Batchelder said was incredibly helpful. However, I found I had cleaner output when I used re.compile to create my re search term:

pattern = re.compile(r"("+username+".*):(.*?):(.*?):(.*?):(.*)"
matches = re.findall(pattern, lines)

Output can be printed using the following:

print(matches[1]) # prints one whole matching line (in this case, the first line)
print(matches[1][3]) # prints the fourth character group (established with the parentheses in the regex statement) of the first line.

List an Array of Strings in alphabetical order

java.util.Collections.sort(listOfCountryNames, Collator.getInstance());

Android - how to make a scrollable constraintlayout?

in scrollview make height and width 0 add Top_toBottomOfand Bottom_toTopOf constraints that's it.

Python extract pattern matches

You can also use a capture group (?P<user>pattern) and access the group like a dictionary match['user'].

string = '''someline abc\n
            someother line\n
            name my_user_name is valid\n
            some more lines\n'''

pattern = r'name (?P<user>.*) is valid'
matches = re.search(pattern, str(string), re.DOTALL)
print(matches['user'])

# my_user_name

PHP XML Extension: Not installed

Had the same problem running PHP 7.2. I had to do the following :

sudo apt-get install php7.2-xml

JSONP call showing "Uncaught SyntaxError: Unexpected token : "

You're trying to access a JSON, not JSONP.

Notice the difference between your source:

https://api.flightstats.com/flex/schedules/rest/v1/json/flight/AA/100/departing/2013/10/4?appId=19d57e69&appKey=e0ea60854c1205af43fd7b1203005d59&callback=?

And actual JSONP (a wrapping function):

http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=processJSON&tags=monkey&tagmode=any&format=json

Search for JSON + CORS/Cross-domain policy and you will find hundreds of SO threads on this very topic.

matplotlib get ylim values

Leveraging from the good answers above and assuming you were only using plt as in

import matplotlib.pyplot as plt

then you can get all four plot limits using plt.axis() as in the following example.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5, 6, 7, 8]  # fake data
y = [1, 2, 3, 4, 3, 2, 5, 6]

plt.plot(x, y, 'k')

xmin, xmax, ymin, ymax = plt.axis()

s = 'xmin = ' + str(round(xmin, 2)) + ', ' + \
    'xmax = ' + str(xmax) + '\n' + \
    'ymin = ' + str(ymin) + ', ' + \
    'ymax = ' + str(ymax) + ' '

plt.annotate(s, (1, 5))

plt.show()

The above code should produce the following output plot. enter image description here

Start redis-server with config file

I think that you should make the reference to your config file

26399:C 16 Jan 08:51:13.413 # Warning: no config file specified, using the default config. In order to specify a config file use ./redis-server /path/to/redis.conf

you can try to start your redis server like

./redis-server /path/to/redis-stable/redis.conf

jQuery or CSS selector to select all IDs that start with some string

$('div[id ^= "player_"]');

This worked for me..select all Div starts with "players_" keyword and display it.

What do the python file extensions, .pyc .pyd .pyo stand for?

  1. .py: This is normally the input source code that you've written.
  2. .pyc: This is the compiled bytecode. If you import a module, python will build a *.pyc file that contains the bytecode to make importing it again later easier (and faster).
  3. .pyo: This was a file format used before Python 3.5 for *.pyc files that were created with optimizations (-O) flag. (see the note below)
  4. .pyd: This is basically a windows dll file. http://docs.python.org/faq/windows.html#is-a-pyd-file-the-same-as-a-dll

Also for some further discussion on .pyc vs .pyo, take a look at: http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html (I've copied the important part below)

  • When the Python interpreter is invoked with the -O flag, optimized code is generated and stored in ‘.pyo’ files. The optimizer currently doesn't help much; it only removes assert statements. When -O is used, all bytecode is optimized; .pyc files are ignored and .py files are compiled to optimized bytecode.
  • Passing two -O flags to the Python interpreter (-OO) will cause the bytecode compiler to perform optimizations that could in some rare cases result in malfunctioning programs. Currently only __doc__ strings are removed from the bytecode, resulting in more compact ‘.pyo’ files. Since some programs may rely on having these available, you should only use this option if you know what you're doing.
  • A program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing that's faster about ‘.pyc’ or ‘.pyo’ files is the speed with which they are loaded.
  • When a script is run by giving its name on the command line, the bytecode for the script is never written to a ‘.pyc’ or ‘.pyo’ file. Thus, the startup time of a script may be reduced by moving most of its code to a module and having a small bootstrap script that imports that module. It is also possible to name a ‘.pyc’ or ‘.pyo’ file directly on the command line.

Note:

On 2015-09-15 the Python 3.5 release implemented PEP-488 and eliminated .pyo files. This means that .pyc files represent both unoptimized and optimized bytecode.

Detect when a window is resized using JavaScript ?

Another way of doing this, using only JavaScript, would be this:

window.addEventListener('resize', functionName);

This fires every time the size changes, like the other answer.

functionName is the name of the function being executed when the window is resized (the brackets on the end aren't necessary).

Intel HAXM installation error - This computer does not support Intel Virtualization Technology (VT-x)

In many cases some antivirus also start HyperV with window start and does not allow HAXM to install. I faced this issue because of AVAST antivirus. So I uninstalled AVAST, then HAXM installed properly after restart. Then I re-installed AVAST.

So its just a check while installing as now even with AVAST installed back, HAXM works properly with virtual box and android emulators.

EditText, inputType values (xml)

Supplemental answer

Here is how the standard keyboard behaves for each of these input types.

enter image description here

See this answer for more details.

Selecting a Record With MAX Value

The query answered by sandip giri was the correct answer, here a similar example getting the maximum id (PresupuestoEtapaActividadHistoricoId), after calculate the maximum value(Base)

select * 
from (
    select PEAA.PresupuestoEtapaActividadId,
        PEAH.PresupuestoEtapaActividadHistoricoId,             
        sum(PEAA.ValorTotalDesperdicioBase) as Base,
        sum(PEAA.ValorTotalDesperdicioEjecucion) as Ejecucion
    from hgc.PresupuestoActividadAnalisis as PEAA
    inner join hgc.PresupuestoEtapaActividad as PEA
        on PEAA.PresupuestoEtapaActividadId = PEA.PresupuestoEtapaActividadId
    inner join hgc.PresupuestoEtapaActividadHistorico as PEAH
        on PEA.PresupuestoEtapaActividadId = PEAH.PresupuestoEtapaActividadId                                                         
    group by PEAH.PresupuestoEtapaActividadHistoricoId, PEAA.PresupuestoEtapaActividadId    
) as t
where exists (
    select 1 
    from (
        select MAX(PEAH.PresupuestoEtapaActividadHistoricoId) as PresupuestoEtapaActividadHistoricoId                                                                     
        from hgc.PresupuestoEtapaActividadHistorico as PEAH                       
        group by PEAH.PresupuestoEtapaActividadId  
    ) as ti
    where t.PresupuestoEtapaActividadHistoricoId = ti.PresupuestoEtapaActividadHistoricoId 
)

Create a folder inside documents folder in iOS apps

This works fine for me,

NSFileManager *fm = [NSFileManager defaultManager];
NSArray *appSupportDir = [fm URLsForDirectory:NSDocumentsDirectory inDomains:NSUserDomainMask];
NSURL* dirPath = [[appSupportDir objectAtIndex:0] URLByAppendingPathComponent:@"YourFolderName"];

NSError*    theError = nil; //error setting
if (![fm createDirectoryAtURL:dirPath withIntermediateDirectories:YES
                           attributes:nil error:&theError])
{
   NSLog(@"not created");
}

MySQL fails on: mysql "ERROR 1524 (HY000): Plugin 'auth_socket' is not loaded"

You can try these some steps:

Stop Mysql Service 1st sudo /etc/init.d/mysql stop

Login as root without password sudo mysqld_safe --skip-grant-tables &

After login mysql terminal you should need execute commands more:

use mysql;

UPDATE mysql.user SET authentication_string=PASSWORD('solutionclub3@*^G'), plugin='mysql_native_password' WHERE User='root';

flush privileges;

sudo mysqladmin -u root -p -S /var/run/mysqld/mysqld.sock shutdown

After you restart your mysql server If you still facing error you must visit : Reset MySQL 5.7 root password Ubuntu 16.04

How do I use reflection to invoke a private method?

Invokes any method despite its protection level on object instance. Enjoy!

public static object InvokeMethod(object obj, string methodName, params object[] methodParams)
{
    var methodParamTypes = methodParams?.Select(p => p.GetType()).ToArray() ?? new Type[] { };
    var bindingFlags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static;
    MethodInfo method = null;
    var type = obj.GetType();
    while (method == null && type != null)
    {
        method = type.GetMethod(methodName, bindingFlags, Type.DefaultBinder, methodParamTypes, null);
        type = type.BaseType;
    }

    return method?.Invoke(obj, methodParams);
}

fetch from origin with deleted remote branches?

From http://www.gitguys.com/topics/adding-and-removing-remote-branches/

After someone deletes a branch from a remote repository, git will not automatically delete the local repository branches when a user does a git pull or git fetch. However, if the user would like to have all tracking branches removed from their local repository that have been deleted in a remote repository, they can type:

git remote prune origin

As a note, the -p param from git fetch -p actually means "prune".
Either way you chose, the non-existing remote branches will be deleted from your local repository.

How do I cancel form submission in submit button onclick event?

you should change the type from submit to button:

<input type='button' value='submit request'>

instead of

<input type='submit' value='submit request'>

you then get the name of your button in javascript and associate whatever action you want to it

var btn = document.forms["frm_name"].elements["btn_name"];
btn.onclick = function(){...};

worked for me hope it helps.

Facebook development in localhost

Latest update: You don't have to give any urls if you are testing it in development. You can leave the fields empty. Make sure your app is in development mode. If not turn off status from live.

No need to provide site url, app domains or valid redirect oauth uri.

enter image description here

How to check radio button is checked using JQuery?


//the following code checks if your radio button having name like 'yourRadioName' 
//is checked or not
$(document).ready(function() {
  if($("input:radio[name='yourRadioName']").is(":checked")) {
      //its checked
  }
});

How to delete Tkinter widgets from a window?

You can call pack_forget to remove a widget (if you use pack to add it to the window).

Example:

from tkinter import *

root = Tk()

b = Button(root, text="Delete me", command=lambda: b.pack_forget())
b.pack()

root.mainloop()

If you use pack_forget, you can later show the widget again calling pack again. If you want to permanently delete it, call destroy on the widget (then you won't be able to re-add it).

If you use the grid method, you can use grid_forget or grid_remove to hide the widget.

Scroll RecyclerView to show selected item on top

//Scroll item pos

linearLayoutManager.scrollToPositionWithOffset(pos, 0);

IndentationError: unindent does not match any outer indentation level

For Spyder users goto Source > Fix Indentation to fix the issue immediately

Arrays.asList() of an array

Arrays.asList(factors) returns a List<int[]>, not a List<Integer>. Since you're doing new ArrayList instead of new ArrayList<Integer> you don't get a compile error for that, but create an ArrayList<Object> which contains an int[] and you then implicitly cast that arraylist to ArrayList<Integer>. Of course the first time you try to use one of those "Integers" you get an exception.

How to Insert BOOL Value to MySQL Database

TRUE and FALSE are keywords, and should not be quoted as strings:

INSERT INTO first VALUES (NULL, 'G22', TRUE);
INSERT INTO first VALUES (NULL, 'G23', FALSE);

By quoting them as strings, MySQL will then cast them to their integer equivalent (since booleans are really just a one-byte INT in MySQL), which translates into zero for any non-numeric string. Thus, you get 0 for both values in your table.

Non-numeric strings cast to zero:

mysql> SELECT CAST('TRUE' AS SIGNED), CAST('FALSE' AS SIGNED), CAST('12345' AS SIGNED);
+------------------------+-------------------------+-------------------------+
| CAST('TRUE' AS SIGNED) | CAST('FALSE' AS SIGNED) | CAST('12345' AS SIGNED) |
+------------------------+-------------------------+-------------------------+
|                      0 |                       0 |                   12345 |
+------------------------+-------------------------+-------------------------+

But the keywords return their corresponding INT representation:

mysql> SELECT TRUE, FALSE;
+------+-------+
| TRUE | FALSE |
+------+-------+
|    1 |     0 |
+------+-------+

Note also, that I have replaced your double-quotes with single quotes as are more standard SQL string enclosures. Finally, I have replaced your empty strings for id with NULL. The empty string may issue a warning.

Twitter bootstrap scrollable table

CSS

.achievements-wrapper { height: 300px; overflow: auto; }

HTML

<div class="span3 achievements-wrapper">
    <h2>Achievements left</h2>
    <table class="table table-striped">
    ...
    </table>
</div>

Angular 2 change event - model changes

Use the (ngModelChange) event to detect changes on the model

How do you send a Firebase Notification to all devices via CURL?

One way to do that is to make all your users' devices subscribe to a topic. That way when you target a message to a specific topic, all devices will get it. I think this how the Notifications section in the Firebase console does it.

Android: adb pull file on desktop

Use a fully-qualified path to the desktop (e.g., /home/mmurphy/Desktop).

Example: adb pull sdcard/log.txt /home/mmurphy/Desktop

connect to host localhost port 22: Connection refused

For what its worth I got the following error trying to ssh into my local machine, running Ubuntu 16.04 Xenial, from a vm.

 ssh: connect to host 192.168.144.18 port 22: Connection refused

It got immediately fixed with:

sudo apt-get install ssh

Take note, Before fix: 'which sshd' returned nothing and 'which ssh' returned

/usr/bin/ssh

And After the fix: 'which sshd' returned

/usr/sbin/sshd

No newline after div?

This works the best, in my case, I tried it all

.div_class {
    clear: left;
}

javascript regex for password containing at least 8 characters, 1 number, 1 upper and 1 lowercase

Your regular expression should look like:

/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/

Here is an explanation:

/^
  (?=.*\d)          // should contain at least one digit
  (?=.*[a-z])       // should contain at least one lower case
  (?=.*[A-Z])       // should contain at least one upper case
  [a-zA-Z0-9]{8,}   // should contain at least 8 from the mentioned characters
$/

How to find out mySQL server ip address from phpmyadmin

select * from SHOW VARIABLES WHERE Variable_name = 'hostname';

A server with the specified hostname could not be found

In Xcode, select Target -> Capabilities, and check "Outgoing Connections (Client)" to enable App Sandbox.

How can I check if two segments intersect?

The answer by Georgy is the cleanest to implement, by far. Had to chase this down, since the brycboe example, while simple as well, had issues with colinearity.

Code for testing:

#!/usr/bin/python
#
# Notes on intersection:
#
# https://bryceboe.com/2006/10/23/line-segment-intersection-algorithm/
#
# https://stackoverflow.com/questions/3838329/how-can-i-check-if-two-segments-intersect

from shapely.geometry import LineString

class Point:
    def __init__(self,x,y):
        self.x = x
        self.y = y

def ccw(A,B,C):
    return (C.y-A.y)*(B.x-A.x) > (B.y-A.y)*(C.x-A.x)

def intersect(A,B,C,D):
    return ccw(A,C,D) != ccw(B,C,D) and ccw(A,B,C) != ccw(A,B,D)


def ShapelyIntersect(A,B,C,D):
    return LineString([(A.x,A.y),(B.x,B.y)]).intersects(LineString([(C.x,C.y),(D.x,D.y)]))


a = Point(0,0)
b = Point(0,1)
c = Point(1,1)
d = Point(1,0)

'''
Test points:

b(0,1)   c(1,1)




a(0,0)   d(1,0)
'''

# F
print(intersect(a,b,c,d))

# T
print(intersect(a,c,b,d))
print(intersect(b,d,a,c))
print(intersect(d,b,a,c))

# F
print(intersect(a,d,b,c))

# same end point cases:
print("same end points")
# F - not intersected
print(intersect(a,b,a,d))
# T - This shows as intersected
print(intersect(b,a,a,d))
# F - this does not
print(intersect(b,a,d,a))
# F - this does not
print(intersect(a,b,d,a))

print("same end points, using shapely")
# T
print(ShapelyIntersect(a,b,a,d))
# T
print(ShapelyIntersect(b,a,a,d))
# T
print(ShapelyIntersect(b,a,d,a))
# T
print(ShapelyIntersect(a,b,d,a))

How to open PDF file in a new tab or window instead of downloading it (using asp.net)?

this may help

Response.Write("<script>");
Response.Write("window.open('../Inventory/pages/printableads.pdf', '_newtab');");
Response.Write("</script>");

getContext is not a function

Your value:

this.element = $(id);

is a jQuery object, not a pure Canvas element.

To turn it back so you can call getContext(), call this.element.get(0), or better yet store the real element and not the jQuery object:

function canvasLayer(location, id) {

    this.width = $(window).width();
    this.height = $(window).height();
    this.element = document.createElement('canvas');

    $(this.element)
       .attr('id', id)
       .text('unsupported browser')
       .attr('width', this.width)       // for pixels
       .attr('height', this.height)
       .width(this.width)               // for CSS scaling
       .height(this.height)
       .appendTo(location);

    this.context = this.element.getContext("2d");
}

See running code at http://jsfiddle.net/alnitak/zbaMh/, ideally using the Chrome Javascript Console so you can see the resulting object in the debug output.

How to compare arrays in C#?

Array.Equals is comparing the references, not their contents:

Currently, when you compare two arrays with the = operator, we are really using the System.Object's = operator, which only compares the instances. (i.e. this uses reference equality, so it will only be true if both arrays points to the exact same instance)

Source

If you want to compare the contents of the arrays you need to loop though the arrays and compare the elements.

The same blog post has an example of how to do this.

Sending multipart/formdata with jQuery.ajax

Starting with Safari 5/Firefox 4, it’s easiest to use the FormData class:

var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
    data.append('file-'+i, file);
});

So now you have a FormData object, ready to be sent along with the XMLHttpRequest.

jQuery.ajax({
    url: 'php/upload.php',
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    method: 'POST',
    type: 'POST', // For jQuery < 1.9
    success: function(data){
        alert(data);
    }
});

It’s imperative that you set the contentType option to false, forcing jQuery not to add a Content-Type header for you, otherwise, the boundary string will be missing from it. Also, you must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.

You may now retrieve the file in PHP using:

$_FILES['file-0']

(There is only one file, file-0, unless you specified the multiple attribute on your file input, in which case, the numbers will increment with each file.)

Using the FormData emulation for older browsers

var opts = {
    url: 'php/upload.php',
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    method: 'POST',
    type: 'POST', // For jQuery < 1.9
    success: function(data){
        alert(data);
    }
};
if(data.fake) {
    // Make sure no text encoding stuff is done by xhr
    opts.xhr = function() { var xhr = jQuery.ajaxSettings.xhr(); xhr.send = xhr.sendAsBinary; return xhr; }
    opts.contentType = "multipart/form-data; boundary="+data.boundary;
    opts.data = data.toString();
}
jQuery.ajax(opts);

Create FormData from an existing form

Instead of manually iterating the files, the FormData object can also be created with the contents of an existing form object:

var data = new FormData(jQuery('form')[0]);

Use a PHP native array instead of a counter

Just name your file elements the same and end the name in brackets:

jQuery.each(jQuery('#file')[0].files, function(i, file) {
    data.append('file[]', file);
});

$_FILES['file'] will then be an array containing the file upload fields for every file uploaded. I actually recommend this over my initial solution as it’s simpler to iterate over.

Executing multiple commands from a Windows cmd script

I don't know the direct answer to your question, but if you do a lot of these scripts, it might be worth learning a more powerful language like perl. Free implementations exist for Windows (e.g. activestate, cygwin). I've found it worth the initial effort for my own tasks.

Edit:

As suggested by @Ferruccio, if you can't install extra software, consider vbscript and/or javascript. They're built into the Windows scripting host.

Efficient thresholding filter of an array with numpy

b = a[a>threshold] this should do

I tested as follows:

import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()

t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetime.datetime.now() - t0

t0 = datetime.datetime.now()
flt = np.array(filter(lambda x:x==0, lrg))
print datetime.datetime.now() - t0

I got

$ python test.py
0:00:00.028000
0:00:02.461000

http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays

Converting integer to digit list

Convert the integer to string first, and then use map to apply int on it:

>>> num = 132
>>> map(int, str(num))    #note, This will return a map object in python 3.
[1, 3, 2]

or using a list comprehension:

>>> [int(x) for x in str(num)]
[1, 3, 2]

Sorting Python list based on the length of the string

Write a function lensort to sort a list of strings based on length.

def lensort(a):
    n = len(a)
    for i in range(n):
        for j in range(i+1,n):
            if len(a[i]) > len(a[j]):
                temp = a[i]
                a[i] = a[j]
                a[j] = temp
    return a
print lensort(["hello","bye","good"])

What version of MongoDB is installed on Ubuntu

When you entered in mongo shell using "mongo" command , that time only you will notice

MongoDB shell version v3.4.0-rc2
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.0-rc2

also you can try command,in mongo shell , db.version()

How to upload a file using Java HttpClient library working with PHP

I ran into the same problem and found out that the file name is required for httpclient 4.x to be working with PHP backend. It was not the case for httpclient 3.x.

So my solution is to add a name parameter in the FileBody constructor. ContentBody cbFile = new FileBody(file, "image/jpeg", "FILE_NAME");

Hope it helps.

Hide element by class in pure Javascript

Array.filter( document.getElementsByClassName('appBanner'), function(elem){ elem.style.visibility = 'hidden'; });

Forked @http://jsfiddle.net/QVJXD/

Warning about SSL connection when connecting to MySQL database

I found this warning too then I fixed it by using SSL=false suffix to the connection string like this example code.

Example:

connectionString = "jdbc:mysql://{server-name}:3306/%s?useUnicode=yes&characterEncoding=UTF-8&useSSL=false"

Detailed 500 error message, ASP + IIS 7.5

If you're on a remote server you can configure your web.config file like so:

<configuration>
<system.webServer>
    <httpErrors errorMode="Detailed" />
    <asp scriptErrorSentToBrowser="true"/>
</system.webServer>
<system.web>
    <customErrors mode="Off"/>
    <compilation debug="true"/>
</system.web>

"Connect failed: Access denied for user 'root'@'localhost' (using password: YES)" from php function

Easy.

open xampp control panel -> Config -> my.ini edit with notepad. now add this below [mysqld]

skip-grant-tables

Save. Start apache and mysql.

I hope help you