Programs & Examples On #Connection timeout

When a process attempts to connect to a remote service, and fails to do so after a predetermined period of time.

Increasing the Command Timeout for SQL command

Since it takes 2 mins to respond, you can increase the timeout to 3 mins by adding the below code

scGetruntotals.CommandTimeout = 180;

Note : the parameter value is in seconds.

Determine if $.ajax error is a timeout

If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.

Per the jQuery documentation:

Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

You can handle your error accordingly then.

I created this fiddle that demonstrates this.

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(response) { alert(response); },
    error: function(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});?

With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.

Hope this helps!

MySQL Workbench: How to keep the connection alive

In 5.2.47 (at least on mac), go the location of the preferences is: MySQLWorkbench->Preferences->SQL Editor

Then you'll see both:

DBMS connection keep-alive interval (in seconds): DBMS connection read time out (in seconds):

The latter is where you'll want to up the limit from 600 to something a bit more.

Set database timeout in Entity Framework

I extended Ronnie's answer with a fluent implementation so you can use it like so:

dm.Context.SetCommandTimeout(120).Database.SqlQuery...

public static class EF
{
    public static DbContext SetCommandTimeout(this DbContext db, TimeSpan? timeout)
    {
        ((IObjectContextAdapter)db).ObjectContext.CommandTimeout = timeout.HasValue ? (int?) timeout.Value.TotalSeconds : null;

        return db;
    }

    public static DbContext SetCommandTimeout(this DbContext db, int seconds)
    {
        return db.SetCommandTimeout(TimeSpan.FromSeconds(seconds));
    } 
}

ssh server connect to host xxx port 22: Connection timed out on linux-ubuntu

Try connecting to a vpn, if possible. That was the reason I was facing problem. Tip: if you're using an ec2 machine, try rebooting it. This worked for me the other day :)

Declare and assign multiple string variables at the same time

Just a reminder: Implicit type var in multiple declaration is not allowed. There might be the following compilation errors.

var Foo = 0, Bar = 0;

Implicitly-typed variables cannot have multiple declarators

Similarly,

var Foo, Bar;

Implicitly-typed variables must be initialized

Iterating over all the keys of a map

A Type agnostic solution:

for _, key := range reflect.ValueOf(yourMap).MapKeys() {
    value := s.MapIndex(key).Interface()
    fmt.Println("Key:", key, "Value:", value)
}  

Git fetch remote branch

I have used fetch followed by checkout...

git fetch <remote> <rbranch>:<lbranch>
git checkout <lbranch>

...where <rbranch> is the remote branch or source ref and <lbranch> is the as yet non-existent local branch or destination ref you want to track and which you probably want to name the same as the remote branch or source ref. This is explained under options in the explanation of <refspec>.

Git is so smart it auto completes the first command if I tab after the first few letters of the remote branch. That is, I don't even have to name the local branch, Git automatically copies the name of the remote branch for me. Thanks Git!

Also as the answer in this similar Stack Overflow post shows, if you don't name the local branch in fetch, you can still create it when you check it out by using the -b flag. That is, git fetch <remote> <branch> followed by git checkout -b <branch> <remote>/<branch> does exactly the same as my initial answer. And evidently, if your repository has only one remote, then you can just do git checkout <branch> after fetch and it will create a local branch for you. For example, you just cloned a repository and want to check out additional branches from the remote.

I believe that some of the documentation for fetch may have been copied verbatim from pull. In particular the section on <refspec> in options is the same. However, I do not believe that fetch will ever merge, so that if you leave the destination side of the colon empty, fetch should do nothing.

NOTE: git fetch <remote> <refspec> is short for git fetch <remote> <refspec>: which would therefore do nothing, but git fetch <remote> <tag> is the same as git fetch <remote> <tag>:<tag> which should copy the remote <tag> locally.

I guess this is only helpful if you want to copy a remote branch locally, but not necessarily check it out right away. Otherwise, I now would use the accepted answer, which is explained in detail in the first section of the checkout description and later in the options section under the explanation of --track, since it's a one-liner. Well... sort of a one-liner, because you would still have to run git fetch <remote> first.

FYI: The order of the <refspecs> (source:destination) explains the bizarre pre Git 1.7 method for deleting remote branches. That is, push nothing into the destination refspec.

How to find the highest value of a column in a data frame in R?

There is a package matrixStats that provides some functions to do column and row summaries, see in the package vignette, but you have to convert your data.frame into a matrix.

Then you run: colMaxs(as.matrix(ozone))

How to determine a Python variable's type?

Just do not do it. Asking for something's type is wrong in itself. Instead use polymorphism. Find or if necessary define by yourself the method that does what you want for any possible type of input and just call it without asking about anything. If you need to work with built-in types or types defined by a third-party library, you can always inherit from them and use your own derivatives instead. Or you can wrap them inside your own class. This is the object-oriented way to resolve such problems.

If you insist on checking exact type and placing some dirty ifs here and there, you can use __class__ property or type function to do it, but soon you will find yourself updating all these ifs with additional cases every two or three commits. Doing it the OO way prevents that and lets you only define a new class for a new type of input instead.

Loaded nib but the 'view' outlet was not set

I ran into this problem in a slightly different way from the other answers here.

If I simply created a new xib file, added a UIViewController to it in Interface Builder, and set that UIViewController's custom class to my view controller, that resulted in the "view outlet was not set" crash. The other solutions here say to control-drag the view outlet to the View, but for me the view outlet was greyed out and I couldn't control-drag it.

the greyed-out View outlet

I figured out that my mistake was in adding a UIViewController in Interface Builder. Instead, I had to add a UIView, and set the Custom Class of the File's Owner to my view controller. Then I could control-drag the view outlet of the File's Owner to my new view UIView and everything worked as it should.

Check if a input box is empty

Another approach is using regex , as show below , you can use the empty regex pattern and achieve the same using ng-pattern

HTML :

 <body ng-app="app" ng-controller="formController">
 <form name="myform">
 <input name="myfield" ng-model="somefield" ng-minlength="5" ng-pattern="mypattern" required>
 <span ng-show="myform.myfield.$error.pattern">Please enter!</span>
 <span ng-show="!myform.myfield.$error.pattern">great!</span>
</form>

Controller:@formController :

var App = angular.module('app', []);
App.controller('formController', function ($scope) {              
  $scope.mypattern = /^\s*$/g;
});

How do you run a command as an administrator from the Windows command line?

Press the start button. In the search box type "cmd", then press Ctrl+Shift+Enter

How to duplicate sys.stdout to a log file?

As per a request by @user5359531 in the comments under @John T's answer, here's a copy of the referenced post to the revised version of the linked discussion in that answer:

Issue of redirecting the stdout to both file and screen
Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon May 28 12:45:51 CEST 2007

    Previous message: Issue of redirecting the stdout to both file and screen
    Next message: Formal interfaces with Python
    Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]

En Mon, 28 May 2007 06:17:39 -0300, ???????,???????
<kelvin.you at gmail.com> escribió:

> I wanna print the log to both the screen and file, so I simulatered a
> 'tee'
>
> class Tee(file):
>
>     def __init__(self, name, mode):
>         file.__init__(self, name, mode)
>         self.stdout = sys.stdout
>         sys.stdout = self
>
>     def __del__(self):
>         sys.stdout = self.stdout
>         self.close()
>
>     def write(self, data):
>         file.write(self, data)
>         self.stdout.write(data)
>
> Tee('logfile', 'w')
> print >>sys.stdout, 'abcdefg'
>
> I found that it only output to the file, nothing to screen. Why?
> It seems the 'write' function was not called when I *print* something.

You create a Tee instance and it is immediately garbage collected. I'd
restore sys.stdout on Tee.close, not __del__ (you forgot to call the
inherited __del__ method, btw).
Mmm, doesn't work. I think there is an optimization somewhere: if it looks
like a real file object, it uses the original file write method, not yours.
The trick would be to use an object that does NOT inherit from file:

import sys
class TeeNoFile(object):
     def __init__(self, name, mode):
         self.file = open(name, mode)
         self.stdout = sys.stdout
         sys.stdout = self
     def close(self):
         if self.stdout is not None:
             sys.stdout = self.stdout
             self.stdout = None
         if self.file is not None:
             self.file.close()
             self.file = None
     def write(self, data):
         self.file.write(data)
         self.stdout.write(data)
     def flush(self):
         self.file.flush()
         self.stdout.flush()
     def __del__(self):
         self.close()

tee=TeeNoFile('logfile', 'w')
print 'abcdefg'
print 'another line'
tee.close()
print 'screen only'
del tee # should do nothing

--
Gabriel Genellina

How to solve WAMP and Skype conflict on Windows 7?

I think it is better to change default port of Skype.

Open skype. Go to Tools, Options, Connections, change the port.

How to change mysql to mysqli?

In case of big projects, many files to change and also if the previous project version of PHP was 5.6 and the new one is 7.1, you can create a new file sql.php and include it in the header or somewhere you use it all the time and needs sql connection. For example:

//local
$sql_host =     "localhost";      
$sql_username = "root";    
$sql_password = "";       
$sql_database = "db"; 


$mysqli = new mysqli($sql_host , $sql_username , $sql_password , $sql_database );

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

// /* change character set to utf8 */
if (!$mysqli->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $mysqli->error);
    exit();
} else {
    // printf("Current character set: %s\n", $mysqli->character_set_name());
}
if (!function_exists('mysql_real_escape_string')) {
    function mysql_real_escape_string($string){
        global $mysqli;
        if($string){
            // $mysqli = new mysqli($sql_host , $sql_username , $sql_password , $sql_database );            
            $newString =  $mysqli->real_escape_string($string);
            return $newString;
        }
    }
}
// $mysqli->close();
$conn = null;
if (!function_exists('mysql_query')) {
    function mysql_query($query) {
        global $mysqli;
        // echo "DAAAAA";
        if($query) {
            $result = $mysqli->query($query);
            return $result;
        }
    }
}
else {
    $conn=mysql_connect($sql_host,$sql_username, $sql_password);
    mysql_set_charset("utf8", $conn);
    mysql_select_db($sql_database);
}

if (!function_exists('mysql_fetch_array')) {
    function mysql_fetch_array($result){
        if($result){
            $row =  $result->fetch_assoc();
            return $row;
        }
    }
}

if (!function_exists('mysql_num_rows')) {
    function mysql_num_rows($result){
        if($result){
            $row_cnt = $result->num_rows;;
            return $row_cnt;
        }
    }
}

if (!function_exists('mysql_free_result')) {
    function mysql_free_result($result){
        if($result){
            global $mysqli;
            $result->free();

        }
    }
}

if (!function_exists('mysql_data_seek')) {
    function mysql_data_seek($result, $offset){
        if($result){
            global $mysqli;
            return $result->data_seek($offset);

        }
    }
}

if (!function_exists('mysql_close')) {
    function mysql_close(){
        global $mysqli;
        return $mysqli->close();
    }
}

if (!function_exists('mysql_insert_id')) {
    function mysql_insert_id(){
            global $mysqli;
            $lastInsertId = $mysqli->insert_id;
            return $lastInsertId;
    }
}

if (!function_exists('mysql_error')) {
    function mysql_error(){
        global $mysqli;
        $error = $mysqli->error;
        return $error;
    }
}

How to read html from a url in python 3

urllib.request.urlopen(url).read() should return you the raw HTML page as a string.

Why is it important to override GetHashCode when Equals method is overridden?

Just to add on above answers:

If you don't override Equals then the default behavior is that references of the objects are compared. The same applies to hashcode - the default implmentation is typically based on a memory address of the reference. Because you did override Equals it means the correct behavior is to compare whatever you implemented on Equals and not the references, so you should do the same for the hashcode.

Clients of your class will expect the hashcode to have similar logic to the equals method, for example linq methods which use a IEqualityComparer first compare the hashcodes and only if they're equal they'll compare the Equals() method which might be more expensive to run, if we didn't implement hashcode, equal object will probably have different hashcodes (because they have different memory address) and will be determined wrongly as not equal (Equals() won't even hit).

In addition, except the problem that you might not be able to find your object if you used it in a dictionary (because it was inserted by one hashcode and when you look for it the default hashcode will probably be different and again the Equals() won't even be called, like Marc Gravell explains in his answer, you also introduce a violation of the dictionary or hashset concept which should not allow identical keys - you already declared that those objects are essentially the same when you overrode Equals so you don't want both of them as different keys on a data structure which suppose to have a unique key. But because they have a different hashcode the "same" key will be inserted as different one.

Failed to execute 'createObjectURL' on 'URL':

I fixed it downloading the latest version from GgitHub GitHub url

nginx: [emerg] "server" directive is not allowed here

Example valid nginx.conf for reverse proxy; In case someone is stuck like me. where 10.x.x.x is the server where you are running the nginx proxy server and to which you are connecting to with the browser, and 10.y.y.y is where your real web server is running

events {
  worker_connections  4096;  ## Default: 1024
}
http {
 server {
   listen 80;
   listen [::]:80;

   server_name 10.x.x.x;
 
   location / {
       proxy_pass http://10.y.y.y:80/;
       proxy_set_header Host $host;
   }
 }
}

Here is the snippet if you want to do SSL pass through. That is if 10.y.y.y is running a HTTPS webserver. Here 10.x.x.x, or where the nignx runs is listening to port 443, and all traffic to 443 is directed to your target web server

events {
  worker_connections  4096;  ## Default: 1024
}

stream {
  server {
    listen     443;
    proxy_pass 10.y.y.y:443;
  }
}

and you can serve it up in docker too

 docker run --name nginx-container --rm --net=host   -v /home/core/nginx/nginx.conf:/etc/nginx/nginx.conf nginx

'tsc command not found' in compiling typescript

This works perfectly on Mac. Tested on macOS High Sierra

sudo npm install -g concurrently
sudo npm install -g lite-server
sudo npm install -g typescript
tsc --init

This generates the tsconfig.json file.

What is the proper #include for the function 'sleep()'?

sleep is a non-standard function.

  • On UNIX, you shall include <unistd.h>.
  • On MS-Windows, Sleep is rather from <windows.h>.

In every case, check the documentation.

Undefined reference to pow( ) in C, despite including math.h

You need to link with the math library:

gcc -o sphere sphere.c -lm

The error you are seeing: error: ld returned 1 exit status is from the linker ld (part of gcc that combines the object files) because it is unable to find where the function pow is defined.

Including math.h brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a. You need to link your program with this library so that the calls to functions like pow() are resolved.

CSS Display an Image Resized and Cropped

img {
    position: absolute;
    clip: rect(0px,60px,200px,0px);
} 

JavaScript: Collision detection

An answer without jQuery, with HTML elements as parameters:

This is a better approach that checks the real position of the elements as they are being shown on the viewport, even if they're absolute, relative or have been manipulated via transformations:

function isCollide(a, b) {
    var aRect = a.getBoundingClientRect();
    var bRect = b.getBoundingClientRect();

    return !(
        ((aRect.top + aRect.height) < (bRect.top)) ||
        (aRect.top > (bRect.top + bRect.height)) ||
        ((aRect.left + aRect.width) < bRect.left) ||
        (aRect.left > (bRect.left + bRect.width))
    );
}

How to fix Subversion lock error

I tried all suggestion from this thread but the only one that worked is:

  1. go to the folder on which the project locked folder is stored
  2. execute svn cleanup

Visual Studio "Could not copy" .... during build

I encountered this problem in VS 2015. The reason for my environment was use of StyleCop project setting for StyleCopAdditionalAddinPaths Include="..." to specify additional StyleCop Addin path. The workaround I used was to remove this project setting from .csproj file, and instead, copy the StyleCop AddIn manually where the StyleCop.CSharp.Rules.dll was present. Not an elegant solution, but I found that the solution never locked the dlls after doing this.

How do I convert a Django QuerySet into list of dicts?

If you need native data types for some reason (e.g. JSON serialization) this is my quick 'n' dirty way to do it:

data = [{'id': blog.pk, 'name': blog.name} for blog in blogs]

As you can see building the dict inside the list is not really DRY so if somebody knows a better way ...

HTML 'td' width and height

Following width worked well in HTML5: -

<table >
  <tr>
    <th style="min-width:120px">Month</th>
    <th style="min-width:60px">Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
  </tr>
</table>

Please note that

  • TD tag is without CSS style.

Merging two CSV files using Python

You need to store all of the extra rows in the files in your dictionary, not just one of them:

dict1 = {row[0]: row[1:] for row in r}
...
dict2 = {row[0]: row[1:] for row in r}

Then, since the values in the dictionaries are lists, you need to just concatenate the lists together:

w.writerows([[key] + dict1.get(key, []) + dict2.get(key, []) for key in keys])

Convert timestamp to string

new Date().toString();

http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/

Dateformatter can make it to any string you want

C# ASP.NET Send Email via TLS

I was almost using the same technology as you did, however I was using my app to connect an Exchange Server via Office 365 platform on WinForms. I too had the same issue as you did, but was able to accomplish by using code which has slight modification of what others have given above.

SmtpClient client = new SmtpClient(exchangeServer, 587);
client.Credentials = new System.Net.NetworkCredential(username, password);
client.EnableSsl = true;
client.Send(msg);

I had to use the Port 587, which is of course the default port over TSL and the did the authentication.

Dynamically Dimensioning A VBA Array?

You need to use a constant.

CONST NumberOfZombies = 20000
Dim Zombies(NumberOfZombies) As Zombies

or if you want to use a variable you have to do it this way:

Dim NumberOfZombies As Integer
NumberOfZombies = 20000

Dim Zombies() As Zombies

ReDim Zombies(NumberOfZombies)

Getting "file not found" in Bridging Header when importing Objective-C frameworks into Swift project

August 2019

In my case I wanted to use a Swift protocol in an Objective-C header file that comes from the same target and for this I needed to use a forward declaration of the Swift protocol to reference it in the Objective-C interface. The same should be valid for using a Swift class in an Objective-C header file. To use forward declaration see the following example from the docs at Include Swift Classes in Objective-C Headers Using Forward Declarations:

// MyObjcClass.h
@class MySwiftClass; // class forward declaration
@protocol MySwiftProtocol; // protocol forward declaration

@interface MyObjcClass : NSObject
- (MySwiftClass *)returnSwiftClassInstance;
- (id <MySwiftProtocol>)returnInstanceAdoptingSwiftProtocol;
// ...
@end

Why do I always get the same sequence of random numbers with rand()?

None of you guys are answering his question.

with this code i get the same sequance everytime the code but it generates random sequences if i add srand(/somevalue/) before the for loop . can someone explain why ?

From what my professor has told me, it is used if you want to make sure your code is running properly and to see if there is something wrong or if you can change something.

Creating a JSON Array in node js

This one helped me,

res.format({
        json:function(){
                            var responseData    = {};
                            responseData['status'] = 200;
                            responseData['outputPath']  = outputDirectoryPath;
                            responseData['sourcePath']  = url;
                            responseData['message'] = 'Scraping of requested resource initiated.';
                            responseData['logfile'] = logFileName;
                            res.json(JSON.stringify(responseData));
                        }
    });

Android Studio and Gradle build error

If you are using the Gradle Wrapper (the recommended option in Android Studio), you enable stacktrace by running gradlew compileDebug --stacktrace from the command line in the root folder of your project (where the gradlew file is).

If you are not using the gradle wrapper, you use gradle compileDebug --stacktrace instead (presumably).

You don't really need to run with --stacktrace though, running gradlew compileDebug by itself, from the command line, should tell you where the error is.

I based this information on this comment:

Android Studio new project can not run, throwing error

Function names in C++: Capitalize or not?

The most common ones I see in production code are (in this order):

myFunctionName     // lower camel case

MyFunctionName     // upper camel case

my_function_name   // K & R ?

I find the naming convention a programmer uses in C++ code usually has something to do with their programming background.

E.g. ex-java programmers tend to use lower camel case for functions

How to append a jQuery variable value inside the .html tag

See this Link

HTML

<div id="products"></div>

JS

var someone = {
"name":"Mahmoude Elghandour",
"price":"174 SR",
"desc":"WE Will BE WITH YOU"
 };
 var name = $("<div/>",{"text":someone.name,"class":"name"
});

var price = $("<div/>",{"text":someone.price,"class":"price"});
var desc = $("<div />", {   
"text": someone.desc,
"class": "desc"
});
$("#products").fadeIn(1500);
$("#products").append(name).append(price).append(desc);

Iterating over arrays in Python 3

While iterating over a list or array with this method:

ar = [10, 11, 12]
for i in ar:
    theSum = theSum + ar[i]

You are actually getting the values of list or array sequentially in i variable. If you print the variable i inside the for loop. You will get following output:

10
11
12

However, in your code you are confusing i variable with index value of array. Therefore, while doing ar[i] will mean ar[10] for the first iteration. Which is of course index out of range throwing IndexError

Edit You can read this for better understanding of different methods of iterating over array or list in Python

Tensorflow installation error: not a supported wheel on this platform

It means that the version of your default python (python -V) and the version of your default pip (pip -V) do not match. You have built tensorflow with your default python and trying to use a different pip version to install it. In mac, delete /usr/local/bin/pip and rename(copy) pipx.y (whatever x.y version that matches your python version) to pip in that folder.

SQL query to group by day

If you're using MySQL:

SELECT
    DATE(created) AS saledate,
    SUM(amount)
FROM
    Sales
GROUP BY
    saledate

If you're using MS SQL 2008:

SELECT
    CAST(created AS date) AS saledate,
    SUM(amount)
FROM
    Sales
GROUP BY
    CAST(created AS date)

Uncaught TypeError: Cannot read property 'appendChild' of null

Nice answers here. I encountered the same problem, but I tried <script src="script.js" defer></script> but I didn't work quite well. I had all the code and links set up fine. The problem is I had put the js file link in the head of the page, so it was loaded before the DOM was loaded. There are 2 solutions to this.

  1. Use
window.onload = () => {
    //write your code here
}
  1. Add the <script src="script.js"></script> to the bottom of the html file so that it loads last.

How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

Here's another form of a solution with normalization of your time object:

def to_unix_time(timestamp):
    epoch = datetime.datetime.utcfromtimestamp(0) # start of epoch time
    my_time = datetime.datetime.strptime(timestamp, "%Y/%m/%d %H:%M:%S.%f") # plugin your time object
    delta = my_time - epoch
    return delta.total_seconds() * 1000.0

NoSql vs Relational database

Not all data is relational. For those situations, NoSQL can be helpful.

With that said, NoSQL stands for "Not Only SQL". It's not intended to knock SQL or supplant it.

SQL has several very big advantages:

  1. Strong mathematical basis.
  2. Declarative syntax.
  3. A well-known language in Structured Query Language (SQL).

Those haven't gone away.

It's a mistake to think about this as an either/or argument. NoSQL is an alternative that people need to consider when it fits, that's all.

Documents can be stored in non-relational databases, like CouchDB.

Maybe reading this will help.

Switch case with fallthrough?

Try this:

case $VAR in
normal)
    echo "This doesn't do fallthrough"
    ;;
special)
    echo -n "This does "
    ;&
fallthrough)
    echo "fall-through"
    ;;
esac

Python locale error: unsupported locale setting

You probably do not have any de_DE locale available.

You can view a list of available locales with the locale -a command. For example, on my machine:

$ locale -a
C
C.UTF-8
en_AG
en_AG.utf8
en_AU.utf8
en_BW.utf8
en_CA.utf8
en_DK.utf8
en_GB.utf8
en_HK.utf8
en_IE.utf8
en_IN
en_IN.utf8
en_NG
en_NG.utf8
en_NZ.utf8
en_PH.utf8
en_SG.utf8
en_US.utf8
en_ZA.utf8
en_ZM
en_ZM.utf8
en_ZW.utf8
it_CH.utf8
it_IT.utf8
POSIX

Note that if you want to set the locale to it_IT you must also specify the .utf8:

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'it_IT')   # error!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/locale.py", line 539, in setlocale
    return _setlocale(category, locale)
locale.Error: unsupported locale setting
>>> locale.setlocale(locale.LC_ALL, 'it_IT.utf8')
'it_IT.utf8'

To install a new locale use:

sudo apt-get install language-pack-id

where id is the language code (taken from here)

After you have installed the locale you should follow Julien Palard advice and reconfigure the locales with:

sudo dpkg-reconfigure locales

How to press back button in android programmatically?

you can simply use onBackPressed();

or if you are using fragment you can use getActivity().onBackPressed()

How to handle AssertionError in Python and find out which line or statement it occurred on?

The traceback module and sys.exc_info are overkill for tracking down the source of an exception. That's all in the default traceback. So instead of calling exit(1) just re-raise:

try:
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
except AssertionError:
    print 'Houston, we have a problem.'
    raise

Which gives the following output that includes the offending statement and line number:

Houston, we have a problem.
Traceback (most recent call last):
  File "/tmp/poop.py", line 2, in <module>
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
AssertionError: Should've asked for pie

Similarly the logging module makes it easy to log a traceback for any exception (including those which are caught and never re-raised):

import logging

try:
    assert False == True 
except AssertionError:
    logging.error("Nothing is real but I can't quit...", exc_info=True)

JavaScript hard refresh of current page

Try to use:

location.reload(true);

When this method receives a true value as argument, it will cause the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.

More info:

How to merge every two lines into one from the command line?

Alternative to sed, awk, grep:

xargs -n2 -d'\n'

This is best when you want to join N lines and you only need space delimited output.

My original answer was xargs -n2 which separates on words rather than lines. -d can be used to split the input by any single character.

What is the difference between window, screen, and document in Javascript?

the window contains everything, so you can call window.screen and window.document to get those elements. Check out this fiddle, pretty-printing the contents of each object: http://jsfiddle.net/JKirchartz/82rZu/

You can also see the contents of the object in firebug/dev tools like this:

console.dir(window);
console.dir(document);
console.dir(screen);

window is the root of everything, screen just has screen dimensions, and document is top DOM object. so you can think of it as window being like a super-document...

Django error - matching query does not exist

You can use this:

comment = Comment.objects.filter(pk=comment_id)

PHP output showing little black diamonds with a question mark

This is a charset issue. As such, it can have gone wrong on many different levels, but most likely, the strings in your database are utf-8 encoded, and you are presenting them as iso-8859-1. Or the other way around.

The proper way to fix this problem, is to get your character-sets straight. The simplest strategy, since you're using PHP, is to use iso-8859-1 throughout your application. To do this, you must ensure that:

  • All PHP source-files are saved as iso-8859-1 (Not to be confused with cp-1252).
  • Your web-server is configured to serve files with charset=iso-8859-1
  • Alternatively, you can override the webservers settings from within the PHP-document, using header.
  • In addition, you may insert a meta-tag in you HTML, that specifies the same thing, but this isn't strictly needed.
  • You may also specify the accept-charset attribute on your <form> elements.
  • Database tables are defined with encoding as latin1
  • The database connection between PHP to and database is set to latin1

If you already have data in your database, you should be aware that they are probably messed up already. If you are not already in production phase, just wipe it all and start over. Otherwise you'll have to do some data cleanup.

A note on meta-tags, since everybody misunderstands what they are:

When a web-server serves a file (A HTML-document), it sends some information, that isn't presented directly in the browser. This is known as HTTP-headers. One such header, is the Content-Type header, which specifies the mimetype of the file (Eg. text/html) as well as the encoding (aka charset). While most webservers will send a Content-Type header with charset info, it's optional. If it isn't present, the browser will instead interpret any meta-tags with http-equiv="Content-Type". It's important to realise that the meta-tag is only interpreted if the webserver doesn't send the header. In practice this means that it's only used if the page is saved to disk and then opened from there.

This page has a very good explanation of these things.

Add a column in a table in HIVE QL

You cannot add a column with a default value in Hive. You have the right syntax for adding the column ALTER TABLE test1 ADD COLUMNS (access_count1 int);, you just need to get rid of default sum(max_count). No changes to that files backing your table will happen as a result of adding the column. Hive handles the "missing" data by interpreting NULL as the value for every cell in that column.

So now your have the problem of needing to populate the column. Unfortunately in Hive you essentially need to rewrite the whole table, this time with the column populated. It may be easier to rerun your original query with the new column. Or you could add the column to the table you have now, then select all of its columns plus value for the new column.

You also have the option to always COALESCE the column to your desired default and leave it NULL for now. This option fails when you want NULL to have a meaning distinct from your desired default. It also requires you to depend on always remembering to COALESCE.

If you are very confident in your abilities to deal with the files backing Hive, you could also directly alter them to add your default. In general I would recommend against this because most of the time it will be slower and more dangerous. There might be some case where it makes sense though, so I've included this option for completeness.

Find mouse position relative to element

I came across this question, but in order to make it work for my case (using dragover on a DOM-element (not being canvas in my case)), I found that you only have have to use offsetX and offsetY on the dragover-mouse event.

onDragOver(event){
 var x = event.offsetX;
 var y = event.offsetY;
}

Why use the params keyword?

No need to create overload methods, just use one single method with params as shown below

// Call params method with one to four integer constant parameters.
//
int sum0 = addTwoEach();
int sum1 = addTwoEach(1);
int sum2 = addTwoEach(1, 2);
int sum3 = addTwoEach(3, 3, 3);
int sum4 = addTwoEach(2, 2, 2, 2);

if A vs if A is not None:

A lot of functions return None if there are no appropriate results. For example, an SQLAlchemy query's .first() method returns None if there were no rows in the result. Suppose you were selecting a value that might return 0 and need to know whether it's actually 0 or whether the query had no results at all.

A common idiom is to give a function or method's optional argument the default value of None, and then to test that value being None to see if it was specified. For example:

def spam(eggs=None):
    if eggs is None:
        eggs = retrievefromconfigfile()

compare that to:

def spam(eggs=None):
    if not eggs:
        eggs = retrievefromconfigfile()

In the latter, what happens if you call spam(0) or spam([])? The function would (incorrectly) detect that you hadn't passed in a value for eggs and would compute a default value for you. That's probably not what you want.

Or imagine a method like "return the list of transactions for a given account". If the account does not exist, it might return None. This is different than returning an empty list (which would mean "this account exists but has not recorded transactions).

Finally, back to database stuff. There's a big difference between NULL and an empty string. An empty string typically says "there's a value here, and that value is nothing at all". NULL says "this value hasn't been entered."

In each of those cases, you'd want to use if A is None. You're checking for a specific value - None - not just "any value that happens to cast to False".

Explicitly calling return in a function or not

My question is: Why is not calling return faster

It’s faster because return is a (primitive) function in R, which means that using it in code incurs the cost of a function call. Compare this to most other programming languages, where return is a keyword, but not a function call: it doesn’t translate to any runtime code execution.

That said, calling a primitive function in this way is pretty fast in R, and calling return incurs a minuscule overhead. This isn’t the argument for omitting return.

or better, and thus preferable?

Because there’s no reason to use it.

Because it’s redundant, and it doesn’t add useful redundancy.

To be clear: redundancy can sometimes be useful. But most redundancy isn’t of this kind. Instead, it’s of the kind that adds visual clutter without adding information: it’s the programming equivalent of a filler word or chartjunk).

Consider the following example of an explanatory comment, which is universally recognised as bad redundancy because the comment merely paraphrases what the code already expresses:

# Add one to the result
result = x + 1

Using return in R falls in the same category, because R is a functional programming language, and in R every function call has a value. This is a fundamental property of R. And once you see R code from the perspective that every expression (including every function call) has a value, the question then becomes: “why should I use return?” There needs to be a positive reason, since the default is not to use it.

One such positive reason is to signal early exit from a function, say in a guard clause:

f = function (a, b) {
    if (! precondition(a)) return() # same as `return(NULL)`!
    calculation(b)
}

This is a valid, non-redundant use of return. However, such guard clauses are rare in R compared to other languages, and since every expression has a value, a regular if does not require return:

sign = function (num) {
    if (num > 0) {
        1
    } else if (num < 0) {
        -1
    } else {
        0
    }
}

We can even rewrite f like this:

f = function (a, b) {
    if (precondition(a)) calculation(b)
}

… where if (cond) expr is the same as if (cond) expr else NULL.

Finally, I’d like to forestall three common objections:

  1. Some people argue that using return adds clarity, because it signals “this function returns a value”. But as explained above, every function returns something in R. Thinking of return as a marker of returning a value isn’t just redundant, it’s actively misleading.

  2. Relatedly, the Zen of Python has a marvellous guideline that should always be followed:

    Explicit is better than implicit.

    How does dropping redundant return not violate this? Because the return value of a function in a functional language is always explicit: it’s its last expression. This is again the same argument about explicitness vs redundancy.

    In fact, if you want explicitness, use it to highlight the exception to the rule: mark functions that don’t return a meaningful value, which are only called for their side-effects (such as cat). Except R has a better marker than return for this case: invisible. For instance, I would write

    save_results = function (results, file) {
        # … code that writes the results to a file …
        invisible()
    }
    
  3. But what about long functions? Won’t it be easy to lose track of what is being returned?

    Two answers: first, not really. The rule is clear: the last expression of a function is its value. There’s nothing to keep track of.

    But more importantly, the problem in long functions isn’t the lack of explicit return markers. It’s the length of the function. Long functions almost (?) always violate the single responsibility principle and even when they don’t they will benefit from being broken apart for readability.

ng-mouseover and leave to toggle item using mouse in angularjs

I'd probably change your example to look like this:

<ul ng-repeat="task in tasks">
  <li ng-mouseover="enableEdit(task)" ng-mouseleave="disableEdit(task)">{{task.name}}</li>
  <span ng-show="task.editable"><a>Edit</a></span>
</ul>

//js
$scope.enableEdit = function(item){
  item.editable = true;
};

$scope.disableEdit = function(item){
  item.editable = false;
};

I know it's a subtle difference, but makes the domain a little less bound to UI actions. Mentally it makes it easier to think about an item being editable rather than having been moused over.

Example jsFiddle.

jQuery map vs. each

The each function iterates over an array, calling the supplied function once per element, and setting this to the active element. This:

function countdown() {
    alert(this + "..");
}

$([5, 4, 3, 2, 1]).each(countdown);

will alert 5.. then 4.. then 3.. then 2.. then 1..

Map on the other hand takes an array, and returns a new array with each element changed by the function. This:

function squared() {
    return this * this;
}

var s = $([5, 4, 3, 2, 1]).map(squared);

would result in s being [25, 16, 9, 4, 1].

Copy to Clipboard for all Browsers using javascript

For security reasons most browsers do not allow to modify the clipboard (except IE, of course...).

The only way to make a copy-to-clipboard function cross-browser compatible is to use Flash.

Get JSF managed bean by name in any Servlet related class

I use this:

public static <T> T getBean(Class<T> clazz) {
    try {
        String beanName = getBeanName(clazz);
        FacesContext facesContext = FacesContext.getCurrentInstance();
        return facesContext.getApplication().evaluateExpressionGet(facesContext, "#{" + beanName + "}", clazz);
    //return facesContext.getApplication().getELResolver().getValue(facesContext.getELContext(), null, nomeBean);
    } catch (Exception ex) {
        return null;
    }
}

public static <T> String getBeanName(Class<T> clazz) {
    ManagedBean managedBean = clazz.getAnnotation(ManagedBean.class);
    String beanName = managedBean.name();

    if (StringHelper.isNullOrEmpty(beanName)) {
        beanName = clazz.getSimpleName();
        beanName = Character.toLowerCase(beanName.charAt(0)) + beanName.substring(1);
    }

    return beanName;
}

And then call:

MyManageBean bean = getBean(MyManageBean.class);

This way you can refactor your code and track usages without problems.

What is the difference between the dot (.) operator and -> in C++?

Use -> when you have a pointer. Use . when you have structure (class).

When you want to point attribute that belongs to structure use .:

structure.attribute

When you want to point to an attribute that has reference to memory by pointer use -> :

pointer->method;

or same as:

(*pointer).method

Reading data from DataGridView in C#

Code Example : Reading data from DataGridView and storing it in an array

int[,] n = new int[3, 19];
for (int i = 0; i < (StartDataView.Rows.Count - 1); i++)
{
    for (int j = 0; j < StartDataView.Columns.Count; j++)
    {
        if(this.StartDataView.Rows[i].Cells[j].Value.ToString() != string.Empty)
        {
            try
            {
                n[i, j] = int.Parse(this.StartDataView.Rows[i].Cells[j].Value.ToString());
            }
            catch (Exception Ee)
            { //get exception of "null"
                MessageBox.Show(Ee.ToString());
            }
        }
    }
}

How to round up a number in Javascript?

Very near to TheEye answer, but I change a little thing to make it work:

_x000D_
_x000D_
var num = 192.16;_x000D_
    _x000D_
console.log(    Math.ceil(num * 10) / 10    );
_x000D_
_x000D_
_x000D_

Null vs. False vs. 0 in PHP

The issues with falsyness comes from the PHP history. The problem targets the not well defined scalar type.

'*' == true -> true (string match)
'*' === true -> false (numberic match)

(int)'*' == true -> false
(string)'*' == true -> true

PHP7 strictness is a step forward, but maybe not enough. https://web-techno.net/typing-with-php-7-what-you-shouldnt-do/

Changing directory in Google colab (breaking out of the python interpreter)

If you want to use the cd or ls functions , you need proper identifiers before the function names ( % and ! respectively) use %cd and !ls to navigate

.

!ls    # to find the directory you're in ,
%cd ./samplefolder  #if you wanna go into a folder (say samplefolder)

or if you wanna go out of the current folder

%cd ../      

and then navigate to the required folder/file accordingly

Multi-dimensional arrays in Bash

I am posting the following because it is a very simple and clear way to mimic (at least to some extent) the behavior of a two-dimensional array in Bash. It uses a here-file (see the Bash manual) and read (a Bash builtin command):

## Store the "two-dimensional data" in a file ($$ is just the process ID of the shell, to make sure the filename is unique)
cat > physicists.$$ <<EOF
Wolfgang Pauli 1900
Werner Heisenberg 1901
Albert Einstein 1879
Niels Bohr 1885
EOF
nbPhysicists=$(wc -l physicists.$$ | cut -sf 1 -d ' ')     # Number of lines of the here-file specifying the physicists.

## Extract the needed data
declare -a person     # Create an indexed array (necessary for the read command).                                                                                 
while read -ra person; do
    firstName=${person[0]}
    familyName=${person[1]}
    birthYear=${person[2]}
    echo "Physicist ${firstName} ${familyName} was born in ${birthYear}"
    # Do whatever you need with data
done < physicists.$$

## Remove the temporary file
rm physicists.$$

Output: Physicist Wolfgang Pauli was born in 1900 Physicist Werner Heisenberg was born in 1901 Physicist Albert Einstein was born in 1879 Physicist Niels Bohr was born in 1885

The way it works:

  • The lines in the temporary file created play the role of one-dimensional vectors, where the blank spaces (or whatever separation character you choose; see the description of the read command in the Bash manual) separate the elements of these vectors.
  • Then, using the read command with its -a option, we loop over each line of the file (until we reach end of file). For each line, we can assign the desired fields (= words) to an array, which we declared just before the loop. The -r option to the read command prevents backslashes from acting as escape characters, in case we typed backslashes in the here-document physicists.$$.

In conclusion a file is created as a 2D-array, and its elements are extracted using a loop over each line, and using the ability of the read command to assign words to the elements of an (indexed) array.

Slight improvement:

In the above code, the file physicists.$$ is given as input to the while loop, so that it is in fact passed to the read command. However, I found that this causes problems when I have another command asking for input inside the while loop. For example, the select command waits for standard input, and if placed inside the while loop, it will take input from physicists.$$, instead of prompting in the command-line for user input. To correct this, I use the -u option of read, which allows to read from a file descriptor. We only have to create a file descriptor (with the exec command) corresponding to physicists.$$ and to give it to the -u option of read, as in the following code:

## Store the "two-dimensional data" in a file ($$ is just the process ID of the shell, to make sure the filename is unique)
cat > physicists.$$ <<EOF
Wolfgang Pauli 1900
Werner Heisenberg 1901
Albert Einstein 1879
Niels Bohr 1885
EOF
nbPhysicists=$(wc -l physicists.$$ | cut -sf 1 -d ' ')     # Number of lines of the here-file specifying the physicists.
exec {id_file}<./physicists.$$     # Create a file descriptor stored in 'id_file'.

## Extract the needed data
declare -a person     # Create an indexed array (necessary for the read command).                                                                                 
while read -ra person -u "${id_file}"; do
firstName=${person[0]}
familyName=${person[1]}
birthYear=${person[2]}
echo "Physicist ${firstName} ${familyName} was born in ${birthYear}"
# Do whatever you need with data
done

## Close the file descriptor
exec {id_file}<&-
## Remove the temporary file
rm physicists.$$

Notice that the file descriptor is closed at the end.

Kubernetes Pod fails with CrashLoopBackOff

I had similar situation. I found that one of my config maps was duplicated. I had two configmaps for the same namespace. One had the correct namespace reference, the other was pointing to the wrong namespace.

I deleted and recreated the configmap with the correct file (or fixed file). I am only using one, and that seemed to make the particular cluster happier.

So I would check the files for any typos or duplicate items that could be causing conflict.

CSS3 Transition not working

For me, it was having display: none;

#spinner-success-text {
    display: none;
    transition: all 1s ease-in;
}

#spinner-success-text.show {
    display: block;
}

Removing it, and using opacity instead, fixed the issue.

#spinner-success-text {
    opacity: 0;
    transition: all 1s ease-in;
}

#spinner-success-text.show {
    opacity: 1;
}

Window.Open with PDF stream instead of PDF location

It looks like window.open will take a Data URI as the location parameter.

So you can open it like this from the question: Opening PDF String in new window with javascript:

window.open("data:application/pdf;base64, " + base64EncodedPDF);

Here's an runnable example in plunker, and sample pdf file that's already base64 encoded.

Then on the server, you can convert the byte array to base64 encoding like this:

string fileName = @"C:\TEMP\TEST.pdf";
byte[] pdfByteArray = System.IO.File.ReadAllBytes(fileName);
string base64EncodedPDF = System.Convert.ToBase64String(pdfByteArray);

NOTE: This seems difficult to implement in IE because the URL length is prohibitively small for sending an entire PDF.

Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304'

So in general dll has to be placed in two places:

  1. GAC ( can have 32 and 64 versions of dll's)
  2. your project bin folder

Thus, you just need add reference to log4net.dll. (In your case 32-bit with PublicKeyToken=692fbea5521e1304)

You can achive that by

Create a basic matrix in C (input by user !)

How about the following?

First ask the user for the number of rows and columns, store that in say, nrows and ncols (i.e. scanf("%d", &nrows);) and then allocate memory for a 2D array of size nrows x ncols. Thus you can have a matrix of a size specified by the user, and not fixed at some dimension you've hardcoded!

Then store the elements with for(i = 0;i < nrows; ++i) ... and display the elements in the same way except you throw in newlines after every row, i.e.

for(i = 0; i < nrows; ++i)
{
   for(j = 0; j < ncols ; ++j) 
   {
      printf("%d\t",mat[i][j]);
   }
printf("\n");
}

SQL Server Output Clause into a scalar variable

Way later but still worth mentioning is that you can also use variables to output values in the SET clause of an UPDATE or in the fields of a SELECT;

DECLARE @val1 int;
DECLARE @val2 int;
UPDATE [dbo].[PortalCounters_TEST]
SET @val1 = NextNum, @val2 = NextNum = NextNum + 1
WHERE [Condition] = 'unique value'
SELECT @val1, @val2

In the example above @val1 has the before value and @val2 has the after value although I suspect any changes from a trigger would not be in val2 so you'd have to go with the output table in that case. For anything but the simplest case, I think the output table will be more readable in your code as well.

One place this is very helpful is if you want to turn a column into a comma-separated list;

DECLARE @list varchar(max) = '';
DECLARE @comma varchar(2) = '';
SELECT @list = @list + @comma + County, @comma = ', ' FROM County
print @list

Razor HtmlHelper Extensions (or other namespaces for views) Not Found

Since ASP.NET MVC 3 RTM is out there is no need for config section for Razor. And these sections can be safely removed.

To the power of in C?

For another approach, note that all the standard library functions work with floating point types. You can implement an integer type function like this:

unsigned power(unsigned base, unsigned degree)
{
    unsigned result = 1;
    unsigned term = base;
    while (degree)
    {
        if (degree & 1)
            result *= term;
        term *= term;
        degree = degree >> 1;
    }
    return result;
}

This effectively does repeated multiples, but cuts down on that a bit by using the bit representation. For low integer powers this is quite effective.

How to redirect the output of DBMS_OUTPUT.PUT_LINE to a file?

As a side note, remember that all this output is generated in the server side.

Using DBMS_OUTPUT, the text is generated in the server while it executes your query and stored in a buffer. It is then redirected to your client app when the server finishes the query data retrieval. That is, you only get this info when the query ends.

With UTL_FILE all the information logged will be stored in a file in the server. When the execution finishes you will have to navigate to this file to get the information.

Hope this helps.

How do I display local image in markdown?

just copy the image and then paste it, you will get the output

![image.png](attachment:image.png)

Filter element based on .data() key/value

Just for the record, you can filter on data with jquery (this question is quite old, and jQuery evolved since then, so it's right to write this solution as well):

$('.navlink[data-selected="true"]');

or, better (for performance):

$('.navlink').filter('[data-selected="true"]');

or, if you want to get all the elements with data-selected set:

$('[data-selected]')

Note that this method will only work with data that was set via html-attributes. If you set or change data with the .data() call, this method will no longer work.

How to sort an array in descending order in Ruby

Regarding the benchmark suite mentioned, these results also hold for sorted arrays.

sort_by/reverse it is:

# foo.rb
require 'benchmark'

NUM_RUNS = 1000

# arr = []
arr1 = 3000.times.map { { num: rand(1000) } }
arr2 = 3000.times.map { |n| { num: n } }.reverse

Benchmark.bm(20) do |x|
  { 'randomized'     => arr1,
    'sorted'         => arr2 }.each do |label, arr|
    puts '---------------------------------------------------'
    puts label

    x.report('sort_by / reverse') {
      NUM_RUNS.times { arr.sort_by { |h| h[:num] }.reverse }
    }
    x.report('sort_by -') {
      NUM_RUNS.times { arr.sort_by { |h| -h[:num] } }
    }
  end
end

And the results:

$: ruby foo.rb
                           user     system      total        real
---------------------------------------------------
randomized
sort_by / reverse      1.680000   0.010000   1.690000 (  1.682051)
sort_by -              1.830000   0.000000   1.830000 (  1.830359)
---------------------------------------------------
sorted
sort_by / reverse      0.400000   0.000000   0.400000 (  0.402990)
sort_by -              0.500000   0.000000   0.500000 (  0.499350)

How do you post to the wall on a facebook page (not profile)

Get PHP SDK from github and run the following code:

<?php
$attachment = array(
    'message' => 'this is my message',
    'name' => 'This is my demo Facebook application!',
    'caption' => "Caption of the Post",
    'link' => 'http://mylink.com',
    'description' => 'this is a description',
    'picture' => 'http://mysite.com/pic.gif',
    'actions' => array(
        array(
            'name' => 'Get Search',
            'link' => 'http://www.google.com'
        )
    )
);

$result = $facebook->api('/me/feed/', 'post', $attachment);

the above code will Post the message on to your wall... and if you want to post onto your friends or others wall then replace me with the Facebook User Id of that user..for further information look out the API Documentation.

How to use: while not in

Using sets will be screaming fast if you have any volume of data

If you are willing to use sets, you have the isdisjoint() method which will check to see if the intersection between your operator list and your other list is empty.

MyOper = set(['AND', 'OR', 'NOT'])
MyList = set(['c1', 'c2', 'NOT', 'c3'])

while not MyList.isdisjoint(MyOper):
    print "No boolean Operator"

http://docs.python.org/library/stdtypes.html#set.isdisjoint

What's the difference between echo, print, and print_r in PHP?

print_r() is used for printing the array in human readable format.

How to plot multiple functions on the same figure, in Matplotlib?

To plot multiple graphs on the same figure you will have to do:

from numpy import *
import math
import matplotlib.pyplot as plt

t = linspace(0, 2*math.pi, 400)
a = sin(t)
b = cos(t)
c = a + b

plt.plot(t, a, 'r') # plotting t, a separately 
plt.plot(t, b, 'b') # plotting t, b separately 
plt.plot(t, c, 'g') # plotting t, c separately 
plt.show()

enter image description here

Change application's starting activity

You add this you want to launch activity android:exported="true" in manifest file like

 <activity
      android:name=".activities.activity.MainActivity"
      android:windowSoftInputMode="adjustPan"
      android:exported="true"/>
  <activity

Open java file of this activity and right click then click on Run 'main Activity'

OR

Open java file of this activity and press Ctrl+Shift+F10.

Pass array to MySQL stored routine

You can pass a string with your list and use a prepared statements to run a query, e.g. -

DELIMITER $$

CREATE PROCEDURE GetFruits(IN fruitArray VARCHAR(255))
BEGIN

  SET @sql = CONCAT('SELECT * FROM Fruits WHERE Name IN (', fruitArray, ')');
  PREPARE stmt FROM @sql;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;

END
$$

DELIMITER ;

How to use:

SET @fruitArray = '\'apple\',\'banana\'';
CALL GetFruits(@fruitArray);

Getting HTML elements by their attribute names

With prototypejs :

 $$('span[property=v.name]');

or

document.body.select('span[property=v.name]');

Both return an array

Is there any way to call a function periodically in JavaScript?

function test() {
 alert('called!');
}
var id = setInterval('test();', 10000); //call test every 10 seconds.
function stop() { // call this to stop your interval.
   clearInterval(id);
}

Reloading submodules in IPython

IPython comes with some automatic reloading magic:

%load_ext autoreload
%autoreload 2

It will reload all changed modules every time before executing a new line. The way this works is slightly different than dreload. Some caveats apply, type %autoreload? to see what can go wrong.


If you want to always enable this settings, modify your IPython configuration file ~/.ipython/profile_default/ipython_config.py[1] and appending:

c.InteractiveShellApp.extensions = ['autoreload']     
c.InteractiveShellApp.exec_lines = ['%autoreload 2']

Credit to @Kos via a comment below.

[1] If you don't have the file ~/.ipython/profile_default/ipython_config.py, you need to call ipython profile create first. Or the file may be located at $IPYTHONDIR.

Drop multiple tables in one shot in MySQL

declare @sql1 nvarchar(max) 
SELECT @sql1 =
  STUFF(
         (
           select ' drop table dbo.[' + name + ']'

           FROM sys.sysobjects AS sobjects
           WHERE (xtype = 'U') AND (name LIKE 'GROUP_BASE_NEW_WORK_%')
           for xml path('')
        ),
     1, 1, '')

  execute sp_executesql @sql1

Failed to resolve version for org.apache.maven.archetypes

Read carefully about the reason.

"Failed to resolve version for org.apache.maven.archetypes:maven-archetype- webapp:pom:RELEASE: Could not find metadata org.apache.maven.archetypes:maven-archetype- webapp/maven-metadata.xml in local"

So all you need to do is download the maven-metadata.xml to your {HOME}.m2\repository

That's it.

Regex allow digits and a single dot

Try the following expression

/^\d{0,2}(\.\d{1,2})?$/.test()

How to sum a variable by group

If x is a dataframe with your data, then the following will do what you want:

require(reshape)
recast(x, Category ~ ., fun.aggregate=sum)

How can I convert a date into an integer?

Using the builtin Date.parse function which accepts input in ISO8601 format and directly returns the desired integer return value:

var dates_as_int = dates.map(Date.parse);

Django: OperationalError No Such Table

This comment on this page worked for me and a few others. It deserves its own answer:

python manage.py migrate --run-syncdb

Xpath for href element

Below works fine.

//a[@id='oldcontent']

If you've tried certain ones and they haven't worked, then let us know, otherwise something simple like this should work.

How do I format a date with Dart?

You can also specify the date format like stated earlier: https://pub.dev/documentation/intl/latest/intl/DateFormat-class.html

import 'package:intl/intl.dart';
String formatDate(DateTime date) => new DateFormat("MMMM d").format(date);

Produces: March 4

How to set thymeleaf th:field value from other variable

The correct approach is to use preprocessing

For example

th:field="*{__${myVar}__}"

Angular ui-grid dynamically calculate height of the grid

tony's approach does work for me but when do a console.log, the function getTableHeight get called too many time(sort, menu click...)

I modify it so the height is recalculated only when i add/remove rows. Note: tableData is the array of rows

$scope.getTableHeight = function() {
   var rowHeight = 30; // your row height
   var headerHeight = 30; // your header height
   return {
      height: ($scope.gridData.data.length * rowHeight + headerHeight) + "px"
   };
};

$scope.$watchCollection('tableData', function (newValue, oldValue) {
    angular.element(element[0].querySelector('.grid')).css($scope.getTableHeight());
});

Html

<div id="grid1" ui-grid="gridData" class="grid" ui-grid-auto-resize"></div>

Get first and last date of current month with JavaScript or jQuery

Very simple, no library required:

var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);

or you might prefer:

var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);

EDIT

Some browsers will treat two digit years as being in the 20th century, so that:

new Date(14, 0, 1);

gives 1 January, 1914. To avoid that, create a Date then set its values using setFullYear:

var date = new Date();
date.setFullYear(14, 0, 1); // 1 January, 14

Import module from subfolder

Just to notify here. (from a newbee, keviv22)

Never and ever for the sake of your own good, name the folders or files with symbols like "-" or "_". If you did so, you may face few issues. like mine, say, though your command for importing is correct, you wont be able to successfully import the desired files which are available inside such named folders.

Invalid Folder namings as follows:

  • Generic-Classes-Folder
  • Generic_Classes_Folder

valid Folder namings for above:

  • GenericClassesFolder or Genericclassesfolder or genericClassesFolder (or like this without any spaces or special symbols among the words)

What mistake I did:

consider the file structure.

Parent
   . __init__.py
   . Setup
     .. __init__.py
     .. Generic-Class-Folder
        ... __init__.py
        ... targetClass.py
   . Check
     .. __init__.py
     .. testFile.py

What I wanted to do?

  • from testFile.py, I wanted to import the 'targetClass.py' file inside the Generic-Class-Folder file to use the function named "functionExecute" in 'targetClass.py' file

What command I did?

  • from 'testFile.py', wrote command, from Core.Generic-Class-Folder.targetClass import functionExecute
  • Got errors like SyntaxError: invalid syntax

Tried many searches and viewed many stackoverflow questions and unable to decide what went wrong. I cross checked my files multiple times, i used __init__.py file, inserted environment path and hugely worried what went wrong......

And after a long long long time, i figured this out while talking with a friend of mine. I am little stupid to use such naming conventions. I should never use space or special symbols to define a name for any folder or file. So, this is what I wanted to convey. Have a good day!

(sorry for the huge post over this... just letting my frustrations go.... :) Thanks!)

Importing csv file into R - numeric values read as characters

Including this in the read.csv command worked for me: strip.white = TRUE

(I found this solution here.)

How do I prevent the error "Index signature of object type implicitly has an 'any' type" when compiling typescript with noImplicitAny flag enabled?

Create an interface to define the 'indexer' interface

Then create your object with that index.

Note: this will still have same issues other answers have described with respect to enforcing the type of each item - but that's often exactly what you want.

You can make the generic type parameter whatever you need : ObjectIndexer< Dog | Cat>

// this should be global somewhere, or you may already be 
// using a library that provides such a type
export interface ObjectIndexer<T> {
  [id: string]: T;
}

interface ISomeObject extends ObjectIndexer<string>
{
    firstKey:   string;
    secondKey:  string;
    thirdKey:   string;
}

let someObject: ISomeObject = {
    firstKey:   'firstValue',
    secondKey:  'secondValue',
    thirdKey:   'thirdValue'
};

let key: string = 'secondKey';

let secondValue: string = someObject[key];

Typescript Playground


You can even use this in a generic constraint when defining a generic type:

export class SmartFormGroup<T extends IndexableObject<any>> extends FormGroup

Then T inside the class can be indexed :-)

How get sound input from microphone in python, and process it on the fly?

I know it's an old question, but if someone is looking here again... see https://python-sounddevice.readthedocs.io/en/0.4.1/index.html .

It has a nice example "Input to Ouput Pass-Through" here https://python-sounddevice.readthedocs.io/en/0.4.1/examples.html#input-to-output-pass-through .

... and a lot of other examples as well ...

Creating and Update Laravel Eloquent

like @JuanchoRamone posted above (thank @Juancho) it's very useful for me, but if your data is array you should modify a little like this:

public static function createOrUpdate($data, $keys) {
    $record = self::where($keys)->first();
    if (is_null($record)) {
        return self::create($data);
    } else {
        return $record->update($data);
    }
}

How do I revert back to an OpenWrt router configuration?

Those who are facing this problem: Don't panic.

Short answer:

Restart your router, and this problem will be fixed. (But if your restart button is not working, you need to do a nine-step process to do the restart. Hitting the restart button is just one of them.)

Long answer: Let's learn how to restart the router.

  1. Set your PC's IP address: 192.168.1.2 and subnetmask 255.255.255.0 and gateway 192.168.1.1
  2. Power off the router
  3. Disconnect the WAN cable
  4. Only connect your PC Ethernet cable to ETH0
  5. Power on the router
  6. Wait for the router to start the boot sequence (SYS LED starts blinking)
  7. When the SYS LED is blinking, hit the restart button (the SYS LED will be blinking at a faster rate means your router is in failsafe mode). (You have to hit the button before the router boots.)
  8. telnet 192.168.1.1
  9. Run these commands:

    mount_root ## this remounts your partitions from read-only to read/write mode
    
    firstboot  ## This will reset your router after reboot
    
    reboot -f ## And force reboot
    
  10. Log in the web interface using web browser.

link to see the official failsafe mode.

Post Build exited with code 1

As a matter of good practice I suggest you replace the post build event with a MS Build File Copy task.

How to execute an Oracle stored procedure via a database link

for me, this worked

exec utl_mail.send@myotherdb(
  sender => '[email protected]',recipients => '[email protected], 
  cc => null, subject => 'my subject', message => 'my message'
); 

JPA Query selecting only specific columns without using Criteria Query?

Yes, it is possible. All you have to do is change your query to something like SELECT i.foo, i.bar FROM ObjectName i WHERE i.id = 10. The result of the query will be a List of array of Object. The first element in each array is the value of i.foo and the second element is the value i.bar. See the relevant section of JPQL reference.

"Least Astonishment" and the Mutable Default Argument

The shortest answer would probably be "definition is execution", therefore the whole argument makes no strict sense. As a more contrived example, you may cite this:

def a(): return []

def b(x=a()):
    print x

Hopefully it's enough to show that not executing the default argument expressions at the execution time of the def statement isn't easy or doesn't make sense, or both.

I agree it's a gotcha when you try to use default constructors, though.

Fast way to discover the row count of a table in PostgreSQL

In Oracle, you could use rownum to limit the number of rows returned. I am guessing similar construct exists in other SQLs as well. So, for the example you gave, you could limit the number of rows returned to 500001 and apply a count(*) then:

SELECT (case when cnt > 500000 then 500000 else cnt end) myCnt
FROM (SELECT count(*) cnt FROM table WHERE rownum<=500001)

Where in memory are my variables stored in C?

  • Variables/automatic variables ---> stack section
  • Dynamically allocated variables ---> heap section
  • Initialised global variables -> data section
  • Uninitialised global variables -> data section (bss)
  • Static variables -> data section
  • String constants -> text section/code section
  • Functions -> text section/code section
  • Text code -> text section/code section
  • Registers -> CPU registers
  • Command line inputs -> environmental/command line section
  • Environmental variables -> environmental/command line section

Rails: How to list database tables/objects using the Rails console?

To get a list of all model classes, you can use ActiveRecord::Base.subclasses e.g.

ActiveRecord::Base.subclasses.map { |cl| cl.name }
ActiveRecord::Base.subclasses.find { |cl| cl.name == "Foo" }

How to stop docker under Linux

The output of ps aux looks like you did not start docker through systemd/systemctl.

It looks like you started it with:

sudo dockerd -H gridsim1103:2376

When you try to stop it with systemctl, nothing should happen as the resulting dockerd process is not controlled by systemd. So the behavior you see is expected.

The correct way to start docker is to use systemd/systemctl:

systemctl enable docker
systemctl start docker

After this, docker should start on system start.

EDIT: As you already have the docker process running, simply kill it by pressing CTRL+C on the terminal you started it. Or send a kill signal to the process.

How to disable auto-play for local video in iframe

What do you think about video tag ? If you don't have to use iframe tag you can use video tag instead.

<video width="500" height="345" src="hey.mp4"  />

You should not use autoplay attribute in your video tag to disable autoplay.

Why is JsonRequestBehavior needed?

By default Jsonresult "Deny get"

Suppose if we have method like below

  [HttpPost]
 public JsonResult amc(){}

By default it "Deny Get".

In the below method

public JsonResult amc(){}

When you need to allowget or use get ,we have to use JsonRequestBehavior.AllowGet.

public JsonResult amc()
{
 return Json(new Modle.JsonResponseData { Status = flag, Message = msg, Html = html }, JsonRequestBehavior.AllowGet);
}

possibly undefined macro: AC_MSG_ERROR

I had the same problem with the Macports port "openocd" (locally modified the Portfile to use the git repository) on a freshly installed machine.

The permanent fix is easy, define a dependency to pkgconfig in the Portfile: depends_lib-append port:pkgconfig

Cannot find firefox binary in PATH. Make sure firefox is installed

java -jar selenium-server-standalone-2.53.1.jar -Dwebdriver.firefox.bin="C:\Program Files (x86)\Mozilla Firefox\firefox.exe"

Put selenium jar file on desktop, go to cmd and run the above command.

pdftk compression option

If file size is still too large it could help using ps2pdf to downscale the resolution of the produced pdf file:

pdf2ps input.pdf tmp.ps
ps2pdf -dPDFSETTINGS=/screen -dDownsampleColorImages=true -dColorImageResolution=200 -dColorImageDownsampleType=/Bicubic tmp.ps output.pdf

Adjust the value of the -dColorImageResolution option to achieve a result that fits your needs (the value describes the image resolution in DPIs). If your input file is in grayscale, replacing Color through Gray or using both options in the above command could also help. Further fine-tuning is possible by changing the -dPDFSETTINGS option to /default or /printer. For explanations of the all possible options consult the ps2pdf manual.

I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely

Add this config to your webpack config file when using webpack-dev-server (you can still specify the host as 0.0.0.0).

devServer: {
    disableHostCheck: true,
    host: '0.0.0.0',
    port: 3000
}

Split a string into array in Perl

You already have multiple answers to your question, but I would like to add another minor one here that might help to add something.

To view data structures in Perl you can use Data::Dumper. To print a string you can use say, which adds a newline character "\n" after every call instead of adding it explicitly.

I usually use \s which matches a whitespace character. If you add + it matches one or more whitespace characters. You can read more about it here perlre.

#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;

use feature 'say';

my $line = "file1.gz file2.gz file3.gz";
my @abc  = split /\s+/, $line;

print Dumper \@abc;
say for @abc;

How do I convert a String to an int in Java?

The two main ways to do this are using the method valueOf() and method parseInt() of the Integer class.

Suppose you are given a String like this

String numberInString = "999";

Then you can convert it into integer by using

int numberInInteger = Integer.parseInt(numberInString);

And alternatively, you can use

int numberInInteger = Integer.valueOf(numberInString);

But the thing here is, the method Integer.valueOf() has the following implementation in Integer class:

public static Integer valueOf(String var0, int var1) throws NumberFormatException {
    return parseInt(var0, var1);
}

As you can see, the Integer.valueOf() internally calls Integer.parseInt() itself. Also, parseInt() returns an int, and valueOf() returns an Integer

Generate random numbers with a given (numerical) distribution

Another answer, probably faster :)

distribution = [(1, 0.2), (2, 0.3), (3, 0.5)]  
# init distribution  
dlist = []  
sumchance = 0  
for value, chance in distribution:  
    sumchance += chance  
    dlist.append((value, sumchance))  
assert sumchance == 1.0 # not good assert because of float equality  

# get random value  
r = random.random()  
# for small distributions use lineair search  
if len(distribution) < 64: # don't know exact speed limit  
    for value, sumchance in dlist:  
        if r < sumchance:  
            return value  
else:  
    # else (not implemented) binary search algorithm  

What is the best way to uninstall gems from a rails3 project?

This will uninstall a gem installed by bundler:

bundle exec gem uninstall GEM_NAME

Note that this throws

ERROR: While executing gem ... (NoMethodError) undefined method `delete' for #<Bundler::SpecSet:0x00000101142268>

but the gem is actually removed. Next time you run bundle install the gem will be reinstalled.

How to unzip a file using the command line?

There is an article on getting to the built-in Windows .ZIP file handling with VBscript here:

https://www.aspfree.com/c/a/Windows-Scripting/Compressed-Folders-in-WSH/

(The last code blurb deals with extraction)

.htaccess - how to force "www." in a generic way?

This won't work with subdomains.

domain.com correctly gets redirected to www.domain.com

but

images.domain.com gets redirected to www.images.domain.com

Instead of checking if the subdomain is "not www", check if there are two dots:

RewriteCond %{HTTP_HOST} ^(.*)$ [NC]
RewriteCond %{HTTP_HOST} !^(.*)\.(.*)\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ HTTP%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Get drop down value

<select onchange = "selectChanged(this.value)">
  <item value = "1">one</item>
  <item value = "2">two</item>
</select>

and then the javascript...

function selectChanged(newvalue) {
  alert("you chose: " + newvalue);
}

JFrame.dispose() vs System.exit()

JFrame.dispose() affects only to this frame (release all of the native screen resources used by this component, its subcomponents, and all children). System.exit() affects to entire JVM.

If you want to close all JFrame or all Window (since Frames extend Windows) to terminate the application in an ordered mode, you can do some like this:

Arrays.asList(Window.getWindows()).forEach(e -> e.dispose()); // or JFrame.getFrames()

Reloading a ViewController

If you know your database has been updated and you want to just refresh your ViewController (which was my case). I didn't find another solution but what I did was when my database updated, I called:

[self viewDidLoad];

again, and it worked. Remember if you override other viewWillAppear or loadView then call them too in same order. like.

[self viewDidLoad]; [self viewWillAppear:YES];

I think there should be a more specific solution like refresh button in browser.

Android : difference between invisible and gone?

I'd like to add to the right and successful answers, that if you initialize a view with visibility as View.GONE, the view could have been not initialized and you will get some random errors.

For example if you initialize a layout as View.GONE and then you try to start an animation, from my experience I've got my animation working randomly times. Sometimes yes, sometimes no.

So before handling (resizing, move, whatever) a view, you have to init it as View.VISIBLE or View.INVISIBLE to render it (draw it) in the screen, and then handle it.

Easiest way to read from and write to files

using (var file = File.Create("pricequote.txt"))
{
    ...........                        
}

using (var file = File.OpenRead("pricequote.txt"))
{
    ..........
}

Simple, easy and also disposes/cleans up the object once you are done with it.

Pass a string parameter in an onclick function

<!----  script ---->
<script>
function myFunction(x) {
  document.getElementById("demo").style.backgroundColor = x; 
}
</script>

<!---- source ---->
<p id="demo" style="width:20px;height:20px;border:1px solid #ccc"></p>

<!----  buttons & function call ----> 
<a  onClick="myFunction('red')" />RED</a> 
<a  onClick="myFunction('blue')" />BLUE</a> 
<a  onClick="myFunction('black')" />BLACK</a>

Download and save PDF file with Python requests module

In Python 3, I find pathlib is the easiest way to do this. Request's response.content marries up nicely with pathlib's write_bytes.

from pathlib import Path
import requests
filename = Path('metadata.pdf')
url = 'http://www.hrecos.org//images/Data/forweb/HRTVBSH.Metadata.pdf'
response = requests.get(url)
filename.write_bytes(response.content)

Why is a ConcurrentModificationException thrown and how to debug it

It sounds less like a Java synchronization issue and more like a database locking problem.

I don't know if adding a version to all your persistent classes will sort it out, but that's one way that Hibernate can provide exclusive access to rows in a table.

Could be that isolation level needs to be higher. If you allow "dirty reads", maybe you need to bump up to serializable.

PowerShell on Windows 7: Set-ExecutionPolicy for regular users

This should solve your problem, you should try to run the following below:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser 

What does "while True" mean in Python?

In some languages True is just and alias for the number. You can learn more why this is by reading more about boolean logic.

Set field value with reflection

You can try this:

static class Student {
    private int age;
    private int number;

    public Student(int age, int number) {
        this.age = age;
        this.number = number;
    }

    public Student() {
    }
}
public static void main(String[] args) throws IllegalAccessException, NoSuchFieldException {
    Student student1=new Student();
   // Class g=student1.getClass();
    Field[]fields=student1.getClass().getDeclaredFields();
    Field age=student1.getClass().getDeclaredField("age");
    age.setAccessible(true);
    age.setInt(student1,13);
    Field number=student1.getClass().getDeclaredField("number");
    number.setAccessible(true);
    number.setInt(student1,936);

    for (Field f:fields
         ) {
        f.setAccessible(true);

        System.out.println(f.getName()+" "+f.getInt(student1));

    }
}

}

How do I remove quotes from a string?

str_replace('"', "", $string);
str_replace("'", "", $string);

I assume you mean quotation marks?

Otherwise, go for some regex, this will work for html quotes for example:

preg_replace("/<!--.*?-->/", "", $string);

C-style quotes:

preg_replace("/\/\/.*?\n/", "\n", $string);

CSS-style quotes:

preg_replace("/\/*.*?\*\//", "", $string);

bash-style quotes:

preg-replace("/#.*?\n/", "\n", $string);

Etc etc...

Visual Studio 64 bit?

Is there any 64 bit Visual Studio at all?

Yes literally there is one called "Visual Studio" and is 64bit, but well,, on Mac not on Windows

Why not?

Decision making is electro-chemical reaction made in our brain and that have an activation point (Nerdest answer I can come up with, but follow). Same situation happened in history: Windows 64!...

So in order to answer this fully I want you to remember old days. Imagine reasons for "why not we see 64bit Windows" are there at the time. I think at the time for Windows64 they had exact same reasons others have enlisted here about "reasons why not 64bit VS on windows" were on "reasons why not 64bit Windows" too. Then why they did start development for Windows 64bit? Simple! If they didn't succeed in making 64bit Windows I bet M$ would have been a history nowadays. If same reasons forcing M$ making 64bit Windows starts to appear on need for 64Bit VS then I bet we will see 64bit VS, even though very same reasons everyone else here enlisted will stay same! In time the limitations of 32bit may hit VS as well, so most likely something like below start to happen:

  • Visual Studio will drop 32bit support and become 64bit,
  • Visual Studio Code will take it's place instead,
  • Visual Studio will have similar functionality like WOW64 for old extensions which is I believe unlikely to happen.

I put my bets on Visual Studio Code taking the place in time; I guess bifurcation point for it will be some CPU manufacturer X starts to compete x86_64 architecture taking its place on mainstream market for laptop and/or workstation,

Write a function that returns the longest palindrome in a given string

Hi Here is my code to find the longest palindrome in the string. Kindly refer to the following link to understand the algorithm http://stevekrenzel.com/articles/longest-palnidrome

Test data used is HYTBCABADEFGHABCDEDCBAGHTFYW12345678987654321ZWETYGDE

 //Function GetPalindromeString

public static string GetPalindromeString(string theInputString)
 { 

        int j = 0;
        int k = 0;
        string aPalindrome = string.Empty;
        string aLongestPalindrome = string.Empty ;          
        for (int i = 1; i < theInputString.Length; i++)
        {
            k = i + 1;
            j = i - 1;
            while (j >= 0 && k < theInputString.Length)
            {
                if (theInputString[j] != theInputString[k])
                {
                    break;
                }
                else
                {
                    j--;
                    k++;
                }
                aPalindrome = theInputString.Substring(j + 1, k - j - 1);
                if (aPalindrome.Length > aLongestPalindrome.Length)
                {
                    aLongestPalindrome = aPalindrome;
                }
            }
        }
        return aLongestPalindrome;     
  }

String delimiter in string.split method

Use the Pattern#quote() method for escaping ||. Try:

final String[] tokens = myString.split(Pattern.quote("||"));

This is required because | is an alternation character and hence gains a special meaning when passed to split call (basically the argument to split is a regular expression in string form).

How to change Rails 3 server default port in develoment?

One more idea for you. Create a rake task that calls rails server with the -p.

task "start" => :environment do
  system 'rails server -p 3001'
end

then call rake start instead of rails server

SQL Server SELECT into existing table

If the destination table does exist but you don't want to specify column names:

DECLARE @COLUMN_LIST NVARCHAR(MAX);
DECLARE @SQL_INSERT NVARCHAR(MAX);

SET @COLUMN_LIST = (SELECT DISTINCT
    SUBSTRING(
        (
            SELECT ', table1.' + SYSCOL1.name  AS [text()]
            FROM sys.columns SYSCOL1
            WHERE SYSCOL1.object_id = SYSCOL2.object_id and SYSCOL1.is_identity <> 1
            ORDER BY SYSCOL1.object_id
            FOR XML PATH ('')
        ), 2, 1000)
FROM
    sys.columns SYSCOL2
WHERE
    SYSCOL2.object_id = object_id('dbo.TableOne') )

SET @SQL_INSERT =  'INSERT INTO dbo.TableTwo SELECT ' + @COLUMN_LIST + ' FROM dbo.TableOne table1 WHERE col3 LIKE ' + @search_key
EXEC sp_executesql @SQL_INSERT

Calculate distance between two latitude-longitude points? (Haversine formula)

Here is a C# Implementation:

static class DistanceAlgorithm
{
    const double PIx = 3.141592653589793;
    const double RADIUS = 6378.16;

    /// <summary>
    /// Convert degrees to Radians
    /// </summary>
    /// <param name="x">Degrees</param>
    /// <returns>The equivalent in radians</returns>
    public static double Radians(double x)
    {
        return x * PIx / 180;
    }

    /// <summary>
    /// Calculate the distance between two places.
    /// </summary>
    /// <param name="lon1"></param>
    /// <param name="lat1"></param>
    /// <param name="lon2"></param>
    /// <param name="lat2"></param>
    /// <returns></returns>
    public static double DistanceBetweenPlaces(
        double lon1,
        double lat1,
        double lon2,
        double lat2)
    {
        double dlon = Radians(lon2 - lon1);
        double dlat = Radians(lat2 - lat1);

        double a = (Math.Sin(dlat / 2) * Math.Sin(dlat / 2)) + Math.Cos(Radians(lat1)) * Math.Cos(Radians(lat2)) * (Math.Sin(dlon / 2) * Math.Sin(dlon / 2));
        double angle = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
        return angle * RADIUS;
    }

}

Objective-C : BOOL vs bool

At the time of writing this is the most recent version of objc.h:

/// Type to represent a boolean value.
#if (TARGET_OS_IPHONE && __LP64__)  ||  TARGET_OS_WATCH
#define OBJC_BOOL_IS_BOOL 1
typedef bool BOOL;
#else
#define OBJC_BOOL_IS_CHAR 1
typedef signed char BOOL; 
// BOOL is explicitly signed so @encode(BOOL) == "c" rather than "C" 
// even if -funsigned-char is used.
#endif

It means that on 64-bit iOS devices and on WatchOS BOOL is exactly the same thing as bool while on all other devices (OS X, 32-bit iOS) it is signed char and cannot even be overridden by compiler flag -funsigned-char

It also means that this example code will run differently on different platforms (tested it myself):

int myValue = 256;
BOOL myBool = myValue;
if (myBool) {
    printf("i'm 64-bit iOS");
} else {
    printf("i'm 32-bit iOS");
}

BTW never assign things like array.count to BOOL variable because about 0.4% of possible values will be negative.

Swift: How to get substring from start to last index of character

edit/update:

In Swift 4 or later (Xcode 10.0+) you can use the new BidirectionalCollection method lastIndex(of:)

func lastIndex(of element: Element) -> Int?

let string = "www.stackoverflow.com"
if let lastIndex = string.lastIndex(of: ".") {
    let subString = string[..<lastIndex]  // "www.stackoverflow"
}

Get IPv4 addresses from Dns.GetHostEntry()

    public static string GetIPAddress(string hostname)
    {
        IPHostEntry host;
        host = Dns.GetHostEntry(hostname);

        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
            {
                //System.Diagnostics.Debug.WriteLine("LocalIPadress: " + ip);
                return ip.ToString();
            }
        }
        return string.Empty;
    }

Laravel Soft Delete posts

Here is the details from laravel.com

http://laravel.com/docs/eloquent#soft-deleting

When soft deleting a model, it is not actually removed from your database. Instead, a deleted_at timestamp is set on the record. To enable soft deletes for a model, specify the softDelete property on the model:

class User extends Eloquent {

    protected $softDelete = true;

}

To add a deleted_at column to your table, you may use the softDeletes method from a migration:

$table->softDeletes();

Now, when you call the delete method on the model, the deleted_at column will be set to the current timestamp. When querying a model that uses soft deletes, the "deleted" models will not be included in query results.

How to clear all inputs, selects and also hidden fields in a form using jQuery?

If you want to apply clear value to a specific number of fields, then assign id or class to them and apply empty value to them. like this:

$('.all_fields').val('');

where all_fields is class applied to desired input fields for applying empty values. It will protect other fields to be empty, that you don't want to change.

Get list from pandas dataframe column or row?

Pandas DataFrame columns are Pandas Series when you pull them out, which you can then call x.tolist() on to turn them into a Python list. Alternatively you cast it with list(x).

import pandas as pd

data_dict = {'one': pd.Series([1, 2, 3], index=['a', 'b', 'c']),
             'two': pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}

df = pd.DataFrame(data_dict)

print(f"DataFrame:\n{df}\n")
print(f"column types:\n{df.dtypes}")

col_one_list = df['one'].tolist()

col_one_arr = df['one'].to_numpy()

print(f"\ncol_one_list:\n{col_one_list}\ntype:{type(col_one_list)}")
print(f"\ncol_one_arr:\n{col_one_arr}\ntype:{type(col_one_arr)}")

Output:

DataFrame:
   one  two
a  1.0    1
b  2.0    2
c  3.0    3
d  NaN    4

column types:
one    float64
two      int64
dtype: object

col_one_list:
[1.0, 2.0, 3.0, nan]
type:<class 'list'>

col_one_arr:
[ 1.  2.  3. nan]
type:<class 'numpy.ndarray'>

Check if a value is within a range of numbers

You must want to determine the lower and upper bound before writing the condition

function between(value,first,last) {

 let lower = Math.min(first,last) , upper = Math.max(first,last);
 return value >= lower &&  value <= upper ;

}

Using cURL with a username and password?

I had the same need in bash (Ubuntu 16.04 LTS) and the commands provided in the answers failed to work in my case. I had to use:

curl -X POST -F 'username="$USER"' -F 'password="$PASS"' "http://api.somesite.com/test/blah?something=123"

Double quotes in the -F arguments are only needed if you're using variables, thus from the command line ... -F 'username=myuser' ... will be fine.

Relevant Security Notice: as Mr. Mark Ribau points in comments this command shows the password ($PASS variable, expanded) in the processlist!

VBA array sort function?

I think my code (tested) is more "educated", assuming the simpler the better.

Option Base 1

'Function to sort an array decscending
Function SORT(Rango As Range) As Variant
    Dim check As Boolean
    check = True
    If IsNull(Rango) Then
        check = False
    End If
    If check Then
        Application.Volatile
        Dim x() As Variant, n As Double, m As Double, i As Double, j As Double, k As Double
        n = Rango.Rows.Count: m = Rango.Columns.Count: k = n * m
        ReDim x(n, m)
        For i = 1 To n Step 1
            For j = 1 To m Step 1
                x(i, j) = Application.Large(Rango, k)
                k = k - 1
            Next j
        Next i
        SORT = x
    Else
        Exit Function
    End If
End Function

Casting string to enum

As an extra, you can take the Enum.Parse answers already provided and put them in an easy-to-use static method in a helper class.

public static T ParseEnum<T>(string value)
{
    return (T)Enum.Parse(typeof(T), value, ignoreCase: true);
}

And use it like so:

{
   Content = ParseEnum<ContentEnum>(fileContentMessage);
};

Especially helpful if you have lots of (different) Enums to parse.

Is there any way to show a countdown on the lockscreen of iphone?

A today extension would be the most fitting solution.

Also you could do something on the lock screen with local notifications queued up to fire at regular intervals showing the latest countdown value.

How do I obtain crash-data from my Android application?

There is this android library called Sherlock. It gives you the full report of crash along with device and application information. Whenever a crash occurs, it displays a notification in the notification bar and on clicking of the notification, it opens the crash details. You can also share crash details with others via email or other sharing options.

Installation

android {
    dataBinding {
      enabled = true
    }
}

compile('com.github.ajitsing:sherlock:1.0.0@aar') {
    transitive = true
}

Demo

enter image description here

Python Threading String Arguments

You're trying to create a tuple, but you're just parenthesizing a string :)

Add an extra ',':

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=(dRecieved,))  # <- note extra ','
processThread.start()

Or use brackets to make a list:

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=[dRecieved])  # <- 1 element list
processThread.start()

If you notice, from the stack trace: self.__target(*self.__args, **self.__kwargs)

The *self.__args turns your string into a list of characters, passing them to the processLine function. If you pass it a one element list, it will pass that element as the first argument - in your case, the string.

Collection was modified; enumeration operation may not execute in ArrayList

You are removing the item during a foreach, yes? Simply, you can't. There are a few common options here:

  • use List<T> and RemoveAll with a predicate
  • iterate backwards by index, removing matching items

    for(int i = list.Count - 1; i >= 0; i--) {
        if({some test}) list.RemoveAt(i);
    }
    
  • use foreach, and put matching items into a second list; now enumerate the second list and remove those items from the first (if you see what I mean)

How can I get a precise time, for example in milliseconds in Objective-C?

Functions based on mach_absolute_time are good for short measurements.
But for long measurements important caveat is that they stop ticking while device is asleep.

There is a function to get time since boot. It doesn't stop while sleeping. Also, gettimeofday is not monotonic, but in my experiments I've always see that boot time changes when system time changes, so I think it should work fine.

func timeSinceBoot() -> TimeInterval
{
    var bootTime = timeval()
    var currentTime = timeval()
    var timeZone = timezone()

    let mib = UnsafeMutablePointer<Int32>.allocate(capacity: 2)
    mib[0] = CTL_KERN
    mib[1] = KERN_BOOTTIME
    var size = MemoryLayout.size(ofValue: bootTime)

    var timeSinceBoot = 0.0

    gettimeofday(&currentTime, &timeZone)

    if sysctl(mib, 2, &bootTime, &size, nil, 0) != -1 && bootTime.tv_sec != 0 {
        timeSinceBoot = Double(currentTime.tv_sec - bootTime.tv_sec)
        timeSinceBoot += Double(currentTime.tv_usec - bootTime.tv_usec) / 1000000.0
    }
    return timeSinceBoot
}

And since iOS 10 and macOS 10.12 we can use CLOCK_MONOTONIC:

if #available(OSX 10.12, *) {
    var uptime = timespec()
    if clock_gettime(CLOCK_MONOTONIC_RAW, &uptime) == 0 {
        return Double(uptime.tv_sec) + Double(uptime.tv_nsec) / 1000000000.0
    }
}

To sum it up:

  • Date.timeIntervalSinceReferenceDate — changes when system time changes, not monotonic
  • CFAbsoluteTimeGetCurrent() — not monotonic, may go backward
  • CACurrentMediaTime() — stops ticking when device is asleep
  • timeSinceBoot() — doesn't sleep, but might be not monotonic
  • CLOCK_MONOTONIC — doesn't sleep, monotonic, supported since iOS 10

What is the facade design pattern?

A facade is a class with a level of functionality that lies between a toolkit and a complete application, offering a simplified usage of the classes in a package or subsystem. The intent of the Facade pattern is to provide an interface that makes a subsystem easy to use. -- Extract from book Design Patterns in C#.

Are there any disadvantages to always using nvarchar(MAX)?

It will make screen design harder as you will no longer be able to predict how wide your controls should be.

ASP.NET Core return JSON with status code

The cleanest solution I have found is to set the following in my ConfigureServices method in Startup.cs (In my case I want the TZ info stripped. I always want to see the date time as the user saw it).

   services.AddControllers()
                .AddNewtonsoftJson(o =>
                {
                    o.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Unspecified;
                });

The DateTimeZoneHandling options are Utc, Unspecified, Local or RoundtripKind

I would still like to find a way to be able to request this on a per-call bases.

something like

  static readonly JsonMediaTypeFormatter _jsonFormatter = new JsonMediaTypeFormatter();
 _jsonFormatter.SerializerSettings = new JsonSerializerSettings()
                {DateTimeZoneHandling = DateTimeZoneHandling.Unspecified};

return Ok("Hello World", _jsonFormatter );

I am converting from ASP.NET and there I used the following helper method

public static ActionResult<T> Ok<T>(T result, HttpContext context)
    {
        var responseMessage = context.GetHttpRequestMessage().CreateResponse(HttpStatusCode.OK, result, _jsonFormatter);
        return new ResponseMessageResult(responseMessage);
    }

How to convert DATE to UNIX TIMESTAMP in shell script on MacOS

date -j -f "%Y-%m-%d" "2010-10-02" "+%s"

How to use Python to execute a cURL command?

Just use this website. It'll convert any curl command into Python, Node.js, PHP, R, or Go.

Example:

curl -X POST -H 'Content-type: application/json' --data '{"text":"Hello, World!"}' https://hooks.slack.com/services/asdfasdfasdf

Becomes this in Python,

import requests

headers = {
    'Content-type': 'application/json',
}

data = '{"text":"Hello, World!"}'

response = requests.post('https://hooks.slack.com/services/asdfasdfasdf', headers=headers, data=data)

Powershell's Get-date: How to get Yesterday at 22:00 in a variable?

(Get-Date (Get-Date -Format d)).AddHours(-2)

Change Active Menu Item on Page Scroll?

If you want the accepted answer to work in JQuery 3 change the code like this:

var scrollItems = menuItems.map(function () {
    var id = $(this).attr("href");
    try {
        var item = $(id);
      if (item.length) {
        return item;
      }
    } catch {}
  });

I also added a try-catch to prevent javascript from crashing if there is no element by that id. Feel free to improve it even more ;)

How to read a local text file?

I know, I am late at this party. Let me show you what I have got.

This is a simple reading of text file

var path = "C:\\path\\filename.txt"
var fs = require('fs')
fs.readFile(path , 'utf8', function(err, data) {
  if (err) throw err;
  console.log('OK: ' + filename);
  console.log(data)
});

I hope this helps.

How to stretch a fixed number of horizontal navigation items evenly and fully across a specified container

if you can, use flexbox:

<ul>
    <li>HOME</li>
    <li>ABOUT US</li>
    <li>SERVICES</li>
    <li>PREVIOUS PROJECTS</li>
    <li>TESTIMONIALS</li>
    <li>NEWS</li>
    <li>RESEARCH &amp; DEV</li>
    <li>CONTACT</li>
</ul>

ul {
  display: flex;
  justify-content:space-between;
  list-style-type: none;
}

jsfiddle: http://jsfiddle.net/RAaJ8/

Browser support is actually quite good (with prefixes an other nasty stuff): http://caniuse.com/flexbox

Can we pass an array as parameter in any function in PHP?

function sendemail(Array $id,$userid){  // forces $id must be an array
Some Process....
}


$ids  = array(121,122,123);
sendmail($ids, $userId);

How to get the HTML's input element of "file" type to only accept pdf files?

The previous posters made a little mistake. The accept attribute is only a display filter. It will not validate your entry before submitting.

This attribute forces the file dialog to display the required mime type only. But the user can override that filter. He can choose . and see all the files in the current directory. By doing so, he can select any file with any extension, and submit the form.

So, to answer to the original poster, NO. You cannot restrict the input file to one particular extension by using HTML.

But you can use javascript to test the filename that has been chosen, just before submitting. Just insert an onclick attribute on your submit button and call the code that will test the input file value. If the extension is forbidden, you'll have to return false to invalidate the form. You may even use a jQuery custom validator and so on, to validate the form.

Finally, you'll have to test the extension on the server side too. Same problem about the maximum allowed file size.

getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)

In Your RecyclerView in Kotlin

inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    fun bind(t: YourObject, listener: OnItemClickListener.YourObjectListener) = with(itemView) {
        textViewcolor.setTextColor(ContextCompat.getColor(itemView.context, R.color.colorPrimary))
        textViewcolor.text = t.name
    }
}

If statement for strings in python?

You want:

answer = str(raw_input("Is the information correct? Enter Y for yes or N for no"))
if answer == "y" or answer == "Y":
  print("this will do the calculation")
else:
  exit()

Or

answer = str(raw_input("Is the information correct? Enter Y for yes or N for no"))
if answer in ["y","Y"]:
  print("this will do the calculation")
else:
  exit()

Note:

  1. It's "if", not "If". Python is case sensitive.
  2. Indentation is important.
  3. There is no colon or semi-colon at the end of python commands.
  4. You want raw_input not input; input evals the input.
  5. "or" gives you the first result if it evaluates to true, and the second result otherwise. So "a" or "b" evaluates to "a", whereas 0 or "b" evaluates to "b". See The Peculiar Nature of and and or.

How to redirect a page using onclick event in php?

Why do people keep confusing php and javascript?

PHP is SERVER SIDE
JAVASCRIPT (like onclick) is CLIENT SIDE

You will have to use just javascript to redirect. Otherwise if you want PHP involved you can use an AJAX call to log a hit or whatever you like to send back a URL or additional detail.

Git: cannot checkout branch - error: pathspec '...' did not match any file(s) known to git

Alright, there are too many answers already. But in my case, I faced this issue while I was working on Eclipse and using git-bash to switch between branches/checkouts. Once I closed the eclipse and relaunched the git-bash to checkout branch everything worked well.

So my suggestion for you to double check if your repository is not being used by another application.

numpy max vs amax vs maximum

np.maximum not only compares elementwise but also compares array elementwise with single value

>>>np.maximum([23, 14, 16, 20, 25], 18)
array([23, 18, 18, 20, 25])

Why doesn't TFS get latest get the latest?

I had the same issue with Visual Studio 2012. No matter what I did, it didn't get the code from TFS source control.

In my case, the cause was mappings a folder + subfolder from the source control separately but to the same tree in my local HD.

The solution was removing the subfolder mapping using the "manage workspaces" window.

How to run Spyder in virtual environment?

Additional to tomaskazemekas's answer: you should install spyder in that virtual environment by:

conda install -n myenv spyder

(on Windows, for Linux or MacOS, you can search for similar commands)

How do I format axis number format to thousands with a comma in matplotlib?

Use , as format specifier:

>>> format(10000.21, ',')
'10,000.21'

Alternatively you can also use str.format instead of format:

>>> '{:,}'.format(10000.21)
'10,000.21'

With matplotlib.ticker.FuncFormatter:

...
ax.get_xaxis().set_major_formatter(
    matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
ax2.get_xaxis().set_major_formatter(
    matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
fig1.show()

enter image description here

Failed to read artifact descriptor for org.apache.maven.plugins:maven-source-plugin:jar:2.4

It may happen, e.g. after an interrupted download, that Maven cached a broken version of the referenced package in your local repository.

Solution: Manually delete the folder of this plugin from cache (i.e. your local repository), and repeat maven install.

How to find the right folder? Folders in Maven repository follow the structure:

<dependency>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-source-plugin</artifactId>
    <version>2.4</version>
</dependency>

is cached in ${USER_HOME}\.m2\repository\org\apache\maven\plugins\maven-source-plugin\2.4

Command to open file with git

You can use the following commands to open a file in git bash:

vi <filename>               -- to open a file

i                           -- to insert into the file 

ESC button followed by :wq   -- to save and close the file 

Hope it helps.

Any other terminal based text editor, like vim, nano and many will also do the job just fine.

Why do we have to normalize the input for an artificial neural network?

It's explained well here.

If the input variables are combined linearly, as in an MLP [multilayer perceptron], then it is rarely strictly necessary to standardize the inputs, at least in theory. The reason is that any rescaling of an input vector can be effectively undone by changing the corresponding weights and biases, leaving you with the exact same outputs as you had before. However, there are a variety of practical reasons why standardizing the inputs can make training faster and reduce the chances of getting stuck in local optima. Also, weight decay and Bayesian estimation can be done more conveniently with standardized inputs.

Error when trying to access XAMPP from a network

This answer is for XAMPP on Ubuntu.

The manual for installation and download is on (site official)

http://www.apachefriends.org/it/xampp-linux.html

After to start XAMPP simply call this command:

sudo /opt/lampp/lampp start

You should now see something like this on your screen:

Starting XAMPP 1.8.1...
LAMPP: Starting Apache...
LAMPP: Starting MySQL...
LAMPP started.

If you have this

Starting XAMPP for Linux 1.8.1...                                                             
XAMPP: Another web server daemon is already running.                                          
XAMPP: Another MySQL daemon is already running.                                               
XAMPP: Starting ProFTPD...                                                                    
XAMPP for Linux started

. The solution is

sudo /etc/init.d/apache2 stop
sudo /etc/init.d/mysql stop

And the restast with sudo //opt/lampp/lampp restart

You to fix most of the security weaknesses simply call the following command:

/opt/lampp/lampp security

After the change this file

sudo kate //opt/lampp/etc/extra/httpd-xampp.conf

Find and replace on

    #
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
    Order deny,allow
    Deny from all
    Allow from ::1 127.0.0.0/8 
    Allow from all
    #\
    #   fc00::/7 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 \
    #   fe80::/10 169.254.0.0/16

    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>

PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

The major difference between the two is that $_SERVER['SERVER_NAME'] is a server controlled variable, while $_SERVER['HTTP_HOST'] is a user-controlled value.

The rule of thumb is to never trust values from the user, so $_SERVER['SERVER_NAME'] is the better choice.

As Gumbo pointed out, Apache will construct SERVER_NAME from user-supplied values if you don't set UseCanonicalName On.

Edit: Having said all that, if the site is using a name-based virtual host, the HTTP Host header is the only way to reach sites that aren't the default site.

DataGrid get selected rows' column values

If you are using an SQL query to populate your DataGrid you can do this :

Datagrid fill

Private Sub UserControl_Loaded(sender As Object, e As RoutedEventArgs)
        Dim cmd As SqlCommand
        Dim da As SqlDataAdapter
        Dim dt As DataTable

        cmd = New SqlCommand With {
            .CommandText = "SELECT * FROM temp_rech_dossier_route",
            .Connection = connSQLServer
        }
        da = New SqlDataAdapter(cmd)
        dt = New DataTable("RECH")
        da.Fill(dt)
        DataGridRech.ItemsSource = dt.DefaultView
End Sub

Value diplay

    Private Sub DataGridRech_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles DataGridRech.SelectionChanged
        Dim val As DataRowView
        val = CType(DataGridRech.SelectedItem, DataRowView)
        Console.WriteLine(val.Row.Item("num_dos"))
    End Sub

I know it's in VB.Net but it can be translated into C#. I put this solution here, it might be useful for someone.

Java character array initializer

you are doing it wrong, you have first split the string using space as a delimiter using String.split() and populate the char array with charcters.

or even simpler just use String.charAt() in the loop to populate array like below:

String ini="Hi there";
  char[] array=new  char[ini.length()];

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

or one liner would be

  String ini="Hi there";
  char[] array=ini.toCharArray();

Bash ignoring error for a particular command

More concisely:

! particular_script

From the POSIX specification regarding set -e (emphasis mine):

When this option is on, if a simple command fails for any of the reasons listed in Consequences of Shell Errors or returns an exit status value >0, and is not part of the compound list following a while, until, or if keyword, and is not a part of an AND or OR list, and is not a pipeline preceded by the ! reserved word, then the shell shall immediately exit.

TypeScript for ... of with index / key?

Or another old school solution:

var someArray = [9, 2, 5];
let i = 0;
for (var item of someArray) {
    console.log(item); // 9,2,5
    i++;
}

T-SQL Substring - Last 3 Characters

declare @newdata varchar(30)
set @newdata='IDS_ENUM_Change_262147_190'
select REVERSE(substring(reverse(@newdata),0,charindex('_',reverse(@newdata))))

=== Explanation ===

I found it easier to read written like this:

SELECT
    REVERSE( --4.
        SUBSTRING( -- 3.
            REVERSE(<field_name>),
            0,
            CHARINDEX( -- 2.
                '<your char of choice>',
                REVERSE(<field_name>) -- 1.
            )
        )
    )
FROM
    <table_name>
  1. Reverse the text
  2. Look for the first occurrence of a specif char (i.e. first occurrence FROM END of text). Gets the index of this char
  3. Looks at the reversed text again. searches from index 0 to index of your char. This gives the string you are looking for, but in reverse
  4. Reversed the reversed string to give you your desired substring

what is the use of xsi:schemaLocation?

The Java XML parser that spring uses will read the schemaLocation values and try to load them from the internet, in order to validate the XML file. Spring, in turn, intercepts those load requests and serves up versions from inside its own JAR files.

If you omit the schemaLocation, then the XML parser won't know where to get the schema in order to validate the config.

error: expected unqualified-id before ‘.’ token //(struct)

ReducedForm is a type, so you cannot say

ReducedForm.iSimplifiedNumerator = iNumerator/iGreatCommDivisor;

You can only use the . operator on an instance:

ReducedForm rf;
rf.iSimplifiedNumerator = iNumerator/iGreatCommDivisor;

Working with UTF-8 encoding in Python source

In the source header you can declare:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
....

It is described in the PEP 0263:

Then you can use UTF-8 in strings:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

u = 'idzie waz waska drózka'
uu = u.decode('utf8')
s = uu.encode('cp1250')
print(s)

This declaration is not needed in Python 3 as UTF-8 is the default source encoding (see PEP 3120).

In addition, it may be worth verifying that your text editor properly encodes your code in UTF-8. Otherwise, you may have invisible characters that are not interpreted as UTF-8.

What is the difference between a schema and a table and a database?

As MusiGenesis put so nicely, in most databases:

schema : database : table :: floor plan : house : room

But, in Oracle it may be easier to think of:

schema : database : table :: owner : house : room

How to count objects in PowerShell?

Just use parenthesis and 'count'. This applies to Powershell v3

(get-alias).count

How to set environment variables in PyCharm?

I was able to figure out this using a PyCharm plugin called EnvFile. This plugin, basically allows setting environment variables to run configurations from one or multiple files.

The installation is pretty simple:

Preferences > Plugins > Browse repositories... > Search for "Env File" > Install Plugin.

Then, I created a file, in my project root, called environment.env which contains:

DATABASE_URL=postgres://127.0.0.1:5432/my_db_name
DEBUG=1

Then I went to Run->Edit Configurations, and I followed the steps in the next image:

Set Environment Variables

In 3, I chose the file environment.env, and then I could just click the play button in PyCharm, and everything worked like a charm.

Android selector & text color

I got by doing several tests until one worked, so: res/color/button_dark_text.xml

<?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_pressed="true"
           android:color="#000000" /> <!-- pressed -->
     <item android:state_focused="true"
           android:color="#000000" /> <!-- focused -->
     <item android:color="#FFFFFF" /> <!-- default -->
 </selector>

res/layout/view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   >
    <Button
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="EXIT"
       android:textColor="@color/button_dark_text" />
</LinearLayout>

PKIX path building failed: unable to find valid certification path to requested target

On Mac OS I had to open the server's self-signed certificate with system Keychain Access tool, import it, dobubleclick it and then select "Always trust" (even though I set the same in importer). Before that, of course I ran java key took with -importcert to import same file to cacert storage.

Check whether values in one data frame column exist in a second data frame

Use %in% as follows

A$C %in% B$C

Which will tell you which values of column C of A are in B.

What is returned is a logical vector. In the specific case of your example, you get:

A$C %in% B$C
# [1]  TRUE FALSE  TRUE  TRUE

Which you can use as an index to the rows of A or as an index to A$C to get the actual values:

# as a row index
A[A$C %in% B$C,  ]  # note the comma to indicate we are indexing rows

# as an index to A$C
A$C[A$C %in% B$C]
[1] 1 3 4  # returns all values of A$C that are in B$C

We can negate it too:

A$C[!A$C %in% B$C]
[1] 2   # returns all values of A$C that are NOT in B$C



If you want to know if a specific value is in B$C, use the same function:

  2 %in% B$C   # "is the value 2 in B$C ?"  
  # FALSE

  A$C[2] %in% B$C  # "is the 2nd element of A$C in B$C ?"  
  # FALSE

An error occurred while executing the command definition. See the inner exception for details

This occurs when you specify the different name for repository table name and database table name. Please check your table name with database and repository.

How to select the comparison of two columns as one column in Oracle

select column1, coulumn2, case when colum1=column2 then 'true' else 'false' end from table;

HTH

AJAX post error : Refused to set unsafe header "Connection"

Remove these two lines:

xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");

XMLHttpRequest isn't allowed to set these headers, they are being set automatically by the browser. The reason is that by manipulating these headers you might be able to trick the server into accepting a second request through the same connection, one that wouldn't go through the usual security checks - that would be a security vulnerability in the browser.

trim left characters in sql server?

use "LEFT"

 select left('Hello World', 5)

or use "SUBSTRING"

 select substring('Hello World', 1, 5)

How to find the most recent file in a directory using .NET, and without looping?

Expanding on the first one above, if you want to search for a certain pattern you may use the following code:

string pattern = "*.txt";
var dirInfo = new DirectoryInfo(directory);
var file = (from f in dirInfo.GetFiles(pattern) orderby f.LastWriteTime descending select f).First();