Programs & Examples On #Dot product

In mathematics, the dot product or scalar product is an algebraic operation that takes two equal-length sequences of numbers (usually coordinate vectors) and returns a single number.

Print string and variable contents on the same line in R

Easiest way to do this is to use paste()

> paste("Today is", date())
[1] "Today is Sat Feb 21 15:25:18 2015"

paste0() would result in the following:

> paste0("Today is", date())
[1] "Today isSat Feb 21 15:30:46 2015"

Notice there is no default seperator between the string and x. Using a space at the end of the string is a quick fix:

> paste0("Today is ", date())
[1] "Today is Sat Feb 21 15:32:17 2015"

Then combine either function with print()

> print(paste("This is", date()))
[1] "This is Sat Feb 21 15:34:23 2015"

Or

> print(paste0("This is ", date()))
[1] "This is Sat Feb 21 15:34:56 2015"

As other users have stated, you could also use cat()

how to set the background image fit to browser using html

Found an easier way to set it. Here's the html and css:

<style>
    #body {
        *background: url(../Images/abcd.jpg) no-repeat center center fixed; /* For IE 6 and 7 */
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
    }
</style>

<body id="body">
    <nav class="navbar navbar-default" id="navColour">
        <div class="container-fluid">
            <div class="navbar-header">
                <a id="clr" class="navbar-brand" href="#">Summer Haze Festival</a>
            </div>
            <div>
                <ul class="nav navbar-nav" >
                    <li id="clr" class="active"><a href="#">Home</a></li>
                    <li id="clr"><a href="#">Page 1</a></li>
                    <li id="clr"><a href="#">Page 2</a></li>
                    <li id="clr"><a href="#">Page 3</a></li>
                </ul>
            </div>
        </div>
    </nav>
</body>

url(../Images/abcd.jpg) being the image stored in your solution in a folder called Images. Hope it helps. Note: I used the id "body" because the navigation bar was somehow overriding my background image.

How to check if DST (Daylight Saving Time) is in effect, and if so, the offset?

Is there an issue using the Date.toString().indexOf('Daylight Time') > -1

"" + new Date()

Sat Jan 01 100050 00:00:00 GMT-0500 (Eastern Standard Time)

"" + new Date(...)

Sun May 01 100033 00:00:00 GMT-0400 (Eastern Daylight Time)

This seems compatible with all browsers.

How to enable authentication on MongoDB through Docker?

a. You can use environment variables via terminal:

$ docker run -d --name container_name \
      -e MONGO_INITDB_ROOT_USERNAME=admin \
      -e MONGO_INITDB_ROOT_PASSWORD=password \
      mongo

If you like to test if everything works:

// ssh into the running container
// Change container name if necessary
$ docker exec -it mongo /bin/bash

// Enter into mongo shell
$ mongo

// Caret will change when you enter successfully
// Switch to admin database
$> use admin
$> db.auth("admin", passwordPrompt())

// Show available databases
$> show dbs

If you like to instantiate a database on first run, check option b.

b. You can use environment variables in your docker stack deploy file or compose file for versions 3.4 through 4.1.

As it is explained on the quick reference section of the official mongo image set MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD in your yaml file:

mongo:
    image: mongo
    environment:
      MONGO_INITDB_ROOT_USERNAME: admin
      MONGO_INITDB_ROOT_PASSWORD: password

docker-entrypoint.sh file in mongo image checks for the existence of these two variables and sets --auth flag accordingly.

c. You can also use docker secrets.

MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD is set indirectly by docker-entrypoint.sh from MONGO_INITDB_ROOT_USERNAME_FILE and MONGO_INITDB_ROOT_PASSWORD_FILE variables:

mongo:
    image: mongo
    environment:
        - MONGO_INITDB_ROOT_USERNAME_FILE=/run/secrets/db_root_username
        - MONGO_INITDB_ROOT_PASSWORD_FILE=/run/secrets/db_root_password
    secrets:
      - db_root_username
      - db_root_password

docker-entrypoint.sh converts MONGO_INITDB_ROOT_USERNAME_FILE and MONGO_INITDB_ROOT_PASSWORD_FILE to MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD.

You can use MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD in your .sh or .js scripts in docker-entrypoint-initdb.d folder while initializing database instance.

When a container is started for the first time it will execute files with extensions .sh and .js that are found in /docker-entrypoint-initdb.d. Files will be executed in alphabetical order. .js files will be executed by mongo using the database specified by the MONGO_INITDB_DATABASE variable, if it is present, or test otherwise. You may also switch databases within the .js script.

This last method is not in the reference docs, so it may not survive an update.

Detect end of ScrollView

I found a simple way to detect this :

   scrollView.getViewTreeObserver()
       .addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
            @Override
            public void onScrollChanged() {
                if (scrollView.getChildAt(0).getBottom()
                     <= (scrollView.getHeight() + scrollView.getScrollY())) {
                    //scroll view is at bottom
                } else {
                    //scroll view is not at bottom
                }
            }
        });
  • Doesn't need to custom ScrollView.
  • Scrollview can host only one direct child, so scrollView.getChildAt(0) is okay.
  • This solution is right even the height of direct child of scroll view is match_parent or wrap_content.

How do you add Boost libraries in CMakeLists.txt?

Put this in your CMakeLists.txt file (change any options from OFF to ON if you want):

set(Boost_USE_STATIC_LIBS OFF) 
set(Boost_USE_MULTITHREADED ON)  
set(Boost_USE_STATIC_RUNTIME OFF) 
find_package(Boost 1.45.0 COMPONENTS *boost libraries here*) 

if(Boost_FOUND)
    include_directories(${Boost_INCLUDE_DIRS}) 
    add_executable(progname file1.cxx file2.cxx) 
    target_link_libraries(progname ${Boost_LIBRARIES})
endif()

Obviously you need to put the libraries you want where I put *boost libraries here*. For example, if you're using the filesystem and regex library you'd write:

find_package(Boost 1.45.0 COMPONENTS filesystem regex)

Logical operator in a handlebars.js {{#if}} conditional

This is possible by 'cheating' with a block helper. This probably goes against the Ideology of the people who developed Handlebars.

Handlebars.registerHelper('ifCond', function(v1, v2, options) {
  if(v1 === v2) {
    return options.fn(this);
  }
  return options.inverse(this);
});

You can then call the helper in the template like this

{{#ifCond v1 v2}}
    {{v1}} is equal to {{v2}}
{{else}}
    {{v1}} is not equal to {{v2}}
{{/ifCond}}

A network-related or instance-specific error occurred while establishing a connection to SQL Server

Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.

  1. Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .

  2. if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .

  3. if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .

  4. after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).

  5. if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.

  6. If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.

  7. If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.

  8. If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property. enter image description here

    1. Restart your sql server instance after making any changes in property as some changes will require restart.

if you further face any difficulty then you need to provide more information about your web site and sql server .

jQuery UI Alert Dialog as a replacement for alert()

There is an issue that if you close the dialog it will execute the onCloseCallback function. This is a better design.

function jAlert2(outputMsg, titleMsg, onCloseCallback) {
    if (!titleMsg)
        titleMsg = 'Alert';

    if (!outputMsg)
        outputMsg = 'No Message to Display.';

    $("<div></div>").html(outputMsg).dialog({
        title: titleMsg,
        resizable: false,
        modal: true,
        buttons: {
            "OK": onCloseCallback,
            "Cancel": function() {
          $( this ).dialog( "destroy" );
            }

        },
    });

Get user profile picture by Id

UPDATE September 2020

Facebook has new requirements change: an access token will be required for all UID-based queries

So you have to add your app access token to the url:

https://graph.facebook.com/{profile_id}/picture?type=large&access_token={app_access_token}

To get your app_access_token use the following url:

https://graph.facebook.com/oauth/access_token?client_id={your-app-id}&client_secret={your-app-secret}&grant_type=client_credentials

You find your-app-id and your-app-secret in the Basic Settings of your Facebook app in Facebook developers

How to run script as another user without password?

Call visudo and add this:

user1 ALL=(user2) NOPASSWD: /home/user2/bin/test.sh

The command paths must be absolute! Then call sudo -u user2 /home/user2/bin/test.sh from a user1 shell. Done.

jQuery-- Populate select from json

A solution is to create your own jquery plugin that take the json map and populate the select with it.

(function($) {     
     $.fn.fillValues = function(options) {
         var settings = $.extend({
             datas : null, 
             complete : null,
         }, options);

         this.each( function(){
            var datas = settings.datas;
            if(datas !=null) {
                $(this).empty();
                for(var key in datas){
                    $(this).append('<option value="'+key+'"+>'+datas[key]+'</option>');
                }
            }
            if($.isFunction(settings.complete)){
                settings.complete.call(this);
            }
        });

    }

}(jQuery));

You can call it by doing this :

$("#select").fillValues({datas:your_map,});

The advantages is that anywhere you will face the same problem you just call

 $("....").fillValues({datas:your_map,});

Et voila !

You can add functions in your plugin as you like

Error in plot.window(...) : need finite 'xlim' values

The problem is that you're (probably) trying to plot a vector that consists exclusively of missing (NA) values. Here's an example:

> x=rep(NA,100)
> y=rnorm(100)
> plot(x,y)
Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf

In your example this means that in your line plot(costs,pseudor2,type="l"), costs is completely NA. You have to figure out why this is, but that's the explanation of your error.


From comments:

Scott C Wilson: Another possible cause of this message (not in this case, but in others) is attempting to use character values as X or Y data. You can use the class function to check your x and Y values to be sure if you think this might be your issue.

stevec: Here is a quick and easy solution to that problem (basically wrap x in as.factor(x))

Spring Boot and how to configure connection details to MongoDB?

Here is How you can do in Spring Boot 2.0 by creating custom MongoClient adding Providing more control for Connection ,

Please follow github Link for Full Source Code

@Configuration
@EnableMongoRepositories(basePackages = { "com.frugalis.repository" })
@ComponentScan(basePackages = { "com.frugalis.*" })
@PropertySource("classpath:application.properties")
public class MongoJPAConfig extends AbstractMongoConfiguration {

    @Value("${com.frugalis.mongo.database}")
    private String database;
    @Value("${com.frugalis.mongo.server}")
    private String host;
    @Value("${com.frugalis.mongo.port}")
    private String port;
    @Value("${com.frugalis.mongo.username}")
    private String username;
    @Value("${com.frugalis.mongo.password}")
    private String password;


    @Override
    protected String getDatabaseName() {
        return database;
    }

    @Override
    protected String getMappingBasePackage() {
        return "com.frugalis.entity.mongo";
    }

    @Bean
    public MongoTemplate mongoTemplate() throws Exception {
        return new MongoTemplate(mongoClient(), getDatabaseName());
    }

    @Override
    @Bean
    public MongoClient mongoClient() {

        List<MongoCredential> allCred = new ArrayList<MongoCredential>();
        System.out.println("???????????????????"+username+" "+database+" "+password+" "+host+" "+port);
        allCred.add(MongoCredential.createCredential(username, database, password.toCharArray()));
        MongoClient client = new MongoClient((new ServerAddress(host, Integer.parseInt(port))), allCred);
        client.setWriteConcern(WriteConcern.ACKNOWLEDGED);

        return client;
    }} 

Integer.toString(int i) vs String.valueOf(int i)

There have no differences between Integer.toString(5) and String.valueOf(5);

because String.valueOf returns:

public static String valueOf(int i) {
    return Integer.toString(i);
}
public static String valueOf(float f) {
    return Float.toString(f);
}

etc..

Using an integer as a key in an associative array in JavaScript

Use an object instead of an array. Arrays in JavaScript are not associative arrays. They are objects with magic associated with any properties whose names look like integers. That magic is not what you want if you're not using them as a traditional array-like structure.

var test = {};
test[2300] = 'some string';
console.log(test);

Trusting all certificates using HttpClient over HTTPS

You can disable HttpURLConnection SSL checking for testing purposes this way since API 8:

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    if (conn instanceof HttpsURLConnection) {
        HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
        httpsConn.setSSLSocketFactory(SSLCertificateSocketFactory.getInsecure(0, null));
        httpsConn.setHostnameVerifier(new AllowAllHostnameVerifier());
    }

Make just one slide different size in Powerpoint

True you can't have different sized slides. NOT true the size of you slide doesn't matter. It will size it to your resolution, but you can click on the magnifying icon(at least on PP 2013) and you can then scroll in all directions of your slide in original resolution.

Turn a single number into single digits Python

If you want to change your number into a list of those numbers, I would first cast it to a string, then casting it to a list will naturally break on each character:

[int(x) for x in str(n)]

ERROR 1148: The used command is not allowed with this MySQL version

I got this error while loading data when using docker[1]. The solution worked after I followed these next steps. Initially, I created the database and table datavault and fdata. When I tried to import the data[2], I got the error[3]. Then I did:

  • SET GLOBAL local_infile = 1;
  • Confirm using SHOW VARIABLES LIKE 'local_infile';
  • Then I restarted my mysql session: mysql -P 3306 -u required --local-infile=1 -p, see [4] for user creation.
  • I recreated my table as this solved my problem:
    • use datavault;
    • drop table fdata;
    • CREATE TABLE fdata (fID INT, NAME VARCHAR(64), LASTNAME VARCHAR(64), EMAIL VARCHAR(128), GENDER VARCHAR(12), IPADDRESS VARCHAR(40));
  • Finally I imported the data using [2].

For completeness, I would add I was running the mysql version inside the container via docker exec -it testdb sh. The mysql version was mysql Ver 8.0.17 for Linux on x86_64 (MySQL Community Server - GPL). This was also tested with mysql.exe Ver 14.14 Distrib 5.7.14, for Win64 (x86_64) which was another version of mysql from WAMP64. The associated commands used are listed in [5].


[1] docker run --name testdb -v //c/Users/C/Downloads/data/csv-data/:/var/data -p 3306 -e MYSQL_ROOT_PASSWORD=password -d mysql:latest

[2] load data local infile '/var/data/mockdata.csv' into table fdata fields terminated by ',' enclosed by '' lines terminated by '\n' IGNORE 1 ROWS;

[3] ERROR 1148 (42000): The used command is not allowed with this MySQL version

[4] The required client was created using:

  • CREATE USER 'required'@'%' IDENTIFIED BY 'password';
  • GRANT ALL PRIVILEGES ON * . * TO 'required'@'%';
  • FLUSH PRIVILEGES;
  • You might need this line ALTER USER 'required'@'%' IDENTIFIED WITH mysql_native_password BY 'password'; if you run into this error: Authentication plugin ‘caching_sha2_password’ cannot be loaded

[5] Commands using mysql from WAMP64:

  • mysql -urequired -ppassword -P 32775 -h 192.168.99.100 --local-infile=1 where the port is thee mapped port into the host as described by docker ps -a and the host ip was optained using docker-machine ip (This depends on OS and possibly Docker version).
  • Create database datavault2 and table fdata as described above
  • load data local infile 'c:/Users/C/Downloads/data/csv-data/mockdata.csv' into table fdata fields terminated by ',' enclosed by '' lines terminated by '\n';
  • For my record, this other alternative to load the file worked after I have previously created datavault3 and fdata: mysql -urequired -ppassword -P 32775 -h 192.168.99.100 --local-infile datavault3 -e "LOAD DATA LOCAL INFILE 'c:/Users/C/Downloads/data/csv-data/mockdata.csv' REPLACE INTO TABLE fdata FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' IGNORE 1 ROWS" and it successfully loaded the data easily checked after running select * from fdata limit 10;.

Save range to variable

... And the answer is:

Set SrcRange = Sheets("Src").Range("A2:A9")
SrcRange.Copy Destination:=Sheets("Dest").Range("A2")

The Set makes all the difference. Then it works like a charm.

How can I obfuscate (protect) JavaScript?

Obfuscation:

Try YUI Compressor. It's a very popular tool, built, enhanced and maintained by the Yahoo UI team.

You may also use:

UPDATE: This question was originally asked more than 10 years ago, and YUI is no longer maintained. Google Closure Compiler is still in use, and UglifyJS can be run locally via node package manager: npm install -g uglify-js

Private String Data:

Keeping string values private is a different concern, and obfuscation won't really be of much benefit. Of course, by packaging up your source into a garbled, minified mess, you have a light version of security through obscurity. Most of the time, it's your user who is viewing the source, and the string values on the client are intended for their use, so that sort of private string value isn't often necessary.

If you really had a value that you never wanted a user to see, you would have a couple of options. First, you could do some kind of encryption, which is decrypted at page load. That would probably be one of the most secure options, but also a lot of work which may be unnecessary. You could probably base64 encode some string values, and that would be easier.. but someone who really wanted those string values could easily decode them. Encryption is the only way to truly prevent anyone from accessing your data, and most people find that to be more security than they need.

Sidenote:

Obfuscation in Javascript has been known to cause some bugs. The obfuscators are getting a little better about it, but many outfits decide that they see enough benefit from minifying and gzipping, and the added savings of obfuscation isn't always worth the trouble. If you're trying to protect your source, maybe you'll decide that it's worth your while, just to make your code harder to read. JSMin is a good alternative.

Extracting the top 5 maximum values in excel

Put the data into a Pivot Table and do a top n filter on it

Excel Demo

Copy array by value

In Javascript, deep-copy techniques depend on the elements in an array. Let's start there.

Three types of elements

Elements can be: literal values, literal structures, or prototypes.

// Literal values (type1)
const booleanLiteral = true;
const numberLiteral = 1;
const stringLiteral = 'true';

// Literal structures (type2)
const arrayLiteral = [];
const objectLiteral = {};

// Prototypes (type3)
const booleanPrototype = new Bool(true);
const numberPrototype = new Number(1);
const stringPrototype = new String('true');
const arrayPrototype = new Array();
const objectPrototype = new Object(); // or `new function () {}`

From these elements we can create three types of arrays.

// 1) Array of literal-values (boolean, number, string) 
const type1 = [true, 1, "true"];

// 2) Array of literal-structures (array, object)
const type2 = [[], {}];

// 3) Array of prototype-objects (function)
const type3 = [function () {}, function () {}];

Deep copy techniques depend on the three array types

Based on the types of elements in the array, we can use various techniques to deep copy.

Javascript deep copy techniques by element types

  • Array of literal-values (type1)
    The [...myArray], myArray.splice(0), myArray.slice(), and myArray.concat() techniques can be used to deep copy arrays with literal values (boolean, number, and string) only; where the Spread operator [...myArray] has the best performance (https://measurethat.net/Benchmarks/Show/4281/0/spread-array-performance-vs-slice-splice-concat).

  • Array of literal-values (type1) and literal-structures (type2)
    The JSON.parse(JSON.stringify(myArray)) technique can be used to deep copy literal values (boolean, number, string) and literal structures (array, object), but not prototype objects.

  • All arrays (type1, type2, type3)
    The jQuery $.extend(myArray) technique can be used to deep-copy all array-types. Libraries like Underscore and Lo-dash offer similar deep-copy functions to jQuery $.extend(), yet have lower performance. More surprisingly, $.extend() has higher performance than the JSON.parse(JSON.stringify(myArray)) technique http://jsperf.com/js-deep-copy/15.
    And for those developers that shy away from third-party libraries (like jQuery), you can use the following custom function; which has higher performance than $.extend, and deep-copies all arrays.

function copy(aObject) {
  if (!aObject) {
    return aObject;
  }

  let v;
  let bObject = Array.isArray(aObject) ? [] : {};
  for (const k in aObject) {
    v = aObject[k];
    bObject[k] = (typeof v === "object") ? copy(v) : v;
  }

  return bObject;
}

So to answer the question...

Question

var arr1 = ['a','b','c'];
var arr2 = arr1;

I realized that arr2 refers to the same array as arr1, rather than a new, independent array. How can I copy the array to get two independent arrays?

Answer

Because arr1 is an array of literal values (boolean, number, or string), you can use any deep copy technique discussed above, where the spread operator ... has the highest performance.

// Highest performance for deep copying literal values
arr2 = [...arr1];

// Any of these techniques will deep copy literal values as well,
//   but with lower performance.
arr2 = arr1.slice();
arr2 = arr1.splice(0);
arr2 = arr1.concat();
arr2 = JSON.parse(JSON.stringify(arr1));
arr2 = $.extend(true, [], arr1); // jQuery.js needed
arr2 = _.extend(arr1); // Underscore.js needed
arr2 = _.cloneDeep(arr1); // Lo-dash.js needed
arr2 = copy(arr1); // Custom-function needed - as provided above

How to split csv whose columns may contain ,

Use the Microsoft.VisualBasic.FileIO.TextFieldParser class. This will handle parsing a delimited file, TextReader or Stream where some fields are enclosed in quotes and some are not.

For example:

using Microsoft.VisualBasic.FileIO;

string csv = "2,1016,7/31/2008 14:22,Geoff Dalgas,6/5/2011 22:21,http://stackoverflow.com,\"Corvallis, OR\",7679,351,81,b437f461b3fd27387c5d8ab47a293d35,34";

TextFieldParser parser = new TextFieldParser(new StringReader(csv));

// You can also read from a file
// TextFieldParser parser = new TextFieldParser("mycsvfile.csv");

parser.HasFieldsEnclosedInQuotes = true;
parser.SetDelimiters(",");

string[] fields;

while (!parser.EndOfData)
{
    fields = parser.ReadFields();
    foreach (string field in fields)
    {
        Console.WriteLine(field);
    }
} 

parser.Close();

This should result in the following output:

2
1016
7/31/2008 14:22
Geoff Dalgas
6/5/2011 22:21
http://stackoverflow.com
Corvallis, OR
7679
351
81
b437f461b3fd27387c5d8ab47a293d35
34

See Microsoft.VisualBasic.FileIO.TextFieldParser for more information.

You need to add a reference to Microsoft.VisualBasic in the Add References .NET tab.

In Django, how do I check if a user is in a certain group?

I have similar situation, I wanted to test if the user is in a certain group. So, I've created new file utils.py where I put all my small utilities that help me through entire application. There, I've have this definition:

utils.py

def is_company_admin(user):
    return user.groups.filter(name='company_admin').exists()

so basically I am testing if the user is in the group company_admin and for clarity I've called this function is_company_admin.

When I want to check if the user is in the company_admin I just do this:

views.py

from .utils import *

if is_company_admin(request.user):
        data = Company.objects.all().filter(id=request.user.company.id)

Now, if you wish to test same in your template, you can add is_user_admin in your context, something like this:

views.py

return render(request, 'admin/users.html', {'data': data, 'is_company_admin': is_company_admin(request.user)})

Now you can evaluate you response in a template:

users.html

{% if is_company_admin %}
     ... do something ...
{% endif %}

Simple and clean solution, based on answers that can be found earlier in this thread, but done differently. Hope it will help someone.

Tested in Django 3.0.4.

Getting the name of a variable as a string

>> my_var = 5
>> my_var_name = [ k for k,v in locals().items() if v == my_var][0]
>> my_var_name 
'my_var'

In case you get an error if myvar points to another variable, try this (suggested by @mherzog)-

 >> my_var = 5
>> my_var_name = [ k for k,v in locals().items() if v is my_var][0]
>> my_var_name 
'my_var'

locals() - Return a dictionary containing the current scope's local variables. by iterating through this dictionary we can check the key which has a value equal to the defined variable, just extracting the key will give us the text of variable in string format.

from (after a bit changes) https://www.tutorialspoint.com/How-to-get-a-variable-name-as-a-string-in-Python

Is it possible that one domain name has multiple corresponding IP addresses?

You can do it. That is what big guys do as well.

First query:

» host google.com 
google.com has address 74.125.232.230
google.com has address 74.125.232.231
google.com has address 74.125.232.232
google.com has address 74.125.232.233
google.com has address 74.125.232.238
google.com has address 74.125.232.224
google.com has address 74.125.232.225
google.com has address 74.125.232.226
google.com has address 74.125.232.227
google.com has address 74.125.232.228
google.com has address 74.125.232.229

Next query:

» host google.com
google.com has address 74.125.232.224
google.com has address 74.125.232.225
google.com has address 74.125.232.226
google.com has address 74.125.232.227
google.com has address 74.125.232.228
google.com has address 74.125.232.229
google.com has address 74.125.232.230
google.com has address 74.125.232.231
google.com has address 74.125.232.232
google.com has address 74.125.232.233
google.com has address 74.125.232.238

As you see, the list of IPs rotated around, but the relative order between two IPs stayed the same.

Update: I see several comments bragging about how DNS round-robin is not convenient for fail-over, so here is the summary: DNS is not for fail-over. So it is obviously not good for fail-over. It was never designed to be a solution for fail-over.

setSupportActionBar toolbar cannot be applied to (android.widget.Toolbar) error

In using toolbar you should extends AppCompatActivity and

import android.support.v7.widget.Toolbar 

Check if PHP-page is accessed from an iOS device

function isIosDevice(){
    $userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);
    $iosDevice = array('iphone', 'ipod', 'ipad');
    $isIos = false;

    foreach ($iosDevice as $val) {
        if(stripos($userAgent, $val) !== false){
            $isIos = true;
            break;
        }
    }

    return $isIos;
}

"The system cannot find the file specified"

Server Error in '/' Application.

The system cannot find the file specified

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ComponentModel.Win32Exception: The system cannot find the file specified

Source Error:

     {
                   SqlCommand cmd = new SqlCommand("select * from tblemployee",con);
                   con.Open();
                   GridView1.DataSource = cmd.ExecuteReader();
                   GridView1.DataBind();

Source File: d:\C# programs\kudvenkat\adobasics1\adobasics1\employeedata.aspx.cs Line: 23

if your error is same like mine..just do this

right click on your table in sqlserver object explorer,choose properties in lower left corner in general option there is a connection block with server and connection specification.in your web config for datasource=. or local choose name specified in server in properties..

Double precision - decimal places

IEEE 754 floating point is done in binary. There's no exact conversion from a given number of bits to a given number of decimal digits. 3 bits can hold values from 0 to 7, and 4 bits can hold values from 0 to 15. A value from 0 to 9 takes roughly 3.5 bits, but that's not exact either.

An IEEE 754 double precision number occupies 64 bits. Of this, 52 bits are dedicated to the significand (the rest is a sign bit and exponent). Since the significand is (usually) normalized, there's an implied 53rd bit.

Now, given 53 bits and roughly 3.5 bits per digit, simple division gives us 15.1429 digits of precision. But remember, that 3.5 bits per decimal digit is only an approximation, not a perfectly accurate answer.

Many (most?) debuggers actually look at the contents of the entire register. On an x86, that's actually an 80-bit number. The x86 floating point unit will normally be adjusted to carry out calculations to 64-bit precision -- but internally, it actually uses a couple of "guard bits", which basically means internally it does the calculation with a few extra bits of precision so it can round the last one correctly. When the debugger looks at the whole register, it'll usually find at least one extra digit that's reasonably accurate -- though since that digit won't have any guard bits, it may not be rounded correctly.

Enabling CORS in Cloud Functions for Firebase

For anyone trying to do this in Typescript this is the code:

import * as cors from 'cors';
const corsHandler = cors({origin: true});

export const exampleFunction= functions.https.onRequest(async (request, response) => {
       corsHandler(request, response, () => {});
       //Your code here
});

Parse v. TryParse

TryParse does not return the value, it returns a status code to indicate whether the parse succeeded (and doesn't throw an exception).

How can I get the count of milliseconds since midnight for the current?

You can use java.util.Calendar class to get time in milliseconds. Example:

Calendar cal = Calendar.getInstance();
int milliSec = cal.get(Calendar.MILLISECOND);
// print milliSec

java.util.Date date = cal.getTime();
System.out.println("Output: " +  new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss:SSS").format(date));

Check if a row exists, otherwise insert

Full solution is below (including cursor structure). Many thanks to Cassius Porcus for the begin trans ... commit code from posting above.

declare @mystat6 bigint
declare @mystat6p varchar(50)
declare @mystat6b bigint

DECLARE mycur1 CURSOR for

 select result1,picture,bittot from  all_Tempnogos2results11

 OPEN mycur1

 FETCH NEXT FROM mycur1 INTO @mystat6, @mystat6p , @mystat6b

 WHILE @@Fetch_Status = 0
 BEGIN

 begin tran /* default read committed isolation level is fine */

 if not exists (select * from all_Tempnogos2results11_uniq with (updlock, rowlock, holdlock)
                     where all_Tempnogos2results11_uniq.result1 = @mystat6 
                        and all_Tempnogos2results11_uniq.bittot = @mystat6b )
     insert all_Tempnogos2results11_uniq values (@mystat6 , @mystat6p , @mystat6b)

 --else
 --  /* update */

 commit /* locks are released here */

 FETCH NEXT FROM mycur1 INTO @mystat6 , @mystat6p , @mystat6b

 END

 CLOSE mycur1

 DEALLOCATE mycur1
 go

PowerShell: Run command from script's directory

This would work fine.

Push-Location $PSScriptRoot

Write-Host CurrentDirectory $CurDir

How do you add a JToken to an JObject?

TL;DR: You should add a JProperty to a JObject. Simple. The index query returns a JValue, so figure out how to get the JProperty instead :)


The accepted answer is not answering the question as it seems. What if I want to specifically add a JProperty after a specific one? First, lets start with terminologies which really had my head worked up.

  • JToken = The mother of all other types. It can be A JValue, JProperty, JArray, or JObject. This is to provide a modular design to the parsing mechanism.
  • JValue = any Json value type (string, int, boolean).
  • JProperty = any JValue or JContainer (see below) paired with a name (identifier). For example "name":"value".
  • JContainer = The mother of all types which contain other types (JObject, JValue).
  • JObject = a JContainer type that holds a collection of JProperties
  • JArray = a JContainer type that holds a collection JValue or JContainer.

Now, when you query Json item using the index [], you are getting the JToken without the identifier, which might be a JContainer or a JValue (requires casting), but you cannot add anything after it, because it is only a value. You can change it itself, query more deep values, but you cannot add anything after it for example.

What you actually want to get is the property as whole, and then add another property after it as desired. For this, you use JOjbect.Property("name"), and then create another JProperty of your desire and then add it after this using AddAfterSelf method. You are done then.

For more info: http://www.newtonsoft.com/json/help/html/ModifyJson.htm

This is the code I modified.

public class Program
{
  public static void Main()
  {
    try
    {
      string jsonText = @"
      {
        ""food"": {
          ""fruit"": {
            ""apple"": {
              ""colour"": ""red"",
              ""size"": ""small""
            },
            ""orange"": {
              ""colour"": ""orange"",
              ""size"": ""large""
            }
          }
        }
      }";

      var foodJsonObj = JObject.Parse(jsonText);
      var bananaJson = JObject.Parse(@"{ ""banana"" : { ""colour"": ""yellow"", ""size"": ""medium""}}");

      var fruitJObject = foodJsonObj["food"]["fruit"] as JObject;
      fruitJObject.Property("orange").AddAfterSelf(new JProperty("banana", fruitJObject));

      Console.WriteLine(foodJsonObj.ToString());
    }
    catch (Exception ex)
    {
      Console.WriteLine(ex.GetType().Name + ": " + ex.Message);
    }
  }
}

Bulk package updates using Conda

You want conda update --all.

conda search --outdated will show outdated packages, and conda update --all will update them (note that the latter will not update you from Python 2 to Python 3, but the former will show Python as being outdated if you do use Python 2).

How to change SmartGit's licensing option after 30 days of commercial use on ubuntu?

it would be helpful to know if you use linux or windows. in linux the settings are located in ~/.smartgit/3. You could try to remove this folder. Imho this is also worth a try in Windows.

How to Use Content-disposition for force a file to download to the hard drive?

With recent browsers you can use the HTML5 download attribute as well:

<a download="quot.pdf" href="../doc/quot.pdf">Click here to Download quotation</a>

It is supported by most of the recent browsers except MSIE11. You can use a polyfill, something like this (note that this is for data uri only, but it is a good start):

(function (){

    addEvent(window, "load", function (){
        if (isInternetExplorer())
            polyfillDataUriDownload();
    });

    function polyfillDataUriDownload(){
        var links = document.querySelectorAll('a[download], area[download]');
        for (var index = 0, length = links.length; index<length; ++index) {
            (function (link){
                var dataUri = link.getAttribute("href");
                var fileName = link.getAttribute("download");
                if (dataUri.slice(0,5) != "data:")
                    throw new Error("The XHR part is not implemented here.");
                addEvent(link, "click", function (event){
                    cancelEvent(event);
                    try {
                        var dataBlob = dataUriToBlob(dataUri);
                        forceBlobDownload(dataBlob, fileName);
                    } catch (e) {
                        alert(e)
                    }
                });
            })(links[index]);
        }
    }

    function forceBlobDownload(dataBlob, fileName){
        window.navigator.msSaveBlob(dataBlob, fileName);
    }

    function dataUriToBlob(dataUri) {
        if  (!(/base64/).test(dataUri))
            throw new Error("Supports only base64 encoding.");
        var parts = dataUri.split(/[:;,]/),
            type = parts[1],
            binData = atob(parts.pop()),
            mx = binData.length,
            uiArr = new Uint8Array(mx);
        for(var i = 0; i<mx; ++i)
            uiArr[i] = binData.charCodeAt(i);
        return new Blob([uiArr], {type: type});
    }

    function addEvent(subject, type, listener){
        if (window.addEventListener)
            subject.addEventListener(type, listener, false);
        else if (window.attachEvent)
            subject.attachEvent("on" + type, listener);
    }

    function cancelEvent(event){
        if (event.preventDefault)
            event.preventDefault();
        else
            event.returnValue = false;
    }

    function isInternetExplorer(){
        return /*@cc_on!@*/false || !!document.documentMode;
    }
    
})();

Free XML Formatting tool

If you are a programmer, many XML parsing programming libraries will let you parse XML, then output it - and generating pretty printed, indented output is an output option.

Node - how to run app.js?

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => res.send('Hello World!'))

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

How do I create a datetime in Python from milliseconds?

Bit heavy because of using pandas but works:

import pandas as pd
pd.to_datetime(msec_from_java, unit='ms').to_pydatetime()

How can I tell which button was clicked in a PHP form submit?

All you need to give the name attribute to the each button. And you need to address each button press from the PHP script. But be careful to give each button a unique name. Because the PHP script only take care of the name most of the time

<input type="submit" name="Submit_this" id="This" />

Generate Java classes from .XSD files...?

JAXB does EXACTLY what you want. It's built into the JRE/JDK starting at 1.6

Python strip() multiple characters?

string.translate with table=None works fine.

>>> name = "Barack (of Washington)"
>>> name = name.translate(None, "(){}<>")
>>> print name
Barack of Washington

How can I take a screenshot with Selenium WebDriver?

There are multiple methods through Selenium's Java and Python client to take a screenshot using Selenium WebDriver.


Java Methods

The following are the different Java methods to take a screenshot:

  • Using getScreenshotAs() from the TakesScreenshot interface:

  • Code block:

         package screenShot;
    
         import java.io.File;
         import java.io.IOException;
    
         import org.apache.commons.io.FileUtils;
         import org.openqa.selenium.OutputType;
         import org.openqa.selenium.TakesScreenshot;
         import org.openqa.selenium.WebDriver;
         import org.openqa.selenium.firefox.FirefoxDriver;
         import org.openqa.selenium.support.ui.ExpectedConditions;
         import org.openqa.selenium.support.ui.WebDriverWait;
    
         public class Firefox_takesScreenshot {
    
             public static void main(String[] args) throws IOException {
    
                 System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
                 WebDriver driver =  new FirefoxDriver();
                 driver.get("https://login.bws.birst.com/login.html/");
                 new WebDriverWait(driver, 20).until(ExpectedConditions.titleContains("Birst"));
                 File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
                 FileUtils.copyFile(scrFile, new File(".\\Screenshots\\Mads_Cruz_screenshot.png"));
                 driver.quit();
             }
         }
    
  • Screenshot:

    Mads_Cruz_screenshot

  • If the webpage is jQuery enabled, you can use from the pazone/ashot library:

  • Code block:

         package screenShot;
    
         import java.io.File;
         import javax.imageio.ImageIO;
         import org.openqa.selenium.WebDriver;
         import org.openqa.selenium.firefox.FirefoxDriver;
         import org.openqa.selenium.support.ui.ExpectedConditions;
         import org.openqa.selenium.support.ui.WebDriverWait;
    
         import ru.yandex.qatools.ashot.AShot;
         import ru.yandex.qatools.ashot.Screenshot;
         import ru.yandex.qatools.ashot.shooting.ShootingStrategies;
    
         public class ashot_CompletePage_Firefox {
    
             public static void main(String[] args) throws Exception {
    
                 System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
                 WebDriver driver =  new FirefoxDriver();
                 driver.get("https://jquery.com/");
                 new WebDriverWait(driver, 20).until(ExpectedConditions.titleContains("jQuery"));
                 Screenshot myScreenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(100)).takeScreenshot(driver);
                 ImageIO.write(myScreenshot.getImage(),"PNG",new File("./Screenshots/firefoxScreenshot.png"));
                 driver.quit();
             }
         }
    
  • Screenshot:

    firefoxScreenshot.png

  • Using from assertthat/selenium-shutterbug library:

  • Code block:

         package screenShot;
    
         import org.openqa.selenium.WebDriver;
         import org.openqa.selenium.firefox.FirefoxDriver;
         import com.assertthat.selenium_shutterbug.core.Shutterbug;
         import com.assertthat.selenium_shutterbug.utils.web.ScrollStrategy;
    
         public class selenium_shutterbug_fullpage_firefox {
    
             public static void main(String[] args) {
    
                 System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
                 WebDriver driver =  new FirefoxDriver();
                 driver.get("https://www.google.co.in");
                 Shutterbug.shootPage(driver, ScrollStrategy.BOTH_DIRECTIONS).save("./Screenshots/");
                 driver.quit();
             }
         }
    
  • Screenshot:

    2019_03_12_16_30_35_787.png


Python Methods

The following are the different Python methods to take a screenshot:

  • Using save_screenshot() method:

  • Code block:

         from selenium import webdriver
    
         driver = webdriver.Chrome(r'C:\Utility\BrowserDrivers\chromedriver.exe')
         driver.get("http://google.com")
         driver.save_screenshot('./Screenshots/save_screenshot_method.png')
         driver.quit()
    
  • Screenshot:

    save_screenshot_method.png

  • Using the get_screenshot_as_file() method:

  • Code block:

         from selenium import webdriver
    
         driver = webdriver.Chrome(r'C:\Utility\BrowserDrivers\chromedriver.exe')
         driver.get("http://google.com")
         driver.get_screenshot_as_file('./Screenshots/get_screenshot_as_file_method.png')
         driver.quit()
    
  • Screenshot:

    get_screenshot_as_file_method.png

  • Using get_screenshot_as_png() method:

  • Code block:

         from selenium import webdriver
    
         driver = webdriver.Chrome(r'C:\Utility\BrowserDrivers\chromedriver.exe')
         driver.get("http://google.com")
         screenPnG = driver.get_screenshot_as_png()
    
         # Crop it back to the window size (it may be taller)
         box = (0, 0, 1366, 728)
         im = Image.open(BytesIO(screenPnG))
         region = im.crop(box)
         region.save('./Screenshots/get_screenshot_as_png_method.png', 'PNG', optimize=True, quality=95)
         driver.quit()
    
  • Screenshot:

    get_screenshot_as_png_method.png

What's the difference between deadlock and livelock?

All the content and examples here are from

Operating Systems: Internals and Design Principles
William Stallings
8º Edition

Deadlock: A situation in which two or more processes are unable to proceed because each is waiting for one the others to do something.

For example, consider two processes, P1 and P2, and two resources, R1 and R2. Suppose that each process needs access to both resources to perform part of its function. Then it is possible to have the following situation: the OS assigns R1 to P2, and R2 to P1. Each process is waiting for one of the two resources. Neither will release the resource that it already owns until it has acquired the other resource and performed the function requiring both resources. The two processes are deadlocked

Livelock: A situation in which two or more processes continuously change their states in response to changes in the other process(es) without doing any useful work:

Starvation: A situation in which a runnable process is overlooked indefinitely by the scheduler; although it is able to proceed, it is never chosen.

Suppose that three processes (P1, P2, P3) each require periodic access to resource R. Consider the situation in which P1 is in possession of the resource, and both P2 and P3 are delayed, waiting for that resource. When P1 exits its critical section, either P2 or P3 should be allowed access to R. Assume that the OS grants access to P3 and that P1 again requires access before P3 completes its critical section. If the OS grants access to P1 after P3 has finished, and subsequently alternately grants access to P1 and P3, then P2 may indefinitely be denied access to the resource, even though there is no deadlock situation.

APPENDIX A - TOPICS IN CONCURRENCY

Deadlock Example

If both processes set their flags to true before either has executed the while statement, then each will think that the other has entered its critical section, causing deadlock.

/* PROCESS 0 */
flag[0] = true;            // <- get lock 0
while (flag[1])            // <- is lock 1 free?
    /* do nothing */;      // <- no? so I wait 1 second, for example
                           // and test again.
                           // on more sophisticated setups we can ask
                           // to be woken when lock 1 is freed
/* critical section*/;     // <- do what we need (this will never happen)
flag[0] = false;           // <- releasing our lock

 /* PROCESS 1 */
flag[1] = true;
while (flag[0])
    /* do nothing */;
/* critical section*/;
flag[1] = false;

Livelock Example

/* PROCESS 0 */
flag[0] = true;          // <- get lock 0
while (flag[1]){         
    flag[0] = false;     // <- instead of sleeping, we do useless work
                         //    needed by the lock mechanism
    /*delay */;          // <- wait for a second
    flag[0] = true;      // <- and restart useless work again.
}
/*critical section*/;    // <- do what we need (this will never happen)
flag[0] = false; 

/* PROCESS 1 */
flag[1] = true;
while (flag[0]) {
    flag[1] = false;
    /*delay */;
    flag[1] = true;
}
/* critical section*/;
flag[1] = false;

[...] consider the following sequence of events:

  • P0 sets flag[0] to true.
  • P1 sets flag[1] to true.
  • P0 checks flag[1].
  • P1 checks flag[0].
  • P0 sets flag[0] to false.
  • P1 sets flag[1] to false.
  • P0 sets flag[0] to true.
  • P1 sets flag[1] to true.

This sequence could be extended indefinitely, and neither process could enter its critical section. Strictly speaking, this is not deadlock, because any alteration in the relative speed of the two processes will break this cycle and allow one to enter the critical section. This condition is referred to as livelock. Recall that deadlock occurs when a set of processes wishes to enter their critical sections but no process can succeed. With livelock, there are possible sequences of executions that succeed, but it is also possible to describe one or more execution sequences in which no process ever enters its critical section.

Not content from the book anymore.

And what about spinlocks?

Spinlock is a technique to avoid the cost of the OS lock mechanism. Typically you would do:

try
{
   lock = beginLock();
   doSomething();
}
finally
{
   endLock();
}

A problem start to appear when beginLock() costs much more than doSomething(). In very exagerated terms, imagine what happens when the beginLock costs 1 second, but doSomething cost just 1 millisecond.

In this case if you waited 1 millisecond, you would avoid being hindered for 1 second.

Why the beginLock would cost so much? If the lock is free is does not cost a lot (see https://stackoverflow.com/a/49712993/5397116), but if the lock is not free the OS will "freeze" your thread, setup a mechanism to wake you when the lock is freed, and then wake you again in the future.

All of this is much more expensive than some loops checking the lock. That is why sometimes is better to do a "spinlock".

For example:

void beginSpinLock(lock)
{
   if(lock) loopFor(1 milliseconds);
   else 
   {
     lock = true;
     return;
   }

   if(lock) loopFor(2 milliseconds);
   else 
   {
     lock = true;
     return;
   }

   // important is that the part above never 
   // cause the thread to sleep.
   // It is "burning" the time slice of this thread.
   // Hopefully for good.

   // some implementations fallback to OS lock mechanism
   // after a few tries
   if(lock) return beginLock(lock);
   else 
   {
     lock = true;
     return;
   }
}

If your implementation is not careful, you can fall on livelock, spending all CPU on the lock mechanism.

Also see:

https://preshing.com/20120226/roll-your-own-lightweight-mutex/
Is my spin lock implementation correct and optimal?

Summary:

Deadlock: situation where nobody progress, doing nothing (sleeping, waiting etc..). CPU usage will be low;

Livelock: situation where nobody progress, but CPU is spent on the lock mechanism and not on your calculation;

Starvation: situation where one procress never gets the chance to run; by pure bad luck or by some of its property (low priority, for example);

Spinlock: technique of avoiding the cost waiting the lock to be freed.

Python division

In Python 2.7, the / operator is an integer division if inputs are integers:

>>>20/15
1

>>>20.0/15.0
1.33333333333

>>>20.0/15
1.33333333333

In Python 3.3, the / operator is a float division even if the inputs are integer.

>>> 20/15
1.33333333333

>>>20.0/15
1.33333333333

For integer division in Python 3, we will use the // operator.

The // operator is an integer division operator in both Python 2.7 and Python 3.3.

In Python 2.7 and Python 3.3:

>>>20//15
1

Now, see the comparison

>>>a = 7.0/4.0
>>>b = 7/4
>>>print a == b

For the above program, the output will be False in Python 2.7 and True in Python 3.3.

In Python 2.7 a = 1.75 and b = 1.

In Python 3.3 a = 1.75 and b = 1.75, just because / is a float division.

Bootstrap datepicker hide after selection

The problem can be stopped, blocking hide event for input element by this linese:

_x000D_
_x000D_
var your_options = { ... };_x000D_
$('.datetimepicker').datetimepicker(your_options).on('hide', function (e) {_x000D_
    e.preventDefault();_x000D_
    e.stopPropagation();_x000D_
});
_x000D_
_x000D_
_x000D_

Align div with fixed position on the right side

You can use two imbricated div. But you need a fixed width for your content, that's the only limitation.

<div style='float:right; width: 180px;'>
 <div style='position: fixed'>
   <!-- Your content -->
 </div>
</div>

jQuery : select all element with custom attribute

As described by the link I've given in comment, this

$('p[MyTag]').each(function(index) {
  document.write(index + ': ' + $(this).text() + "<br>");});

works (playable example).

Regex expressions in Java, \\s vs. \\s+

Those two replaceAll calls will always produce the same result, regardless of what x is. However, it is important to note that the two regular expressions are not the same:

  • \\s - matches single whitespace character
  • \\s+ - matches sequence of one or more whitespace characters.

In this case, it makes no difference, since you are replacing everything with an empty string (although it would be better to use \\s+ from an efficiency point of view). If you were replacing with a non-empty string, the two would behave differently.

Running two projects at once in Visual Studio

Max has the best solution for when you always want to start both projects, but you can also right click a project and choose menu Debug ? Start New Instance.

This is an option when you only occasionally need to start the second project or when you need to delay the start of the second project (maybe the server needs to get up and running before the client tries to connect, or something).

How to get Toolbar from fragment?

toolbar = (Toolbar) getView().findViewById(R.id.toolbar);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);

How to comment lines in rails html.erb files?

Note that if you want to comment out a single line of printing erb you should do like this

<%#= ["Buck", "Papandreou"].join(" you ") %>

Create Test Class in IntelliJ

  1. Right click on project then select new->directory. Create a new directory and name it "test".
  2. Right click on "test" folder then select Mark Directory As->Test Sources Root
  3. Click on Navigate->Test->Create New Test
    Select Testing library(JUnit4 or any)
    Specify Class Name
    Select Member

That's it. We can modify the directory structure as per our need. Good luck!

Getting text from td cells with jQuery

$(".field-group_name").each(function() {
        console.log($(this).text());
    });

creating batch script to unzip a file without additional zip tools

Here's my overview about built-in zi/unzip (compress/decompress) capabilities in windows - How can I compress (/ zip ) and uncompress (/ unzip ) files and folders with batch file without using any external tools?

To unzip file you can use this script :

zipjs.bat unzip -source C:\myDir\myZip.zip -destination C:\MyDir -keep yes -force no

How to find duplicate records in PostgreSQL

In order to make it easier I assume that you wish to apply a unique constraint only for column year and the primary key is a column named id.

In order to find duplicate values you should run,

SELECT year, COUNT(id)
FROM YOUR_TABLE
GROUP BY year
HAVING COUNT(id) > 1
ORDER BY COUNT(id);

Using the sql statement above you get a table which contains all the duplicate years in your table. In order to delete all the duplicates except of the the latest duplicate entry you should use the above sql statement.

DELETE
FROM YOUR_TABLE A USING YOUR_TABLE_AGAIN B
WHERE A.year=B.year AND A.id<B.id;

How to assign name for a screen?

The easiest way use screen with name

screen -S 'name' 'application'
  • Ctrl+a, d = exit and leave application open

Return to screen:

screen -r 'name'

for example using lynx with screen

Create screen:

screen -S lynx lynx

Ctrl+a, d =exit

later you can return with:

screen -r lynx

Get content uri from file path in android

Try with:

ImageView.setImageURI(Uri.fromFile(new File("/sdcard/cats.jpg")));

Or with:

ImageView.setImageURI(Uri.parse(new File("/sdcard/cats.jpg").toString()));

git am error: "patch does not apply"

This kind of error can be caused by LF vs CRLF line ending mismatches, e.g. when you're looking at the patch file and you're absolutely sure it should be able to apply, but it just won't.

To test this out, if you have a patch that applies to just one file, you can try running 'unix2dos' or 'dos2unix' on just that file (try both, to see which one causes the file to change; you can get these utilities for Windows as well as Unix), then commit that change as a test commit, then try applying the patch again. If that works, that was the problem.

NB git am applies patches as LF by default (even if the patch file contains CRLF), so if you want to apply CRLF patches to CRLF files you must use git am --keep-cr, as per this answer.

PHP If Statement with Multiple Conditions

You can try this:

<?php
    echo (($var=='abc' || $var=='def' || $var=='hij' || $var=='klm' || $var=='nop') ? "true" : "false");
?>

Getting DOM elements by classname

There is also another approach without the use of DomXPath or Zend_Dom_Query.

Based on dav's original function, I wrote the following function that returns all the children of the parent node whose tag and class match the parameters.

function getElementsByClass(&$parentNode, $tagName, $className) {
    $nodes=array();

    $childNodeList = $parentNode->getElementsByTagName($tagName);
    for ($i = 0; $i < $childNodeList->length; $i++) {
        $temp = $childNodeList->item($i);
        if (stripos($temp->getAttribute('class'), $className) !== false) {
            $nodes[]=$temp;
        }
    }

    return $nodes;
}

suppose you have a variable $html the following HTML:

<html>
 <body>
  <div id="content_node">
    <p class="a">I am in the content node.</p>
    <p class="a">I am in the content node.</p>
    <p class="a">I am in the content node.</p>    
  </div>
  <div id="footer_node">
    <p class="a">I am in the footer node.</p>
  </div>
 </body>
</html>

use of getElementsByClass is as simple as:

$dom = new DOMDocument('1.0', 'utf-8');
$dom->loadHTML($html);
$content_node=$dom->getElementById("content_node");

$div_a_class_nodes=getElementsByClass($content_node, 'div', 'a');//will contain the three nodes under "content_node".

Run on server option not appearing in Eclipse

Did you create a Web Project? If you right click on the project and go to Properties > Project Facets is Dynamic Web Module selected?

Concatenate a vector of strings/character

Another way would be to use glue package:

glue_collapse(glue("{sdata}"))
paste(glue("{sdata}"), collapse = '')

jQuery issue in Internet Explorer 8

Correction:

Check your script include tag, is it using

type="application/javascript" src="/path/to/jquery" 

change to

type="text/javascript" src="/path/to/jquery" 

How to Correctly Use Lists in R?

Regarding your questions, let me address them in order and give some examples:

1) A list is returned if and when the return statement adds one. Consider

 R> retList <- function() return(list(1,2,3,4)); class(retList())
 [1] "list"
 R> notList <- function() return(c(1,2,3,4)); class(notList())
 [1] "numeric"
 R> 

2) Names are simply not set:

R> retList <- function() return(list(1,2,3,4)); names(retList())
NULL
R> 

3) They do not return the same thing. Your example gives

R> x <- list(1,2,3,4)
R> x[1]
[[1]]
[1] 1
R> x[[1]]
[1] 1

where x[1] returns the first element of x -- which is the same as x. Every scalar is a vector of length one. On the other hand x[[1]] returns the first element of the list.

4) Lastly, the two are different between they create, respectively, a list containing four scalars and a list with a single element (that happens to be a vector of four elements).

How do I set cell value to Date and apply default Excel date format?

To set to default Excel type Date (defaulted to OS level locale /-> i.e. xlsx will look different when opened by a German or British person/ and flagged with an asterisk if you choose it in Excel's cell format chooser) you should:

    CellStyle cellStyle = xssfWorkbook.createCellStyle();
    cellStyle.setDataFormat((short)14);
    cell.setCellStyle(cellStyle);

I did it with xlsx and it worked fine.

Illegal Escape Character "\"

The character '\' is a special character and needs to be escaped when used as part of a String, e.g., "\". Here is an example of a string comparison using the '\' character:

if (invName.substring(j,k).equals("\\")) {...}

You can also perform direct character comparisons using logic similar to the following:

if (invName.charAt(j) == '\\') {...}

How to use the PRINT statement to track execution as stored procedure is running?

Can I just ask about the long term need for this facility - is it for debuging purposes?

If so, then you may want to consider using a proper debugger, such as the one found in Visual Studio, as this allows you to step through the procedure in a more controlled way, and avoids having to constantly add/remove PRINT statement from the procedure.

Just my opinion, but I prefer the debugger approach - for code and databases.

How to move Docker containers between different hosts?

I tried many solutions for this, and this is the one that worked for me :

1.commit/save container to new image :

  1. ++ commit the container:
    # docker stop
    # docker commit CONTAINER_NAME
    # docker save --output IMAGE_NAME.tar IMAGE_NAME:TAG


ps:"Our container CONTAINER_NAME has a mounted volume at '/var/home'" ( you have to inspect your container to specify its volume path : # docker inspect CONTAINER_NAME )

  1. ++ save its volume : we will use an ubuntu image to do the thing.
    # mkdir backup
    # docker run --rm --volumes-from CONTAINER_NAME -v ${pwd}/backup:/backup ubuntu bash -c “cd /var/home && tar cvf /backup/volume_backup.tar .”

Now when you look at ${pwd}/backup , you will find our volume under tar format.
Until now, we have our conatainer's image 'IMAGE_NAME.tar' and its volume 'volume_backup.tar'.

Now you can , recreate the same old container on a new host.

Which keycode for escape key with jQuery

To get the hex code for all the characters: http://asciitable.com/

git recover deleted file where no commit was made after the delete

Just do git checkout path/to/file-I-want-to-bring-back.txt

Has Facebook sharer.php changed to no longer accept detailed parameters?

I review your url in use:

https://www.facebook.com/sharer/sharer.php?s=100&p[title]=EXAMPLE&p[summary]=EXAMPLE&p[url]=EXAMPLE&p[images][0]=EXAMPLE

and see this differences:

  1. The sharer URL not is same.
  2. The strings are in different order. ( Do not know if this affects ).

I use this URL string:

http://www.facebook.com/sharer.php?s=100&p[url]=http://www.example.com/&p[images][0]=/images/image.jpg&p[title]=Title&p[summary]=Summary

In the "title" and "summary" section, I use the php function urlencode(); like this:

<?php echo urlencode($detail->title); ?>

And working fine for me.

VBA ADODB excel - read data from Recordset

I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.

Set cn = CreateObject("ADODB.Connection")
With cn
 .Provider = "Microsoft.Jet.OLEDB.4.0"
  .ConnectionString = "Data Source=D:\test.xls " & _
  ";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
  For i = 0 To rs.Fields.Count - 1
    Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
    strNaam = rs.Fields(0).Value
  Next
  rs.MoveNext
Loop
rs.Close

There are other ways, depending on what you want to do, such as GetString (GetString Method Description).

Is there a "do ... while" loop in Ruby?

From what I gather, Matz does not like the construct

begin
    <multiple_lines_of_code>
end while <cond>

because, it's semantics is different than

<single_line_of_code> while <cond>

in that the first construct executes the code first before checking the condition, and the second construct tests the condition first before it executes the code (if ever). I take it Matz prefers to keep the second construct because it matches one line construct of if statements.

I never liked the second construct even for if statements. In all other cases, the computer executes code left-to-right (eg. || and &&) top-to-bottom. Humans read code left-to-right top-to-bottom.

I suggest the following constructs instead:

if <cond> then <one_line_code>      # matches case-when-then statement

while <cond> then <one_line_code>

<one_line_code> while <cond>

begin <multiple_line_code> end while <cond> # or something similar but left-to-right

I don't know if those suggestions will parse with the rest of the language. But in any case I prefere keeping left-to-right execution as well as language consistency.

How to show the "Are you sure you want to navigate away from this page?" when changes committed?

There is an "onunload" parameter for the body tag you can call javascript functions from there. If it returns false it prevents navigating away.

How to align this span to the right of the div?

If you can modify the HTML: http://jsfiddle.net/8JwhZ/3/

<div class="title">
  <span class="name">Cumulative performance</span>
  <span class="date">20/02/2011</span>
</div>

.title .date { float:right }
.title .name { float:left }

When is it practical to use Depth-First Search (DFS) vs Breadth-First Search (BFS)?

Some algorithms depend on particular properties of DFS (or BFS) to work. For example the Hopcroft and Tarjan algorithm for finding 2-connected components takes advantage of the fact that each already visited node encountered by DFS is on the path from root to the currently explored node.

CSS hexadecimal RGBA?

See here http://www.w3.org/TR/css3-color/#rgba-color

It is not possible, most probably because 0xFFFFFFFF is greater than the maximum value for 32bit integers

Are static methods inherited in Java?

We can declare static methods with same signature in subclass, but it is not considered overriding as there won’t be any run-time polymorphism.Because since all static members of a class are loaded at the time of class loading so it decide at compile time(overriding at run time) Hence the answer is ‘No’.

How to retrieve records for last 30 minutes in MS SQL?

Change this (CURRENT_TIMESTAMP-30)

To This: DateADD(mi, -30, Current_TimeStamp)

To get the current date use GetDate().

MSDN Link to DateAdd Function
MSDN Link to Get Date Function

How do I print uint32_t and uint16_t variables value?

The macros defined in <inttypes.h> are the most correct way to print values of types uint32_t, uint16_t, and so forth -- but they're not the only way.

Personally, I find those macros difficult to remember and awkward to use. (Given the syntax of a printf format string, that's probably unavoidable; I'm not claiming I could have come up with a better system.)

An alternative is to cast the values to a predefined type and use the format for that type.

Types int and unsigned int are guaranteed by the language to be at least 16 bits wide, and therefore to be able to hold any converted value of type int16_t or uint16_t, respectively. Similarly, long and unsigned long are at least 32 bits wide, and long long and unsigned long long are at least 64 bits wide.

For example, I might write your program like this (with a few additional tweaks):

#include <stdio.h>
#include <stdint.h>
#include <netinet/in.h>  

int main(void)
{
    uint32_t a=12, a1;
    uint16_t b=1, b1;
    a1 = htonl(a);
    printf("%lu---------%lu\n", (unsigned long)a, (unsigned long)a1);
    b1 = htons(b);
    printf("%u-----%u\n", (unsigned)b, (unsigned)b1);
    return 0;
}

One advantage of this approach is that it can work even with pre-C99 implementations that don't support <inttypes.h>. Such an implementation most likely wouldn't have <stdint.h> either, but the technique is useful for other integer types.

pandas how to check dtype for all columns in a dataframe?

To go one step further, I assume you want to do something with these dtypes. df.dtypes.to_dict() comes in handy.

my_type = 'float64' #<---

dtypes = dataframe.dtypes.to_dict()

for col_nam, typ in dtypes.items():
    if (typ != my_type): #<---
        raise ValueError(f"Yikes - `dataframe['{col_name}'].dtype == {typ}` not {my_type}")

You'll find that Pandas did a really good job comparing NumPy classes and user-provided strings. For example: even things like 'double' == dataframe['col_name'].dtype will succeed when .dtype==np.float64.

Fully custom validation error message with Rails

If you want to list them all in a nice list but without using the cruddy non human friendly name, you can do this...

object.errors.each do |attr,message|
  puts "<li>"+message+"</li>"
end

Does Notepad++ show all hidden characters?

Yes, it does. The way to enable this depends on your version of Notepad++. On newer versions you can use:

Menu View ? Show Symbol ? *Show All Characters`

or

Menu View ? Show Symbol ? Show White Space and TAB

(Thanks to bers' comment and bkaid's answers below for these updated locations.)


On older versions you can look for:

Menu View ? Show all characters

or

Menu View ? Show White Space and TAB

What is let-* in Angular 2 templates?

The Angular microsyntax lets you configure a directive in a compact, friendly string. The microsyntax parser translates that string into attributes on the <ng-template>. The let keyword declares a template input variable that you reference within the template.

How to print out all the elements of a List in Java?

Or you could simply use the Apache Commons utilities:

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/ArrayUtils.html#toString-java.lang.Object-

List<MyObject> myObjects = ...
System.out.println(ArrayUtils.toString(myObjects));

"rm -rf" equivalent for Windows?

There is also deltree if you're on an older version of windows.

You can learn more about it from here: SS64: DELTREE - Delete all subfolders and files.

Global variables in Java

Lots of good answers, but I want to give this example as it's considered the more proper way to access variables of a class by another class: using getters and setters.

The reason why you use getters and setters this way instead of just making the variable public is as follows. Lets say your var is going to be a global parameter that you NEVER want someone to change during the execution of your program (in the case when you are developing code with a team), something like maybe the URL for a website. In theory this could change and may be used many times in your program, so you want to use a global var to be able to update it all at once. But you do not want someone else to go in and change this var (possibly without realizing how important it is). In that case you simply do not include a setter method, and only include the getter method.

public class Global{
    private static int var = 5;

    public static int getVar(){
        return Global.var;
    }

    //If you do not want to change the var ever then do not include this
    public static void setVar(int var){
        Global.var = var;
    }
}

How to create a file in Linux from terminal window?

Depending on what you want the file to contain:

  • touch /path/to/file for an empty file
  • somecommand > /path/to/file for a file containing the output of some command.

      eg: grep --help > randomtext.txt
          echo "This is some text" > randomtext.txt
    
  • nano /path/to/file or vi /path/to/file (or any other editor emacs,gedit etc)
    It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist


Create the file using cat

$ cat > myfile.txt

Now, just type whatever you want in the file:

Hello World!

CTRL-D to save and exit


There are several possible solutions:

Create an empty file

touch file

>file

echo -n > file

printf '' > file

The echo version will work only if your version of echo supports the -n switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.

Create a file containing a newline and nothing else

echo '' > file

printf '\n' > file

This is a valid "text file" because it ends in a newline.

Write text into a file

"$EDITOR" file

echo 'text' > file

cat > file <<END \
text
END

printf 'text\n' > file

These are equivalent. The $EDITOR command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat version presumes a literal newline after the \ and after each other line. Other than that these will all work in a POSIX shell.

Of course there are many other methods of writing and creating files, too.

How to create a Rectangle object in Java using g.fillRect method

Note:drawRect and fillRect are different.

Draws the outline of the specified rectangle:

public void drawRect(int x,
        int y,
        int width,
        int height)

Fills the specified rectangle. The rectangle is filled using the graphics context's current color:

public abstract void fillRect(int x,
        int y,
        int width,
        int height)

Can I have an IF block in DOS batch file?

I ran across this article in the results returned by a search related to the IF command in a batch file, and I couldn't resist the opportunity to correct the misconception that IF blocks are limited to single commands. Following is a portion of a production Windows NT command script that runs daily on the machine on which I am composing this reply.

    if "%COPYTOOL%" equ "R" (
    WWLOGGER.exe "%APPDATA%\WizardWrx\%~n0.LOG" "Using RoboCopy to make a backup of %USERPROFILE%\My Documents\Outlook Files\*"
    %TOOLPATH% %SRCEPATH% %DESTPATH% /copyall %RCLOGSTR% /m /np /r:0 /tee
    C:\BIN\ExitCodeMapper.exe C:\BIN\ExitCodeMapper.INI[Robocopy] %TEMP%\%~n0.TMP %ERRORLEVEL%
) else (
    WWLOGGER.exe "%APPDATA%\WizardWrx\%~n0.LOG" "Using XCopy to make a backup of %USERPROFILE%\My Documents\Outlook Files\*"
    call %TOOLPATH%  "%USERPROFILE%\My Documents\Outlook Files\*" "%USERPROFILE%\My Documents\Outlook Files\_backups" /f /m /v /y
    C:\BIN\ExitCodeMapper.exe C:\BIN\ExitCodeMapper.INI[Xcopy] %TEMP%\%~n0.TMP %ERRORLEVEL%
)

Perhaps blocks of two or more lines applies exclusively to Windows NT command scripts (.CMD files), because a search of the production scripts directory of an application that is restricted to old school batch (.BAT) files, revealed only one-command blocks. Since the application has gone into extended maintenance (meaning that I am not actively involved in supporting it), I can't say whether that is because I didn't need more than one line, or that I couldn't make them work.

Regardless, if the latter is true, there is a simple workaround; move the multiple lines into either a separate batch file or a batch file subroutine. I know that the latter works in both kinds of scripts.

How to show the text on a ImageButton?

Actually, android:text is not an argument accepted by ImageButton but, If you're trying to get a button with a specified background (not android default) use the android:background xml attribute, or declare it from the class with .setBackground();

Lost connection to MySQL server at 'reading initial communication packet', system error: 0

If bind-address is not present in your configuration file and mysql is hosted on AWS instance, please check your security group. In ideal conditions, the inbound rules should accept all connection from port 3306 and outbound rule should respond back to all valid IPs.

How to pass text in a textbox to JavaScript function?

You could just get the input value in the onclick-event like so:

onclick="execute(document.getElementById('textbox1').value);"

You would of course have to add an id to your textbox

CSS body background image fixed to full screen even when zooming in/out

Add this in your css file:

.custom_class
 {
    background-image: url(../img/beach.jpg);
    -moz-background-size: cover;
    -webkit-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
 }

and then, in your .html (or .php) file call this class like that:

<div class="custom_class">
   ...
</div>

Add resources, config files to your jar using gradle

I came across this post searching how to add an extra directory for resources. I found a solution that may be useful to someone. Here is my final configuration to get that:

sourceSets {
    main {
        resources {
            srcDirs "src/main/resources", "src/main/configs"
        }
    }
}

javascript filter array of objects

For those who want to filter from an array of objects using any key:

_x000D_
_x000D_
function filterItems(items, searchVal) {_x000D_
  return items.filter((item) => Object.values(item).includes(searchVal));_x000D_
}_x000D_
let data = [_x000D_
  { "name": "apple", "type": "fruit", "id": 123234 },_x000D_
  { "name": "cat", "type": "animal", "id": 98989 },_x000D_
  { "name": "something", "type": "other", "id": 656565 }]_x000D_
_x000D_
_x000D_
console.log("Filtered by name: ", filterItems(data, "apple"));_x000D_
console.log("Filtered by type: ", filterItems(data, "animal"));_x000D_
console.log("Filtered by id: ", filterItems(data, 656565));
_x000D_
_x000D_
_x000D_

filter from an array of the JSON objects:**

How to empty a redis database?

There are right answers but I just want to add one more option (requires downtime):

  1. Stop Redis.
  2. Delete RDB file (find location in redis.conf).
  3. Start Redis.

How to get the bluetooth devices as a list?

package com.sekurtrack.myapplication;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Set;

public class MainActivity extends AppCompatActivity {
    ListView listView;
    private BluetoothAdapter BA;
    private ArrayList<String> mDeviceList = new ArrayList<String>();
    private Set<BluetoothDevice> pairedDevices;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView=(ListView)findViewById(R.id.devicesList);



        BA = BluetoothAdapter.getDefaultAdapter();
        BA.startDiscovery();
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);

       /* BA = BluetoothAdapter.getDefaultAdapter();
        pairedDevices = BA.getBondedDevices();
        ArrayList list = new ArrayList();
        for(BluetoothDevice bt : pairedDevices) list.add(bt.getName());
        Toast.makeText(getApplicationContext(), "Showing Paired Devices",Toast.LENGTH_SHORT).show();
        final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
        listView.setAdapter(adapter);*/

    }


    @Override
    protected void onDestroy() {
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                mDeviceList.add(device.getName() + "\n" + device.getAddress());
                Log.i("BT1", device.getName() + "\n" + device.getAddress());
                listView.setAdapter(new ArrayAdapter<String>(context,
                        android.R.layout.simple_list_item_1, mDeviceList));
            }
        }
    };
}

How do I escape only single quotes?

To replace only single quotes, use this simple statement:

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

SQL Server : SUM() of multiple rows including where clauses

The WHERE clause is always conceptually applied (the execution plan can do what it wants, obviously) prior to the GROUP BY. It must come before the GROUP BY in the query, and acts as a filter before things are SUMmed, which is how most of the answers here work.

You should also be aware of the optional HAVING clause which must come after the GROUP BY. This can be used to filter on the resulting properties of groups after GROUPing - for instance HAVING SUM(Amount) > 0

How to alter a column and change the default value?

For DEFAULT CURRENT_TIMESTAMP:

ALTER TABLE tablename
 CHANGE COLUMN columnname1 columname1 DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
 CHANGE COLUMN columnname2 columname2 DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;

Please note double columnname declaration

Removing DEFAULT CURRENT_TIMESTAMP:

ALTER TABLE tablename
 ALTER COLUMN columnname1 DROP DEFAULT,
 ALTER COLUMN columnname2 DROPT DEFAULT;

How to get object length

In jQuery i've made it in a such way:

len = function(obj) {
    var L=0;
    $.each(obj, function(i, elem) {
        L++;
    });
    return L;
}

How do I install ASP.NET MVC 5 in Visual Studio 2012?

You should be able to install from NuGet (http://www.nuget.org/packages/Microsoft.AspNet.Mvc) into VS2012. Change the Target Framework to .NET 4.5.

Not sure the new project templates are ready for VS2012. But if you have an ASP.NET MVC 4 app you can upgrade using the link below.

http://www.asp.net/mvc/tutorials/mvc-5/how-to-upgrade-an-aspnet-mvc-4-and-web-api-project-to-aspnet-mvc-5-and-web-api-2

Session variables in ASP.NET MVC

There are 3 ways to do it.

  1. You can directly access HttpContext.Current.Session

  2. You can Mock HttpContextBase

  3. Create a extension method for HttpContextBase

I prefer 3rd way.This link is good reference.

Get/Set HttpContext Session Methods in BaseController vs Mocking HttpContextBase to create Get/Set methods

Recursive mkdir() system call on Unix

Here's another take on mkpath(), using recursion, which is both small and readable. It makes use of strdupa() to avoid altering the given dir string argument directly and to avoid using malloc() & free(). Make sure to compile with -D_GNU_SOURCE to activate strdupa() ... meaning this code only works on GLIBC, EGLIBC, uClibc, and other GLIBC compatible C libraries.

int mkpath(char *dir, mode_t mode)
{
    if (!dir) {
        errno = EINVAL;
        return 1;
    }

    if (strlen(dir) == 1 && dir[0] == '/')
        return 0;

    mkpath(dirname(strdupa(dir)), mode);

    return mkdir(dir, mode);
}

After input both here and from Valery Frolov, in the Inadyn project, the following revised version of mkpath() has now been pushed to libite

int mkpath(char *dir, mode_t mode)
{
    struct stat sb;

    if (!dir) {
        errno = EINVAL;
        return 1;
    }

    if (!stat(dir, &sb))
        return 0;

    mkpath(dirname(strdupa(dir)), mode);

    return mkdir(dir, mode);
}

It uses one more syscall, but otoh the code is more readable now.

How do you make div elements display inline?

I would use spans or float the div left. The only problem with floating is that you have to clear the float afterwards or the containing div must have the overflow style set to auto

Create a menu Bar in WPF?

<DockPanel>
    <Menu DockPanel.Dock="Top">
        <MenuItem Header="_File">
            <MenuItem Header="_Open"/>
            <MenuItem Header="_Close"/>
            <MenuItem Header="_Save"/>
        </MenuItem>
    </Menu>
    <StackPanel></StackPanel>
</DockPanel>

How to disable Home and other system buttons in Android?

Refreshing an old topic. I was able to achieve that my activity does not fold when the home button (physical or virtual) is pressed. Here is my code for activity onCreate() method:

super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm_screen);
        context = getApplicationContext();
        int windowType;
        if (Build.VERSION.SDK_INT>=26) windowType = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        else windowType = WindowManager.LayoutParams.TYPE_TOAST;
        final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                windowType,
                WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                        | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                        | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                        | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                        | WindowManager.LayoutParams.FLAG_FULLSCREEN,
                PixelFormat.TRANSLUCENT
        );
        wm = (WindowManager) getApplicationContext()
                .getSystemService(Context.WINDOW_SERVICE);

        mTopView = (ViewGroup) getLayoutInflater().inflate(R.layout.activity_alarm_screen, null);
        getWindow().setAttributes(params);
        //Set up your views here
        testView = mTopView.findViewById(R.id.test);
        wm.addView(mTopView, params);

On API 26 and abovem you need to get screen overlay permission from the user. Tested on Android 7 and 8.

Remove leading and trailing spaces?

Should be noted that strip() method would trim any leading and trailing whitespace characters from the string (if there is no passed-in argument). If you want to trim space character(s), while keeping the others (like newline), this answer might be helpful:

sample = '  some string\n'
sample_modified = sample.strip(' ')

print(sample_modified)  # will print 'some string\n'

strip([chars]): You can pass in optional characters to strip([chars]) method. Python will look for occurrences of these characters and trim the given string accordingly.

How to create a numpy array of arbitrary length strings?

You could use the object data type:

>>> import numpy
>>> s = numpy.array(['a', 'b', 'dude'], dtype='object')
>>> s[0] += 'bcdef'
>>> s
array([abcdef, b, dude], dtype=object)

get number of columns of a particular row in given excel using Java

There are two Things you can do

use

int noOfColumns = sh.getRow(0).getPhysicalNumberOfCells();

or

int noOfColumns = sh.getRow(0).getLastCellNum();

There is a fine difference between them

  1. Option 1 gives the no of columns which are actually filled with contents(If the 2nd column of 10 columns is not filled you will get 9)
  2. Option 2 just gives you the index of last column. Hence done 'getLastCellNum()'

RedirectToAction with parameter

It is also worth noting that you can pass through more than 1 parameter. id will be used to make up part of the URL and any others will be passed through as parameters after a ? in the url and will be UrlEncoded as default.

e.g.

return RedirectToAction("ACTION", "CONTROLLER", new {
           id = 99, otherParam = "Something", anotherParam = "OtherStuff" 
       });

So the url would be:

    /CONTROLLER/ACTION/99?otherParam=Something&anotherParam=OtherStuff

These can then be referenced by your controller:

public ActionResult ACTION(string id, string otherParam, string anotherParam) {
   // Your code
          }

HttpClient.GetAsync(...) never returns when using await/async

Edit: Generally try to avoid doing the below except as a last ditch effort to avoid deadlocks. Read the first comment from Stephen Cleary.

Quick fix from here. Instead of writing:

Task tsk = AsyncOperation();
tsk.Wait();

Try:

Task.Run(() => AsyncOperation()).Wait();

Or if you need a result:

var result = Task.Run(() => AsyncOperation()).Result;

From the source (edited to match the above example):

AsyncOperation will now be invoked on the ThreadPool, where there won’t be a SynchronizationContext, and the continuations used inside of AsyncOperation won’t be forced back to the invoking thread.

For me this looks like a useable option since I do not have the option of making it async all the way (which I would prefer).

From the source:

Ensure that the await in the FooAsync method doesn’t find a context to marshal back to. The simplest way to do that is to invoke the asynchronous work from the ThreadPool, such as by wrapping the invocation in a Task.Run, e.g.

int Sync() { return Task.Run(() => Library.FooAsync()).Result; }

FooAsync will now be invoked on the ThreadPool, where there won’t be a SynchronizationContext, and the continuations used inside of FooAsync won’t be forced back to the thread that’s invoking Sync().

How to check if a char is equal to an empty space?

Character.isSpaceChar(c) || Character.isWhitespace(c) worked for me.

Empty brackets '[]' appearing when using .where

Stuarts' answer is correct, but if you are not sure if you are saving the titles in lowercase, you can also make a case insensitive search

There are a lot of answered questions in Stack Overflow with more data on this:

Example 1

Example 2

What's the difference between console.dir and console.log?

None of the 7 prior answers mentioned that console.dir supports extra arguments: depth, showHidden, and whether to use colors.

Of particular interest is depth, which (in theory) allows travering objects into more than the default 2 levels that console.log supports.

I wrote "in theory" because in practice when I had a Mongoose object and ran console.log(mongoose) and console.dir(mongoose, { depth: null }), the output was the same. What actually recursed deeply into the mongoose object was using util.inspect:

import * as util from 'util';
console.log(util.inspect(myObject, {showHidden: false, depth: null}));

How to obtain the start time and end time of a day?

Another one solution which does not depend on any framework is:

static public Date getStartOfADay(Date day) {
    final long oneDayInMillis = 24 * 60 * 60 * 1000;
    return new Date(day.getTime() / oneDayInMillis * oneDayInMillis);
}

static public Date getEndOfADay(Date day) {
    final long oneDayInMillis = 24 * 60 * 60 * 1000;
    return new Date((day.getTime() / oneDayInMillis + 1) * oneDayInMillis - 1);
}

Note that it returns UTC based time

jQuery hasAttr checking to see if there is an attribute on an element

Object.prototype.hasAttr = function(attr) {
    if(this.attr) {
        var _attr = this.attr(attr);
    } else {
        var _attr = this.getAttribute(attr);
    }
    return (typeof _attr !== "undefined" && _attr !== false && _attr !== null);      
};

I came a crossed this while writing my own function to do the same thing... I though I'd share in case someone else stumbles here. I added null because getAttribute() will return null if the attribute does not exist.

This method will allow you to check jQuery objects and regular javascript objects.

:before and background-image... should it work?

The problem with other answers here is that they use position: absolute;

This makes it difficult to layout the element itself in relation to the ::before pseudo-element. For example, if you wish to show an image before a link like this: enter image description here

Here's how I was able to achieve the layout in the picture:

_x000D_
_x000D_
a::before {_x000D_
  content: "";_x000D_
  float: left;_x000D_
  width: 16px;_x000D_
  height: 16px;_x000D_
  margin-right: 5px;_x000D_
  background: url(../../lhsMenu/images/internal_link.png) no-repeat 0 0;_x000D_
  background-size: 80%;_x000D_
}
_x000D_
_x000D_
_x000D_

Note that this method allows you to scale the background image, as well as keep the ability to use margins and padding for layout.

Using Spring MVC Test to unit test multipart POST request

Have a look at this example taken from the spring MVC showcase, this is the link to the source code:

@RunWith(SpringJUnit4ClassRunner.class)
public class FileUploadControllerTests extends AbstractContextControllerTests {

    @Test
    public void readString() throws Exception {

        MockMultipartFile file = new MockMultipartFile("file", "orig", null, "bar".getBytes());

        webAppContextSetup(this.wac).build()
            .perform(fileUpload("/fileupload").file(file))
            .andExpect(model().attribute("message", "File 'orig' uploaded successfully"));
    }

}

Generate SQL Create Scripts for existing tables with Query

Try this (using "Results to text"):

SELECT
ISNULL(smsp.definition, ssmsp.definition) AS [Definition]
FROM
sys.all_objects AS sp
LEFT OUTER JOIN sys.sql_modules AS smsp ON smsp.object_id = sp.object_id
LEFT OUTER JOIN sys.system_sql_modules AS ssmsp ON ssmsp.object_id = sp.object_id
WHERE
(sp.type = N'V' OR sp.type = N'P' OR sp.type = N'RF' OR sp.type=N'PC')and(sp.name=N'YourObjectName' and SCHEMA_NAME(sp.schema_id)=N'dbo')
  • C: Check constraint
  • D: Default constraint
  • F: Foreign Key constraint
  • L: Log
  • P: Stored procedure
  • PK: Primary Key constraint
  • RF: Replication Filter stored procedure
  • S: System table
  • TR: Trigger
  • U: User table
  • UQ: Unique constraint
  • V: View
  • X: Extended stored procedure

Cheers,

How to execute a .bat file from a C# windows form app?

For the problem you're having about the batch file asking the user if the destination is a folder or file, if you know the answer in advance, you can do as such:

If destination is a file: echo f | [batch file path]

If folder: echo d | [batch file path]

It will essentially just pipe the letter after "echo" to the input of the batch file.

How to get out of while loop in java with Scanner method "hasNext" as condition?

The Scanner will continue to read until it finds an "end of file" condition.

As you're reading from stdin, that'll either be when you send an EOF character (usually ^d on Unix), or at the end of the file if you use < style redirection.

Using Camera in the Android emulator

Does not seem like it, but android recognises a webcam as a device. Every time I run the emulator my webcam's active light comes on.

How can I test an AngularJS service from the console?

TLDR: In one line the command you are looking for:

angular.element(document.body).injector().get('serviceName')

Deep dive

AngularJS uses Dependency Injection (DI) to inject services/factories into your components,directives and other services. So what you need to do to get a service is to get the injector of AngularJS first (the injector is responsible for wiring up all the dependencies and providing them to components).

To get the injector of your app you need to grab it from an element that angular is handling. For example if your app is registered on the body element you call injector = angular.element(document.body).injector()

From the retrieved injector you can then get whatever service you like with injector.get('ServiceName')

More information on that in this answer: Can't retrieve the injector from angular
And even more here: Call AngularJS from legacy code


Another useful trick to get the $scope of a particular element. Select the element with the DOM inspection tool of your developer tools and then run the following line ($0 is always the selected element):
angular.element($0).scope()

How can I make text appear on next line instead of overflowing?

Just add

white-space: initial;

to the text, a line text will come automatically in the next line.

PHP post_max_size overrides upload_max_filesize

change in php.ini max_input_vars 1000

How do you find all subclasses of a given class in Java?

You can use org.reflections library and then, create an object of Reflections class. Using this object, you can get list of all subclasses of given class. https://www.javadoc.io/doc/org.reflections/reflections/0.9.10/org/reflections/Reflections.html

    Reflections reflections = new Reflections("my.project.prefix");
    System.out.println(reflections.getSubTypesOf(A.class)));

How do I find the location of Python module sources?

I realize this answer is 4 years late, but the existing answers are misleading people.

The right way to do this is never __file__, or trying to walk through sys.path and search for yourself, etc. (unless you need to be backward compatible beyond 2.1).

It's the inspect module—in particular, getfile or getsourcefile.

Unless you want to learn and implement the rules (which are documented, but painful, for CPython 2.x, and not documented at all for other implementations, or 3.x) for mapping .pyc to .py files; dealing with .zip archives, eggs, and module packages; trying different ways to get the path to .so/.pyd files that don't support __file__; figuring out what Jython/IronPython/PyPy do; etc. In which case, go for it.

Meanwhile, every Python version's source from 2.0+ is available online at http://hg.python.org/cpython/file/X.Y/ (e.g., 2.7 or 3.3). So, once you discover that inspect.getfile(datetime) is a .so or .pyd file like /usr/local/lib/python2.7/lib-dynload/datetime.so, you can look it up inside the Modules directory. Strictly speaking, there's no way to be sure of which file defines which module, but nearly all of them are either foo.c or foomodule.c, so it shouldn't be hard to guess that datetimemodule.c is what you want.

Using a Glyphicon as an LI bullet point (Bootstrap 3)

If you want to have a different icon for each list-item, I suggest adding icons in HTML instead of using a pseudo element to keep your CSS down. It can be done quite simply as follows:

<ul>
  <li><span><i class="mdi mdi-lightbulb-outline"></i></span>An electric light with a wire filament heated to such a high temperature that it glows with visible light</li>
  <li><span><i class="mdi mdi-clipboard-check-outline"></i></span>A thin, rigid board with a clip at the top for holding paper in place.</li>
  <li><span><i class="mdi mdi-finance"></i></span>A graphical representation of data, in which the data is represented by symbols, such as bars in a bar chart, lines in a line chart, or slices in a pie chart.</li>
  <li><span><i class="mdi mdi-server"></i></span>A system that responds to requests across a computer network worldwide to provide, or help to provide, a network or data service.</li>
</ul>

-

ul {
  list-style-type: none;
  margin-left: 2.5em;
  padding-left: 0;
}
ul>li {
  position: relative;
}
span {
  left: -2em;
  position: absolute;
  text-align: center;
  width: 2em;
  line-height: inherit;
}

enter image description here

In this case I used Material Design Icons

VIEW DEMO

mySQL convert varchar to date

select date_format(str_to_date('31/12/2010', '%d/%m/%Y'), '%Y%m'); 

or

select date_format(str_to_date('12/31/2011', '%m/%d/%Y'), '%Y%m'); 

hard to tell from your example

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory in ionic 3

In my case it was a recursion that was causing react to use up all memory.

This happened when I was refactoring my code and didn't notice this.

const SumComponent = () => {
  return (
    <>
      <SumComponent />
    </>
  ) 
}

In other node apps this might look like:

const someFunction = () => {
  ...
  someFunction(); 
  ...
}

error while loading shared libraries: libncurses.so.5:

Mixaz's above answer worked for me. However I had issues installing the package because of PGP check failures. Installing it by skipping the signature worked, you could try this :

yaourt --m-arg "--skipchecksums --skippgpcheck" -Sb <your-package>

Is there a <meta> tag to turn off caching in all browsers?

I noticed some caching issues with service calls when repeating the same service call (long polling). Adding metadata didn't help. One solution is to pass a timestamp to ensure ie thinks it's a different http service request. That worked for me, so adding a server side scripting code snippet to automatically update this tag wouldn't hurt:

<meta http-equiv="expires" content="timestamp">

Using different Web.config in development and production environment

The Enterprise Library configuration editor can help you do this. It allows you to create a base config file and then deltas for each environment. You can then merge the base config and the delta to create an environment-specific web.config. Take a look at the information here which takes you through it better than I can.

Input from the keyboard in command line application

Lots of outdated answers to this question. As of Swift 2+ the Swift Standard Library contains the readline() function. It will return an Optional but it will only be nil if EOF has been reached, which will not happen when getting input from the keyboard so it can safely be unwrapped by force in those scenarios. If the user does not enter anything its (unwrapped) value will be an empty string. Here's a small utility function that uses recursion to prompt the user until at least one character has been entered:

func prompt(message: String) -> String {
    print(message)
    let input: String = readLine()!
    if input == "" {
        return prompt(message: message)
    } else {
        return input
    }
}

let input = prompt(message: "Enter something!")
print("You entered \(input)")

Note that using optional binding (if let input = readLine()) to check if something was entered as proposed in other answers will not have the desired effect, as it will never be nil and at least "" when accepting keyboard input.

This will not work in a Playground or any other environment where you does not have access to the command prompt. It seems to have issues in the command-line REPL as well.

HTTP Error 503. The service is unavailable. App pool stops on accessing website

I had a similar issue, all my app pools were stopping whenever a web request was made to them. Although I was getting the following error in the Event Viewer:

The worker process for application pool 'appPoolName' encountered an error 'Configuration file is not well-formed XML ' trying to read configuration data from file '\?\C:\inetpub\temp\apppools\appPoolName\appPoolName.config', line number '3'. The data field contains the error code.

Which told me that there were errors in the application.config at:

C:\Windows\System32\inetsrv\config\applicationHost.config

In my scenario, I edited the web.config on deploy with an element IIS clearly dislikes, the applicationHost.config scraped the web.config and inserted this bad element and wouldn't resolve until I manually removed it

How do I set up IntelliJ IDEA for Android applications?

I've spent a day on trying to put all the pieces together, been in hundreds of sites and tutorials, but they all skip trivial steps.

So here's the full guide:

  1. Download and install Java JDK (Choose the Java platform)
  2. Download and install Android SDK (Installer is recommended)
  3. After android SD finishes installing, open SDK Manager under Android SDK Tools (sometimes needs to be opened under admin's privileges)
  4. Choose everything and mark Accept All and install.
  5. Download and install IntelliJ IDEA (The community edition is free)
  6. Wait for all downloads and installations and stuff to finish.

New Project:

  1. Run IntelliJ
  2. Create a new project (there's a tutorial here)
  3. Enter the name, choose Android type.
  4. There's a step missing in the tutorial, when you are asked to choose the JDK (before choosing the SDK) you need to choose the Java JDK you've installed earlier. Should be under C:\Program Files\Java\jdk{version}
  5. Choose a New platform ( if there's not one selected ) , the SDK platform is the android platform at C:\Program Files\Android\android-sdk-windows.
  6. Choose the android version.
  7. Now you can write your program.

Compiling:

  1. Near the Run button you need to select the drop-down-list, choose Edit Configurations
  2. In the Prefer Android Virtual device select the ... button
  3. Click on create, give it a name, press OK.
  4. Double click the new device to choose it.
  5. Press OK.
  6. You're ready to run the program.

Java 8, Streams to find the duplicate elements

An O(n) way would be as below:

List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 4, 4);
Set<Integer> duplicatedNumbersRemovedSet = new HashSet<>();
Set<Integer> duplicatedNumbersSet = numbers.stream().filter(n -> !duplicatedNumbersRemovedSet.add(n)).collect(Collectors.toSet());

The space complexity would go double in this approach, but that space is not a waste; in-fact, we now have the duplicated alone only as a Set as well as another Set with all the duplicates removed too.

Convert array of indices to 1-hot encoded numpy array

In case you are using keras, there is a built in utility for that:

from keras.utils.np_utils import to_categorical   

categorical_labels = to_categorical(int_labels, num_classes=3)

And it does pretty much the same as @YXD's answer (see source-code).

Parsing JSON in Spring MVC using Jackson JSON

I'm using json lib from http://json-lib.sourceforge.net/
json-lib-2.1-jdk15.jar

import net.sf.json.JSONObject;
...

public void send()
{
    //put attributes
    Map m = New HashMap();
    m.put("send_to","[email protected]");
    m.put("email_subject","this is a test email");
    m.put("email_content","test email content");

    //generate JSON Object
    JSONObject json = JSONObject.fromObject(content);
    String message = json.toString();
    ...
}

public void receive(String jsonMessage)
{
    //parse attributes
    JSONObject json = JSONObject.fromObject(jsonMessage);
    String to = (String) json.get("send_to");
    String title = (String) json.get("email_subject");
    String content = (String) json.get("email_content");
    ...
}

More samples here http://json-lib.sourceforge.net/usage.html

How do you determine what technology a website is built on?

http://guess.scritch.org/ does this for CMSs.

Just pop in the URL and it'll try to guess the CMS. In this case it tells me my blog is running wordpress 3.4.2 (which is correct, I just checked!)

enter image description here

Searching if value exists in a list of objects using Linq

Another possibility

if (list.Count(customer => customer.Firstname == "John") > 0) {
 //bla
}

Prevent overwriting a file using cmd if exist

Use the FULL path to the folder in your If Not Exist code. Then you won't even have to CD anymore:

If Not Exist "C:\Documents and Settings\John\Start Menu\Programs\SoftWareFolder\"

Replacement for deprecated sizeWithFont: in iOS 7?

Here is the monotouch equivalent if anyone needs it:

/// <summary>
/// Measures the height of the string for the given width.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="font">The font.</param>
/// <param name="width">The width.</param>
/// <param name="padding">The padding.</param>
/// <returns></returns>
public static float MeasureStringHeightForWidth(this string text, UIFont font, float width, float padding = 20)
{
    NSAttributedString attributedString = new NSAttributedString(text, new UIStringAttributes() { Font = font });
    RectangleF rect = attributedString.GetBoundingRect(new SizeF(width, float.MaxValue), NSStringDrawingOptions.UsesLineFragmentOrigin, null);
    return rect.Height + padding;
}

which can be used like this:

public override float GetHeightForRow(UITableView tableView, NSIndexPath indexPath)
{
    //Elements is a string array
    return Elements[indexPath.Row].MeasureStringHeightForWidth(UIFont.SystemFontOfSize(UIFont.LabelFontSize), tableView.Frame.Size.Width - 15 - 30 - 15);
}

Add Expires headers

try this solution and it is working fine for me

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>

<IfModule mod_headers.c>
  <FilesMatch "\.(js|css|xml|gz)$">
    Header append Vary: Accept-Encoding
  </FilesMatch>
</IfModule>

<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

<IfModule mod_deflate.c>
SetOutputFilter DEFLATE
AddOutputFilterByType DEFLATE text/html text/css text/plain text/xml text/x-js text/js 
</IfModule>

## EXPIRES CACHING ##

Select first 4 rows of a data.frame in R

For at DataFrame one can simply type

head(data, num=10L)

to get the first 10 for example.

For a data.frame one can simply type

head(data, 10)

to get the first 10.

ExecutorService, how to wait for all tasks to finish

If you want to wait for the executor service to finish executing, call shutdown() and then, awaitTermination(units, unitType), e.g. awaitTermination(1, MINUTE). The ExecutorService does not block on it's own monitor, so you can't use wait etc.

Stretch Image to Fit 100% of Div Height and Width

Or you can put in the CSS,

<style>
div#img {
  background-image: url(“file.png");
  color:yellow (this part doesn't matter;
  height:100%;
  width:100%;
}
</style>

Nginx fails to load css files

For me this was ad blocker installed on web browser. It was not letting load the style.css

Generate table relationship diagram from existing schema (SQL Server)

Try DBVis - download at https://www.dbvis.com/download - there is a pro version (not needed) and a open version that should suffice.

All you have to do is to get the right JDBC - database driver for SQL Server, the tool shows tables and references orthogonal, hierarchical, in a circle ;-) etc. just by pressing one single button. I use the free version for years now.

Convert list to array in Java

This is works. Kind of.

public static Object[] toArray(List<?> a) {
    Object[] arr = new Object[a.size()];
    for (int i = 0; i < a.size(); i++)
        arr[i] = a.get(i);
    return arr;
}

Then the main method.

public static void main(String[] args) {
    List<String> list = new ArrayList<String>() {{
        add("hello");
        add("world");
    }};
    Object[] arr = toArray(list);
    System.out.println(arr[0]);
}

split string in two on given index and return both parts

You can also do it like this.
https://jsfiddle.net/Devashish2910/8hbosLj3/1/#&togetherjs=iugeGcColp

var str, result;
str = prompt("Enter Any Number");

var valueSplit = function (value, length) {
    if (length < 7) {
        var index = length - 3;
        return str.slice(0, index) + ',' + str.slice(index);
    }
    else if (length < 10 && length > 6) {
        var index1, index2;
        index1 = length - 6;
        index2 = length - 3;
        return str.slice(0,index1) + "," + str.slice(index1,index2) + "," + str.slice(index2);
    }
}

result = valueSplit(str, str.length);
alert(result);

Changing CSS for last <li>

One alternative for IE7+ and other browsers may be to use :first-child instead, and invert your styles.

For example, if you're setting the margin on each li:

ul li {
  margin-bottom: 1em;
}
ul li:last-child {
  margin-bottom: 0;
}

You could replace it with this:

ul li {
  margin-top: 1em;
}
ul li:first-child {
  margin-top: 0;
}

This will work well for some other cases like borders.

According to sitepoint, :first-child buggy, but only to the extent that it will select some root elements (the doctype or html), and may not change styles if other elements are inserted.

CORS: credentials mode is 'include'

If it helps, I was using centrifuge with my reactjs app, and, after checking some comments below, I looked at the centrifuge.js library file, which in my version, had the following code snippet:

if ('withCredentials' in xhr) {
 xhr.withCredentials = true;
}

After I removed these three lines, the app worked fine, as expected.

Hope it helps!

Good tool for testing socket connections?

Another tool is tcpmon. This is a java open-source tool to monitor a TCP connection. It's not directly a test server. It is placed in-between a client and a server but allow to see what is going through the "tube" and also to change what is going through.

How to make Python speak

There are a number of ways to make Python speak in both Python3 and Python2, two great methods are:

  • Using os

If you are on mac you will have the os module built into your computer. You can import the os module using:

import os

You can then use os to run terminal commands using the os.system command:

os.system("Your terminal")

In terminal, the way you make your computer speak is using the "say" command, thus to make the computer speak you simply use:

os.system("say 'some text'")

If you want to use this to speak a variable you can use:

os.system("say " + myVariable)

The second way to get python to speak is to use

  • The pyttsx module

You will have to install this using

pip isntall pyttsx3

or for Python3

pip3 install pyttsx3

You can then use the following code to get it to speak:

import pyttsx3
engine = pyttsx3.init()

engine.say("Your Text")

engine.runAndWait()

I hope this helps! :)

How do you get the contextPath from JavaScript, the right way?

I render context path to attribute of link tag with id="contextPahtHolder" and then obtain it in JS code. For example:

<html>
    <head>
        <link id="contextPathHolder" data-contextPath="${pageContext.request.contextPath}"/>
    <body>
        <script src="main.js" type="text/javascript"></script>
    </body>
</html>

main.js

var CONTEXT_PATH = $('#contextPathHolder').attr('data-contextPath');
$.get(CONTEXT_PATH + '/action_url', function() {});

If context path is empty (like in embedded servlet container istance), it will be empty string. Otherwise it contains contextPath string

Using 'starts with' selector on individual class names

If an element has multiples classes "[class^='apple-']" dosen't work, e.g.

<div class="fruits apple-monkey"></div>

MySQL - Make an existing Field Unique

Just write this query in your db phpmyadmin.

ALTER TABLE TableName ADD UNIQUE (FieldName)

Eg: ALTER TABLE user ADD UNIQUE (email)

Logging request/response messages when using HttpClient

An example of how you could do this:

Some notes:

  • LoggingHandler intercepts the request before it handles it to HttpClientHandler which finally writes to the wire.

  • PostAsJsonAsync extension internally creates an ObjectContent and when ReadAsStringAsync() is called in the LoggingHandler, it causes the formatter inside ObjectContent to serialize the object and that's the reason you are seeing the content in json.

Logging handler:

public class LoggingHandler : DelegatingHandler
{
    public LoggingHandler(HttpMessageHandler innerHandler)
        : base(innerHandler)
    {
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        Console.WriteLine("Request:");
        Console.WriteLine(request.ToString());
        if (request.Content != null)
        {
            Console.WriteLine(await request.Content.ReadAsStringAsync());
        }
        Console.WriteLine();

        HttpResponseMessage response = await base.SendAsync(request, cancellationToken);

        Console.WriteLine("Response:");
        Console.WriteLine(response.ToString());
        if (response.Content != null)
        {
            Console.WriteLine(await response.Content.ReadAsStringAsync());
        }
        Console.WriteLine();

        return response;
    }
}

Chain the above LoggingHandler with HttpClient:

HttpClient client = new HttpClient(new LoggingHandler(new HttpClientHandler()));
HttpResponseMessage response = client.PostAsJsonAsync(baseAddress + "/api/values", "Hello, World!").Result;

Output:

Request:
Method: POST, RequestUri: 'http://kirandesktop:9095/api/values', Version: 1.1, Content: System.Net.Http.ObjectContent`1[
[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], Headers:
{
  Content-Type: application/json; charset=utf-8
}
"Hello, World!"

Response:
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Date: Fri, 20 Sep 2013 20:21:26 GMT
  Server: Microsoft-HTTPAPI/2.0
  Content-Length: 15
  Content-Type: application/json; charset=utf-8
}
"Hello, World!"

How to get all elements inside "div" that starts with a known text

var matches = [];
var searchEles = document.getElementById("myDiv").children;
for(var i = 0; i < searchEles.length; i++) {
    if(searchEles[i].tagName == 'SELECT' || searchEles.tagName == 'INPUT') {
        if(searchEles[i].id.indexOf('q1_') == 0) {
            matches.push(searchEles[i]);
        }
    }
}

Once again, I strongly suggest jQuery for such tasks:

$("#myDiv :input").hide(); // :input matches all input elements, including selects

How to get the mysql table columns data type?

SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='SCHEMA_NAME' AND COLUMN_KEY='PRI'; WHERE COLUMN_KEY='PRI';

Tokenizing strings in C

You can simplify the code by introducing an extra variable.

#include <string.h>
#include <stdio.h>

int main()
{
    char str[100], *s = str, *t = NULL;

    strcpy(str, "a space delimited string");
    while ((t = strtok(s, " ")) != NULL) {
        s = NULL;
        printf(":%s:\n", t);
    }
    return 0;
}

How to find event listeners on a DOM node when debugging or from the JavaScript code?

If you have Firebug, you can use console.dir(object or array) to print a nice tree in the console log of any JavaScript scalar, array, or object.

Try:

console.dir(clickEvents);

or

console.dir(window);

Return index of greatest value in an array

Here is another solution, If you are using ES6 using spread operator:

var arr = [0, 21, 22, 7];

const indexOfMaxValue = arr.indexOf(Math.max(...arr));

Get free disk space

I had the same problem and i saw waruna manjula giving the best answer. However writing it all down on the console is not what you might want. To get string off al info use the following

Step one: declare values at begin

    //drive 1
    public static string drivename = "";
    public static string drivetype = "";
    public static string drivevolumelabel = "";
    public static string drivefilesystem = "";
    public static string driveuseravailablespace = "";
    public static string driveavailablespace = "";
    public static string drivetotalspace = "";

    //drive 2
    public static string drivename2 = "";
    public static string drivetype2 = "";
    public static string drivevolumelabel2 = "";
    public static string drivefilesystem2 = "";
    public static string driveuseravailablespace2 = "";
    public static string driveavailablespace2 = "";
    public static string drivetotalspace2 = "";

    //drive 3
    public static string drivename3 = "";
    public static string drivetype3 = "";
    public static string drivevolumelabel3 = "";
    public static string drivefilesystem3 = "";
    public static string driveuseravailablespace3 = "";
    public static string driveavailablespace3 = "";
    public static string drivetotalspace3 = "";

Step 2: actual code

                DriveInfo[] allDrives = DriveInfo.GetDrives();
                int drive = 1;
                foreach (DriveInfo d in allDrives)
                {
                    if (drive == 1)
                    {
                        drivename = String.Format("Drive {0}", d.Name);
                        drivetype = String.Format("Drive type: {0}", d.DriveType);
                        if (d.IsReady == true)
                        {
                            drivevolumelabel = String.Format("Volume label: {0}", d.VolumeLabel);
                            drivefilesystem = String.Format("File system: {0}", d.DriveFormat);
                            driveuseravailablespace = String.Format("Available space to current user:{0, 15} bytes", d.AvailableFreeSpace);
                            driveavailablespace = String.Format("Total available space:{0, 15} bytes", d.TotalFreeSpace);
                            drivetotalspace = String.Format("Total size of drive:{0, 15} bytes ", d.TotalSize);
                        }
                        drive = 2;
                    }
                    else if (drive == 2)
                    {
                        drivename2 = String.Format("Drive {0}", d.Name);
                        drivetype2 = String.Format("Drive type: {0}", d.DriveType);
                        if (d.IsReady == true)
                        {
                            drivevolumelabel2 = String.Format("Volume label: {0}", d.VolumeLabel);
                            drivefilesystem2 = String.Format("File system: {0}", d.DriveFormat);
                            driveuseravailablespace2 = String.Format("Available space to current user:{0, 15} bytes", d.AvailableFreeSpace);
                            driveavailablespace2 = String.Format("Total available space:{0, 15} bytes", d.TotalFreeSpace);
                            drivetotalspace2 = String.Format("Total size of drive:{0, 15} bytes ", d.TotalSize);
                        }
                        drive = 3;
                    }
                    else if (drive == 3)
                    {
                        drivename3 = String.Format("Drive {0}", d.Name);
                        drivetype3 = String.Format("Drive type: {0}", d.DriveType);
                        if (d.IsReady == true)
                        {
                            drivevolumelabel3 = String.Format("Volume label: {0}", d.VolumeLabel);
                            drivefilesystem3 = String.Format("File system: {0}", d.DriveFormat);
                            driveuseravailablespace3 = String.Format("Available space to current user:{0, 15} bytes", d.AvailableFreeSpace);
                            driveavailablespace3 = String.Format("Total available space:{0, 15} bytes", d.TotalFreeSpace);
                            drivetotalspace3 = String.Format("Total size of drive:{0, 15} bytes ", d.TotalSize);
                        }
                        drive = 4;
                    }
                    if (drive == 4)
                    {
                        drive = 1;
                    }
                }

                //part 2: possible debug - displays in output

                //drive 1
                Console.WriteLine(drivename);
                Console.WriteLine(drivetype);
                Console.WriteLine(drivevolumelabel);
                Console.WriteLine(drivefilesystem);
                Console.WriteLine(driveuseravailablespace);
                Console.WriteLine(driveavailablespace);
                Console.WriteLine(drivetotalspace);

                //drive 2
                Console.WriteLine(drivename2);
                Console.WriteLine(drivetype2);
                Console.WriteLine(drivevolumelabel2);
                Console.WriteLine(drivefilesystem2);
                Console.WriteLine(driveuseravailablespace2);
                Console.WriteLine(driveavailablespace2);
                Console.WriteLine(drivetotalspace2);

                //drive 3
                Console.WriteLine(drivename3);
                Console.WriteLine(drivetype3);
                Console.WriteLine(drivevolumelabel3);
                Console.WriteLine(drivefilesystem3);
                Console.WriteLine(driveuseravailablespace3);
                Console.WriteLine(driveavailablespace3);
                Console.WriteLine(drivetotalspace3);

I want to note that you can just make all the console writelines comment code, but i thought it would be nice for you to test it. If you display all these after each other you get the same list as waruna majuna

Drive C:\ Drive type: Fixed Volume label: File system: NTFS Available space to current user: 134880153600 bytes Total available space: 134880153600 bytes Total size of drive: 499554185216 bytes

Drive D:\ Drive type: CDRom

Drive H:\ Drive type: Fixed Volume label: HDD File system: NTFS Available space to current user: 2000010817536 bytes Total available space: 2000010817536 bytes Total size of drive: 2000263573504 bytes

However you can now acces all of the loose information at strings

How to solve the system.data.sqlclient.sqlexception (0x80131904) error

You also need to change the DataSource of the connection string. KELVIN-PC is the name of your local machine and the sql server is running on the default instance.

If you are sure the the server is running as the default instance, you can always use . in the DataSource, eg.

connectionString="Data Source=.;Initial Catalog=LMS;User ID=sa;Password=temperament"

otherwise, you need to specify the name of the instance of the server,

connectionString="Data Source=.\INSTANCENAME;Initial Catalog=LMS;User ID=sa;Password=temperament"

What is NODE_ENV and how to use it in Express?

NODE_ENV is an environment variable made popular by the express web server framework. When a node application is run, it can check the value of the environment variable and do different things based on the value. NODE_ENV specifically is used (by convention) to state whether a particular environment is a production or a development environment. A common use-case is running additional debugging or logging code if running in a development environment.

Accessing NODE_ENV

You can use the following code to access the environment variable yourself so that you can perform your own checks and logic:

var environment = process.env.NODE_ENV

Assume production if you don't recognise the value:

var isDevelopment = environment === 'development'

if (isDevelopment) {
  setUpMoreVerboseLogging()
}

You can alternatively using express' app.get('env') function, but note that this is NOT RECOMMENDED as it defaults to "development", which may result in development code being accidentally run in a production environment - it's much safer if your app throws an error if this important value is not set (or if preferred, defaults to production logic as above).

Be aware that if you haven't explicitly set NODE_ENV for your environment, it will be undefined if you access it from process.env, there is no default.

Setting NODE_ENV

How to actually set the environment variable varies from operating system to operating system, and also depends on your user setup.

If you want to set the environment variable as a one-off, you can do so from the command line:

  • linux & mac: export NODE_ENV=production
  • windows: $env:NODE_ENV = 'production'

In the long term, you should persist this so that it isn't unset if you reboot - rather than list all the possible methods to do this, I'll let you search how to do that yourself!

Convention has dictated that there are two 'main' values you should use for NODE_ENV, either production or development, all lowercase. There's nothing to stop you from using other values, (test, for example, if you wish to use some different logic when running automated tests), but be aware that if you are using third-party modules, they may explicitly compare with 'production' or 'development' to determine what to do, so there may be side effects that aren't immediately obvious.

Finally, note that it's a really bad idea to try to set NODE_ENV from within a node application itself - if you do, it will only be applied to the process from which it was set, so things probably won't work like you'd expect them to. Don't do it - you'll regret it.

.htaccess, order allow, deny, deny from all: confused?

This is a quite confusing way of using Apache configuration directives.

Technically, the first bit is equivalent to

Allow From All

This is because Order Deny,Allow makes the Deny directive evaluated before the Allow Directives. In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.

Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.

The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.

Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.

It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.

The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):

#
# The following lines prevent .htaccess and .htpasswd files from being 
# viewed by Web clients. 
#
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy all
</Files>

which forbids access to any file beginning by ".ht".

The equivalent Apache 2.4 configuration should look like:

<Files ~ "^\.ht">
    Require all denied
</Files>

"Uncaught TypeError: Illegal invocation" in Chrome

When you execute a method (i.e. function assigned to an object), inside it you can use this variable to refer to this object, for example:

_x000D_
_x000D_
var obj = {_x000D_
  someProperty: true,_x000D_
  someMethod: function() {_x000D_
    console.log(this.someProperty);_x000D_
  }_x000D_
};_x000D_
obj.someMethod(); // logs true
_x000D_
_x000D_
_x000D_

If you assign a method from one object to another, its this variable refers to the new object, for example:

_x000D_
_x000D_
var obj = {_x000D_
  someProperty: true,_x000D_
  someMethod: function() {_x000D_
    console.log(this.someProperty);_x000D_
  }_x000D_
};_x000D_
_x000D_
var anotherObj = {_x000D_
  someProperty: false,_x000D_
  someMethod: obj.someMethod_x000D_
};_x000D_
_x000D_
anotherObj.someMethod(); // logs false
_x000D_
_x000D_
_x000D_

The same thing happens when you assign requestAnimationFrame method of window to another object. Native functions, such as this, has build-in protection from executing it in other context.

There is a Function.prototype.call() function, which allows you to call a function in another context. You just have to pass it (the object which will be used as context) as a first parameter to this method. For example alert.call({}) gives TypeError: Illegal invocation. However, alert.call(window) works fine, because now alert is executed in its original scope.

If you use .call() with your object like that:

support.animationFrame.call(window, function() {});

it works fine, because requestAnimationFrame is executed in scope of window instead of your object.

However, using .call() every time you want to call this method, isn't very elegant solution. Instead, you can use Function.prototype.bind(). It has similar effect to .call(), but instead of calling the function, it creates a new function which will always be called in specified context. For example:

_x000D_
_x000D_
window.someProperty = true;_x000D_
var obj = {_x000D_
  someProperty: false,_x000D_
  someMethod: function() {_x000D_
    console.log(this.someProperty);_x000D_
  }_x000D_
};_x000D_
_x000D_
var someMethodInWindowContext = obj.someMethod.bind(window);_x000D_
someMethodInWindowContext(); // logs true
_x000D_
_x000D_
_x000D_

The only downside of Function.prototype.bind() is that it's a part of ECMAScript 5, which is not supported in IE <= 8. Fortunately, there is a polyfill on MDN.

As you probably already figured out, you can use .bind() to always execute requestAnimationFrame in context of window. Your code could look like this:

var support = {
    animationFrame: (window.requestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        window.oRequestAnimationFrame).bind(window)
};

Then you can simply use support.animationFrame(function() {});.

Maximum size of an Array in Javascript

Like @maerics said, your target machine and browser will determine performance.

But for some real world numbers, on my 2017 enterprise Chromebook, running the operation:

console.time();
Array(x).fill(0).filter(x => x < 6).length
console.timeEnd();
  • x=5e4 takes 16ms, good enough for 60fps
  • x=4e6 takes 250ms, which is noticeable but not a big deal
  • x=3e7 takes 1300ms, which is pretty bad
  • x=4e7 takes 11000ms and allocates an extra 2.5GB of memory

So around 30 million elements is a hard upper limit, because the javascript VM falls off a cliff at 40 million elements and will probably crash the process.


EDIT: In the code above, I'm actually filling the array with elements and looping over them, simulating the minimum of what an app might want to do with an array. If you just run Array(2**32-1) you're creating a sparse array that's closer to an empty JavaScript object with a length, like {length: 4294967295}. If you actually tried to use all those 4 billion elements, you'll definitely your user's javascript process.

Retrieving Data from SQL Using pyodbc

In order to receive actual data stored in the table, you should use one of fetch...() functions or use the cursor as an iterator (i.e. "for row in cursor"...). This is described in the documentation:

cursor.execute("select user_id, user_name from users where user_id < 100")
rows = cursor.fetchall()
for row in rows:
    print row.user_id, row.user_name

How to get the groups of a user in Active Directory? (c#, asp.net)

My solution:

UserPrincipal user = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain, myDomain), IdentityType.SamAccountName, myUser);
List<string> UserADGroups = new List<string>();            
foreach (GroupPrincipal group in user.GetGroups())
{
    UserADGroups.Add(group.ToString());
}

Python: read all text file lines in loop

You can stop the 2-line separation in the output by using

    with open('t.ini') as f:
       for line in f:
           print line.strip()
           if 'str' in line:
              break

regex match any single character (one character only)

Match any single character

  • Use the dot . character as a wildcard to match any single character.

Example regex: a.c

abc   // match
a c   // match
azc   // match
ac    // no match
abbc  // no match

Match any specific character in a set

  • Use square brackets [] to match any characters in a set.
  • Use \w to match any single alphanumeric character: 0-9, a-z, A-Z, and _ (underscore).
  • Use \d to match any single digit.
  • Use \s to match any single whitespace character.

Example 1 regex: a[bcd]c

abc   // match
acc   // match
adc   // match
ac    // no match
abbc  // no match

Example 2 regex: a[0-7]c

a0c   // match
a3c   // match
a7c   // match
a8c   // no match
ac    // no match
a55c  // no match

Match any character except ...

Use the hat in square brackets [^] to match any single character except for any of the characters that come after the hat ^.

Example regex: a[^abc]c

aac   // no match
abc   // no match
acc   // no match
a c   // match
azc   // match
ac    // no match
azzc  // no match

(Don't confuse the ^ here in [^] with its other usage as the start of line character: ^ = line start, $ = line end.)

Match any character optionally

Use the optional character ? after any character to specify zero or one occurrence of that character. Thus, you would use .? to match any single character optionally.

Example regex: a.?c

abc   // match
a c   // match
azc   // match
ac    // match
abbc  // no match

See also

Batch file to delete files older than N days

How about this modification on 7daysclean.cmd to take a leap year into account?

It can be done in less than 10 lines of coding!

set /a Leap=0
if (Month GEQ 2 and ((Years%4 EQL 0 and Years%100 NEQ 0) or Years%400 EQL 0)) set /a Leap=day
set /a Months=!_months!+Leap

Edit by Mofi:

The condition above contributed by J.R. evaluates always to false because of invalid syntax.

And Month GEQ 2 is also wrong because adding 86400 seconds for one more day must be done in a leap year only for the months March to December, but not for February.

A working code to take leap day into account - in current year only - in batch file 7daysclean.cmd posted by Jay would be:

set "LeapDaySecs=0"
if %Month% LEQ 2 goto CalcMonths
set /a "LeapRule=Years%%4"
if %LeapRule% NEQ 0 goto CalcMonths
rem The other 2 rules can be ignored up to year 2100.
set /A "LeapDaySecs=day"
:CalcMonths
set /a Months=!_months!+LeapDaySecs

How do I get monitor resolution in Python?

For later versions of PyGtk:

import gi
gi.require_version("Gdk", "3.0")
from gi.repository import Gdk

display = Gdk.Display.get_default()
n_monitors = display.get_n_monitors()
print("there are %d monitors" % n_monitors)
for m in range(n_monitors):
  monitor = display.get_monitor(m)
  geometry = monitor.get_geometry()
  print("monitor %d: %d x %d" % (m, geometry.width, geometry.height))

Find the host name and port using PSQL commands

You can use the command in psql \conninfo you will get You are connected to database "your_database" as user "user_name" on host "host_name" at port "port_number".

How to remove all CSS classes using jQuery/JavaScript?

Hang on, doesn't removeClass() default to removing all classes if nothing specific is specified? So

$("#item").removeClass();

will do it on its own...

Add colorbar to existing axis

Couldn't add this as a comment, but in case anyone is interested in using the accepted answer with subplots, the divider should be formed on specific axes object (rather than on the numpy.ndarray returned from plt.subplots)

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots(ncols=2, nrows=2)
for row in ax:
    for col in row:
        im = col.imshow(data, cmap='bone')
        divider = make_axes_locatable(col)
        cax = divider.append_axes('right', size='5%', pad=0.05)
        fig.colorbar(im, cax=cax, orientation='vertical')
plt.show()

Abort a git cherry-pick?

You can do the following

git cherry-pick --abort

From the git cherry-pick docs

--abort  

Cancel the operation and return to the pre-sequence state.

-XX:MaxPermSize with or without -XX:PermSize

-XX:PermSize specifies the initial size that will be allocated during startup of the JVM. If necessary, the JVM will allocate up to -XX:MaxPermSize.

javascript: get a function's variable's value within another function

nameContent only exists within the first() function, as you defined it within the first() function.

To make its scope broader, define it outside of the functions:

var nameContent;

function first(){
    nameContent=document.getElementById('full_name').value;
}

function second() {
    first();
    y=nameContent; alert(y);
}
second();

A slightly better approach would be to return the value, as global variables get messy very quickly:

function getFullName() {
  return document.getElementById('full_name').value;
}

function doStuff() {
  var name = getFullName();

  alert(name);
}

doStuff();

Best XML Parser for PHP

It depends on what you are trying to do with the XML files. If you are just trying to read the XML file (like a configuration file), The Wicked Flea is correct in suggesting SimpleXML since it creates what amounts to nested ArrayObjects. e.g. value will be accessible by $xml->root->child.

If you are looking to manipulate the XML files you're probably best off using DOM XML

How do implement a breadth first traversal?

Use the following algorithm to traverse in breadth first search-

  1. First add the root node into the queue with the put method.
  2. Iterate while the queue is not empty.
  3. Get the first node in the queue, and then print its value.
  4. Add both left and right children into the queue (if the current nodehas children).
  5. Done. We will print the value of each node, level by level,by poping/removing the element

Code is written below-

    Queue<TreeNode> queue= new LinkedList<>();
    private void breadthWiseTraversal(TreeNode root) {
        if(root==null){
            return;
        }
        TreeNode temp = root;
        queue.clear();
        ((LinkedList<TreeNode>) queue).add(temp);
        while(!queue.isEmpty()){
            TreeNode ref= queue.remove();
            System.out.print(ref.data+" ");
            if(ref.left!=null) {
                ((LinkedList<TreeNode>) queue).add(ref.left);
            }
            if(ref.right!=null) {
                ((LinkedList<TreeNode>) queue).add(ref.right);
            }
        }
    }

Shrink a YouTube video to responsive width

See full gist here and live example here.

#hero { width:100%;height:100%;background:url('{$img_ps_dir}cms/how-it-works/hero.jpg') no-repeat top center; }
.videoWrapper { position:relative;padding-bottom:56.25%;padding-top:25px;max-width:100%; }

<div id="hero">
    <div class="container">
        <div class="row-fluid">
            <script src="https://www.youtube.com/iframe_api"></script>
            <center>
            <div class="videoWrapper">
                 <div id="player"></div>
            </div>
            </center>
            <script>
            function onYouTubeIframeAPIReady() { 
                player = new YT.Player('player', {
                   videoId:'xxxxxxxxxxx',playerVars: {  controls:0,autoplay:0,disablekb:1,enablejsapi:1,iv_load_policy:3,modestbranding:1,showinfo:0,rel:0,theme:'light' }
                } );
                resizeHeroVideo();
             }
             </script>
        </div>
    </div>
</div>

var player = null;
$( document ).ready(function() {
    resizeHeroVideo();
} );

$(window).resize(function() {
    resizeHeroVideo();
});

function resizeHeroVideo() {
    var content = $('#hero');
    var contentH = viewportSize.getHeight();
    contentH -= 158;
    content.css('height',contentH);

    if(player != null) {
        var iframe = $('.videoWrapper iframe');
        var iframeH = contentH - 150;
        if (isMobile) {
            iframeH = 163; 
        }
        iframe.css('height',iframeH);
        var iframeW = iframeH/9 * 16;
        iframe.css('width',iframeW);
    }
}

resizeHeroVideo is called only after the Youtube player has fully loaded (on page load does not work), and whenever the browser window is resized. When it runs, it calculates the height and width of the iframe and assigns the appropriate values maintaining the correct aspect ratio. This works whether the window is resized horizontally or vertically.

Listing files in a specific "folder" of a AWS S3 bucket

Everything in S3 is an object. To you, it may be files and folders. But to S3, they're just objects.

Objects that end with the delimiter (/ in most cases) are usually perceived as a folder, but it's not always the case. It depends on the application. Again, in your case, you're interpretting it as a folder. S3 is not. It's just another object.

In your case above, the object users/<user-id>/contacts/<contact-id>/ exists in S3 as a distinct object, but the object users/<user-id>/ does not. That's the difference in your responses. Why they're like that, we cannot tell you, but someone made the object in one case, and didn't in the other. You don't see it in the AWS Management Console because the console is interpreting it as a folder and hiding it from you.

Since S3 just sees these things as objects, it won't "exclude" certain things for you. It's up to the client to deal with the objects as they should be dealt with.

Your Solution

Since you're the one that doesn't want the folder objects, you can exclude it yourself by checking the last character for a /. If it is, then ignore the object from the response.

Change Bootstrap input focus blue glow

This will work 100% use this:

.form-control, .form-control:focus{
   box-shadow: 0 0 0 0 rgba(255, 255, 255, 0);
   border: rgba(255, 255, 255, 0);
}

Make page to tell browser not to cache/preserve input values

Another approach would be to reset the form using JavaScript right after the form in the HTML:

<form id="myForm">
  <input type="text" value="" name="myTextInput" />
</form>

<script type="text/javascript">
  document.getElementById("myForm").reset();
</script>

"CAUTION: provisional headers are shown" in Chrome debugger

For chrome v72+ what solved it for me was only this:

go to chrome://flags/ and disable this 3 flags

  • Disable site isolation
  • Enable network service
  • Runs network service in-process

enter image description here

or you can do it from command line :

chrome --disable-site-isolation-trials --disable-features=NetworkService,NetworkServiceInProcess

why this happen?

It seems that Google is refactoring their Chromium engine into modular structure, where different services will be separated into stand-alone modules and processes. They call this process servicification. Network service is the first step, Ui service, Identity service and Device service are coming up. Google provides the official information at the Chromium project site.

is it dangerous to change that?

An example is networking: once we have a network service we can choose to run it out of process for better stability/security, or in-process if we're resource constrained. source

Is a Python list guaranteed to have its elements stay in the order they are inserted in?

Yes, the order of elements in a python list is persistent.

Using media breakpoints in Bootstrap 4-alpha

Bootstrap has a way of using media queries to define the different task for different sites. It uses four breakpoints.

we have extra small screen sizes which are less than 576 pixels that small in which I mean it's size from 576 to 768 pixels.

medium screen sizes take up screen size from 768 pixels up to 992 pixels large screen size from 992 pixels up to 1200 pixels.

E.g Small Text

This means that at the small screen between 576px and 768px, center the text For medium screen, change "sm" to "md" and same goes to large "lg"

How to undo a successful "git cherry-pick"?

Faced with this same problem, I discovered if you have committed and/or pushed to remote since your successful cherry-pick, and you want to remove it, you can find the cherry-pick's SHA by running:

git log --graph --decorate --oneline

Then, (after using :wq to exit the log) you can remove the cherry-pick using

git rebase -p --onto YOUR_SHA_HERE^ YOUR_SHA_HERE

where YOUR_SHA_HERE equals the cherry-picked commit's 40- or abbreviated 7-character SHA.

At first, you won't be able to push your changes because your remote repo and your local repo will have different commit histories. You can force your local commits to replace what's on your remote by using

git push --force origin YOUR_REPO_NAME

(I adapted this solution from Seth Robertson: See "Removing an entire commit.")