Programs & Examples On #C++builder 6

The 2002 release of C++Builder, a rapid visual C++ development environment. Use this tag for issues related to development in C++Builder 6.

Send FormData with other field in AngularJS

Using $resource in AngularJS you can do:

task.service.js

$ngTask.factory("$taskService", [
    "$resource",
    function ($resource) {
        var taskModelUrl = 'api/task/';
        return {
            rest: {
                taskUpload: $resource(taskModelUrl, {
                    id: '@id'
                }, {
                    save: {
                        method: "POST",
                        isArray: false,
                        headers: {"Content-Type": undefined},
                        transformRequest: angular.identity
                    }
                })
            }
        };
    }
]);

And then use it in a module:

task.module.js

$ngModelTask.controller("taskController", [
    "$scope",
    "$taskService",
    function (
        $scope,
        $taskService,
    ) {
    $scope.saveTask = function (name, file) {
        var newTask,
            payload = new FormData();
        payload.append("name", name);
        payload.append("file", file);
        newTask = $taskService.rest.taskUpload.save(payload);
        // check if exists
    }
}

JQuery Event for user pressing enter in a textbox?

If your input is search, you also can use on 'search' event. Example

<input type="search" placeholder="Search" id="searchTextBox">

.

$("#searchPostTextBox").on('search', function () {
    alert("search value: "+$(this).val());
});

<> And Not In VB.NET

Here's the technical answer (expanding on Rowland Shaw's answer).

The Is keyword checks whether the two operands are references to the same object memory, and only returns true if this is the case. I believe it is functionally equivalent to Object.ReferenceEquals. The IsNot keyword is simply shorthand syntax for writing Not ... Is ..., nothing more.

The = (equality) operator compares values and in this case (as in many others) is equivalent to String.Equals. Now, the <> (inequality) operator does not quite have the same analogy as the Is and IsNot keywords, since it can be overriden separately from the = operator depending on the class. I believe the case should always be that it returns the logical inverse of the = operator (and certainly is in the case of String), and just allows for a more efficient comparison to made when testing for inequality rather than equality.

When dealing with strings, unless you actually mean to compare references, always use the = operator (or String.Equals I suppose). In your case, because you are testing for null (Nothing), it seems you need to use the Is or IsNot keyword (the equality operator will fail because it can't compare the values of null objects). Syntactically, the IsNot keyword is a bit nicer here, so go with that.

How do I get JSON data from RESTful service using Python?

Something like this should work unless I'm missing the point:

import json
import urllib2
json.load(urllib2.urlopen("url"))

Compute mean and standard deviation by group for multiple variables in a data.frame

There are a few different ways to go about it. reshape2 is a helpful package. Personally, I like using data.table

Below is a step-by-step

If myDF is your data.frame:

library(data.table)
DT <- data.table(myDF)

DT

# this will get you your mean and SD's for each column
DT[, sapply(.SD, function(x) list(mean=mean(x), sd=sd(x)))]

# adding a `by` argument will give you the groupings
DT[, sapply(.SD, function(x) list(mean=mean(x), sd=sd(x))), by=ID]

# If you would like to round the values: 
DT[, sapply(.SD, function(x) list(mean=round(mean(x), 3), sd=round(sd(x), 3))), by=ID]

# If we want to add names to the columns 
wide <- setnames(DT[, sapply(.SD, function(x) list(mean=round(mean(x), 3), sd=round(sd(x), 3))), by=ID], c("ID", sapply(names(DT)[-1], paste0, c(".men", ".SD"))))

wide

   ID Obs.1.men Obs.1.SD Obs.2.men Obs.2.SD Obs.3.men Obs.3.SD
1:  1    35.333    8.021    36.333   10.214      33.0    9.644
2:  2    29.750    3.594    32.250    4.193      30.5    5.916
3:  3    41.500    4.950    43.500    4.950      39.0    4.243

Also, this may or may not be helpful

> DT[, sapply(.SD, summary), .SDcols=names(DT)[-1]]
        Obs.1 Obs.2 Obs.3
Min.    25.00 28.00 22.00
1st Qu. 29.00 31.00 27.00
Median  33.00 32.00 36.00
Mean    34.22 36.11 33.22
3rd Qu. 38.00 40.00 37.00
Max.    45.00 48.00 42.00

Read Variable from Web.Config

Given the following web.config:

<appSettings>
     <add key="ClientId" value="127605460617602"/>
     <add key="RedirectUrl" value="http://localhost:49548/Redirect.aspx"/>
</appSettings>

Example usage:

using System.Configuration;

string clientId = ConfigurationManager.AppSettings["ClientId"];
string redirectUrl = ConfigurationManager.AppSettings["RedirectUrl"];

Laravel where on relationship object

The correct syntax to do this on your relations is:

Event::whereHas('participants', function ($query) {
    return $query->where('IDUser', '=', 1);
})->get();

Read more at https://laravel.com/docs/5.8/eloquent-relationships#eager-loading

PHP CURL Enable Linux

It dipends on which distribution you are in general but... You have to install the php-curl module and then enable it on php.ini like you did in windows. Once you are done remember to restart apache demon!

Create a table without a header in Markdown

Omitting the header above the divider produces a headerless table in at least Perl Text::MultiMarkdown and in FletcherPenney MultiMarkdown

|-------------|--------|
|**Name:**    |John Doe|
|**Position:**|CEO     |

See PHP Markdown feature request


Empty headers in PHP Parsedown produce tables with empty headers that are usually invisible (depending on your CSS) and so look like headerless tables.

|     |     |
|-----|-----|
|Foo  |37   |
|Bar  |101  |

Resize jqGrid when browser is resized?

As a follow-up:

The previous code shown in this post was eventually abandoned because it was unreliable. I am now using the following API function to resize the grid, as recommended by the jqGrid documentation:

jQuery("#targetGrid").setGridWidth(width);

To do the actual resizing, a function implementing the following logic is bound to the window's resize event:

  • Calculate the width of the grid using its parent's clientWidth and (if that is not available) its offsetWidth attribute.

  • Perform a sanity check to make sure width has changed more than x pixels (to work around some application-specific problems)

  • Finally, use setGridWidth() to change the grid's width

Here is example code to handle resizing:

jQuery(window).bind('resize', function() {

    // Get width of parent container
    var width = jQuery(targetContainer).attr('clientWidth');
    if (width == null || width < 1){
        // For IE, revert to offsetWidth if necessary
        width = jQuery(targetContainer).attr('offsetWidth');
    }
    width = width - 2; // Fudge factor to prevent horizontal scrollbars
    if (width > 0 &&
        // Only resize if new width exceeds a minimal threshold
        // Fixes IE issue with in-place resizing when mousing-over frame bars
        Math.abs(width - jQuery(targetGrid).width()) > 5)
    {
        jQuery(targetGrid).setGridWidth(width);
    }

}).trigger('resize');

And example markup:

<div id="grid_container">
    <table id="grid"></table>
    <div id="grid_pgr"></div>
</div>

Android – Listen For Incoming SMS Messages

Note that on some devices your code wont work without android:priority="1000" in intent filter:

<receiver android:name=".listener.SmsListener">
    <intent-filter android:priority="1000">
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

And here is some optimizations:

public class SmsListener extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(intent.getAction())) {
            for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
                String messageBody = smsMessage.getMessageBody();
            }
        }
    }
}

Note:
The value must be an integer, such as "100". Higher numbers have a higher priority. The default value is 0. The value must be greater than -1000 and less than 1000.

Here's a link.

Creating Threads in python

You don't need to use a subclass of Thread to make this work - take a look at the simple example I'm posting below to see how:

from threading import Thread
from time import sleep

def threaded_function(arg):
    for i in range(arg):
        print("running")
        sleep(1)


if __name__ == "__main__":
    thread = Thread(target = threaded_function, args = (10, ))
    thread.start()
    thread.join()
    print("thread finished...exiting")

Here I show how to use the threading module to create a thread which invokes a normal function as its target. You can see how I can pass whatever arguments I need to it in the thread constructor.

npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY

For me the issue was VPN, I disconnected the VPN and "npm i" command worked with no fail.

Adding new line of data to TextBox

C# - serialData is ReceivedEventHandler in TextBox.

SerialPort sData = sender as SerialPort;
string recvData = sData.ReadLine();

serialData.Invoke(new Action(() => serialData.Text = String.Concat(recvData)));

Now Visual Studio drops my lines. TextBox, of course, had all the correct options on.

Serial:

Serial.print(rnd);
Serial.( '\n' );  //carriage return

Check if at least two out of three booleans are true

The most obvious set of improvements are:

// There is no point in an else if you already returned.
boolean atLeastTwo(boolean a, boolean b, boolean c) {
    if ((a && b) || (b && c) || (a && c)) {
        return true;
    }
    return false;
}

and then

// There is no point in an if(true) return true otherwise return false.
boolean atLeastTwo(boolean a, boolean b, boolean c) {
    return ((a && b) || (b && c) || (a && c));
}

But those improvements are minor.

How to get current route in Symfony 2?

if you want to get route name in your controller than you have to inject the request (instead of getting from container due to Symfony UPGRADE and than call get('_route').

public function indexAction(Request $request)
{
    $routeName = $request->get('_route');
}

if you want to get route name in twig than you have to get it like

{{ app.request.attributes.get('_route') }}

How to take screenshot of a div with JavaScript?

As far as I know you can't do that, I may be wrong. However I'd do this with php, generate a JPEG using php standard functions and then display the image, should not be a very hard job, however depends on how flashy the contents of the DIV are

Calling another method java GUI

I'm not sure what you're trying to do, but here's something to consider: c(); won't do anything. c is an instance of the class checkbox and not a method to be called. So consider this:

public class FirstWindow extends JFrame {      public FirstWindow() {         checkbox c = new checkbox();         c.yourMethod(yourParameters); // call the method you made in checkbox     } }  public class checkbox extends JFrame {      public checkbox(yourParameters) {          // this is the constructor method used to initialize instance variables     }      public void yourMethod() // doesn't have to be void     {         // put your code here     } } 

How to set UTF-8 encoding for a PHP file

PHP, by default, always returns the following header: "Content-Type: text/html" (notice no charset), therefore you must use

<?php header('Content-type: text/plain; charset=utf-8'); ?>

Fatal error: Call to a member function fetch_assoc() on a non-object

I happen to miss spaces in my query and this error comes.

Ex: $sql= "SELECT * FROM";
$sql .= "table1";

Though the example might look simple, when coding complex queries, the probability for this error is high. I was missing space before word "table1".

How to replace innerHTML of a div using jQuery?

Answer:

$("#regTitle").html('Hello World');

Explanation:

$ is equivalent to jQuery. Both represent the same object in the jQuery library. The "#regTitle" inside the parenthesis is called the selector which is used by the jQuery library to identify which element(s) of the html DOM (Document Object Model) you want to apply code to. The # before regTitle is telling jQuery that regTitle is the id of an element inside the DOM.

From there, the dot notation is used to call the html function which replaces the inner html with whatever parameter you place in-between the parenthesis, which in this case is 'Hello World'.

Select mysql query between date?

All the above works, and here is another way if you just want to number of days/time back rather a entering date

select * from *table_name* where *datetime_column* BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY)  AND NOW() 

Algorithm for Determining Tic Tac Toe Game Over

How about a following approach for 9 slots? Declare 9 integer variables for a 3x3 matrix (a1,a2....a9) where a1,a2,a3 represent row-1 and a1,a4,a7 would form column-1 (you get the idea). Use '1' to indicate Player-1 and '2' to indicate Player-2.

There are 8 possible win combinations: Win-1: a1+a2+a3 (answer could be 3 or 6 based on which player won) Win-2: a4+a5+a6 Win-3: a7+a8+a9 Win-4: a1+a4+a7 .... Win-7: a1+a5+a9 Win-8: a3+a5+a7

Now we know that if player one crosses a1 then we need to reevaluate sum of 3 variables: Win-1, Win-4 and Win-7. Whichever 'Win-?' variables reaches 3 or 6 first wins the game. If Win-1 variable reaches 6 first then Player-2 wins.

I do understand that this solution is not scalable easily.

How to break/exit from a each() function in JQuery?

Return false from the anonymous function:

$(xml).find("strengths").each(function() {
  // Code
  // To escape from this block based on a condition:
  if (something) return false;
});

From the documentation of the each method:

Returning 'false' from within the each function completely stops the loop through all of the elements (this is like using a 'break' with a normal loop). Returning 'true' from within the loop skips to the next iteration (this is like using a 'continue' with a normal loop).

Make the current Git branch a master branch

Edit: You didn't say you had pushed to a public repo! That makes a world of difference.

There are two ways, the "dirty" way and the "clean" way. Suppose your branch is named new-master. This is the clean way:

git checkout new-master
git branch -m master old-master
git branch -m new-master master
# And don't do this part.  Just don't.  But if you want to...
# git branch -d --force old-master

This will make the config files change to match the renamed branches.

You can also do it the dirty way, which won't update the config files. This is kind of what goes on under the hood of the above...

mv -i .git/refs/new-master .git/refs/master
git checkout master

How to compare two dates in Objective-C

Get Today's Date:

NSDate* date = [NSDate date];

Create a Date From Scratch:    
NSDateComponents* comps = [[NSDateComponents alloc]init];
comps.year = 2015;
comps.month = 12;
comps.day = 31;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* date = [calendar dateFromComponents:comps];


Add a day to a Date:  
NSDate* date = [NSDate date];
NSDateComponents* comps = [[NSDateComponents alloc]init];
comps.day = 1;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* tomorrow = [calendar dateByAddingComponents:comps toDate:date options:nil];


Subtract a day from a Date:    
NSDate* date = [NSDate date];
NSDateComponents* comps = [[NSDateComponents alloc]init];
comps.day = -1;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* yesterday = [calendar dateByAddingComponents:comps toDate:date options:nil];



Convert a Date to a String:  

NSDate* date = [NSDate date];
NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = @"MMMM dd, yyyy";
NSString* dateString = [formatter stringFromDate:date];


Convert a String to a Date:

NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = @"MMMM dd, yyyy";
NSDate* date = [formatter dateFromString:@"August 02, 2014"];


Find how many days are in a month:    
NSDate* date = [NSDate date];
NSCalendar* cal = [NSCalendar currentCalendar];
NSRange currentRange = [cal rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:date];
NSInteger numberOfDays = currentRange.length;


Calculate how much time something took:   

NSDate* start = [NSDate date];
for(int i = 0; i < 1000000000; i++);
NSDate* end = [NSDate date];
NSTimeInterval duration = [end timeIntervalSinceDate:start];


Find the Day Of Week for a specific Date:

NSDate* date = [NSDate date];
NSCalendar* cal = [NSCalendar currentCalendar];
NSInteger dow = [cal ordinalityOfUnit:NSWeekdayCalendarUnit inUnit:NSWeekCalendarUnit forDate:date];

Then use NSComparisonResult to compare date.

Loop through JSON object List

This will work!

$(document).ready(function ()
    {
        $.ajax(
            {
            type: 'POST',
            url: "/Home/MethodName",
            success: function (data) {
                //data is the string that the method returns in a json format, but in string
                var jsonData = JSON.parse(data); //This converts the string to json

                for (var i = 0; i < jsonData.length; i++) //The json object has lenght
                {
                    var object = jsonData[i]; //You are in the current object
                    $('#olListId').append('<li class="someclass>' + object.Atributte  + '</li>'); //now you access the property.

                }

                /* JSON EXAMPLE
                [{ "Atributte": "value" }, 
                { "Atributte": "value" }, 
                { "Atributte": "value" }]
                */
            }
        });
    });

The main thing about this is using the property exactly the same as the attribute of the JSON key-value pair.

Write to file, but overwrite it if it exists

Just noting that if you wish to redirect both stderr and stdout to a file while you have noclobber set (i.e. set -o noclobber), you can use the code:

cmd >| file.txt 2>&1

More information about this can be seen at https://stackoverflow.com/a/876242.

Also this answer's @TuBui's question on the answer @BrDaHa provided above at Aug 9 '18 at 9:34.

Component is not part of any NgModule or the module has not been imported into your module

Verify your component is properly imported in app-routing.module.ts. In my case that was the reason

making a paragraph in html contain a text from a file

You can do something like that in pure html using an <object> tag:
<div><object data="file.txt"></object></div>

This method has some limitations though, like, it won't fit size of the block to the content - you have to specify width and height manually. And styles won't be applied to the text.

Tokenizing strings in C

When reading the strtok documentation, I see you need to pass in a NULL pointer after the first "initializing" call. Maybe you didn't do that. Just a guess of course.

Redefining the Index in a Pandas DataFrame object

Why don't you simply use set_index method?

In : col = ['a','b','c']

In : data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)

In : data
Out:
    a   b   c
0   1   2   3
1  10  11  12
2  20  21  22

In : data2 = data.set_index('a')

In : data2
Out:
     b   c
a
1    2   3
10  11  12
20  21  22

Rock, Paper, Scissors Game Java

Why not check for what the user entered and then ask the user to enter correct input again?

eg:

//Get player's play from input-- note that this is 
// stored as a string 
System.out.println("Enter your play: "); 
response = scan.next();
if(response=="R"||response=="P"||response=="S"){
  personPlay = response;
}else{
  System.out.println("Invaild Input")
}

for the other modifications, please check my total code at pastebin

What is the difference between putting a property on application.yml or bootstrap.yml in spring boot?

I have just asked the Spring Cloud guys and thought I should share the info I have here.

bootstrap.yml is loaded before application.yml.

It is typically used for the following:

  • when using Spring Cloud Config Server, you should specify spring.application.name and spring.cloud.config.server.git.uri inside bootstrap.yml
  • some encryption/decryption information

Technically, bootstrap.yml is loaded by a parent Spring ApplicationContext. That parent ApplicationContext is loaded before the one that uses application.yml.

Android dependency has different version for the compile and runtime

_x000D_
_x000D_
    configurations.all {_x000D_
        resolutionStrategy.force_x000D_
        //"com.android.support:appcompat-v7:25.3.1"_x000D_
        //here put the library that made the error with the version you want to use_x000D_
    }
_x000D_
_x000D_
_x000D_

add this to gradle (project) inside allprojects

TSQL: How to convert local time to UTC? (SQL Server 2008)

While a few of these answers will get you in the ballpark, you cannot do what you're trying to do with arbitrary dates for SqlServer 2005 and earlier because of daylight savings time. Using the difference between the current local and current UTC will give me the offset as it exists today. I have not found a way to determine what the offset would have been for the date in question.

That said, I know that SqlServer 2008 provides some new date functions that may address that issue, but folks using an earlier version need to be aware of the limitations.

Our approach is to persist UTC and perform the conversion on the client side where we have more control over the conversion's accuracy.

What is the meaning of curly braces?

In Python, curly braces are used to define a dictionary.

a={'one':1, 'two':2, 'three':3}
a['one']=1
a['three']=3

In other languages, { } are used as part of the flow control. Python however used indentation as its flow control because of its focus on readable code.

for entry in entries:
     code....

There's a little easter egg in Python when it comes to braces. Try running this on the Python Shell and enjoy.

from __future__ import braces

Calculate distance in meters when you know longitude and latitude in java

You can use the Java Geodesy Library for GPS, it uses the Vincenty's formulae which takes account of the earths surface curvature.

Implementation goes like this:

import org.gavaghan.geodesy.*;

...

GeodeticCalculator geoCalc = new GeodeticCalculator();

Ellipsoid reference = Ellipsoid.WGS84;  

GlobalPosition pointA = new GlobalPosition(latitude, longitude, 0.0); // Point A

GlobalPosition userPos = new GlobalPosition(userLat, userLon, 0.0); // Point B

double distance = geoCalc.calculateGeodeticCurve(reference, userPos, pointA).getEllipsoidalDistance(); // Distance between Point A and Point B

The resulting distance is in meters.

Nginx: Permission denied for nginx on Ubuntu

This works for me,

sudo chmod -R 777 /var/log/nginx

Get JSF managed bean by name in any Servlet related class

I had same requirement.

I have used the below way to get it.

I had session scoped bean.

@ManagedBean(name="mb")
@SessionScopedpublic 
class ManagedBean {
     --------
}

I have used the below code in my servlet doPost() method.

ManagedBean mb = (ManagedBean) request.getSession().getAttribute("mb");

it solved my problem.

What are the -Xms and -Xmx parameters when starting JVM?

The flag Xmx specifies the maximum memory allocation pool for a Java Virtual Machine (JVM), while Xms specifies the initial memory allocation pool.

This means that your JVM will be started with Xms amount of memory and will be able to use a maximum of Xmx amount of memory. For example, starting a JVM like below will start it with 256 MB of memory and will allow the process to use up to 2048 MB of memory:

java -Xms256m -Xmx2048m

The memory flag can also be specified in different sizes, such as kilobytes, megabytes, and so on.

-Xmx1024k
-Xmx512m
-Xmx8g

The Xms flag has no default value, and Xmx typically has a default value of 256 MB. A common use for these flags is when you encounter a java.lang.OutOfMemoryError.

When using these settings, keep in mind that these settings are for the JVM's heap, and that the JVM can and will use more memory than just the size allocated to the heap. From Oracle's documentation:

Note that the JVM uses more memory than just the heap. For example Java methods, thread stacks and native handles are allocated in memory separate from the heap, as well as JVM internal data structures.

count number of rows in a data frame in R based on group

library(plyr)
ddply(data, .(MONTH-YEAR), nrow)

This will give you the answer, if "MONTH-YEAR" is a variable. First, try unique(data$MONTH-YEAR) and see if it returns unique values (no duplicates).

Then above simple split-apply-combine will return what you are looking for.

Return JSON with error status code MVC

A simple way to send a error to Json is control Http Status Code of response object and set a custom error message.

Controller

public JsonResult Create(MyObject myObject) 
{
  //AllFine
  return Json(new { IsCreated = True, Content = ViewGenerator(myObject));

  //Use input may be wrong but nothing crashed
  return Json(new { IsCreated = False, Content = ViewGenerator(myObject));  

  //Error
  Response.StatusCode = (int)HttpStatusCode.InternalServerError;
  return Json(new { IsCreated = false, ErrorMessage = 'My error message');
}

JS

$.ajax({
     type: "POST",
     dataType: "json",
     url: "MyController/Create",
     data: JSON.stringify(myObject),
     success: function (result) {
       if(result.IsCreated)
     {
    //... ALL FINE
     }
     else
     {
    //... Use input may be wrong but nothing crashed
     }
   },
    error: function (error) {
            alert("Error:" + erro.responseJSON.ErrorMessage ); //Error
        }
  });

How can I initialize base class member variables in derived class constructor?

You can't initialize a and b in B because they are not members of B. They are members of A, therefore only A can initialize them. You can make them public, then do assignment in B, but that is not a recommended option since it would destroy encapsulation. Instead, create a constructor in A to allow B (or any subclass of A) to initialize them:

class A 
{
protected:
    A(int a, int b) : a(a), b(b) {} // Accessible to derived classes
    // Change "protected" to "public" to allow others to instantiate A.
private:
    int a, b; // Keep these variables private in A
};

class B : public A 
{
public:
    B() : A(0, 0) // Calls A's constructor, initializing a and b in A to 0.
    {
    } 
};

how to make div click-able?

<div style="cursor: pointer;" onclick="theFunction()" onmouseover="this.style.background='red'" onmouseout="this.style.background=''" ><span>shanghai</span><span>male</span></div>

This will change the background color as well

How to use ArgumentCaptor for stubbing?

Hypothetically, if search landed you on this question then you probably want this:

doReturn(someReturn).when(someObject).doSomething(argThat(argument -> argument.getName().equals("Bob")));

Why? Because like me you value time and you are not going to implement .equals just for the sake of the single test scenario.

And 99 % of tests fall apart with null returned from Mock and in a reasonable design you would avoid return null at all costs, use Optional or move to Kotlin. This implies that verify does not need to be used that often and ArgumentCaptors are just too tedious to write.

Update Query with INNER JOIN between tables in 2 different databases on 1 server

//For Access Database:
UPDATE ((tblEmployee
LEFT JOIN tblCity ON (tblEmployee.CityCode = tblCity.CityCode))
LEFT JOIN tblCountry ON (tblEmployee.CountryCode = tblCountryCode))
SET tblEmployee.CityName = tblCity.CityName, 
tblEmployee.CountryName = tblCountry.CountryName
WHERE (tblEmployee.CityName = '' OR tblEmployee.CountryName = '')

What is __future__ in Python used for and how/when to use it, and how it works

After Python 3.0 onward, print is no longer just a statement, its a function instead. and is included in PEP 3105.

Also I think the Python 3.0 package has still these special functionality. Lets see its usability through a traditional "Pyramid program" in Python:

from __future__ import print_function

class Star(object):
    def __init__(self,count):
        self.count = count

    def start(self):
        for i in range(1,self.count):
            for j in range (i): 
                print('*', end='') # PEP 3105: print As a Function 
            print()

a = Star(5)
a.start()

Output:
*
**
***
****

If we use normal print function, we won't be able to achieve the same output, since print() comes with a extra newline. So every time the inner for loop execute, it will print * onto the next line.

Switch statement multiple cases in JavaScript

My situation was something akin to:

switch (text) {
  case SOME_CONSTANT || ANOTHER_CONSTANT:
    console.log('Case 1 entered');

  break;

  case THIRD_CONSTANT || FINAL_CONSTANT:
    console.log('Case 2 entered');

  break;

  default:
    console.log('Default entered');
}

The default case always entered. If you're running into a similar multi-case switch statement issue, you're looking for this:

switch (text) {
  case SOME_CONSTANT:
  case ANOTHER_CONSTANT:
    console.log('Case 1 entered');

  break;

  case THIRD_CONSTANT:
  case FINAL_CONSTANT:
    console.log('Case 2 entered');

  break;

  default:
    console.log('Default entered');
}

How to secure database passwords in PHP?

If you're hosting on someone else's server and don't have access outside your webroot, you can always put your password and/or database connection in a file and then lock the file using a .htaccess:

<files mypasswdfile>
order allow,deny
deny from all
</files>

Using async/await for multiple tasks

I was curious to see the results of the methods provided in the question as well as the accepted answer, so I put it to the test.

Here's the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace AsyncTest
{
    class Program
    {
        class Worker
        {
            public int Id;
            public int SleepTimeout;

            public async Task DoWork(DateTime testStart)
            {
                var workerStart = DateTime.Now;
                Console.WriteLine("Worker {0} started on thread {1}, beginning {2} seconds after test start.",
                    Id, Thread.CurrentThread.ManagedThreadId, (workerStart-testStart).TotalSeconds.ToString("F2"));
                await Task.Run(() => Thread.Sleep(SleepTimeout));
                var workerEnd = DateTime.Now;
                Console.WriteLine("Worker {0} stopped; the worker took {1} seconds, and it finished {2} seconds after the test start.",
                   Id, (workerEnd-workerStart).TotalSeconds.ToString("F2"), (workerEnd-testStart).TotalSeconds.ToString("F2"));
            }
        }

        static void Main(string[] args)
        {
            var workers = new List<Worker>
            {
                new Worker { Id = 1, SleepTimeout = 1000 },
                new Worker { Id = 2, SleepTimeout = 2000 },
                new Worker { Id = 3, SleepTimeout = 3000 },
                new Worker { Id = 4, SleepTimeout = 4000 },
                new Worker { Id = 5, SleepTimeout = 5000 },
            };

            var startTime = DateTime.Now;
            Console.WriteLine("Starting test: Parallel.ForEach...");
            PerformTest_ParallelForEach(workers, startTime);
            var endTime = DateTime.Now;
            Console.WriteLine("Test finished after {0} seconds.\n",
                (endTime - startTime).TotalSeconds.ToString("F2"));

            startTime = DateTime.Now;
            Console.WriteLine("Starting test: Task.WaitAll...");
            PerformTest_TaskWaitAll(workers, startTime);
            endTime = DateTime.Now;
            Console.WriteLine("Test finished after {0} seconds.\n",
                (endTime - startTime).TotalSeconds.ToString("F2"));

            startTime = DateTime.Now;
            Console.WriteLine("Starting test: Task.WhenAll...");
            var task = PerformTest_TaskWhenAll(workers, startTime);
            task.Wait();
            endTime = DateTime.Now;
            Console.WriteLine("Test finished after {0} seconds.\n",
                (endTime - startTime).TotalSeconds.ToString("F2"));

            Console.ReadKey();
        }

        static void PerformTest_ParallelForEach(List<Worker> workers, DateTime testStart)
        {
            Parallel.ForEach(workers, worker => worker.DoWork(testStart).Wait());
        }

        static void PerformTest_TaskWaitAll(List<Worker> workers, DateTime testStart)
        {
            Task.WaitAll(workers.Select(worker => worker.DoWork(testStart)).ToArray());
        }

        static Task PerformTest_TaskWhenAll(List<Worker> workers, DateTime testStart)
        {
            return Task.WhenAll(workers.Select(worker => worker.DoWork(testStart)));
        }
    }
}

And the resulting output:

Starting test: Parallel.ForEach...
Worker 1 started on thread 1, beginning 0.21 seconds after test start.
Worker 4 started on thread 5, beginning 0.21 seconds after test start.
Worker 2 started on thread 3, beginning 0.21 seconds after test start.
Worker 5 started on thread 6, beginning 0.21 seconds after test start.
Worker 3 started on thread 4, beginning 0.21 seconds after test start.
Worker 1 stopped; the worker took 1.90 seconds, and it finished 2.11 seconds after the test start.
Worker 2 stopped; the worker took 3.89 seconds, and it finished 4.10 seconds after the test start.
Worker 3 stopped; the worker took 5.89 seconds, and it finished 6.10 seconds after the test start.
Worker 4 stopped; the worker took 5.90 seconds, and it finished 6.11 seconds after the test start.
Worker 5 stopped; the worker took 8.89 seconds, and it finished 9.10 seconds after the test start.
Test finished after 9.10 seconds.

Starting test: Task.WaitAll...
Worker 1 started on thread 1, beginning 0.01 seconds after test start.
Worker 2 started on thread 1, beginning 0.01 seconds after test start.
Worker 3 started on thread 1, beginning 0.01 seconds after test start.
Worker 4 started on thread 1, beginning 0.01 seconds after test start.
Worker 5 started on thread 1, beginning 0.01 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.01 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.01 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.01 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.01 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.01 seconds after the test start.
Test finished after 5.01 seconds.

Starting test: Task.WhenAll...
Worker 1 started on thread 1, beginning 0.00 seconds after test start.
Worker 2 started on thread 1, beginning 0.00 seconds after test start.
Worker 3 started on thread 1, beginning 0.00 seconds after test start.
Worker 4 started on thread 1, beginning 0.00 seconds after test start.
Worker 5 started on thread 1, beginning 0.00 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.00 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.00 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.00 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.00 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.00 seconds after the test start.
Test finished after 5.00 seconds.

iOS Safari – How to disable overscroll but allow scrollable divs to scroll normally?

First prevent default actions on your entire document as usual:

$(document).bind('touchmove', function(e){
  e.preventDefault();           
});

Then stop your class of elements from propagating to the document level. This stops it from reaching the function above and thus e.preventDefault() is not initiated:

$('.scrollable').bind('touchmove', function(e){
  e.stopPropagation();
});

This system seems to be more natural and less intensive than calculating the class on all touch moves. Use .on() rather than .bind() for dynamically generated elements.

Also consider these meta tags to prevent unfortunate things from happening while using your scrollable div:

<meta content='True' name='HandheldFriendly' />
<meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0' name='viewport' />
<meta name="viewport" content="width=device-width" />

Using a bitmask in C#

I have included an example here which demonstrates how you might store the mask in a database column as an int, and how you would reinstate the mask later on:

public enum DaysBitMask { Mon=0, Tues=1, Wed=2, Thu = 4, Fri = 8, Sat = 16, Sun = 32 }


DaysBitMask mask = DaysBitMask.Sat | DaysBitMask.Thu;
bool test;
if ((mask & DaysBitMask.Sat) == DaysBitMask.Sat)
    test = true;
if ((mask & DaysBitMask.Thu) == DaysBitMask.Thu)
    test = true;
if ((mask & DaysBitMask.Wed) != DaysBitMask.Wed)
    test = true;

// Store the value
int storedVal = (int)mask;

// Reinstate the mask and re-test
DaysBitMask reHydratedMask = (DaysBitMask)storedVal;

if ((reHydratedMask & DaysBitMask.Sat) == DaysBitMask.Sat)
    test = true;
if ((reHydratedMask & DaysBitMask.Thu) == DaysBitMask.Thu)
    test = true;
if ((reHydratedMask & DaysBitMask.Wed) != DaysBitMask.Wed)
    test = true;

Extract the filename from a path

Use :

[System.IO.Path]::GetFileName("c:\foo.txt") returns foo.txt. [System.IO.Path]::GetFileNameWithoutExtension("c:\foo.txt") returns foo

Flask raises TemplateNotFound error even though template file exists

You must create your template files in the correct location; in the templates subdirectory next to the python module (== the module where you create your Flask app).

The error indicates that there is no home.html file in the templates/ directory. Make sure you created that directory in the same directory as your python module, and that you did in fact put a home.html file in that subdirectory. If your app is a package, the templates folder should be created inside the package.

myproject/
    app.py
    templates/
        home.html
myproject/
    mypackage/
        __init__.py
        templates/
            home.html

Alternatively, if you named your templates folder something other than templates and don't want to rename it to the default, you can tell Flask to use that other directory.

app = Flask(__name__, template_folder='template')  # still relative to module

You can ask Flask to explain how it tried to find a given template, by setting the EXPLAIN_TEMPLATE_LOADING option to True. For every template loaded, you'll get a report logged to the Flask app.logger, at level INFO.

This is what it looks like when a search is successful; in this example the foo/bar.html template extends the base.html template, so there are two searches:

[2019-06-15 16:03:39,197] INFO in debughelpers: Locating template "foo/bar.html":
    1: trying loader of application "flaskpackagename"
       class: jinja2.loaders.FileSystemLoader
       encoding: 'utf-8'
       followlinks: False
       searchpath:
         - /.../project/flaskpackagename/templates
       -> found ('/.../project/flaskpackagename/templates/foo/bar.html')
[2019-06-15 16:03:39,203] INFO in debughelpers: Locating template "base.html":
    1: trying loader of application "flaskpackagename"
       class: jinja2.loaders.FileSystemLoader
       encoding: 'utf-8'
       followlinks: False
       searchpath:
         - /.../project/flaskpackagename/templates
       -> found ('/.../project/flaskpackagename/templates/base.html')

Blueprints can register their own template directories too, but this is not a requirement if you are using blueprints to make it easier to split a larger project across logical units. The main Flask app template directory is always searched first even when using additional paths per blueprint.

Python 3: UnboundLocalError: local variable referenced before assignment

Why not simply return your calculated value and let the caller modify the global variable. It's not a good idea to manipulate a global variable within a function, as below:

Var1 = 1
Var2 = 0

def function(): 
    if Var2 == 0 and Var1 > 0:
        print("Result One")
    elif Var2 == 1 and Var1 > 0:
        print("Result Two")
    elif Var1 < 1:
        print("Result Three")
    return Var1 - 1

Var1 = function()

or even make local copies of the global variables and work with them and return the results which the caller can then assign appropriately

def function():
v1, v2 = Var1, Var2
# calculate using the local variables v1 & v2
return v1 - 1

Var1 = function()

Is there a better way to iterate over two lists, getting one element from each list for each iteration?

in case your Latitude and Longitude lists are large and lazily loaded:

from itertools import izip
for lat, lon in izip(latitudes, longitudes):
    process(lat, lon)

or if you want to avoid the for-loop

from itertools import izip, imap
out = imap(process, izip(latitudes, longitudes))

mongo - couldn't connect to server 127.0.0.1:27017

This work me:-

In Mongo 3.2 for window, you should start Mongodb service. So, run the Command Prompt as Administrator then net start MongoDB

xcode-select active developer directory error

None of the above worked for me. I originally installed Command Line Tools separately, and then all of Xcode. What worked for me was to uninstall Command Line Tools as shown here. Then, when trying to run xcode-select again, I was asked to reinstall them.

*By the way, the very reason why I found this thread was because I had installed some libraries (particularly gcc) with macports, presumably using the old Command Line Tools, and then I installed the full Xcode midway into development. So anyways, for my case, I had to reinstall macports after removing the stand-alone Command Line Tools, reinstalling them, reinstalling gcc, and then my compilation worked.

VBA macro that search for file in multiple subfolders

If this helps, you can also use FileSystemObject to retrieve all subfolders of a folder. You need to check the reference "Microsot Scripting Runtime" to get Intellisense and use the "new" keyword.

Sub GetSubFolders()

    Dim fso As New FileSystemObject
    Dim f As Folder, sf As Folder

    Set f = fso.GetFolder("D:\Proj\")
    For Each sf In f.SubFolders
        'Code inside
    Next

End Sub

Convert ArrayList to String array in Android

Well in general:

List<String> names = new ArrayList<String>();
names.add("john");
names.add("ann");

String[] namesArr = new String[names.size()];
for (int i = 0; i < names.size(); i++) {
    namesArr[i] = names.get(i);  
}

Or better yet, using built in:

List<String> names = new ArrayList<String>();
String[] namesArr = names.toArray(new String[names.size()]);

How to invoke bash, run commands inside the new shell, and then give control back to user?

The accepted answer is really helpful! Just to add that process substitution (i.e., <(COMMAND)) is not supported in some shells (e.g., dash).

In my case, I was trying to create a custom action (basically a one-line shell script) in Thunar file manager to start a shell and activate the selected Python virtual environment. My first attempt was:

urxvt -e bash --rcfile <(echo ". $HOME/.bashrc; . %f/bin/activate;")

where %f is the path to the virtual environment handled by Thunar. I got an error (by running Thunar from command line):

/bin/sh: 1: Syntax error: "(" unexpected

Then I realized that my sh (essentially dash) does not support process substitution.

My solution was to invoke bash at the top level to interpret the process substitution, at the expense of an extra level of shell:

bash -c 'urxvt -e bash --rcfile <(echo "source $HOME/.bashrc; source %f/bin/activate;")'

Alternatively, I tried to use here-document for dash but with no success. Something like:

echo -e " <<EOF\n. $HOME/.bashrc; . %f/bin/activate;\nEOF\n" | xargs -0 urxvt -e bash --rcfile

P.S.: I do not have enough reputation to post comments, moderators please feel free to move it to comments or remove it if not helpful with this question.

phpmyadmin - count(): Parameter must be an array or an object that implements Countable

Ubuntu 18.10 (December, 2018)

Line 613, 614, 615, replace with:

        || count($analyzed_sql_results['select_expr']) == 1
            && ($analyzed_sql_results['select_expr'][0] == '*'))
    && count($analyzed_sql_results['select_tables']) == 1;

How to Use Order By for Multiple Columns in Laravel 4?

Use order by like this:

return User::orderBy('name', 'DESC')
    ->orderBy('surname', 'DESC')
    ->orderBy('email', 'DESC')
    ...
    ->get();

How to state in requirements.txt a direct github source

requirements.txt allows the following ways of specifying a dependency on a package in a git repository as of pip 7.0:1

[-e] git+git://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+https://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+ssh://git.myproject.org/SomeProject#egg=SomeProject
-e [email protected]:SomeProject#egg=SomeProject (deprecated as of Jan 2020)

For Github that means you can do (notice the omitted -e):

git+git://github.com/mozilla/elasticutils.git#egg=elasticutils

Why the extra answer?
I got somewhat confused by the -e flag in the other answers so here's my clarification:

The -e or --editable flag means that the package is installed in <venv path>/src/SomeProject and thus not in the deeply buried <venv path>/lib/pythonX.X/site-packages/SomeProject it would otherwise be placed in.2

Documentation

Jquery click not working with ipad

I found that when I made my binding more specific, it began to work on iOS. I had:

$(document).on('click tap', 'span.clickable', function(e){ ... });

When I changed it to:

$("div.content").on('click tap', 'span.clickable', function(e){ ... });

iOS began responding.

Why does JPA have a @Transient annotation?

For Kotlin developers, remember the Java transient keyword becomes the built-in Kotlin @Transient annotation. Therefore, make sure you have the JPA import if you're using JPA @Transient in your entity:

import javax.persistence.Transient

Round up to Second Decimal Place in Python

x = math.ceil(x * 100.0) / 100.0

Shell Script — Get all files modified after <date>

This will work for some number of files. You want to include "-print0" and "xargs -0" in case any of the paths have spaces in them. This example looks for files modified in the last 7 days. To find those modified before the last 7 days, use "+7".

find . -mtime -7 -print0 | xargs -0 tar -cjf /foo/archive.tar.bz2

As this page warns, xargs can cause the tar command to be executed multiple times if there are a lot of arguments, and the "-c" flag could cause problems. In that case, you would want this:

find . -mtime -7 -print0 | xargs -0 tar -rf /foo/archive.tar

You can't update a zipped tar archive with tar, so you would have to bzip2 or gzip it in a second step.

Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?

I think create a custom EditorTemplate is not good solution, beause you need to care about many possible tepmlates for different cases: strings, numsers, comboboxes and so on. Other solution is custom extention to HtmlHelper.

Model:

public class MyViewModel
{
    [PlaceHolder("Enter title here")]
    public string Title { get; set; }
}

Html helper extension:

   public static MvcHtmlString BsEditorFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TValue>> expression, string htmlClass = "")
{
    var modelMetadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
    var metadata = modelMetadata;

    var viewData = new
    {
        HtmlAttributes = new
            {
                @class = htmlClass,
                placeholder = metadata.Watermark,
            }
    };
    return htmlHelper.EditorFor(expression, viewData);

}

A corresponding view:

@Html.BsEditorFor(x => x.Title)

Using jQuery to build table rows from AJAX response(json)

Data as JSON:

data = [
       {
       "rank":"9",
       "content":"Alon",
       "UID":"5"
       },
       {
       "rank":"6",
       "content":"Tala",
       "UID":"6"
       }
       ]

You can use jQuery to iterate over JSON and create tables dynamically:

num_rows = data.length;
num_cols = size_of_array(data[0]);

table_id = 'my_table';
table = $("<table id=" + table_id + "></table>");

header = $("<tr class='table_header'></tr>");
$.each(Object.keys(data[0]), function(ind_header, val_header) {
col = $("<td>" + val_header + "</td>");
header.append(col);
})
table.append(header);

$.each(data, function(ind_row, val) {
row = $("<tr></tr>");
$.each(val, function(ind_cell, val_cell) {
col = $("<td>" + val_cell + "</td>");
row.append(col);
})
table.append(row);
})

Here is the size_of_array function:

function size_of_array(obj) {
    size = Object.keys(obj).length;
    return(size)
    };

You can also add styling if needed:

$('.' + content['this_class']).children('canvas').remove();
$('.' + content['this_class']).append(table);
$('#' + table_id).css('width', '100%').css('border', '1px solid black').css('text-align', 'center').css('border-collapse', 'collapse');
$('#' + table_id + ' td').css('border', '1px solid black');

Result:

enter image description here

How to catch and print the full exception traceback without halting/exiting the program?

I don't see this mentioned in any of the other answers. If you're passing around an Exception object for whatever reason...

In Python 3.5+ you can get a trace from an Exception object using traceback.TracebackException.from_exception(). For example:

import traceback


def stack_lvl_3():
    raise Exception('a1', 'b2', 'c3')


def stack_lvl_2():
    try:
        stack_lvl_3()
    except Exception as e:
        # raise
        return e


def stack_lvl_1():
    e = stack_lvl_2()
    return e

e = stack_lvl_1()

tb1 = traceback.TracebackException.from_exception(e)
print(''.join(tb1.format()))

However, the above code results in:

Traceback (most recent call last):
  File "exc.py", line 10, in stack_lvl_2
    stack_lvl_3()
  File "exc.py", line 5, in stack_lvl_3
    raise Exception('a1', 'b2', 'c3')
Exception: ('a1', 'b2', 'c3')

This is just two levels of the stack, as opposed to what would have been printed on screen had the exception been raised in stack_lvl_2() and not intercepted (uncomment the # raise line).

As I understand it, that's because an exception records only the current level of the stack when it is raised, stack_lvl_3() in this case. As it's passed back up through the stack, more levels are being added to its __traceback__. But we intercepted it in stack_lvl_2(), meaning all it got to record was levels 3 and 2. To get the full trace as printed on stdout we'd have to catch it at the highest (lowest?) level:

import traceback


def stack_lvl_3():
    raise Exception('a1', 'b2', 'c3')


def stack_lvl_2():
    stack_lvl_3()


def stack_lvl_1():
    stack_lvl_2()


try:
    stack_lvl_1()
except Exception as exc:
    tb = traceback.TracebackException.from_exception(exc)

print('Handled at stack lvl 0')
print(''.join(tb.stack.format()))

Which results in:

Handled at stack lvl 0
  File "exc.py", line 17, in <module>
    stack_lvl_1()
  File "exc.py", line 13, in stack_lvl_1
    stack_lvl_2()
  File "exc.py", line 9, in stack_lvl_2
    stack_lvl_3()
  File "exc.py", line 5, in stack_lvl_3
    raise Exception('a1', 'b2', 'c3')

Notice that the stack print is different, the first and last lines are missing. Because it's a different format().

Intercepting the exception as far away from the point where it was raised as possible makes for simpler code while also giving more information.

How can I upload files asynchronously?

This AJAX file upload jQuery plugin uploads the file somehwere, and passes the response to a callback, nothing else.

  • It does not depend on specific HTML, just give it a <input type="file">
  • It does not require your server to respond in any particular way
  • It does not matter how many files you use, or where they are on the page

-- Use as little as --

$('#one-specific-file').ajaxfileupload({
  'action': '/upload.php'
});

-- or as much as --

$('input[type="file"]').ajaxfileupload({
  'action': '/upload.php',
  'params': {
    'extra': 'info'
  },
  'onComplete': function(response) {
    console.log('custom handler for file:');
    alert(JSON.stringify(response));
  },
  'onStart': function() {
    if(weWantedTo) return false; // cancels upload
  },
  'onCancel': function() {
    console.log('no file selected');
  }
});

How to increment a letter N times per iteration and store in an array?

Here is your solution for the problem,

$letter = array();
for ($i = 'A'; $i !== 'ZZ'; $i++){
        if(ord($i) % 2 != 0)
           $letter[] .= $i;
}
print_r($letter);

You need to get the ASCII value for that character which will solve your problem.

Here is ord doc and working code.

For your requirement, you can do like this,

for ($i = 'A'; $i !== 'ZZ'; ord($i)+$x){
  $letter[] .= $i;
}
print_r($letter);

Here set $x as per your requirement.

How to use a keypress event in AngularJS?

I'm a bit late .. but i found a simpler solution using auto-focus .. This could be useful for buttons or other when popping a dialog :

<button auto-focus ng-click="func()">ok</button>

That should be fine if you want to press the button onSpace or Enter clicks .

C# Return Different Types?

It's a sample using Generic Types.

public T GetAnything<T>() where T : class, new()
    => new T();

And you'll use this method calling this way:

var hello = GetAnything<Hello>();

In this case, you can use an interface to specify a type to pass as parameter.

public T GetAnything<T>() where T : ISomeInterface, new()
    => new T();

You must have a parameterless construtor in each class to use new() constraint.

Follow the full sample:

internal sealed class Program
{
    private static void Main(string[] args)
    {
        GetAnything<Hello>().Play();
        GetAnything<Radio>().Play();
        GetAnything<Computer>().Play();
    }

    private static T GetAnything<T>() where T : ISomeInterface, new()
        => new T();
}

internal interface ISomeInterface
{
    void Play();
}

internal sealed class Hello : ISomeInterface
{
    // parameterless constructor.
    public Hello() { }
    public void Play() => Console.WriteLine("Saying hello!");
}

internal sealed class Radio : ISomeInterface
{
    // parameterless constructor.
    public Radio() { }
    public void Play() => Console.WriteLine("Playing radio!");
}

internal sealed class Computer : ISomeInterface
{
    // parameterless constructor.
    public Computer() { }
    public void Play() => Console.WriteLine("Playing from computer!");
}

How do I list all the files in a directory and subdirectories in reverse chronological order?

try this:

ls -ltraR |egrep -v '\.$|\.\.|\.:|\.\/|total' |sed '/^$/d'

How do I execute a program from Python? os.system fails due to spaces in path

I suspect it's the same problem as when you use shortcuts in Windows... Try this:

import os;
os.system("\"C:\\Temp\\a b c\\Notepad.exe\" C:\\test.txt");

What is the difference between null=True and blank=True in Django?

When we save anything in Django admin two steps validation happens, on Django level and on Database level. We can't save text in a number field.

Database has data type NULL, it's nothing. When Django creates columns in the database it specifies that they can't be empty. And if you will try to save NULL you will get the database error.

Also on Django-Admin level, all fields are required by default, you can't save blank field, Django will throw you an error.

So, if you want to save blank field you need to allow it on Django and Database level. blank=True - will allow empty field in admin panel null=True - will allow saving NULL to the database column.

How to get all registered routes in Express?

Express 4

Given an Express 4 configuration with endpoints and nested routers

const express = require('express')
const app = express()
const router = express.Router()

app.get(...)
app.post(...)

router.use(...)
router.get(...)
router.post(...)

app.use(router)

Expanding the @caleb answer it is possible to obtain all routes recursively and sorted.

getRoutes(app._router && app._router.stack)
// =>
// [
//     [ 'GET', '/'], 
//     [ 'POST', '/auth'],
//     ...
// ]

/**
* Converts Express 4 app routes to an array representation suitable for easy parsing.
* @arg {Array} stack An Express 4 application middleware list.
* @returns {Array} An array representation of the routes in the form [ [ 'GET', '/path' ], ... ].
*/
function getRoutes(stack) {
        const routes = (stack || [])
                // We are interested only in endpoints and router middleware.
                .filter(it => it.route || it.name === 'router')
                // The magic recursive conversion.
                .reduce((result, it) => {
                        if (! it.route) {
                                // We are handling a router middleware.
                                const stack = it.handle.stack
                                const routes = getRoutes(stack)

                                return result.concat(routes)
                        }

                        // We are handling an endpoint.
                        const methods = it.route.methods
                        const path = it.route.path

                        const routes = Object
                                .keys(methods)
                                .map(m => [ m.toUpperCase(), path ])

                        return result.concat(routes)
                }, [])
                // We sort the data structure by route path.
                .sort((prev, next) => {
                        const [ prevMethod, prevPath ] = prev
                        const [ nextMethod, nextPath ] = next

                        if (prevPath < nextPath) {
                                return -1
                        }

                        if (prevPath > nextPath) {
                                return 1
                        }

                        return 0
                })

        return routes
}

For basic string output.

infoAboutRoutes(app)

Console output

/**
* Converts Express 4 app routes to a string representation suitable for console output.
* @arg {Object} app An Express 4 application
* @returns {string} A string representation of the routes.
*/
function infoAboutRoutes(app) {
        const entryPoint = app._router && app._router.stack
        const routes = getRoutes(entryPoint)

        const info = routes
                .reduce((result, it) => {
                        const [ method, path ] = it

                        return result + `${method.padEnd(6)} ${path}\n`
                }, '')

        return info
}

Update 1:

Due to the internal limitations of Express 4 it is not possible to retrieve mounted app and mounted routers. For example it is not possible to obtain routes from this configuration.

const subApp = express()
app.use('/sub/app', subApp)

const subRouter = express.Router()
app.use('/sub/route', subRouter)

Replacing .NET WebBrowser control with a better browser, like Chrome?

I had the same problem, the WebBrowser was using an old version of IE, with some googling I came across the following code that makes a change into registry and makes the WebBrowser to use the lastest IE version possible:

 public enum BrowserEmulationVersion
    {
        Default = 0,
        Version7 = 7000,
        Version8 = 8000,
        Version8Standards = 8888,
        Version9 = 9000,
        Version9Standards = 9999,
        Version10 = 10000,
        Version10Standards = 10001,
        Version11 = 11000,
        Version11Edge = 11001
    }
    public static class WBEmulator
    {
        private const string InternetExplorerRootKey = @"Software\Microsoft\Internet Explorer";

        public static int GetInternetExplorerMajorVersion()
        {
            int result;

            result = 0;

            try
            {
                RegistryKey key;

                key = Registry.LocalMachine.OpenSubKey(InternetExplorerRootKey);

                if (key != null)
                {
                    object value;

                    value = key.GetValue("svcVersion", null) ?? key.GetValue("Version", null);

                    if (value != null)
                    {
                        string version;
                        int separator;

                        version = value.ToString();
                        separator = version.IndexOf('.');
                        if (separator != -1)
                        {
                            int.TryParse(version.Substring(0, separator), out result);
                        }
                    }
                }
            }
            catch (SecurityException)
            {
                // The user does not have the permissions required to read from the registry key.
            }
            catch (UnauthorizedAccessException)
            {
                // The user does not have the necessary registry rights.
            }

            return result;
        }
        private const string BrowserEmulationKey = InternetExplorerRootKey + @"\Main\FeatureControl\FEATURE_BROWSER_EMULATION";

        public static BrowserEmulationVersion GetBrowserEmulationVersion()
        {
            BrowserEmulationVersion result;

            result = BrowserEmulationVersion.Default;

            try
            {
                RegistryKey key;

                key = Registry.CurrentUser.OpenSubKey(BrowserEmulationKey, true);
                if (key != null)
                {
                    string programName;
                    object value;

                    programName = Path.GetFileName(Environment.GetCommandLineArgs()[0]);
                    value = key.GetValue(programName, null);

                    if (value != null)
                    {
                        result = (BrowserEmulationVersion)Convert.ToInt32(value);
                    }
                }
            }
            catch (SecurityException)
            {
                // The user does not have the permissions required to read from the registry key.
            }
            catch (UnauthorizedAccessException)
            {
                // The user does not have the necessary registry rights.
            }

            return result;
        }
        public static bool SetBrowserEmulationVersion(BrowserEmulationVersion browserEmulationVersion)
        {
            bool result;

            result = false;

            try
            {
                RegistryKey key;

                key = Registry.CurrentUser.OpenSubKey(BrowserEmulationKey, true);

                if (key != null)
                {
                    string programName;

                    programName = Path.GetFileName(Environment.GetCommandLineArgs()[0]);

                    if (browserEmulationVersion != BrowserEmulationVersion.Default)
                    {
                        // if it's a valid value, update or create the value
                        key.SetValue(programName, (int)browserEmulationVersion, RegistryValueKind.DWord);
                    }
                    else
                    {
                        // otherwise, remove the existing value
                        key.DeleteValue(programName, false);
                    }

                    result = true;
                }
            }
            catch (SecurityException)
            {
                // The user does not have the permissions required to read from the registry key.
            }
            catch (UnauthorizedAccessException)
            {
                // The user does not have the necessary registry rights.
            }

            return result;
        }

        public static bool SetBrowserEmulationVersion()
        {
            int ieVersion;
            BrowserEmulationVersion emulationCode;

            ieVersion = GetInternetExplorerMajorVersion();

            if (ieVersion >= 11)
            {
                emulationCode = BrowserEmulationVersion.Version11;
            }
            else
            {
                switch (ieVersion)
                {
                    case 10:
                        emulationCode = BrowserEmulationVersion.Version10;
                        break;
                    case 9:
                        emulationCode = BrowserEmulationVersion.Version9;
                        break;
                    case 8:
                        emulationCode = BrowserEmulationVersion.Version8;
                        break;
                    default:
                        emulationCode = BrowserEmulationVersion.Version7;
                        break;
                }
            }

            return SetBrowserEmulationVersion(emulationCode);
        }
        public static bool IsBrowserEmulationSet()
        {
            return GetBrowserEmulationVersion() != BrowserEmulationVersion.Default;
        }
    } 

You just need to create a class and put this code in it, then run the following code when the program starts:

 if (!WBEmulator.IsBrowserEmulationSet())
            {
                WBEmulator.SetBrowserEmulationVersion();
            }

VB.NET:

Imports Microsoft.Win32
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Imports System.Security
Imports System.Text
Imports System.Threading.Tasks

Public Enum BrowserEmulationVersion
    [Default] = 0
    Version7 = 7000
    Version8 = 8000
    Version8Standards = 8888
    Version9 = 9000
    Version9Standards = 9999
    Version10 = 10000
    Version10Standards = 10001
    Version11 = 11000
    Version11Edge = 11001
End Enum


Public Class WBEmulator
    Private Const InternetExplorerRootKey As String = "Software\Microsoft\Internet Explorer"
    Public Shared Function GetInternetExplorerMajorVersion() As Integer

        Dim result As Integer

        result = 0

        Try
            Dim key As RegistryKey
            key = Registry.LocalMachine.OpenSubKey(InternetExplorerRootKey)
            If key IsNot Nothing Then
                Dim value As Object = If(key.GetValue("svcVersion", Nothing), key.GetValue("Version", Nothing))

                Dim Version As String
                Dim separator As Integer
                Version = value.ToString()
                separator = Version.IndexOf(".")
                If separator <> -1 Then
                    Integer.TryParse(Version.Substring(0, separator), result)
                End If
            End If

        Catch ex As SecurityException
            'The user does Not have the permissions required to read from the registry key.
        Catch ex As UnauthorizedAccessException
            'The user does Not have the necessary registry rights.
        Catch

        End Try
        GetInternetExplorerMajorVersion = result
    End Function
    Private Const BrowserEmulationKey = InternetExplorerRootKey + "\Main\FeatureControl\FEATURE_BROWSER_EMULATION"

    Public Shared Function GetBrowserEmulationVersion() As BrowserEmulationVersion

        Dim result As BrowserEmulationVersion
        result = BrowserEmulationVersion.Default

        Try
            Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(BrowserEmulationKey, True)
            If key IsNot Nothing Then
                Dim programName As String
                Dim value As Object
                programName = Path.GetFileName(Environment.GetCommandLineArgs()(0))
                value = key.GetValue(programName, Nothing)
                If value IsNot Nothing Then
                    result = CType(Convert.ToInt32(value), BrowserEmulationVersion)
                End If
            End If
        Catch ex As SecurityException
            'The user does Not have the permissions required to read from the registry key.
        Catch ex As UnauthorizedAccessException
            'The user does Not have the necessary registry rights.
        Catch

        End Try

        GetBrowserEmulationVersion = result
    End Function
    Public Shared Function SetBrowserEmulationVersion(BEVersion As BrowserEmulationVersion) As Boolean

        Dim result As Boolean = False

        Try
            Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(BrowserEmulationKey, True)
            If key IsNot Nothing Then
                Dim programName As String = Path.GetFileName(Environment.GetCommandLineArgs()(0))
                If BEVersion <> BrowserEmulationVersion.Default Then
                    'if it's a valid value, update or create the value
                    key.SetValue(programName, CType(BEVersion, Integer), RegistryValueKind.DWord)
                Else
                    'otherwise, remove the existing value
                    key.DeleteValue(programName, False)
                End If
                result = True
            End If
        Catch ex As SecurityException

            ' The user does Not have the permissions required to read from the registry key.

        Catch ex As UnauthorizedAccessException

            ' The user does Not have the necessary registry rights.

        End Try

        SetBrowserEmulationVersion = result
    End Function


    Public Shared Function SetBrowserEmulationVersion() As Boolean
        Dim ieVersion As Integer
        Dim emulationCode As BrowserEmulationVersion
        ieVersion = GetInternetExplorerMajorVersion()

        If ieVersion >= 11 Then

            emulationCode = BrowserEmulationVersion.Version11
        Else

            Select Case ieVersion
                Case 10
                    emulationCode = BrowserEmulationVersion.Version10
                Case 9
                    emulationCode = BrowserEmulationVersion.Version9
                Case 8
                    emulationCode = BrowserEmulationVersion.Version8
                Case Else
                    emulationCode = BrowserEmulationVersion.Version7
            End Select
        End If

        SetBrowserEmulationVersion = SetBrowserEmulationVersion(emulationCode)
    End Function

    Public Shared Function IsBrowserEmulationSet() As Boolean
        IsBrowserEmulationSet = GetBrowserEmulationVersion() <> BrowserEmulationVersion.Default
    End Function
End Class

You may use it like:

If Not WBEmulator.IsBrowserEmulationSet() Then
    WBEmulator.SetBrowserEmulationVersion()
End If

BackgroundWorker vs background Thread

Also you are tying up a threadpool thread for the lifetime of the background worker, which may be of concern as there are only a finite number of them. I would say that if you are only ever creating the thread once for your app (and not using any of the features of background worker) then use a thread, rather than a backgroundworker/threadpool thread.

Invalid length parameter passed to the LEFT or SUBSTRING function

CHARINDEX will return 0 if no spaces are in the string and then you look for a substring of -1 length.

You can tack a trailing space on to the end of the string to ensure there is always at least one space and avoid this problem.

SELECT SUBSTRING(PostCode, 1 , CHARINDEX(' ', PostCode + ' ' ) -1)

Passing on command line arguments to runnable JAR

When you run your application this way, the java excecutable read the MANIFEST inside your jar and find the main class you defined. In this class you have a static method called main. In this method you may use the command line arguments.

Error message 'Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.'

I solved this issue by setting the Copy Local attribute of my project's references to true.

How to add comments into a Xaml file in WPF?

You cannot put comments inside UWP XAML tags. Your syntax is right.

TO DO:

<xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:System="clr-namespace:System;assembly=mscorlib"/>
<!-- Cool comment -->

NOT TO DO:

<xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    <!-- Cool comment -->
xmlns:System="clr-namespace:System;assembly=mscorlib"/>

How can I turn a List of Lists into a List in Java 8?

Just as @Saravana mentioned:

flatmap is better but there are other ways to achieve the same

 listStream.reduce(new ArrayList<>(), (l1, l2) -> {
        l1.addAll(l2);
        return l1;
 });

To sum up, there are several ways to achieve the same as follows:

private <T> List<T> mergeOne(Stream<List<T>> listStream) {
    return listStream.flatMap(List::stream).collect(toList());
}

private <T> List<T> mergeTwo(Stream<List<T>> listStream) {
    List<T> result = new ArrayList<>();
    listStream.forEach(result::addAll);
    return result;
}

private <T> List<T> mergeThree(Stream<List<T>> listStream) {
    return listStream.reduce(new ArrayList<>(), (l1, l2) -> {
        l1.addAll(l2);
        return l1;
    });
}

private <T> List<T> mergeFour(Stream<List<T>> listStream) {
    return listStream.reduce((l1, l2) -> {
        List<T> l = new ArrayList<>(l1);
        l.addAll(l2);
        return l;
    }).orElse(new ArrayList<>());
}

private <T> List<T> mergeFive(Stream<List<T>> listStream) {
    return listStream.collect(ArrayList::new, List::addAll, List::addAll);
}

How do I update a Python package?

Get all the outdated packages and create a batch file with the following commands pip install xxx --upgrade for each outdated packages

How to filter by object property in angularJS

The documentation has the complete answer. Anyway this is how it is done:

<input type="text" ng-model="filterValue">
<li ng-repeat="i in data | filter:{age:filterValue}:true"> {{i | json }}</li>

will filter only age in data array and true is for exact match.

For deep filtering,

<li ng-repeat="i in data | filter:{$:filterValue}:true"> {{i}}</li>

The $ is a special property for deep filter and the true is for exact match like above.

How to correctly represent a whitespace character

Which whitespace character? The empty string is pretty unambiguous - it's a sequence of 0 characters. However, " ", "\t" and "\n" are all strings containing a single character which is characterized as whitespace.

If you just mean a space, use a space. If you mean some other whitespace character, there may well be a custom escape sequence for it (e.g. "\t" for tab) or you can use a Unicode escape sequence ("\uxxxx"). I would discourage you from including non-ASCII characters in your source code, particularly whitespace ones.

EDIT: Now that you've explained what you want to do (which should have been in your question to start with) you'd be better off using Regex.Split with a regular expression of \s which represents whitespace:

Regex regex = new Regex(@"\s");
string[] bits = regex.Split(text.ToLower());

See the Regex Character Classes documentation for more information on other character classes.

Extract number from string with Oracle function

You can use regular expressions for extracting the number from string. Lets check it. Suppose this is the string mixing text and numbers 'stack12345overflow569'. This one should work:

select regexp_replace('stack12345overflow569', '[[:alpha:]]|_') as numbers from dual;

which will return "12345569".

also you can use this one:

select regexp_replace('stack12345overflow569', '[^0-9]', '') as numbers,
       regexp_replace('Stack12345OverFlow569', '[^a-z and ^A-Z]', '') as characters
from dual

which will return "12345569" for numbers and "StackOverFlow" for characters.

Parse JSON from HttpURLConnection object

The JSON string will just be the body of the response you get back from the URL you have called. So add this code

...
BufferedReader in = new BufferedReader(new InputStreamReader(
                            conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) 
    System.out.println(inputLine);
in.close();

That will allow you to see the JSON being returned to the console. The only missing piece you then have is using a JSON library to read that data and provide you with a Java representation.

Here's an example using JSON-LIB

Bootstrap dropdown not working

Copy/paste the CSS link followed by the JS link from the bootstrap site here. Then the dropdown should work.

My page looks like:

<html>
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

    <title>Website Title</title>
  </head>
  <body>
    <div id="content" />
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
      <a class="navbar-brand" href="#">Navbar</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav mr-auto">
          <li class="nav-item active">
            <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">Link</a>
          </li>
          <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
              Dropdown
            </a>
            <div class="dropdown-menu" aria-labelledby="navbarDropdown">
              <a class="dropdown-item" href="#">Action</a>
              <a class="dropdown-item" href="#">Another action</a>
              <div class="dropdown-divider"></div>
              <a class="dropdown-item" href="#">Something else here</a>
            </div>
          </li>
          <li class="nav-item">
            <a class="nav-link disabled" href="#">Disabled</a>
          </li>
        </ul>
        <form class="form-inline my-2 my-lg-0">
          <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
          <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
        </form>
      </div>
    </nav>
  </body>
</html>

(Navbar from here)

How to write "not in ()" sql query using join

I would opt for NOT EXISTS in this case.

SELECT D1.ShortCode
FROM Domain1 D1
WHERE NOT EXISTS
    (SELECT 'X'
     FROM Domain2 D2
     WHERE D2.ShortCode = D1.ShortCode
    )

How to copy a file from one directory to another using PHP?

You could use the rename() function :

rename('foo/test.php', 'bar/test.php');

This however will move the file not copy

MySQL command line client for Windows

When you go to the MySQL download page, choose the platform "Microsoft Windows". Then download the "Windows (x86, xx-bit), ZIP Archive" (be sure to select the one with size over 140M.

The binaries will be in the "bin" folder.

I understand that this is not just the client binaries, but at least you don't have to install and setup the entire server.

Best way to increase heap size in catalina.bat file

increase heap size of tomcat for window add this file in apache-tomcat-7.0.42\bin

enter image description here

heap size can be changed based on Requirements.

  set JAVA_OPTS=-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256m

How can I fill a div with an image while keeping it proportional?

You can use div to achieve this. without img tag :) hope this helps.

_x000D_
_x000D_
.img{_x000D_
 width:100px;_x000D_
 height:100px;_x000D_
 background-image:url('http://www.mandalas.com/mandala/htdocs/images/Lrg_image_Pages/Flowers/Large_Orange_Lotus_8.jpg');_x000D_
 background-repeat:no-repeat;_x000D_
 background-position:center center;_x000D_
 border:1px solid red;_x000D_
 background-size:cover;_x000D_
}_x000D_
.img1{_x000D_
 width:100px;_x000D_
 height:100px;_x000D_
 background-image:url('https://images.freeimages.com/images/large-previews/9a4/large-pumpkin-1387927.jpg');_x000D_
 background-repeat:no-repeat;_x000D_
 background-position:center center;_x000D_
 border:1px solid red;_x000D_
 background-size:cover;_x000D_
}
_x000D_
<div class="img"> _x000D_
</div>_x000D_
<div class="img1"> _x000D_
</div>
_x000D_
_x000D_
_x000D_

Converting Epoch time into the datetime

>>> import datetime
>>> datetime.datetime.fromtimestamp(1347517370).strftime('%Y-%m-%d %H:%M:%S')
'2012-09-13 14:22:50' # Local time

To get UTC:

>>> datetime.datetime.utcfromtimestamp(1347517370).strftime('%Y-%m-%d %H:%M:%S')
  '2012-09-13 06:22:50'

How to check if a string is a number?

rewrite the whole function as below:

bool IsValidNumber(char * string)
{
   for(int i = 0; i < strlen( string ); i ++)
   {
      //ASCII value of 0 = 48, 9 = 57. So if value is outside of numeric range then fail
      //Checking for negative sign "-" could be added: ASCII value 45.
      if (string[i] < 48 || string[i] > 57)
         return FALSE;
   }

   return TRUE;
}

what does the __file__ variable mean/do?

When a module is loaded from a file in Python, __file__ is set to its path. You can then use that with other functions to find the directory that the file is located in.

Taking your examples one at a time:

A = os.path.join(os.path.dirname(__file__), '..')
# A is the parent directory of the directory where program resides.

B = os.path.dirname(os.path.realpath(__file__))
# B is the canonicalised (?) directory where the program resides.

C = os.path.abspath(os.path.dirname(__file__))
# C is the absolute path of the directory where the program resides.

You can see the various values returned from these here:

import os
print(__file__)
print(os.path.join(os.path.dirname(__file__), '..'))
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.abspath(os.path.dirname(__file__)))

and make sure you run it from different locations (such as ./text.py, ~/python/text.py and so forth) to see what difference that makes.


I just want to address some confusion first. __file__ is not a wildcard it is an attribute. Double underscore attributes and methods are considered to be "special" by convention and serve a special purpose.

http://docs.python.org/reference/datamodel.html shows many of the special methods and attributes, if not all of them.

In this case __file__ is an attribute of a module (a module object). In Python a .py file is a module. So import amodule will have an attribute of __file__ which means different things under difference circumstances.

Taken from the docs:

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

In your case the module is accessing it's own __file__ attribute in the global namespace.

To see this in action try:

# file: test.py

print globals()
print __file__

And run:

python test.py

{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__':
 'test_print__file__.py', '__doc__': None, '__package__': None}
test_print__file__.py

'Microsoft.ACE.OLEDB.16.0' provider is not registered on the local machine. (System.Data)

You have to use now the new XLSX-Driver from Access-Redist (32/64-Bit). The current XLS-Driver are corrupted since last cumulative update.

SQL Developer is returning only the date, not the time. How do I fix this?

To expand on some of the previous answers, I found that Oracle DATE objects behave different from Oracle TIMESTAMP objects. In particular, if you set your NLS_DATE_FORMAT to include fractional seconds, the entire time portion is omitted.

  • Format "YYYY-MM-DD HH24:MI:SS" works as expected, for DATE and TIMESTAMP
  • Format "YYYY-MM-DD HH24:MI:SSXFF" displays just the date portion for DATE, works as expected for TIMESTAMP

My personal preference is to set DATE to "YYYY-MM-DD HH24:MI:SS", and to set TIMESTAMP to "YYYY-MM-DD HH24:MI:SSXFF".

How can I get onclick event on webview in android?

Hamidreza's solution almost worked for me.

I noticed from experimentation that a simple tap usually has 2-5 action move events. Checking the time between action down and up was simpler and behaved more like what I expected.

private class CheckForClickTouchLister implements View.OnTouchListener {
    private final static long MAX_TOUCH_DURATION = 100;

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN:
                m_DownTime = event.getEventTime(); //init time

                break;

            case MotionEvent.ACTION_UP:
                if(event.getEventTime() - m_DownTime <= MAX_TOUCH_DURATION)
                    //On click action

                break;

            default:
                break; //No-Op

        }
        return false;
    }

Getting list of lists into pandas DataFrame

With approach explained by EdChum above, the values in the list are shown as rows. To show the values of lists as columns in DataFrame instead, simply use transpose() as following:

table = [[1 , 2], [3, 4]]
df = pd.DataFrame(table)
df = df.transpose()
df.columns = ['Heading1', 'Heading2']

The output then is:

      Heading1  Heading2
0         1        3
1         2        4

MySQL error: key specification without a key length

DROP that table and again run Spring Project. That might help. Sometime you are overriding foreignKey.

"Specified argument was out of the range of valid values"

try this.

if (ViewState["CurrentTable"] != null)
            {
                DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
                DataRow drCurrentRow = null;
                if (dtCurrentTable.Rows.Count > 0)
                {
                    for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                    {
                        //extract the TextBox values
                        TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("txt_type");
                        TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("txt_total");
                        TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("txt_max");
                        TextBox box4 = (TextBox)Gridview1.Rows[i].Cells[4].FindControl("txt_min");
                        TextBox box5 = (TextBox)Gridview1.Rows[i].Cells[5].FindControl("txt_rate");

                        drCurrentRow = dtCurrentTable.NewRow();
                        drCurrentRow["RowNumber"] = i + 1;

                        dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
                        dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
                        dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
                        dtCurrentTable.Rows[i - 1]["Column4"] = box4.Text;
                        dtCurrentTable.Rows[i - 1]["Column5"] = box5.Text;

                        rowIndex++;
                    }
                    dtCurrentTable.Rows.Add(drCurrentRow);
                    ViewState["CurrentTable"] = dtCurrentTable;

                    Gridview1.DataSource = dtCurrentTable;
                    Gridview1.DataBind();
                }
            }
            else
            {
                Response.Write("ViewState is null");
            }

How to split a dos path into its components in Python

You can recursively os.path.split the string

import os
def parts(path):
    p,f = os.path.split(path)
    return parts(p) + [f] if f else [p]

Testing this against some path strings, and reassembling the path with os.path.join

>>> for path in [
...         r'd:\stuff\morestuff\furtherdown\THEFILE.txt',
...         '/path/to/file.txt',
...         'relative/path/to/file.txt',
...         r'C:\path\to\file.txt',
...         r'\\host\share\path\to\file.txt',
...     ]:
...     print parts(path), os.path.join(*parts(path))
... 
['d:\\', 'stuff', 'morestuff', 'furtherdown', 'THEFILE.txt'] d:\stuff\morestuff\furtherdown\THEFILE.txt
['/', 'path', 'to', 'file.txt'] /path\to\file.txt
['', 'relative', 'path', 'to', 'file.txt'] relative\path\to\file.txt
['C:\\', 'path', 'to', 'file.txt'] C:\path\to\file.txt
['\\\\', 'host', 'share', 'path', 'to', 'file.txt'] \\host\share\path\to\file.txt

The first element of the list may need to be treated differently depending on how you want to deal with drive letters, UNC paths and absolute and relative paths. Changing the last [p] to [os.path.splitdrive(p)] forces the issue by splitting the drive letter and directory root out into a tuple.

import os
def parts(path):
    p,f = os.path.split(path)
    return parts(p) + [f] if f else [os.path.splitdrive(p)]

[('d:', '\\'), 'stuff', 'morestuff', 'furtherdown', 'THEFILE.txt']
[('', '/'), 'path', 'to', 'file.txt']
[('', ''), 'relative', 'path', 'to', 'file.txt']
[('C:', '\\'), 'path', 'to', 'file.txt']
[('', '\\\\'), 'host', 'share', 'path', 'to', 'file.txt']

Edit: I have realised that this answer is very similar to that given above by user1556435. I'm leaving my answer up as the handling of the drive component of the path is different.

Open mvc view in new window from controller

Yeah you can do some tricky works to simulate what you want:

1) Call your controller from a view by ajax. 2) Return your View

3) Use something like the following in the success (or maybe error! error works for me!) section of your $.ajax request:

$("#imgPrint").click(function () {
        $.ajax({
            url: ...,
            type: 'POST', dataType: 'json',
            data: $("#frm").serialize(),
            success: function (data, textStatus, jqXHR) {
                //Here it is:
                //Gets the model state
                var isValid = '@Html.Raw(Json.Encode(ViewData.ModelState.IsValid))'; 
                // checks that model is valid                    
                if (isValid == 'true') {
                    //open new tab or window - according to configs of browser
                    var w = window.open();
                    //put what controller gave in the new tab or win 
                    $(w.document.body).html(jqXHR.responseText);
                }
                $("#imgSpinner1").hide();
            },
            error: function (jqXHR, textStatus, errorThrown) {
                // And here it is for error section. 
                //Pay attention to different order of 
                //parameters of success and error sections!
                var isValid = '@Html.Raw(Json.Encode(ViewData.ModelState.IsValid))';                    
                if (isValid == 'true') {
                    var w = window.open();
                    $(w.document.body).html(jqXHR.responseText);
                }
                $("#imgSpinner1").hide();
            },
            beforeSend: function () { $("#imgSpinner1").show(); },
            complete: function () { $("#imgSpinner1").hide(); }
        });            
    });      

Getting the parent of a directory in Bash

Motivation for another answer

I like very short, clear, guaranteed code. Bonus point if it does not run an external program, since the day you need to process a huge number of entries, it will be noticeably faster.

Principle

Not sure about what guarantees you have and want, so offering anyway.

If you have guarantees you can do it with very short code. The idea is to use bash text substitution feature to cut the last slash and whatever follows.

Answer from simple to more complex cases of the original question.

If path is guaranteed to end without any slash (in and out)

P=/home/smith/Desktop/Test ; echo "${P%/*}"
/home/smith/Desktop

If path is guaranteed to end with exactly one slash (in and out)

P=/home/smith/Desktop/Test/ ; echo "${P%/*/}/"
/home/smith/Desktop/

If input path may end with zero or one slash (not more) and you want output path to end without slash

for P in \
    /home/smith/Desktop/Test \
    /home/smith/Desktop/Test/
do
    P_ENDNOSLASH="${P%/}" ; echo "${P_ENDNOSLASH%/*}"
done

/home/smith/Desktop
/home/smith/Desktop

If input path may have many extraneous slashes and you want output path to end without slash

for P in \
    /home/smith/Desktop/Test \
    /home/smith/Desktop/Test/ \
    /home/smith///Desktop////Test// 
do
    P_NODUPSLASH="${P//\/*(\/)/\/}"
    P_ENDNOSLASH="${P_NODUPSLASH%%/}"
    echo "${P_ENDNOSLASH%/*}";   
done

/home/smith/Desktop
/home/smith/Desktop
/home/smith/Desktop

The type initializer for 'MyClass' threw an exception

I too faced this error in two situation

  1. While performing redirection from BAL layer to DAL layer I faced this exception. Inner exception says that "Object Reference error".

  2. Web.Config file key does not match.

Hope this useful to solve your problem.

How to change the background-color of jumbrotron?

Try this:

<div style="background:transparent !important" class="jumbotron">
    <h1>Welcome!</h1>
    <p>We're an awesome company that creates virtual things for portable devices.</p>
    <p><a class="btn btn-primary btn-lg" role="button">Learn more</a></p>
</div>

Inline CSS gets preference over classes defined in a .css file and the classes declared inside <style>

Can I set max_retries for requests.request?

It is the underlying urllib3 library that does the retrying. To set a different maximum retry count, use alternative transport adapters:

from requests.adapters import HTTPAdapter

s = requests.Session()
s.mount('http://stackoverflow.com', HTTPAdapter(max_retries=5))

The max_retries argument takes an integer or a Retry() object; the latter gives you fine-grained control over what kinds of failures are retried (an integer value is turned into a Retry() instance which only handles connection failures; errors after a connection is made are by default not handled as these could lead to side-effects).


Old answer, predating the release of requests 1.2.1:

The requests library doesn't really make this configurable, nor does it intend to (see this pull request). Currently (requests 1.1), the retries count is set to 0. If you really want to set it to a higher value, you'll have to set this globally:

import requests

requests.adapters.DEFAULT_RETRIES = 5

This constant is not documented; use it at your own peril as future releases could change how this is handled.

Update: and this did change; in version 1.2.1 the option to set the max_retries parameter on the HTTPAdapter() class was added, so that now you have to use alternative transport adapters, see above. The monkey-patch approach no longer works, unless you also patch the HTTPAdapter.__init__() defaults (very much not recommended).

Is there a JavaScript / jQuery DOM change listener?

Edit

This answer is now deprecated. See the answer by apsillers.

Since this is for a Chrome extension, you might as well use the standard DOM event - DOMSubtreeModified. See the support for this event across browsers. It has been supported in Chrome since 1.0.

$("#someDiv").bind("DOMSubtreeModified", function() {
    alert("tree changed");
});

See a working example here.

Invalid Host Header when ngrok tries to connect to React dev server

Option 1

If you do not need to use Authentication you can add configs to ngrok commands

ngrok http 9000 --host-header=rewrite

or

ngrok http 9000 --host-header="localhost:9000"

But in this case Authentication will not work on your website because ngrok rewriting headers and session is not valid for your ngrok domain

Option 2

If you are using webpack you can add the following configuration

devServer: {
    disableHostCheck: true
}

In that case Authentication header will be valid for your ngrok domain

Use jquery to set value of div tag

To put text, use .text('text')

If you want to use .html(SomeValue), SomeValue should have html tags that can be inside a div it must work too.

Just check your script location, as farzad said.

Reference: .html and text

Is there a kind of Firebug or JavaScript console debug for Android?

I installed console add-on of the firefox (https://addons.mozilla.org/en-US/android/addon/console/) on my firefox browser on android and it worked quite well. Helped me debug my angular2 app.

jQuery ui dialog change title after load-callback

Even better!

    jQuery( "#dialog" ).attr('title', 'Error');
    jQuery( "#dialog" ).text('You forgot to enter your first name');

Closing Excel Application using VBA

You can try out

ThisWorkbook.Save
ThisWorkbook.Saved = True
Application.Quit

How do I implement basic "Long Polling"?

I think the client looks like a normal asynchronous AJAX request, but you expect it to take a "long time" to come back.

The server then looks like this.

while (!hasNewData())
    usleep(50);

outputNewData();

So, the AJAX request goes to the server, probably including a timestamp of when it was last update so that your hasNewData() knows what data you have already got. The server then sits in a loop sleeping until new data is available. All the while, your AJAX request is still connected, just hanging there waiting for data. Finally, when new data is available, the server gives it to your AJAX request and closes the connection.

C# Form.Close vs Form.Dispose

This forum on MSDN tells you.

Form.Close() sends the proper Windows messages to shut down the win32 window. During that process, if the form was not shown modally, Dispose is called on the form. Disposing the form frees up the unmanaged resources that the form is holding onto.

If you do a form1.Show() or Application.Run(new Form1()), Dispose will be called when Close() is called.

However, if you do form1.ShowDialog() to show the form modally, the form will not be disposed, and you'll need to call form1.Dispose() yourself. I believe this is the only time you should worry about disposing the form yourself.

how to initialize a char array?

The C-like method may not be as attractive as the other solutions to this question, but added here for completeness:

You can initialise with NULLs like this:

char msg[65536] = {0};

Or to use zeros consider the following:

char msg[65536] = {'0' another 65535 of these separated by comma};

But do not try it as not possible, so use memset!

In the second case, add the following after the memset if you want to use msg as a string.

msg[65536 - 1] =  '\0'

Answers to this question also provide further insight.

Checking if object is empty, works with ng-show but not from controller?

Use an empty object literal isn't necessary here, you can use null or undefined:

$scope.items = null;

In this way, ng-show should keep working, and in your controller you can just do:

if ($scope.items) {
    // items have value
} else {
    // items is still null
}

And in your $http callbacks, you do the following:

$http.get(..., function(data) {
    $scope.items = {
        data: data,
        // other stuff
    };
});

Assign value from successful promise resolve to external variable

The then() method returns a Promise. It takes two arguments, both are callback functions for the success and failure cases of the Promise. the promise object itself doesn't give you the resolved data directly, the interface of this object only provides the data via callbacks supplied. So, you have to do this like this:

getFeed().then(function(data) { vm.feed = data;});

The then() function returns the promise with a resolved value of the previous then() callback, allowing you the pass the value to subsequent callbacks:

promiseB = promiseA.then(function(result) {
  return result + 1;
});

// promiseB will be resolved immediately after promiseA is resolved
// and its value will be the result of promiseA incremented by 1

How to insert selected columns from a CSV file to a MySQL database using LOAD DATA INFILE

For those who have the following error:

Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

You can simply run this command to see which folder can load files from:

SHOW VARIABLES LIKE "secure_file_priv";

After that, you have to copy the files in that folder and run the query with LOAD DATA LOCAL INFILE instead of LOAD DATA INFILE.

Delete last N characters from field in a SQL Server database

I got the answer to my own question, ant this is:

select reverse(stuff(reverse('a,b,c,d,'), 1, N, ''))

Where N is the number of characters to remove. This avoids to write the complex column/string twice

Javascript isnull

return results == null ? 0 : ( results[1] || 0 );

Mongoose query where value is not null

Hello guys I am stucked with this. I've a Document Profile who has a reference to User,and I've tried to list the profiles where user ref is not null (because I already filtered by rol during the population), but after googleing a few hours I cannot figure out how to get this. I have this query:

const profiles = await Profile.find({ user: {$exists: true,  $ne: null }})
                            .select("-gallery")
                            .sort( {_id: -1} )
                            .skip( skip )
                            .limit(10)
                            .select(exclude)
                            .populate({
                                path: 'user',
                                match: { role: {$eq: customer}},
                                select: '-password -verified -_id -__v'
                              })

                            .exec();

And I get this result, how can I remove from the results the user:null colletions? . I meant, I dont want to get the profile when user is null (the role does not match).
{
    "code": 200,
    "profiles": [
        {
            "description": null,
            "province": "West Midlands",
            "country": "UK",
            "postal_code": "83000",
            "user": null
        },
        {
            "description": null,

            "province": "Madrid",
            "country": "Spain",
            "postal_code": "43000",
            "user": {
                "role": "customer",
                "name": "pedrita",
                "email": "[email protected]",
                "created_at": "2020-06-05T11:05:36.450Z"
            }
        }
    ],
    "page": 1
}

Thanks in advance.

How to get only filenames within a directory using c#?

You can simply use linq

Directory.EnumerateFiles(LoanFolder).Select(file => Path.GetFileName(file));

Note: EnumeratesFiles is more efficient compared to Directory.GetFiles as you can start enumerating the collection of names before the whole collection is returned.

Shorten string without cutting words in JavaScript

There are lots of ways to do it, but a regular expression is a useful one line method:

"this is a longish string of text".replace(/^(.{11}[^\s]*).*/, "$1"); 
//"this is a longish"

This expressions returns the first 11 (any) characters plus any subsequent non-space characters.

Example script:

<pre>
<script>
var t = "this is a longish string of text";

document.write("1:   " + t.replace(/^(.{1}[^\s]*).*/, "$1") + "\n");
document.write("2:   " + t.replace(/^(.{2}[^\s]*).*/, "$1") + "\n");
document.write("5:   " + t.replace(/^(.{5}[^\s]*).*/, "$1") + "\n");
document.write("11:  " + t.replace(/^(.{11}[^\s]*).*/, "$1") + "\n");
document.write("20:  " + t.replace(/^(.{20}[^\s]*).*/, "$1") + "\n");
document.write("100: " + t.replace(/^(.{100}[^\s]*).*/, "$1") + "\n");
</script>

Output:

1:   this
2:   this
5:   this is
11:  this is a longish
20:  this is a longish string
100: this is a longish string of text

Concatenate text files with Windows command line, dropping leading lines

more +2 file2.txt > temp
type temp file1.txt > out.txt

or you can use copy. See copy /? for more.

copy /b temp+file1.txt  out.txt

Regex, every non-alphanumeric character except white space or colon

[^a-zA-Z\d\s:]
  • \d - numeric class
  • \s - whitespace
  • a-zA-Z - matches all the letters
  • ^ - negates them all - so you get - non numeric chars, non spaces and non colons

babel-loader jsx SyntaxError: Unexpected token

You can find a really good boilerplate made by Henrik Joreteg (ampersandjs) here: https://github.com/HenrikJoreteg/hjs-webpack

Then in your webpack.config.js

var getConfig = require('hjs-webpack')

module.exports = getConfig({
  in: 'src/index.js',
  out: 'public',
  clearBeforeBuild: true,
  https: process.argv.indexOf('--https') !== -1
})

Compile c++14-code with g++

For gcc 4.8.4 you need to use -std=c++1y in later versions, looks like starting with 5.2 you can use -std=c++14.

If we look at the gcc online documents we can find the manuals for each version of gcc and we can see by going to Dialect options for 4.9.3 under the GCC 4.9.3 manual it says:

‘c++1y’

The next revision of the ISO C++ standard, tentatively planned for 2014. Support is highly experimental, and will almost certainly change in incompatible ways in future releases.

So up till 4.9.3 you had to use -std=c++1y while the gcc 5.2 options say:

‘c++14’ ‘c++1y’

The 2014 ISO C++ standard plus amendments. The name ‘c++1y’ is deprecated.

It is not clear to me why this is listed under Options Controlling C Dialect but that is how the documents are currently organized.

How to make URL/Phone-clickable UILabel?

You can use a UITextView and select Detection for Links, Phone Numbers and other things in the inspector.

PHP - syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

Wrong quoting: (and missing option closing tag xd)

$out.='<option value="'.$key.'">'.$value["name"].'</option>';

How do I tar a directory of files and folders without including the directory itself?

tar -czvf mydir.tgz -C my_dir/ `ls -A mydir`

Run it one level above mydir. This won't include any [.] or stuff.

How find out which process is using a file in Linux?

$ lsof | tree MyFold

As shown in the image attached:

enter image description here

Pythonic way to print list items

Expanding @lucasg's answer (inspired by the comment it received):

To get a formatted list output, you can do something along these lines:

l = [1,2,5]
print ", ".join('%02d'%x for x in l)

01, 02, 05

Now the ", " provides the separator (only between items, not at the end) and the formatting string '02d'combined with %x gives a formatted string for each item x - in this case, formatted as an integer with two digits, left-filled with zeros.

Twitter Bootstrap button click to toggle expand/collapse text section above button

html:

<h4 data-toggle-selector="#me">toggle</h4>
<div id="me">content here</div>

js:

$(function () {
    $('[data-toggle-selector]').on('click',function () {
        $($(this).data('toggle-selector')).toggle(300);
    })
})

Adding a new line/break tag in XML

The easiest way to give a line break is to do the following :
1> Add the following in CSS - e{display:block}
2> Now wherever you want to give a line break, type -

<e></e>

How to serve .html files with Spring

I'd just add that you don't need to implement a controller method for that as you can use the view-controller tag (Spring 3) in the servlet configuration file:

<mvc:view-controller path="/" view-name="/WEB-INF/jsp/index.html"/>

How to display request headers with command line curl

A popular answer for displaying response headers, but OP asked about request headers.

curl -s -D - -o /dev/null http://example.com
  • -s : Avoid showing progress bar
  • -D - : Dump headers to a file, but - sends it to stdout
  • -o /dev/null : Ignore response body

This is better than -I as it doesn't send a HEAD request, which can produce different results.

It's better than -v because you don't need so many hacks to un-verbose it.

How can I remove a character from a string using JavaScript?

I dislike using replace function to remove characters from string. This is not logical to do it like that. Usually I program in C# (Sharp), and whenever I want to remove characters from string, I use the Remove method of the String class, but no Replace method, even though it exists, because when I am about to remove, I remove, no replace. This is logical!

In Javascript, there is no remove function for string, but there is substr function. You can use the substr function once or twice to remove characters from string. You can make the following function to remove characters at start index to the end of string, just like the c# method first overload String.Remove(int startIndex):

function Remove(str, startIndex) {
    return str.substr(0, startIndex);
}

and/or you also can make the following function to remove characters at start index and count, just like the c# method second overload String.Remove(int startIndex, int count):

function Remove(str, startIndex, count) {
    return str.substr(0, startIndex) + str.substr(startIndex + count);
}

and then you can use these two functions or one of them for your needs!

Example:

alert(Remove("crt/r2002_2", 4, 1));

Output: crt/2002_2

Achieving goals by doing techniques with no logic might cause confusions in understanding of the code, and future mistakes, if you do this a lot in a large project!

How to debug ORA-01775: looping chain of synonyms?

ORA-01775: looping chain of synonyms I faced the above error while I was trying to compile a Package which was using an object for which synonym was created however underlying object was not available.

How to update a value in a json file and save it through node.js

Doing this asynchronously is quite easy. It's particularly useful if you're concerned for blocking the thread (likely).

const fs = require('fs');
const fileName = './file.json';
const file = require(fileName);
    
file.key = "new value";
    
fs.writeFile(fileName, JSON.stringify(file), function writeJSON(err) {
  if (err) return console.log(err);
  console.log(JSON.stringify(file));
  console.log('writing to ' + fileName);
});

The caveat is that json is written to the file on one line and not prettified. ex:

{
  "key": "value"
}

will be...

{"key": "value"}

To avoid this, simply add these two extra arguments to JSON.stringify

JSON.stringify(file, null, 2)

null - represents the replacer function. (in this case we don't want to alter the process)

2 - represents the spaces to indent.

How to use Global Variables in C#?

A useful feature for this is using static

As others have said, you have to create a class for your globals:

public static class Globals {
    public const float PI = 3.14;
}

But you can import it like this in order to no longer write the class name in front of its static properties:

using static Globals;
[...]
Console.WriteLine("Pi is " + PI);

How to run ssh-add on windows?

In order to run ssh-add on Windows one could install git using choco install git. The ssh-add command is recognized once C:\Program Files\Git\usr\bin has been added as a PATH variable and the command prompt has been restarted:

C:\Users\user\Desktop\repository>ssh-add .ssh/id_rsa
Enter passphrase for .ssh/id_rsa:
Identity added: .ssh/id_rsa (.ssh/id_rsa)

C:\Users\user\Desktop\repository> 

mysql: see all open connections to a given database?

If you're running a *nix system, also consider mytop.

To limit the results to one database, press "d" when it's running then type in the database name.

How To Run PHP From Windows Command Line in WAMPServer

just do these steps if you don't need your old php version:

  • open wamp and right click on wamp manager than go : tools/Change PHP CLI Version than change php version to latest
  • another time right click on wamp manager than go : tools/Delete unuserd versions and delete the oldest version which your system insist on it to be your pc php version :D
  • go to control panel/user account/change my environment variables and in PATH variable click edit and add your latest php version path which is in your wamp server bin folder
  • close all command lines or IDEs and restart them and check for php -v

this works well

Does React Native styles support gradients?

Just export your gradient as SVG and use it using react-native-svg and when after you import your component set width and height and preserveAspectRatio="xMinYMin slice"to scale an SVG gradient at your needs.

What does the 'L' in front a string mean in C++?

'L' means wchar_t, which, as opposed to a normal character, requires 16-bits of storage rather than 8-bits. Here's an example:

"A"    = 41
"ABC"  = 41 42 43
L"A"   = 00 41
L"ABC" = 00 41 00 42 00 43

A wchar_t is twice big as a simple char. In daily use you don't need to use wchar_t, but if you are using windows.h you are going to need it.

Bash tool to get nth line from a file

Lots of good answers already. I personally go with awk. For convenience, if you use bash, just add the below to your ~/.bash_profile. And, the next time you log in (or if you source your .bash_profile after this update), you will have a new nifty "nth" function available to pipe your files through.

Execute this or put it in your ~/.bash_profile (if using bash) and reopen bash (or execute source ~/.bach_profile)

# print just the nth piped in line
nth () { awk -vlnum=${1} 'NR==lnum {print; exit}'; } 

Then, to use it, simply pipe through it. E.g.,:

$ yes line | cat -n | nth 5
     5  line

How to check whether an object is a date?

As indicated above, it's probably easiest to just check if the function exists before using it. If you really care that it's a Date, and not just an object with a getMonth() function, try this:

function isValidDate(value) {
    var dateWrapper = new Date(value);
    return !isNaN(dateWrapper.getDate());
}

This will create either a clone of the value if it's a Date, or create an invalid date. You can then check if the new date's value is invalid or not.

Could not find the main class, program will exit

I got this issue in opening JMeter 4.0. I fixed as below.

I have JRE 7 installed in Program Files (x86) folder and JDK 8 installed in Program files folder. So I just uninstalled JRE7 from machine. I just kept latest version of JDK. It fixed the problem.

Combine a list of data frames into one data frame by row

For the purpose of completeness, I thought the answers to this question required an update. "My guess is that using do.call("rbind", ...) is going to be the fastest approach that you will find..." It was probably true for May 2010 and some time after, but in about Sep 2011 a new function rbindlist was introduced in the data.table package version 1.8.2, with a remark that "This does the same as do.call("rbind",l), but much faster". How much faster?

library(rbenchmark)
benchmark(
  do.call = do.call("rbind", listOfDataFrames),
  plyr_rbind.fill = plyr::rbind.fill(listOfDataFrames), 
  plyr_ldply = plyr::ldply(listOfDataFrames, data.frame),
  data.table_rbindlist = as.data.frame(data.table::rbindlist(listOfDataFrames)),
  replications = 100, order = "relative", 
  columns=c('test','replications', 'elapsed','relative')
  ) 

                  test replications elapsed relative
4 data.table_rbindlist          100    0.11    1.000
1              do.call          100    9.39   85.364
2      plyr_rbind.fill          100   12.08  109.818
3           plyr_ldply          100   15.14  137.636

Is the size of C "int" 2 bytes or 4 bytes?

This depends on implementation, but usually on x86 and other popular architectures like ARM ints take 4 bytes. You can always check at compile time using sizeof(int) or whatever other type you want to check.

If you want to make sure you use a type of a specific size, use the types in <stdint.h>

What is the difference between supervised learning and unsupervised learning?

Supervised learning

You have input x and a target output t. So you train the algorithm to generalize to the missing parts. It is supervised because the target is given. You are the supervisor telling the algorithm: For the example x, you should output t!

Unsupervised learning

Although segmentation, clustering and compression are usually counted in this direction, I have a hard time to come up with a good definition for it.

Let's take auto-encoders for compression as an example. While you only have the input x given, it is the human engineer how tells the algorithm that the target is also x. So in some sense, this is not different from supervised learning.

And for clustering and segmentation, I'm not too sure if it really fits the definition of machine learning (see other question).

UIImageView - How to get the file name of the image assigned?

Yes you can compare with the help of data like below code

UITableViewCell *cell = (UITableViewCell*)[self.view viewWithTag:indexPath.row + 100];

UIImage *secondImage = [UIImage imageNamed:@"boxhover.png"];

NSData *imgData1 = UIImagePNGRepresentation(cell.imageView.image);
NSData *imgData2 = UIImagePNGRepresentation(secondImage);

BOOL isCompare =  [imgData1 isEqual:imgData2];
if(isCompare)
{
    //contain same image
    cell.imageView.image = [UIImage imageNamed:@"box.png"];
}
else
{
    //does not contain same image
    cell.imageView.image = secondImage;
}

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

In my Angular Bootstrap dropdowns I initialize the JSON Array (vm.zoneDropdown) with ng-init (you can also have ng-init inside the directive template) and I pass the Array in a custom src attribute

<custom-dropdown control-id="zone" label="Zona" model="vm.form.zone" src="vm.zoneDropdown"
                         ng-init="vm.getZoneDropdownSrc()" is-required="true" form="farmaciaForm" css-class="custom-dropdown col-md-3"></custom-dropdown>

Inside the controller:

vm.zoneDropdown = [];
vm.getZoneDropdownSrc = function () {
    vm.zoneDropdown = $customService.getZone();
}

And inside the customDropdown directive template(note that this is only one part of the bootstrap dropdown):

<ul class="uib-dropdown-menu" role="menu" aria-labelledby="btn-append-to-body">
    <li role="menuitem" ng-repeat="dropdownItem in vm.src" ng-click="vm.setValue(dropdownItem)">
        <a ng-click="vm.preventDefault($event)" href="##">{{dropdownItem.text}}</a>
    </li>
</ul>

Using python's eval() vs. ast.literal_eval()?

datamap = eval(input('Provide some data here: ')) means that you actually evaluate the code before you deem it to be unsafe or not. It evaluates the code as soon as the function is called. See also the dangers of eval.

ast.literal_eval raises an exception if the input isn't a valid Python datatype, so the code won't be executed if it's not.

Use ast.literal_eval whenever you need eval. You shouldn't usually evaluate literal Python statements.

How to remove a package from Laravel using composer?

We have come with a great solution. This solution is practically done in Laravel 6. If you want to remove any package from your Laravel Project then you can easily remove the package by following below steps:

Step 1: You must know the package name which you want to remove. If you don't know complete package name then you can open your project folder and go to composer.json file and check name in require an array

"require": {
        "php": "^7.2",
        "fideloper/proxy": "^4.0",
        "laravel/framework": "^6.2",
        "laravel/passport": "^8.3",
        "laravel/tinker": "^2.0"
    },

Suppose, here I am going to remove "fideloper/proxy" package.

Step 2: Open command prompt with your project root folder directory enter image description here Step 3: First of all clear all cache by following commands. Run commands one by one.

php artisan cache:clear  
php artisan config:clear 

Step 4: Now write the following command to remove the package. Here you need to change your package name instead of my example package.

composer remove fideloper/proxy

Now, wait for a few seconds your package is removing.

How can I capture the result of var_dump to a string?

Use output buffering:

<?php
ob_start();
var_dump($someVar);
$result = ob_get_clean();
?>

How to find which git branch I am on when my disk is mounted on other server

.git/HEAD contains the path of the current ref, the working directory is using as HEAD.

Difference between java.exe and javaw.exe

The javaw.exe command is identical to java.exe, except that with javaw.exe there is no associated console window

Ways to implement data versioning in MongoDB

I worked through this solution that accommodates a published, draft and historical versions of the data:

{
  published: {},
  draft: {},
  history: {
    "1" : {
      metadata: <value>,
      document: {}
    },
    ...
  }
}

I explain the model further here: http://software.danielwatrous.com/representing-revision-data-in-mongodb/

For those that may implement something like this in Java, here's an example:

http://software.danielwatrous.com/using-java-to-work-with-versioned-data/

Including all the code that you can fork, if you like

https://github.com/dwatrous/mongodb-revision-objects

How to focus on a form input text field on page load using jQuery?

Set focus on the first text field:

 $("input:text:visible:first").focus();

This also does the first text field, but you can change the [0] to another index:

$('input[@type="text"]')[0].focus(); 

Or, you can use the ID:

$("#someTextBox").focus();

AJAX POST and Plus Sign ( + ) -- How to Encode?

Use encodeURIComponent() in JS and in PHP you should receive the correct values.

Note: When you access $_GET, $_POST or $_REQUEST in PHP, you are retrieving values that have already been decoded.

Example:

In your JS:

// url encode your string
var string = encodeURIComponent('+'); // "%2B"
// send it to your server
window.location = 'http://example.com/?string='+string; // http://example.com/?string=%2B

On your server:

echo $_GET['string']; // "+"

It is only the raw HTTP request that contains the url encoded data.

For a GET request you can retrieve this from the URI. $_SERVER['REQUEST_URI'] or $_SERVER['QUERY_STRING']. For a urlencoded POST, file_get_contents('php://stdin')

NB:

decode() only works for single byte encoded characters. It will not work for the full UTF-8 range.

eg:

text = "\u0100"; // A
// incorrect
escape(text); // %u0100 
// correct
encodeURIComponent(text); // "%C4%80"

Note: "%C4%80" is equivalent to: escape('\xc4\x80')

Which is the byte sequence (\xc4\x80) that represents A in UTF-8. So if you use encodeURIComponent() your server side must know that it is receiving UTF-8. Otherwise PHP will mangle the encoding.

What is the difference between HTML tags <div> and <span>?

This means that to use them semantically, divs should be used to wrap sections of a document, while spans should be used to wrap small portions of text, images, etc.

For example:

<div>This a large main division, with <span>a small bit</span> of spanned text!</div>

Note that it is illegal to place a block-level element within an inline element, so:

<div>Some <span>text that <div>I want</div> to mark</span> up</div>

...is illegal.


EDIT: As of HTML5, some block elements can be placed inside of some inline elements. See the MDN reference here for a pretty clear listing. The above is still illegal, as <span> only accepts phrasing content, and <div> is flow content.


You asked for some concrete examples, so is one taken from my bowling website, BowlSK:

_x000D_
_x000D_
<div id="header">_x000D_
  <div id="userbar">_x000D_
    Hi there, <span class="username">Chris Marasti-Georg</span> |_x000D_
    <a href="/edit-profile.html">Profile</a> |_x000D_
    <a href="https://www.bowlsk.com/_ah/logout?...">Sign out</a>_x000D_
  </div>_x000D_
  <h1><a href="/">Bowl<span class="sk">SK</span></a></h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Ok, what's going on?

At the top of my page, I have a logical section, the "header". Since this is a section, I use a div (with an appropriate id). Within that, I have a couple of sections: the user bar and the actual page title. The title uses the appropriate tag, h1. The userbar, being a section, is wrapped in a div. Within that, the username is wrapped in a span, so that I can change the style. As you can see, I have also wrapped a span around 2 letters in the title - this allows me to change their color in my stylesheet.

Also note that HTML5 includes a broad new set of elements that define common page structures, such as article, section, nav, etc.

Section 4.4 of the HTML 5 working draft lists them and gives hints as to their usage. HTML5 is still a working spec, so nothing is "final" yet, but it is highly doubtful that any of these elements are going anywhere. There is a javascript hack that you will need to use if you want to style these elements in some older version of IE - You need to create one of each element using document.createElement before any of those elements are specified in your source. There are a bunch of libraries that will take care of this for you - a quick Google search turned up html5shiv.

Android Respond To URL in Intent

I did it! Using <intent-filter>. Put the following into your manifest file:

<intent-filter>
  <action android:name="android.intent.action.VIEW" />
  <category android:name="android.intent.category.DEFAULT" />
  <category android:name="android.intent.category.BROWSABLE" />
  <data android:host="www.youtube.com" android:scheme="http" />
</intent-filter>

This works perfectly!

Getting Python error "from: can't read /var/mail/Bio"

Same here. I had this error when running an import command from terminal without activating python3 shell through manage.py in a django project (yes, I am a newbie yet). As one must expect, activating shell allowed the command to be interpreted correctly.

./manage.py shell

and only then

>>> from django.contrib.sites.models import Site

How to change TextField's height and width?

use contentPadding, it will reduce the textbox or dropdown list height

InputDecorator(
                  decoration: InputDecoration(
                      errorStyle: TextStyle(
                          color: Colors.redAccent, fontSize: 16.0),
                      hintText: 'Please select expense',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(1.0),
                      ),
                      contentPadding: EdgeInsets.all(8)),//Add this edge option
                  child: DropdownButton(
                    isExpanded: true,
                    isDense: true,
                    itemHeight: 50.0,

                    hint: Text(
                        'Please choose a location'), // Not necessary for Option 1
                    value: _selectedLocation,
                    onChanged: (newValue) {
                      setState(() {
                        _selectedLocation = newValue;
                      });
                    },
                    items: citys.map((location) {
                      return DropdownMenuItem(
                        child: new Text(location.name),
                        value: location.id,
                      );
                    }).toList(),
                  ),
                ),

Get difference between two dates in months using Java

You can use Joda time library for Java. It would be much easier to calculate time-diff between dates with it.

Sample snippet for time-diff:

Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();

validation of input text field in html using javascript

If you are not using jQuery then I would simply write a validation method that you can be fired when the form is submitted. The method can validate the text fields to make sure that they are not empty or the default value. The method will return a bool value and if it is false you can fire off your alert and assign classes to highlight the fields that did not pass validation.

HTML:

<form name="form1" method="" action="" onsubmit="return validateForm(this)">
<input type="text" name="name" value="Name"/><br />
<input type="text" name="addressLine01" value="Address Line 1"/><br />
<input type="submit"/>
</form>

JavaScript:

function validateForm(form) {

    var nameField = form.name;
    var addressLine01 = form.addressLine01;

    if (isNotEmpty(nameField)) {
        if(isNotEmpty(addressLine01)) {
            return true;
        {
    {
    return false;
}

function isNotEmpty(field) {

    var fieldData = field.value;

    if (fieldData.length == 0 || fieldData == "" || fieldData == fieldData) {

        field.className = "FieldError"; //Classs to highlight error
        alert("Please correct the errors in order to continue.");
        return false;
    } else {

        field.className = "FieldOk"; //Resets field back to default
        return true; //Submits form
    }
}

The validateForm method assigns the elements you want to validate and then in this case calls the isNotEmpty method to validate if the field is empty or has not been changed from the default value. it continuously calls the inNotEmpty method until it returns a value of true or if the conditional fails for that field it will return false.

Give this a shot and let me know if it helps or if you have any questions. of course you can write additional custom methods to validate numbers only, email address, valid URL, etc.

If you use jQuery at all I would look into trying out the jQuery Validation plug-in. I have been using it for my last few projects and it is pretty nice. Check it out if you get a chance. http://docs.jquery.com/Plugins/Validation

Display back button on action bar

ActionBar actionBar=getActionBar();

actionBar.setDisplayHomeAsUpEnabled(true);

@Override
public boolean onOptionsItemSelected(MenuItem item) { 
        switch (item.getItemId()) {
        case android.R.id.home: 
            onBackPressed();
            return true;
        }

    return super.onOptionsItemSelected(item);
}

How do you debug MySQL stored procedures?

MySQL user defined variable (shared in session) could be used as logging output:

DELIMITER ;;
CREATE PROCEDURE Foo(tableName VARCHAR(128))
BEGIN
  SET @stmt = CONCAT('SELECT * FROM ', tableName);
  PREPARE pStmt FROM @stmt;
  EXECUTE pStmt;
  DEALLOCATE PREPARE pStmt;
  -- uncomment after debugging to cleanup
  -- SET @stmt = null;
END;;
DELIMITER ;
call Foo('foo');
select @stmt;

will output:

SELECT * FROM foo

SQL Server: Query fast, but slow from procedure

Though I'm usually against it (though in this case it seems that you have a genuine reason), have you tried providing any query hints on the SP version of the query? If SQL Server is preparing a different execution plan in those two instances, can you use a hint to tell it what index to use, so that the plan matches the first one?

For some examples, you can go here.

EDIT: If you can post your query plan here, perhaps we can identify some difference between the plans that's telling.

SECOND: Updated the link to be SQL-2000 specific. You'll have to scroll down a ways, but there's a second titled "Table Hints" that's what you're looking for.

THIRD: The "Bad" query seems to be ignoring the [IX_Openers_SessionGUID] on the "Openers" table - any chance adding an INDEX hint to force it to use that index will change things?

How to symbolicate crash log Xcode?

Follow these steps in Xcode 10 to symbolicate a crash log from an app build on the same machine:

  1. Inside Organizer, locate the archive where the app is based on.
  2. Click on the Download Debug Symbols button. Nothing will appear in your Downloads folder, but that's OK.
  3. Connect the build machine to an iOS device.
  4. Select the device in Devices and Simulators.
  5. Click on the View Devices Logs button.
  6. Drag-and-drop the crash file to the left panel. The file must end with a .crash extension, otherwise the drag fails.
  7. Switch to the All Logs tab.
  8. Select the added crash file.
  9. The file should automatically symbolicate, otherwise use the right-click context menu item Re-Symbolicate Log.

How can I pass a reference to a function, with parameters?

What you are after is called partial function application.

Don't be fooled by those that don't understand the subtle difference between that and currying, they are different.

Partial function application can be used to implement, but is not currying. Here is a quote from a blog post on the difference:

Where partial application takes a function and from it builds a function which takes fewer arguments, currying builds functions which take multiple arguments by composition of functions which each take a single argument.

This has already been answered, see this question for your answer: How can I pre-set arguments in JavaScript function call?

Example:

var fr = partial(f, 1, 2, 3);

// now, when you invoke fr() it will invoke f(1,2,3)
fr();

Again, see that question for the details.

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

If you want to just select the id use select max(id) from customer.

If you want to select the entire row then use a query like this:

select c1.*
from customer c1, (select max(id) as max_id from customer )c2 
where c1.id=c2.max_id

c2 is an alias for the new temporary table which contains max id. Then its cross product is taken with customer table to get the entire row.

Here we are writing a query in the from clause, which can often be quite useful.

Parsing JSON object in PHP using json_decode

When you json decode , force it to return an array instead of object.

$data = json_decode($json, TRUE); -> // TRUE

This will return an array and you can access the values by giving the keys.

Send raw ZPL to Zebra printer via USB

Install an share your printer: \localhost\zebra Send ZPL as text, try with copy first:

copy file.zpl \localhost\zebra

very simple, almost no coding.

Setting the selected value on a Django forms.ChoiceField

Try setting the initial value when you instantiate the form:

form = MyForm(initial={'max_number': '3'})

ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller

string Index = i;
            string FileName = "Mutton" + Index + ".xml";
            XmlDocument xmlDoc = new XmlDocument();

            var path = Path.Combine(Server.MapPath("~/Content/FilesXML"), FileName);
            xmlDoc.Load(path); // Can use xmlDoc.LoadXml(YourString);

this is the best Solution to get the path what is exactly need for now

How do I check how many options there are in a dropdown menu?

Get the number of options in a particular select element

$("#elementid option").length

Simple dynamic breadcrumb

This may be overkill for a simple breadcrumb, but it's worth a shot. I remember having this issue a long time ago when I first started, but I never really solved it. That is, until I just decided to write this up now. :)

I have documented as best I can inline, at the bottom are 3 possible use cases. Enjoy! (feel free to ask any questions you may have)

<?php

// This function will take $_SERVER['REQUEST_URI'] and build a breadcrumb based on the user's current path
function breadcrumbs($separator = ' &raquo; ', $home = 'Home') {
    // This gets the REQUEST_URI (/path/to/file.php), splits the string (using '/') into an array, and then filters out any empty values
    $path = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));

    // This will build our "base URL" ... Also accounts for HTTPS :)
    $base = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';

    // Initialize a temporary array with our breadcrumbs. (starting with our home page, which I'm assuming will be the base URL)
    $breadcrumbs = Array("<a href=\"$base\">$home</a>");

    // Find out the index for the last value in our path array
    $last = end(array_keys($path));

    // Build the rest of the breadcrumbs
    foreach ($path AS $x => $crumb) {
        // Our "title" is the text that will be displayed (strip out .php and turn '_' into a space)
        $title = ucwords(str_replace(Array('.php', '_'), Array('', ' '), $crumb));

        // If we are not on the last index, then display an <a> tag
        if ($x != $last)
            $breadcrumbs[] = "<a href=\"$base$crumb\">$title</a>";
        // Otherwise, just display the title (minus)
        else
            $breadcrumbs[] = $title;
    }

    // Build our temporary array (pieces of bread) into one big string :)
    return implode($separator, $breadcrumbs);
}

?>

<p><?= breadcrumbs() ?></p>
<p><?= breadcrumbs(' > ') ?></p>
<p><?= breadcrumbs(' ^^ ', 'Index') ?></p>

Sorting Python list based on the length of the string

The easiest way to do this is:

list.sort(key = lambda x:len(x))

Unsupported major.minor version 52.0 in my app

Changing com.android.tools.build:gradle:2.2.0-beta1 to com.android.tools.build:gradle:2.1.2 fixed it for me.

My Android Studio version is 2.1.2, perhaps that's why

how to check for null with a ng-if values in a view with angularjs?

Here is a simple example that I tried to explain.

<div>
    <div *ngIf="product">     <!--If "product" exists-->
      <h2>Product Details</h2><hr>
      <h4>Name: {{ product.name }}</h4>
      <h5>Price: {{ product.price | currency }}</h5>
      <p> Description: {{ product.description }}</p>
    </div>

    <div *ngIf="!product">     <!--If "product" not exists-->
       *Product not found
    </div>
</div>

Java string replace and the NUL (NULL, ASCII 0) character?

Should be probably changed to

firstName = firstName.trim().replaceAll("\\.", "");

How to assign execute permission to a .sh file in windows to be executed in linux

The ZIP file format does allow to store the permission bits, but Windows programs normally ignore it. The zip utility on Cygwin however does preserve the x bit, just like it does on Linux. If you do not want to use Cygwin, you can take a source code and tweak it so that all *.sh files get the executable bit set. Or write a script like explained here

Countdown timer using Moment js

Timezones. You have to deal with them, by using getTimezoneOffset() if you want your visitors from around the wolrd to get the same time.

Try this http://jsfiddle.net/cxyms/2/, it works for me, but I'm not sure will it work with other timezones.

var eventTimeStamp = '1366549200'; // Timestamp - Sun, 21 Apr 2013 13:00:00 GMT
var currentTimeStamp = '1366547400'; // Timestamp - Sun, 21 Apr 2013 12:30:00 GMT

var eventTime = new Date();
eventTime.setTime(366549200);

var Offset = new Date(eventTime.getTimezoneOffset()*60000)

var Diff = eventTimeStamp - currentTimeStamp + (Offset.getTime() / 2);
var duration = moment.duration(Diff, 'milliseconds');
var interval = 1000;

setInterval(function(){
  duration = moment.duration(duration.asMilliseconds() - interval, 'milliseconds');
  $('.countdown').text(moment(duration.asMilliseconds()).format('H[h]:mm[m]:ss[s]'));
}, interval);

Extension mysqli is missing, phpmyadmin doesn't work

Latest phpMyAdmin versions require mysqli extension and will no longer work with mysql one (note the extra "i" at the end of its name).

For PHP 5

sudo apt-get install php5-mysqli

For PHP 7.3

sudo apt-get install php7.3-mysqli

Will install package containing both old one and the new one, so afterwards all you need to do is to add

extension=mysqli.so

in your php.ini, under the subject Dynamic Extensions.

Restart apache:

sudo systemctl restart apache2

Authenitacate and press enter.

Should be done! If problem still occurs remove the browser cache.

How to select rows with one or more nulls from a pandas DataFrame without listing columns explicitly?

If you want to filter rows by a certain number of columns with null values, you may use this:

df.iloc[df[(df.isnull().sum(axis=1) >= qty_of_nuls)].index]

So, here is the example:

Your dataframe:

>>> df = pd.DataFrame([range(4), [0, np.NaN, 0, np.NaN], [0, 0, np.NaN, 0], range(4), [np.NaN, 0, np.NaN, np.NaN]])
>>> df
     0    1    2    3
0  0.0  1.0  2.0  3.0
1  0.0  NaN  0.0  NaN
2  0.0  0.0  NaN  0.0
3  0.0  1.0  2.0  3.0
4  NaN  0.0  NaN  NaN

If you want to select the rows that have two or more columns with null value, you run the following:

>>> qty_of_nuls = 2
>>> df.iloc[df[(df.isnull().sum(axis=1) >=qty_of_nuls)].index]
     0    1    2   3
1  0.0  NaN  0.0 NaN
4  NaN  0.0  NaN NaN

Change Twitter Bootstrap Tooltip content on click

if you have set the title attribute in HTML then use on click of the icon or button $(this).attr('title',newValue);

How to add,set and get Header in request of HttpClient?

You can test-drive this code exactly as is using the public GitHub API (don't go over the request limit):

public class App {

    public static void main(String[] args) throws IOException {

        CloseableHttpClient client = HttpClients.custom().build();

        // (1) Use the new Builder API (from v4.3)
        HttpUriRequest request = RequestBuilder.get()
                .setUri("https://api.github.com")
                // (2) Use the included enum
                .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
                // (3) Or your own
                .setHeader("Your own very special header", "value")
                .build();

        CloseableHttpResponse response = client.execute(request);

        // (4) How to read all headers with Java8
        List<Header> httpHeaders = Arrays.asList(response.getAllHeaders());
        httpHeaders.stream().forEach(System.out::println);

        // close client and response
    }
}

How to add Button over image using CSS?

Adapt this example to your code

HTML

<div class="img-holder">
    <img src="images/img-1.png" alt="image description"/>
    <a class="link" href=""></a>
</div>

CSS

.img-holder {position: relative;}
.img-holder .link {
    position: absolute;
    bottom: 10px; /*your button position*/
    right: 10px; /*your button position*/
}

importing external ".txt" file in python

This answer is modified from infrared's answer at Splitting large text file by a delimiter in Python

with open('words.txt') as fp:
    contents = fp.read()
    for entry in contents:
        # do something with entry