Programs & Examples On #Gzip

GZip/gzip is both the name for a compressed data format and any of several software applications implementing this format. It is commonly used to compress HTTP requests and responses, and combined with the tar format for archival.

Excluding directory when creating a .tar.gz file

tar -pczf <target_file.tar.gz> --exclude /path/to/exclude --exclude /another/path/to/exclude/* /path/to/include/ /another/path/to/include/*

Tested in Ubuntu 19.10.

  1. The = after exclude is optional. You can use = instead of space after keyword exclude if you like.
  2. Parameter exclude must be placed before the source.
  3. The difference between use folder name (like the 1st) or the * (like the 2nd) is: the 2nd one will include an empty folder in package but the 1st will not.

Enable IIS7 gzip

Global Gzip in HttpModule

If you don't have access to the final IIS instance (shared hosting...) you can create a HttpModule that adds this code to every HttpApplication.Begin_Request event :

HttpContext context = HttpContext.Current;
context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
HttpContext.Current.Response.AppendHeader("Content-encoding", "gzip");
HttpContext.Current.Response.Cache.VaryByHeaders["Accept-encoding"] = true;

Testing

Kudos, no solution is done without testing. I like to use the Firefox plugin "Liveheaders" it shows all the information about every http message between the browser and server, including compression, file size (which you could compare to the file size on the server).

How to enable GZIP compression in IIS 7.5

Global Gzip in HttpModule

If you don't have access to shared hosting - the final IIS instance. You can create a HttpModule that gets added this code to every HttpApplication.Begin_Request event:-

HttpContext context = HttpContext.Current;
context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
HttpContext.Current.Response.AppendHeader("Content-encoding", "gzip");
HttpContext.Current.Response.Cache.VaryByHeaders["Accept-encoding"] = true;

How to unzip gz file using Python

From the documentation:

import gzip
f = gzip.open('file.txt.gz', 'rb')
file_content = f.read()
f.close()

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

TL;DR

find /my/dir/ -printf "%P\n" | tar -czf mydir.tgz --no-recursion -C /my/dir/ -T -

With some conditions (archive only files, dirs and symlinks):

find /my/dir/ -printf "%P\n" -type f -o -type l -o -type d | tar -czf mydir.tgz --no-recursion -C /my/dir/ -T -

Explanation

The below unfortunately includes a parent directory ./ in the archive:

tar -czf mydir.tgz -C /my/dir .

You can move all the files out of that directory by using the --transform configuration option, but that doesn't get rid of the . directory itself. It becomes increasingly difficult to tame the command.

You could use $(find ...) to add a file list to the command (like in magnus' answer), but that potentially causes a "file list too long" error. The best way is to combine it with tar's -T option, like this:

find /my/dir/ -printf "%P\n" -type f -o -type l -o -type d | tar -czf mydir.tgz --no-recursion -C /my/dir/ -T -

Basically what it does is list all files (-type f), links (-type l) and subdirectories (-type d) under your directory, make all filenames relative using -printf "%P\n", and then pass that to the tar command (it takes filenames from STDIN using -T -). The -C option is needed so tar knows where the files with relative names are located. The --no-recursion flag is so that tar doesn't recurse into folders it is told to archive (causing duplicate files).

If you need to do something special with filenames (filtering, following symlinks etc), the find command is pretty powerful, and you can test it by just removing the tar part of the above command:

$ find /my/dir/ -printf "%P\n" -type f -o -type l -o -type d
> textfile.txt
> documentation.pdf
> subfolder2
> subfolder
> subfolder/.gitignore

For example if you want to filter PDF files, add ! -name '*.pdf'

$ find /my/dir/ -printf "%P\n" -type f ! -name '*.pdf' -o -type l -o -type d
> textfile.txt
> subfolder2
> subfolder
> subfolder/.gitignore

Non-GNU find

The command uses printf (available in GNU find) which tells find to print its results with relative paths. However, if you don't have GNU find, this works to make the paths relative (removes parents with sed):

find /my/dir/ -type f -o -type l -o -type d | sed s,^/my/dir/,, | tar -czf mydir.tgz --no-recursion -C /my/dir/ -T -

How can I get Apache gzip compression to work?

Ran into this problem using the same .htaccess configuration. I realized that my server was serving javascript files as text/javascript instead of application/javascript. Once I added text/javascript to the AddOutputFilterByType declaration, gzip started working.

As to why javascript was being served as text/javascript: there was an AddType 'text/javascript' js declaration at the top of my root .htaccess file. After removing it (it had been added in error), javascript starting serving as application/javascript.

Using GZIP compression with Spring Boot/MVC/JavaConfig with RESTful

This is basically the same solution as @andy-wilkinson provided, but as of Spring Boot 1.0 the customize(...) method has a ConfigurableEmbeddedServletContainer parameter.

Another thing that is worth mentioning is that Tomcat only compresses content types of text/html, text/xml and text/plain by default. Below is an example that supports compression of application/json as well:

@Bean
public EmbeddedServletContainerCustomizer servletContainerCustomizer() {
    return new EmbeddedServletContainerCustomizer() {
        @Override
        public void customize(ConfigurableEmbeddedServletContainer servletContainer) {
            ((TomcatEmbeddedServletContainerFactory) servletContainer).addConnectorCustomizers(
                    new TomcatConnectorCustomizer() {
                        @Override
                        public void customize(Connector connector) {
                            AbstractHttp11Protocol httpProtocol = (AbstractHttp11Protocol) connector.getProtocolHandler();
                            httpProtocol.setCompression("on");
                            httpProtocol.setCompressionMinSize(256);
                            String mimeTypes = httpProtocol.getCompressableMimeTypes();
                            String mimeTypesWithJson = mimeTypes + "," + MediaType.APPLICATION_JSON_VALUE;
                            httpProtocol.setCompressableMimeTypes(mimeTypesWithJson);
                        }
                    }
            );
        }
    };
}

How to check if a Unix .tar.gz file is a valid file without uncompressing?

If you want to do a real test extract of a tar file without extracting to disk, use the -O option. This spews the extract to standard output instead of the filesystem. If the tar file is corrupt, the process will abort with an error.

Example of failed tar ball test...

$ echo "this will not pass the test" > hello.tgz
$ tar -xvzf hello.tgz -O > /dev/null
gzip: stdin: not in gzip format
tar: Child returned status 1
tar: Error exit delayed from previous errors
$ rm hello.*

Working Example...

$ ls hello*
ls: hello*: No such file or directory
$ echo "hello1" > hello1.txt
$ echo "hello2" > hello2.txt
$ tar -cvzf hello.tgz hello[12].txt
hello1.txt
hello2.txt
$ rm hello[12].txt
$ ls hello*
hello.tgz
$ tar -xvzf hello.tgz -O
hello1.txt
hello1
hello2.txt
hello2
$ ls hello*
hello.tgz
$ tar -xvzf hello.tgz
hello1.txt
hello2.txt
$ ls hello*
hello1.txt  hello2.txt  hello.tgz
$ rm hello*

How to create tar.gz archive file in Windows?

tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.

If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.

compression and decompression of string data in java

This is because of

String outStr = obj.toString("UTF-8");

Send the byte[] which you can get from your ByteArrayOutputStream and use it as such in your ByteArrayInputStream to construct your GZIPInputStream. Following are the changes which need to be done in your code.

byte[] compressed = compress(string); //In the main method

public static byte[] compress(String str) throws Exception {
    ...
    ...
    return obj.toByteArray();
}

public static String decompress(byte[] bytes) throws Exception {
    ...
    GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes));
    ...
}

tar: Error is not recoverable: exiting now

The problem is that you do not have bzip2 installed. The tar program relies upon this external program to do compression. For installing bzip2, it depends on the system you are using. For example, with Ubuntu that would be on Ubuntu

sudo apt-get install bzip2

The GNU tar program does not know how to compress an existing file such as user-logs.tar (bzip2 does that). The tar program can use external compression programs gzip, bzip2, xz by opening a pipe to those programs, sending a tar archive via the pipe to the compression utility, which compresses the data which it reads from tar and writes the result to the filename which the tar program specifies.

Alternatively, the tar and compression utility could be the same program. BSD tar does its compression using lib archive (they're not really distinct except in name).

How to uncompress a tar.gz in another directory

gzip -dc archive.tar.gz | tar -xf - -C /destination

or, with GNU tar

tar xzf archive.tar.gz -C /destination

How to extract filename.tar.gz file

It happens sometimes for the files downloaded with "wget" command. Just 10 minutes ago, I was trying to install something to server from the command screen and the same thing happened. As a solution, I just downloaded the .tar.gz file to my machine from the web then uploaded it to the server via FTP. After that, the "tar" command worked as it was expected.

JavaScript implementation of Gzip

Most browsers can decompress gzip on the fly. That might be a better option than a javascript implementation.

Extract and delete all .gz in a directory- Linux

Try:

ls -1 | grep -E "\.tar\.gz$" | xargs -n 1 tar xvfz

Then Try:

ls -1 | grep -E "\.tar\.gz$" | xargs -n 1 rm

This will untar all .tar.gz files in the current directory and then delete all the .tar.gz files. If you want an explanation, the "|" takes the stdout of the command before it, and uses that as the stdin of the command after it. Use "man command" w/o the quotes to figure out what those commands and arguments do. Or, you can research online.

How are zlib, gzip and zip related? What do they have in common and how are they different?

The most important difference is that gzip is only capable to compress a single file while zip compresses multiple files one by one and archives them into one single file afterwards. Thus, gzip comes along with tar most of the time (there are other possibilities, though). This comes along with some (dis)advantages.

If you have a big archive and you only need one single file out of it, you have to decompress the whole gzip file to get to that file. This is not required if you have a zip file.

On the other hand, if you compress 10 similiar or even identical files, the zip archive will be much bigger because each file is compressed individually, whereas in gzip in combination with tar a single file is compressed which is much more effective if the files are similiar (equal).

Utilizing multi core for tar+gzip/bzip compression/decompression

You can also use the tar flag "--use-compress-program=" to tell tar what compression program to use.

For example use:

tar -c --use-compress-program=pigz -f tar.file dir_to_zip 

Import and insert sql.gz file into database with putty

If the mysql dump was a .gz file, you need to gunzip to uncompress the file by typing $ gunzip mysqldump.sql.gz

This will uncompress the .gz file and will just store mysqldump.sql in the same location.

Type the following command to import sql data file:

$ mysql -u username -p -h localhost test-database < mysqldump.sql password: _

TypeError: 'str' does not support the buffer interface

There is an easier solution to this problem.

You just need to add a t to the mode so it becomes wt. This causes Python to open the file as a text file and not binary. Then everything will just work.

The complete program becomes this:

plaintext = input("Please enter the text you want to compress")
filename = input("Please enter the desired filename")
with gzip.open(filename + ".gz", "wt") as outfile:
    outfile.write(plaintext)

Node.js: Gzip compression?

How about this?

node-compress
A streaming compression / gzip module for node.js
To install, ensure that you have libz installed, and run:
node-waf configure
node-waf build
This will put the compress.node binary module in build/default.
...

Read from a gzip file in python

python: read lines from compressed text files

Using gzip.GzipFile:

import gzip

with gzip.open('input.gz','r') as fin:        
    for line in fin:        
        print('got line', line)

htaccess - How to force the client's browser to clear the cache?

In my case, I change a lot an specific JS file and I need it to be in its last version in all browsers where is being used.

I do not have a specific version number for this file, so I simply hash the current date and time (hour and minute) and pass it as the version number:

<script src="/js/panel/app.js?v={{ substr(md5(date("Y-m-d_Hi")),10,18) }}"></script>

I need it to be loaded every minute, but you can decide when it should be reloaded.

How to gzip all files in all sub-directories into one compressed file in bash

tar -zcvf compressFileName.tar.gz folderToCompress

everything in folderToCompress will go to compressFileName

Edit: After review and comments I realized that people may get confused with compressFileName without an extension. If you want you can use .tar.gz extension(as suggested) with the compressFileName

Why use deflate instead of gzip for text files served by Apache?

mod_deflate requires fewer resources on your server, although you may pay a small penalty in terms of the amount of compression.

If you are serving many small files, I'd recommend benchmarking and load testing your compressed and uncompressed solutions - you may find some cases where enabling compression will not result in savings.

Adding a guideline to the editor in Visual Studio

Visual Studio 2017 / 2019

For anyone looking for an answer for a newer version of Visual Studio, install the Editor Guidelines plugin, then right-click in the editor and select this:

Add guidelines in Visual Studio 2017

Verify host key with pysftp

Hi We sort of had the same problem if I understand you well. So check what pysftp version you're using. If it's the latest one which is 0.2.9 downgrade to 0.2.8. Check this out. https://github.com/Yenthe666/auto_backup/issues/47

GoogleTest: How to skip a test?

For another approach, you can wrap your tests in a function and use normal conditional checks at runtime to only execute them if you want.

#include <gtest/gtest.h>

const bool skip_some_test = true;

bool some_test_was_run = false;

void someTest() {
   EXPECT_TRUE(!skip_some_test);
   some_test_was_run = true;
}

TEST(BasicTest, Sanity) {
   EXPECT_EQ(1, 1);
   if(!skip_some_test) {
      someTest();
      EXPECT_TRUE(some_test_was_run);
   }
}

This is useful for me as I'm trying to run some tests only when a system supports dual stack IPv6.

Technically that dualstack stuff shouldn't really be a unit test as it depends on the system. But I can't really make any integration tests until I have tested they work anyway and this ensures that it won't report failures when it's not the codes fault.

As for the test of it I have stub objects that simulate a system's support for dualstack (or lack of) by constructing fake sockets.

The only downside is that the test output and the number of tests will change which could cause issues with something that monitors the number of successful tests.

You can also use ASSERT_* rather than EQUAL_*. Assert will about the rest of the test if it fails. Prevents a lot of redundant stuff being dumped to the console.

PostgreSQL : cast string to date DD/MM/YYYY

A DATE column does not have a format. You cannot specify a format for it.

You can use DateStyle to control how PostgreSQL emits dates, but it's global and a bit limited.

Instead, you should use to_char to format the date when you query it, or format it in the client application. Like:

SELECT to_char("date", 'DD/MM/YYYY') FROM mytable;

e.g.

regress=> SELECT to_char(DATE '2014-04-01', 'DD/MM/YYYY');
  to_char   
------------
 01/04/2014
(1 row)

How to call a parent method from child class in javascript?

ES6 style allows you to use new features, such as super keyword. super keyword it's all about parent class context, when you are using ES6 classes syntax. As a very simple example, checkout:

class Foo {
    static classMethod() {
        return 'hello';
    }
}

class Bar extends Foo {
    static classMethod() {
        return super.classMethod() + ', too';
    }
}
Bar.classMethod(); // 'hello, too'

Also, you can use super to call parent constructor:

class Foo {}

class Bar extends Foo {
    constructor(num) {
        let tmp = num * 2; // OK
        this.num = num; // ReferenceError
        super();
        this.num = num; // OK
    }
}

And of course you can use it to access parent class properties super.prop. So, use ES6 and be happy.

Moving all files from one directory to another using Python

Copying the ".txt" file from one folder to another is very simple and question contains the logic. Only missing part is substituting with right information as below:

import os, shutil, glob

src_fldr = r"Source Folder/Directory path"; ## Edit this

dst_fldr = "Destiantion Folder/Directory path"; ## Edit this

try:
  os.makedirs(dst_fldr); ## it creates the destination folder
except:
  print "Folder already exist or some error";

below lines of code will copy the file with *.txt extension files from src_fldr to dst_fldr

for txt_file in glob.glob(src_fldr+"\\*.txt"):
    shutil.copy2(txt_file, dst_fldr);

How to get a random number between a float range?

Most commonly, you'd use:

import random
random.uniform(a, b) # range [a, b) or [a, b] depending on floating-point rounding

Python provides other distributions if you need.

If you have numpy imported already, you can used its equivalent:

import numpy as np
np.random.uniform(a, b) # range [a, b)

Again, if you need another distribution, numpy provides the same distributions as python, as well as many additional ones.

Kotlin - Property initialization using "by lazy" vs. "lateinit"

In addition to all of the great answers, there is a concept called lazy loading:

Lazy loading is a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed.

Using it properly, you can reduce the loading time of your application. And Kotlin way of it's implementation is by lazy() which loads the needed value to your variable whenever it's needed.

But lateinit is used when you are sure a variable won't be null or empty and will be initialized before you use it -e.g. in onResume() method for android- and so you don't want to declare it as a nullable type.

Convert stdClass object to array in PHP

You can convert an std object to array like this:

$objectToArray = (array)$object;

Using Gulp to Concatenate and Uglify files

Jun 10 2015: Note from the author of gulp-uglifyjs:

DEPRECATED: This plugin has been blacklisted as it relies on Uglify to concat the files instead of using gulp-concat, which breaks the "It should do one thing" paradigm. When I created this plugin, there was no way to get source maps to work with gulp, however now there is a gulp-sourcemaps plugin that achieves the same goal. gulp-uglifyjs still works great and gives very granular control over the Uglify execution, I'm just giving you a heads up that other options now exist.


Feb 18 2015: gulp-uglify and gulp-concat both work nicely with gulp-sourcemaps now. Just make sure to set the newLine option correctly for gulp-concat; I recommend \n;.


Original Answer (Dec 2014): Use gulp-uglifyjs instead. gulp-concat isn't necessarily safe; it needs to handle trailing semi-colons correctly. gulp-uglify also doesn't support source maps. Here's a snippet from a project I'm working on:

gulp.task('scripts', function () {
    gulp.src(scripts)
        .pipe(plumber())
        .pipe(uglify('all_the_things.js',{
            output: {
                beautify: false
            },
            outSourceMap: true,
            basePath: 'www',
            sourceRoot: '/'
        }))
        .pipe(plumber.stop())
        .pipe(gulp.dest('www/js'))
});

Git: How to return from 'detached HEAD' state

Use git reflog to find the hashes of previously checked out commits.

A shortcut command to get to your last checked out branch (not sure if this work correctly with detached HEAD and intermediate commits though) is git checkout -

Pretty git branch graphs

Many of the answers here are great, but for those that just want a simple one line to the point answer without having to set up aliases or anything extra, here it is:

git log --all --decorate --oneline --graph

Not everyone would be doing a git log all the time, but when you need it just remember:

"A Dog" = git log --all --decorate --oneline --graph

enter image description here

How do I set the icon for my application in visual studio 2008?

You add the .ico in your resource as bobobobo said and then in your main dialog's constructor you modify:

m_hIcon = AfxGetApp()->LoadIcon(ICON_ID_FROM_RESOURCE.H);

Show just the current branch in Git

With Git 2.22 (Q2 2019), you will have a simpler approach: git branch --show-current.

See commit 0ecb1fc (25 Oct 2018) by Daniels Umanovskis (umanovskis).
(Merged by Junio C Hamano -- gitster -- in commit 3710f60, 07 Mar 2019)

branch: introduce --show-current display option

When called with --show-current, git branch will print the current branch name and terminate.
Only the actual name gets printed, without refs/heads.
In detached HEAD state, nothing is output.

Intended both for scripting and interactive/informative use.
Unlike git branch --list, no filtering is needed to just get the branch name.

See the original discussion on the Git mailing list in Oct. 2018, and the actual pathc.

Move SQL Server 2008 database files to a new folder location

You forgot to mention the name of your database (is it "my"?).

ALTER DATABASE my SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

ALTER DATABASE my SET OFFLINE;

ALTER DATABASE my MODIFY FILE 
(
   Name = my_Data,
   Filename = 'D:\DATA\my.MDF'
);

ALTER DATABASE my MODIFY FILE 
(
   Name = my_Log, 
   Filename = 'D:\DATA\my_1.LDF'
);

Now here you must manually move the files from their current location to D:\Data\ (and remember to rename them manually if you changed them in the MODIFY FILE command) ... then you can bring the database back online:

ALTER DATABASE my SET ONLINE;

ALTER DATABASE my SET MULTI_USER;

This assumes that the SQL Server service account has sufficient privileges on the D:\Data\ folder. If not you will receive errors at the SET ONLINE command.

Remove Item from ArrayList

If you use "=", a replica is created for the original arraylist in the second one, but the reference is same so if you change in one list , the other one will also get modified. Use this instead of "="

        List_Of_Array1.addAll(List_Of_Array);

PHP order array by date?

He was considering having the date as a key, but worried that values will be written one above other, all I wanted to show (maybe not that obvious, that why I do edit) is that he can still have values intact, not written one above other, isn't this okay?!

<?php
 $data['may_1_2002']=
 Array(
 'title_id_32'=>'Good morning', 
 'title_id_21'=>'Blue sky',
 'title_id_3'=>'Summer',
 'date'=>'1 May 2002'
 );

 $data['may_2_2002']=
 Array(
 'title_id_34'=>'Leaves', 
 'title_id_20'=>'Old times',
  'date'=>'2 May   2002 '
 );


 echo '<pre>';
 print_r($data);
?>

Kill some processes by .exe file name

public void EndTask(string taskname)
{
      string processName = taskname.Replace(".exe", "");

      foreach (Process process in Process.GetProcessesByName(processName))
      {
          process.Kill();
      }
}

//EndTask("notepad");

Summary: no matter if the name contains .exe, the process will end. You don't need to "leave off .exe from process name", It works 100%.

How do I find the install time and date of Windows?

After trying a variety of methods, I figured that the NTFS volume creation time of the system volume is probably the best proxy. While there are tools to check this (see this link ) I wanted a method without an additional utility. I settled on the creation date of "C:\System Volume Information" and it seemed to check out in various cases.

One-line of PowerShell to get it is:

([DateTime](Get-Item -Force 'C:\System Volume Information\').CreationTime).ToString('MM/dd/yyyy')

How to submit http form using C#

Response.Write("<script> try {this.submit();} catch(e){} </script>");

How to change MySQL timezone in a database connection using Java?

useTimezone is an older workaround. MySQL team rewrote the setTimestamp/getTimestamp code fairly recently, but it will only be enabled if you set the connection parameter useLegacyDatetimeCode=false and you're using the latest version of mysql JDBC connector. So for example:

String url =
 "jdbc:mysql://localhost/mydb?useLegacyDatetimeCode=false

If you download the mysql-connector source code and look at setTimestamp, it's very easy to see what's happening:

If use legacy date time code = false, newSetTimestampInternal(...) is called. Then, if the Calendar passed to newSetTimestampInternal is NULL, your date object is formatted in the database's time zone:

this.tsdf = new SimpleDateFormat("''yyyy-MM-dd HH:mm:ss", Locale.US);
this.tsdf.setTimeZone(this.connection.getServerTimezoneTZ());
timestampString = this.tsdf.format(x);

It's very important that Calendar is null - so make sure you're using:

setTimestamp(int,Timestamp).

... NOT setTimestamp(int,Timestamp,Calendar).

It should be obvious now how this works. If you construct a date: January 5, 2011 3:00 AM in America/Los_Angeles (or whatever time zone you want) using java.util.Calendar and call setTimestamp(1, myDate), then it will take your date, use SimpleDateFormat to format it in the database time zone. So if your DB is in America/New_York, it will construct the String '2011-01-05 6:00:00' to be inserted (since NY is ahead of LA by 3 hours).

To retrieve the date, use getTimestamp(int) (without the Calendar). Once again it will use the database time zone to build a date.

Note: The webserver time zone is completely irrelevant now! If you don't set useLegacyDatetimecode to false, the webserver time zone is used for formatting - adding lots of confusion.


Note:

It's possible MySQL my complain that the server time zone is ambiguous. For example, if your database is set to use EST, there might be several possible EST time zones in Java, so you can clarify this for mysql-connector by telling it exactly what the database time zone is:

String url =
 "jdbc:mysql://localhost/mydb?useLegacyDatetimeCode=false&serverTimezone=America/New_York";

You only need to do this if it complains.

Oracle Installer:[INS-13001] Environment does not meet minimum requirements

To make @Raghavendra's answer more specific:

Once you've downloaded 2 zip files,

copy ALL the contents of "win64_11gR2_database_2of2.zip -> Database -> Stage -> Components" folder to "win64_11gR2_database_1of2.zip -> Database -> Stage -> Components" folder.

You'll still get the same warning, however, the installation will run completely without generating any errors.

Pandas unstack problems: ValueError: Index contains duplicate entries, cannot reshape

There's a far more simpler solution to tackle this.

The reason why you get ValueError: Index contains duplicate entries, cannot reshape is because, once you unstack "Location", then the remaining index columns "id" and "date" combinations are no longer unique.

You can avoid this by retaining the default index column (row #) and while setting the index using "id", "date" and "location", add it in "append" mode instead of the default overwrite mode.

So use,

e.set_index(['id', 'date', 'location'], append=True)

Once this is done, your index columns will still have the default index along with the set indexes. And unstack will work.

Let me know how it works out.

How to fix getImageData() error The canvas has been tainted by cross-origin data?

I was having the same issue, and for me it worked by simply concatenating https:${image.getAttribute('src')}

Check if a radio button is checked jquery

First of all, have only one id="test"

Secondly, try this:

if ($('[name="test"]').is(':checked'))

How to set response header in JAX-RS so that user sees download popup for Excel?

@Context ServletContext ctx;
@Context private HttpServletResponse response;

@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Path("/download/{filename}")
public StreamingOutput download(@PathParam("filename") String fileName) throws Exception {
    final File file = new File(ctx.getInitParameter("file_save_directory") + "/", fileName);
    response.setHeader("Content-Length", String.valueOf(file.length()));
    response.setHeader("Content-Disposition", "attachment; filename=\""+ file.getName() + "\"");
    return new StreamingOutput() {
        @Override
        public void write(OutputStream output) throws IOException,
                WebApplicationException {
            Utils.writeBuffer(new BufferedInputStream(new FileInputStream(file)), new BufferedOutputStream(output));
        }
    };
}

R - " missing value where TRUE/FALSE needed "

Can you change the if condition to this:

if (!is.na(comments[l])) print(comments[l]);

You can only check for NA values with is.na().

How to set encoding in .getJSON jQuery

You need to analyze the JSON calls using Wireshark, so you will see if you include the charset in the formation of the JSON page or not, for example:

  • If the page is simple if text / html
0000  48 54 54 50 2f 31 2e 31  20 32 30 30 20 4f 4b 0d   HTTP/1.1  200 OK.
0010  0a 43 6f 6e 74 65 6e 74  2d 54 79 70 65 3a 20 74   .Content -Type: t
0020  65 78 74 2f 68 74 6d 6c  0d 0a 43 61 63 68 65 2d   ext/html ..Cache-
0030  43 6f 6e 74 72 6f 6c 3a  20 6e 6f 2d 63 61 63 68   Control:  no-cach
  • If the page is of the type including custom JSON with MIME "charset = ISO-8859-1"
0000  48 54 54 50 2f 31 2e 31  20 32 30 30 20 4f 4b 0d   HTTP/1.1  200 OK.
0010  0a 43 61 63 68 65 2d 43  6f 6e 74 72 6f 6c 3a 20   .Cache-C ontrol: 
0020  6e 6f 2d 63 61 63 68 65  0d 0a 43 6f 6e 74 65 6e   no-cache ..Conten
0030  74 2d 54 79 70 65 3a 20  74 65 78 74 2f 68 74 6d   t-Type:  text/htm
0040  6c 3b 20 63 68 61 72 73  65 74 3d 49 53 4f 2d 38   l; chars et=ISO-8
0050  38 35 39 2d 31 0d 0a 43  6f 6e 6e 65 63 74 69 6f   859-1..C onnectio

Why is that? because we can not put on the page of JSON a goal like this:

In my case I use the manufacturer Connect Me 9210 Digi:

  • I had to use a flag to indicate that one would use non-standard MIME: p-> theCgiPtr-> = fDataType eRpDataTypeOther;
  • It added the new MIME in the variable: strcpy (p-> theCgiPtr-> fOtherMimeType, "text / html; charset = ISO-8859-1 ");

It worked for me without having to convert the data passed by JSON for UTF-8 and then redo the conversion on the page ...

How to prevent the "Confirm Form Resubmission" dialog?

I found an unorthodox way to accomplish this.

Just put the script page in an iframe. Doing so allows the page to be refreshed, seemingly even on older browsers without the "confirm form resubmission" message ever appearing.

How to send file contents as body entity using cURL

I believe you're looking for the @filename syntax, e.g.:

strip new lines

curl --data "@/path/to/filename" http://...

keep new lines

curl --data-binary "@/path/to/filename" http://...

curl will strip all newlines from the file. If you want to send the file with newlines intact, use --data-binary in place of --data

curl Failed to connect to localhost port 80

In my case, the file ~/.curlrc had a wrong proxy configured.

"static const" vs "#define" vs "enum"

It is ALWAYS preferable to use const, instead of #define. That's because const is treated by the compiler and #define by the preprocessor. It is like #define itself is not part of the code (roughly speaking).

Example:

#define PI 3.1416

The symbolic name PI may never be seen by compilers; it may be removed by the preprocessor before the source code even gets to a compiler. As a result, the name PI may not get entered into the symbol table. This can be confusing if you get an error during compilation involving the use of the constant, because the error message may refer to 3.1416, not PI. If PI were defined in a header file you didn’t write, you’d have no idea where that 3.1416 came from.

This problem can also crop up in a symbolic debugger, because, again, the name you’re programming with may not be in the symbol table.

Solution:

const double PI = 3.1416; //or static const...

Extension exists but uuid_generate_v4 fails

The extension is available but not installed in this database.

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

jQuery get the rendered height of an element?

Sometimes offsetHeight will return zero because the element you've created has not been rendered in the Dom yet. I wrote this function for such circumstances:

function getHeight(element)
{
    var e = element.cloneNode(true);
    e.style.visibility = "hidden";
    document.body.appendChild(e);
    var height = e.offsetHeight + 0;
    document.body.removeChild(e);
    e.style.visibility = "visible";
    return height;
}

Change the color of cells in one column when they don't match cells in another column

In my case I had to compare column E and I.

I used conditional formatting with new rule. Formula was "=IF($E1<>$I1,1,0)" for highlights in orange and "=IF($E1=$I1,1,0)" to highlight in green.

Next problem is how many columns you want to highlight. If you open Conditional Formatting Rules Manager you can edit for each rule domain of applicability: Check "Applies to"

In my case I used "=$E:$E,$I:$I" for both rules so I highlight only two columns for differences - column I and column E.

Assigning default value while creating migration file

Default migration generator does not handle default values (column modifiers are supported but do not include default or null), but you could create your own generator.

You can also manually update the migration file prior to running rake db:migrate by adding the options to add_column:

add_column :tweet, :retweets_count, :integer, :null => false, :default => 0

... and read Rails API

Looking for simple Java in-memory cache

Try Ehcache? It allows you to plug in your own caching expiry algorithms so you could control your peek functionality.

You can serialize to disk, database, across a cluster etc...

disable horizontal scroll on mobile web

For me, the viewport meta tag actually caused a horizontal scroll issue on the Blackberry.

I removed content="initial-scale=1.0; maximum-scale=1.0; from the viewport tag and it fixed the issue. Below is my current viewport tag:

<meta name="viewport" content="user-scalable=0;"/>

How do I set up access control in SVN?

Although I would suggest the Apache approach is better, SVN Serve works fine and is pretty straightforward.

Assuming your repository is called "my_repo", and it is stored in C:\svn_repos:

  1. Create a file called "passwd" in "C:\svn_repos\my_repo\conf". This file should look like:

    [Users]
    username = password
    john = johns_password
    steve = steves_password
    
  2. In C:\svn_repos\my_repo\conf\svnserve.conf set:

    [general]
    password-db = passwd
    auth-access=read
    auth-access=write
    

This will force users to log in to read or write to this repository.

Follow these steps for each repository, only including the appropriate users in the passwd file for each repository.

JAX-RS / Jersey how to customize error handling?

I was facing the same issue.

I wanted to catch all the errors at a central place and transform them.

Following is the code for how I handled it.

Create the following class which implements ExceptionMapper and add @Provider annotation on this class. This will handle all the exceptions.

Override toResponse method and return the Response object populated with customised data.

//ExceptionMapperProvider.java
/**
 * exception thrown by restful endpoints will be caught and transformed here
 * so that client gets a proper error message
 */
@Provider
public class ExceptionMapperProvider implements ExceptionMapper<Throwable> {
    private final ErrorTransformer errorTransformer = new ErrorTransformer();

    public ExceptionMapperProvider() {

    }

    @Override
    public Response toResponse(Throwable throwable) {
        //transforming the error using the custom logic of ErrorTransformer 
        final ServiceError errorResponse = errorTransformer.getErrorResponse(throwable);
        final ResponseBuilder responseBuilder = Response.status(errorResponse.getStatus());

        if (errorResponse.getBody().isPresent()) {
            responseBuilder.type(MediaType.APPLICATION_JSON_TYPE);
            responseBuilder.entity(errorResponse.getBody().get());
        }

        for (Map.Entry<String, String> header : errorResponse.getHeaders().entrySet()) {
            responseBuilder.header(header.getKey(), header.getValue());
        }

        return responseBuilder.build();
    }
}

// ErrorTransformer.java
/**
 * Error transformation logic
 */
public class ErrorTransformer {
    public ServiceError getErrorResponse(Throwable throwable) {
        ServiceError serviceError = new ServiceError();
        //add you logic here
        serviceError.setStatus(getStatus(throwable));
        serviceError.setBody(getBody(throwable));
        serviceError.setHeaders(getHeaders(throwable));

    }
    private String getStatus(Throwable throwable) {
        //your logic
    }
    private Optional<String> getBody(Throwable throwable) {
        //your logic
    }
    private Map<String, String> getHeaders(Throwable throwable) {
        //your logic
    }
}

//ServiceError.java
/**
 * error data holder
 */
public class ServiceError {
    private int status;
    private Map<String, String> headers;
    private Optional<String> body;
    //setters and getters
}

How to select an element by classname using jqLite?

angualr uses the lighter version of jquery called as jqlite which means it doesnt have all the features of jQuery. here is a reference in angularjs docs about what you can use from jquery. Angular Element docs

In your case you need to find a div with ID or class name. for class name you can use

var elems =$element.find('div') //returns all the div's in the $elements
    angular.forEach(elems,function(v,k)){
    if(angular.element(v).hasClass('class-name')){
     console.log(angular.element(v));
}}

or you can use much simpler way by query selector

angular.element(document.querySelector('#id'))

angular.element(elem.querySelector('.classname'))

it is not as flexible as jQuery but what

Can you delete multiple branches in one command with Git?

git branch -d branch1 branch2 branch3 already works, but will be faster with Git 2.31 (Q1 2021).
Before, when removing many branches and tags, the code used to do so one ref at a time.
There is another API it can use to delete multiple refs, and it makes quite a lot of performance difference when the refs are packed.

See commit 8198907 (20 Jan 2021) by Phil Hord (phord).
(Merged by Junio C Hamano -- gitster -- in commit f6ef8ba, 05 Feb 2021)

8198907795:use delete_refs when deleting tags or branches

Acked-by: Elijah Newren
Signed-off-by: Phil Hord

'git tag -d'(man) accepts one or more tag refs to delete, but each deletion is done by calling delete_ref on each argv.
This is very slow when removing from packed refs.
Use delete_refs instead so all the removals can be done inside a single transaction with a single update.

Do the same for 'git branch -d'(man).

Since delete_refs performs all the packed-refs delete operations inside a single transaction, if any of the deletes fail then all them will be skipped.
In practice, none of them should fail since we verify the hash of each one before calling delete_refs, but some network error or odd permissions problem could have different results after this change.

Also, since the file-backed deletions are not performed in the same transaction, those could succeed even when the packed-refs transaction fails.

After deleting branches, remove the branch config only if the branch ref was removed and was not subsequently added back in.

A manual test deleting 24,000 tags took about 30 minutes using delete_ref.
It takes about 5 seconds using delete_refs.

Xcode doesn't see my iOS device but iTunes does

I get this problem once, using a not official Apple cable.

Hope it helps.

Get textarea text with javascript or Jquery

To get the value from a textarea with an id you just have to do

Edited

$("#area1").val();

If you are having more than one element with the same id in the document then the HTML is invalid.

Wait for shell command to complete

Dim wsh as new wshshell

chdir "Directory of Batch File"

wsh.run "Full Path of Batch File",vbnormalfocus, true

Done Son

Android ListView with Checkbox and all clickable

holder.checkbox.setTag(row_id);

and

holder.checkbox.setOnClickListener( new OnClickListener() {

                @Override
                public void onClick(View v) {
                    CheckBox c = (CheckBox) v;

                    int row_id = (Integer) v.getTag();

                    checkboxes.put(row_id, c.isChecked());


                }
        });

How to append to the end of an empty list?

I personally prefer the + operator than append:

for i in range(0, n):

    list1 += [[i]]

But this is creating a new list every time, so might not be the best if performance is critical.

git replace local version with remote version

This is the safest solution:

git stash

Now you can do whatever you want without fear of conflicts.

For instance:

git checkout origin/master

If you want to include the remote changes in the master branch you can do:

git reset --hard origin/master

This will make you branch "master" to point to "origin/master".

jQuery post() with serialize and extra data

In new version of jquery, could done it via following steps:

  • get param array via serializeArray()
  • call push() or similar methods to add additional params to the array,
  • call $.param(arr) to get serialized string, which could be used as jquery ajax's data param.

Example code:

var paramArr = $("#loginForm").serializeArray();
paramArr.push( {name:'size', value:7} );
$.post("rest/account/login", $.param(paramArr), function(result) {
    // ...
}

Sorting table rows according to table header column using javascript or jquery

I've been working on a function to work within a library for a client, and have been having a lot of trouble keeping the UI responsive during the sorts (even with only a few hundred results).

The function has to resort the entire table each AJAX pagination, as new data may require injection further up. This is what I had so far:

  • jQuery library required.
  • table is the ID of the table being sorted.
  • The table attributes sort-attribute, sort-direction and the column attribute column are all pre-set.

Using some of the details above I managed to improve performance a bit.

function sorttable(table) {
    var context = $('#' + table), tbody = $('#' + table + ' tbody'), sortfield = $(context).data('sort-attribute'), c, dir = $(context).data('sort-direction'), index = $(context).find('thead th[data-column="' + sortfield + '"]').index();
    if (!sortfield) {
        sortfield = $(context).data('id-attribute');
    };
    switch (dir) {
        case "asc":
            tbody.find('tr').sort(function (a, b) {
                var sortvala = parseFloat($(a).find('td:eq(' + index + ')').text());
                var sortvalb = parseFloat($(b).find('td:eq(' + index + ')').text());
                // if a < b return 1
                return sortvala < sortvalb ? 1
                       // else if a > b return -1
                       : sortvala > sortvalb ? -1
                       // else they are equal - return 0    
                       : 0;
            }).appendTo(tbody);
            break;
        case "desc":
        default:
            tbody.find('tr').sort(function (a, b) {
                var sortvala = parseFloat($(a).find('td:eq(' + index + ')').text());
                var sortvalb = parseFloat($(b).find('td:eq(' + index + ')').text());
                // if a < b return 1
                return sortvala > sortvalb ? 1
                       // else if a > b return -1
                       : sortvala < sortvalb ? -1
                       // else they are equal - return 0    
                       : 0;
            }).appendTo(tbody);
        break;
  }

In principle the code works perfectly, but it's painfully slow... are there any ways to improve performance?

How to use Oracle ORDER BY and ROWNUM correctly?

An alternate I would suggest in this use case is to use the MAX(t_stamp) to get the latest row ... e.g.

select t.* from raceway_input_labo t
where t.t_stamp = (select max(t_stamp) from raceway_input_labo) 
limit 1

My coding pattern preference (perhaps) - reliable, generally performs at or better than trying to select the 1st row from a sorted list - also the intent is more explicitly readable.
Hope this helps ...

SQLer

Javascript - Track mouse position

Here is the simplest way to track your mouse position

Html

<body id="mouse-position" ></body>

js

document.querySelector('#mouse-position').addEventListener('mousemove', (e) => {
        console.log("mouse move X: ", e.clientX);
        console.log("mouse move X: ", e.screenX);


    }, );

know more

How can I change the color of a Google Maps marker?

enter image description here enter image description here Material Design

EDITED MARCH 2019 now with programmatic pin color,

PURE JAVASCRIPT, NO IMAGES, SUPPORTS LABELS

no longer relies on deprecated Charts API

    var pinColor = "#FFFFFF";
    var pinLabel = "A";

    // Pick your pin (hole or no hole)
    var pinSVGHole = "M12,11.5A2.5,2.5 0 0,1 9.5,9A2.5,2.5 0 0,1 12,6.5A2.5,2.5 0 0,1 14.5,9A2.5,2.5 0 0,1 12,11.5M12,2A7,7 0 0,0 5,9C5,14.25 12,22 12,22C12,22 19,14.25 19,9A7,7 0 0,0 12,2Z";
    var labelOriginHole = new google.maps.Point(12,15);
    var pinSVGFilled = "M 12,2 C 8.1340068,2 5,5.1340068 5,9 c 0,5.25 7,13 7,13 0,0 7,-7.75 7,-13 0,-3.8659932 -3.134007,-7 -7,-7 z";
    var labelOriginFilled =  new google.maps.Point(12,9);


    var markerImage = {  // https://developers.google.com/maps/documentation/javascript/reference/marker#MarkerLabel
        path: pinSVGFilled,
        anchor: new google.maps.Point(12,17),
        fillOpacity: 1,
        fillColor: pinColor,
        strokeWeight: 2,
        strokeColor: "white",
        scale: 2,
        labelOrigin: labelOriginFilled
    };
    var label = {
        text: pinLabel,
        color: "white",
        fontSize: "12px",
    }; // https://developers.google.com/maps/documentation/javascript/reference/marker#Symbol
    this.marker        = new google.maps.Marker({
        map: map.MapObject,
        //OPTIONAL: label: label,
        position: this.geographicCoordinates,
        icon: markerImage,
        //OPTIONAL: animation: google.maps.Animation.DROP,
    });

check if directory exists and delete in one command unix

Assuming $WORKING_DIR is set to the directory... this one-liner should do it:

if [ -d "$WORKING_DIR" ]; then rm -Rf $WORKING_DIR; fi

(otherwise just replace with your directory)

How do I resolve a path relative to an ASP.NET MVC 4 application root?

I find this code useful when I need a path outside of a controller, such as when I'm initializing components in Global.asax.cs:

HostingEnvironment.MapPath("~/Data/data.html")

Mockito. Verify method arguments

Have you checked the equals method for the mockable class? If this one returns always true or you test the same instance against the same instance and the equal method is not overwritten (and therefor only checks against the references), then it returns true.

Automate scp file transfer using a shell script

here's bash code for SCP with a .pem key file. Just save it to a script.sh file then run with 'sh script.sh'

Enjoy

#!/bin/bash
#Error function
function die(){
echo "$1"
exit 1
}

Host=ec2-53-298-45-63.us-west-1.compute.amazonaws.com
User=ubuntu
#Directory at sent destination
SendDirectory=scp
#File to send at host
FileName=filetosend.txt
#Key file
Key=MyKeyFile.pem

echo "Aperture in Process...";

#The code that will send your file scp
scp -i $Key $FileName $User@$Host:$SendDirectory || \
die "@@@@@@@Houston we have problem"

echo "########Aperture Complete#########";

Add comma to numbers every three digits

You could use Number.toLocaleString():

_x000D_
_x000D_
var number = 1557564534;_x000D_
document.body.innerHTML = number.toLocaleString();_x000D_
// 1,557,564,534
_x000D_
_x000D_
_x000D_

Undefined variable: $_SESSION

Turned out there was some extra code in the AppModel that was messing things up:

in beforeFind and afterFind:

App::Import("Session");
$session = new CakeSession();
$sim_id = $session->read("Simulation.id");

I don't know why, but that was what the problem was. Removing those lines fixed the issue I was having.

Extracting extension from filename in Python

This is a direct string representation techniques : I see a lot of solutions mentioned, but I think most are looking at split. Split however does it at every occurrence of "." . What you would rather be looking for is partition.

string = "folder/to_path/filename.ext"
extension = string.rpartition(".")[-1]

USB Debugging option greyed out

FYI My Motorola Xyboard had an "Off" icon at the top of developer options. Once I tapped that it worked.

How to add a constant column in a Spark DataFrame?

Spark 2.2+

Spark 2.2 introduces typedLit to support Seq, Map, and Tuples (SPARK-19254) and following calls should be supported (Scala):

import org.apache.spark.sql.functions.typedLit

df.withColumn("some_array", typedLit(Seq(1, 2, 3)))
df.withColumn("some_struct", typedLit(("foo", 1, 0.3)))
df.withColumn("some_map", typedLit(Map("key1" -> 1, "key2" -> 2)))

Spark 1.3+ (lit), 1.4+ (array, struct), 2.0+ (map):

The second argument for DataFrame.withColumn should be a Column so you have to use a literal:

from pyspark.sql.functions import lit

df.withColumn('new_column', lit(10))

If you need complex columns you can build these using blocks like array:

from pyspark.sql.functions import array, create_map, struct

df.withColumn("some_array", array(lit(1), lit(2), lit(3)))
df.withColumn("some_struct", struct(lit("foo"), lit(1), lit(.3)))
df.withColumn("some_map", create_map(lit("key1"), lit(1), lit("key2"), lit(2)))

Exactly the same methods can be used in Scala.

import org.apache.spark.sql.functions.{array, lit, map, struct}

df.withColumn("new_column", lit(10))
df.withColumn("map", map(lit("key1"), lit(1), lit("key2"), lit(2)))

To provide names for structs use either alias on each field:

df.withColumn(
    "some_struct",
    struct(lit("foo").alias("x"), lit(1).alias("y"), lit(0.3).alias("z"))
 )

or cast on the whole object

df.withColumn(
    "some_struct", 
    struct(lit("foo"), lit(1), lit(0.3)).cast("struct<x: string, y: integer, z: double>")
 )

It is also possible, although slower, to use an UDF.

Note:

The same constructs can be used to pass constant arguments to UDFs or SQL functions.

How to index an element of a list object in R

Indexing a list is done using double bracket, i.e. hypo_list[[1]] (e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table does not return a table but a dataframe (see value section in ?read.table). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.

Note: In R, the index for the first entry is a 1 (not 0 like in some other languages).

Dataframes

l <- list(anscombe, iris)   # put dfs in list
l[[1]]             # returns anscombe dataframe

anscombe[1:2, 2]   # access first two rows and second column of dataset
[1] 10  8

l[[1]][1:2, 2]     # the same but selecting the dataframe from the list first
[1] 10  8

Table objects

tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2)  # put tables in a list

tbl1[1:2]              # access first two elements of table 1 

Now with the list

l[[1]]                 # access first table from the list

1  2  3  4  5 
9 11 12  9  9 

l[[1]][1:2]            # access first two elements in first table

1  2 
9 11 

ValueError: cannot reshape array of size 30470400 into shape (50,1104,104)

In Matrix terms, the number of elements always has to equal the product of the number of rows and columns. In this particular case, the condition is not matching.

Directly assigning values to C Pointers

First Program with comments

#include <stdio.h>

int main(){
    int *ptr;             //Create a pointer that points to random memory address

    *ptr = 20;            //Dereference that pointer, 
                          // and assign a value to random memory address.
                          //Depending on external (not inside your program) state
                          // this will either crash or SILENTLY CORRUPT another 
                          // data structure in your program.  

    printf("%d", *ptr);   //Print contents of same random memory address
                          // May or may not crash, depending on who owns this address

    return 0;             
}

Second Program with comments

#include <stdio.h>

int main(){
    int *ptr;              //Create pointer to random memory address

    int q = 50;            //Create local variable with contents int 50

    ptr = &q;              //Update address targeted by above created pointer to point
                           // to local variable your program properly created

    printf("%d", *ptr);    //Happily print the contents of said local variable (q)
    return 0;
}

The key is you cannot use a pointer until you know it is assigned to an address that you yourself have managed, either by pointing it at another variable you created or to the result of a malloc call.

Using it before is creating code that depends on uninitialized memory which will at best crash but at worst work sometimes, because the random memory address happens to be inside the memory space your program already owns. God help you if it overwrites a data structure you are using elsewhere in your program.

Setting the number of map tasks and reduce tasks

It's important to keep in mind that the MapReduce framework in Hadoop allows us only to

suggest the number of Map tasks for a job

which like Praveen pointed out above will correspond to the number of input splits for the task. Unlike it's behavior for the number of reducers (which is directly related to the number of files output by the MapReduce job) where we can

demand that it provide n reducers.

EOFError: EOF when reading a line

width, height = map(int, input().split())
def rectanglePerimeter(width, height):
   return ((width + height)*2)
print(rectanglePerimeter(width, height))

Running it like this produces:

% echo "1 2" | test.py
6

I suspect IDLE is simply passing a single string to your script. The first input() is slurping the entire string. Notice what happens if you put some print statements in after the calls to input():

width = input()
print(width)
height = input()
print(height)

Running echo "1 2" | test.py produces

1 2
Traceback (most recent call last):
  File "/home/unutbu/pybin/test.py", line 5, in <module>
    height = input()
EOFError: EOF when reading a line

Notice the first print statement prints the entire string '1 2'. The second call to input() raises the EOFError (end-of-file error).

So a simple pipe such as the one I used only allows you to pass one string. Thus you can only call input() once. You must then process this string, split it on whitespace, and convert the string fragments to ints yourself. That is what

width, height = map(int, input().split())

does.

Note, there are other ways to pass input to your program. If you had run test.py in a terminal, then you could have typed 1 and 2 separately with no problem. Or, you could have written a program with pexpect to simulate a terminal, passing 1 and 2 programmatically. Or, you could use argparse to pass arguments on the command line, allowing you to call your program with

test.py 1 2

Retrieve a single file from a repository

To export a single file from a remote:

git archive --remote=ssh://host/pathto/repo.git HEAD README.md | tar -x

This will download the file README.md to your current directory.

If you want the contents of the file exported to STDOUT:

git archive --remote=ssh://host/pathto/repo.git HEAD README.md | tar -xO

You can provide multiple paths at the end of the command.

Removing whitespace from strings in Java

You've already got the correct answer from Gursel Koca but I believe that there's a good chance that this is not what you really want to do. How about parsing the key-values instead?

import java.util.Enumeration;
import java.util.Hashtable;

class SplitIt {
  public static void main(String args[])  {

    String person = "name=john age=13 year=2001";

    for (String p : person.split("\\s")) {
      String[] keyValue = p.split("=");
      System.out.println(keyValue[0] + " = " + keyValue[1]);
    }
  }
}

output:
name = john
age = 13
year = 2001

How to vertically align text inside a flexbox?

Instead of using align-self: center use align-items: center.

There's no need to change flex-direction or use text-align.

Here's your code, with one adjustment, to make it all work:

ul {
  height: 100%;
}

li {
  display: flex;
  justify-content: center;
  /* align-self: center;    <---- REMOVE */
  align-items: center;   /* <---- NEW    */
  background: silver;
  width: 100%;
  height: 20%; 
}

The align-self property applies to flex items. Except your li is not a flex item because its parent – the ul – does not have display: flex or display: inline-flex applied.

Therefore, the ul is not a flex container, the li is not a flex item, and align-self has no effect.

The align-items property is similar to align-self, except it applies to flex containers.

Since the li is a flex container, align-items can be used to vertically center the child elements.

_x000D_
_x000D_
* {_x000D_
  padding: 0;_x000D_
  margin: 0;_x000D_
}_x000D_
html, body {_x000D_
  height: 100%;_x000D_
}_x000D_
ul {_x000D_
  height: 100%;_x000D_
}_x000D_
li {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
  /* align-self: center; */_x000D_
  align-items: center;_x000D_
  background: silver;_x000D_
  width: 100%;_x000D_
  height: 20%;_x000D_
}
_x000D_
<ul>_x000D_
  <li>This is the text</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

codepen demo


Technically, here's how align-items and align-self work...

The align-items property (on the container) sets the default value of align-self (on the items). Therefore, align-items: center means all flex items will be set to align-self: center.

But you can override this default by adjusting the align-self on individual items.

For example, you may want equal height columns, so the container is set to align-items: stretch. However, one item must be pinned to the top, so it is set to align-self: flex-start.

example


How is the text a flex item?

Some people may be wondering how a run of text...

<li>This is the text</li>

is a child element of the li.

The reason is that text that is not explicitly wrapped by an inline-level element is algorithmically wrapped by an inline box. This makes it an anonymous inline element and child of the parent.

From the CSS spec:

9.2.2.1 Anonymous inline boxes

Any text that is directly contained inside a block container element must be treated as an anonymous inline element.

The flexbox specification provides for similar behavior.

4. Flex Items

Each in-flow child of a flex container becomes a flex item, and each contiguous run of text that is directly contained inside a flex container is wrapped in an anonymous flex item.

Hence, the text in the li is a flex item.

Java - Check if JTextField is empty or not

What you need is something called Document Listener. See How to Write a Document Listener.

Quickest way to convert XML to JSON in Java

I have uploaded the project you can directly open in eclipse and run that's all https://github.com/pareshmutha/XMLToJsonConverterUsingJAVA

Thank You

Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in

The reason is that php cannot find the correct path of mysql.sock.

Please make sure that your mysql is running first.

Then, please confirm that which path is the mysql.sock located, for example /tmp/mysql.sock

then add this path string to php.ini:

  • mysql.default_socket = /tmp/mysql.sock
  • mysqli.default_socket = /tmp/mysql.sock
  • pdo_mysql.default_socket = /tmp/mysql.sock

Finally, restart Apache.

How to create friendly URL in php?

I recently used the following in an application that is working well for my needs.

.htaccess

<IfModule mod_rewrite.c>
# enable rewrite engine
RewriteEngine On

# if requested url does not exist pass it as path info to index.php
RewriteRule ^$ index.php?/ [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php?/$1 [QSA,L]
</IfModule>

index.php

foreach (explode ("/", $_SERVER['REQUEST_URI']) as $part)
{
    // Figure out what you want to do with the URL parts.
}

How do I localize the jQuery UI Datepicker?

  $.datepicker.setDefaults({
    closeText: "??",
    prevText: "&#x3C;??",
    nextText: "??&#x3E;",
    currentText: "??",
    monthNames: [ "??","??","??","??","??","??",
    "??","??","??","??","???","???" ],
    monthNamesShort: [ "??","??","??","??","??","??",
    "??","??","??","??","???","???" ],
    dayNames: [ "???","???","???","???","???","???","???" ],
    dayNamesShort: [ "??","??","??","??","??","??","??" ],
    dayNamesMin: [ "?","?","?","?","?","?","?" ],
    weekHeader: "?",
    dateFormat: "yy-mm-dd",
    firstDay: 1,
    isRTL: false,
    showMonthAfterYear: true,
    yearSuffix: "?"
  });

the i18n code could be copied from https://github.com/jquery/jquery-ui/tree/master/ui/i18n

Markdown `native` text alignment

In order to center text in md files you can use the center tag like html tag:

<center>Centered text</center>

Bootstrap: how do I change the width of the container?

For bootstrap 4 if you are using Sass here is the variable to edit

// Grid containers
//
// Define the maximum width of `.container` for different screen sizes.

$container-max-widths: (
  sm: 540px,
  md: 720px,
  lg: 960px,
  xl: 1140px
) !default;

To override this variable I declared $container-max-widths without the !default in my .sass file before importing bootstrap.

Note : I only needed to change the xl value so I didn't care to think about breakpoints.

Exec : display stdout "live"

child_process.spawn returns an object with stdout and stderr streams. You can tap on the stdout stream to read data that the child process sends back to Node. stdout being a stream has the "data", "end", and other events that streams have. spawn is best used to when you want the child process to return a large amount of data to Node - image processing, reading binary data etc.

so you can solve your problem using child_process.spawn as used below.

var spawn = require('child_process').spawn,
ls = spawn('coffee -cw my_file.coffee');

ls.stdout.on('data', function (data) {
  console.log('stdout: ' + data.toString());
});

ls.stderr.on('data', function (data) {
  console.log('stderr: ' + data.toString());
});

ls.on('exit', function (code) {
  console.log('code ' + code.toString());
});

Scale an equation to fit exact page width

The graphicx package provides the command \resizebox{width}{height}{object}:

\documentclass{article}
\usepackage{graphicx}
\begin{document}
\hrule
%%%
\makeatletter%
\setlength{\@tempdima}{\the\columnwidth}% the, well columnwidth
\settowidth{\@tempdimb}{(\ref{Equ:TooLong})}% the width of the "(1)"
\addtolength{\@tempdima}{-\the\@tempdimb}% which cannot be used for the math
\addtolength{\@tempdima}{-1em}%
% There is probably some variable giving the required minimal distance
% between math and label, but because I do not know it I used 1em instead.
\addtolength{\@tempdima}{-1pt}% distance must be greater than "1em"
\xdef\Equ@width{\the\@tempdima}% space remaining for math
\begin{equation}%
\resizebox{\Equ@width}{!}{$\displaystyle{% to get everything inside "big"
 A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z}$}%
\label{Equ:TooLong}%
\end{equation}%
\makeatother%
%%%
\hrule
\end{document}

Java String to SHA1

UPDATE
You can use Apache Commons Codec (version 1.7+) to do this job for you.

DigestUtils.sha1Hex(stringToConvertToSHexRepresentation)

Thanks to @Jon Onstott for this suggestion.


Old Answer
Convert your Byte Array to Hex String. Real's How To tells you how.

return byteArrayToHexString(md.digest(convertme))

and (copied from Real's How To)

public static String byteArrayToHexString(byte[] b) {
  String result = "";
  for (int i=0; i < b.length; i++) {
    result +=
          Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
  }
  return result;
}

BTW, you may get more compact representation using Base64. Apache Commons Codec API 1.4, has this nice utility to take away all the pain. refer here

How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite?

brew install rbenv ruby-build

Add rbenv to bash so that it loads every time you open a terminal

echo 'if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi' >> ~/.bash_profile

source ~/.bash_profile

Install Ruby

rbenv install 2.6.5

rbenv global 2.6.5

ruby -v

Link to the source page

How to view log output using docker-compose run?

Unfortunately we need to run docker-compose logs separately from docker-compose run. In order to get this to work reliably we need to suppress the docker-compose run exit status then redirect the log and exit with the right status.

#!/bin/bash
set -euo pipefail
docker-compose run app | tee app.log || failed=yes
docker-compose logs --no-color > docker-compose.log
[[ -z "${failed:-}" ]] || exit 1

When to use pthread_exit() and when to use pthread_join() in Linux?

Both methods ensure that your process doesn't end before all of your threads have ended.

The join method has your thread of the main function explicitly wait for all threads that are to be "joined".

The pthread_exit method terminates your main function and thread in a controlled way. main has the particularity that ending main otherwise would be terminating your whole process including all other threads.

For this to work, you have to be sure that none of your threads is using local variables that are declared inside them main function. The advantage of that method is that your main doesn't have to know all threads that have been started in your process, e.g because other threads have themselves created new threads that main doesn't know anything about.

AngularJS: how to enable $locationProvider.html5Mode with deeplinking

This problem was due to the use of AngularJS 1.1.5 (which was unstable, and obviously had some bug or different implementation of the routing than it was in 1.0.7)

turning it back to 1.0.7 solved the problem instantly.

have tried the 1.2.0rc1 version, but have not finished testing as I had to rewrite some of the router functionality since they took it out of the core.

anyway, this problem is fixed when using AngularJS vs 1.0.7.

Hex transparency in colors

I realize this is an old question, but I came across it when doing something similar.

Using SASS, you have a very elegant way to convert RGBA to hex ARGB: ie-hex-str. I've used it here in a mixin.

@mixin ie8-rgba ($r, $g, $b, $a){
    $rgba: rgba($r, $g, $b, $a);
    $ie8-rgba: ie-hex-str($rgba);
    .lt-ie9 &{
      background-color: transparent;
      filter:progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#{$ie8-rgba}', endColorstr='#{$ie8-rgba}');
  }
}

.transparent{
    @include ie8-rgba(88,153,131,.8);
    background-color: rgba(88,153,131,.8);
}

outputs:

_x000D_
_x000D_
.transparent {_x000D_
  background-color: rgba(88, 153, 131, 0.8);_x000D_
}_x000D_
.lt-ie9 .transparent {_x000D_
  background-color: transparent;_x000D_
  filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#CC589983', endColorstr='#CC589983');_x000D_
  zoom: 1;_x000D_
}
_x000D_
_x000D_
_x000D_

Detect URLs in text with JavaScript

If you want to detect links with http:// OR without http:// OR ftp OR other possible cases like removing trailing punctuation at the end, take a look at this code.

https://jsfiddle.net/AndrewKang/xtfjn8g3/

A simple way to use that is to use NPM

npm install --save url-knife

How to change Rails 3 server default port in develoment?

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

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

then call rake start instead of rails server

How to check if pytorch is using the GPU?

If you are here because your pytorch always gives False for torch.cuda.is_available() that's probably because you installed your pytorch version without GPU support. (Eg: you coded up in laptop then testing on server).

The solution is to uninstall and install pytorch again with the right command from pytorch downloads page. Also refer this pytorch issue.

Difference between malloc and calloc?

malloc() and calloc() are functions from the C standard library that allow dynamic memory allocation, meaning that they both allow memory allocation during runtime.

Their prototypes are as follows:

void *malloc( size_t n);
void *calloc( size_t n, size_t t)

There are mainly two differences between the two:

  • Behavior: malloc() allocates a memory block, without initializing it, and reading the contents from this block will result in garbage values. calloc(), on the other hand, allocates a memory block and initializes it to zeros, and obviously reading the content of this block will result in zeros.

  • Syntax: malloc() takes 1 argument (the size to be allocated), and calloc() takes two arguments (number of blocks to be allocated and size of each block).

The return value from both is a pointer to the allocated block of memory, if successful. Otherwise, NULL will be returned indicating the memory allocation failure.

Example:

int *arr;

// allocate memory for 10 integers with garbage values
arr = (int *)malloc(10 * sizeof(int)); 

// allocate memory for 10 integers and sets all of them to 0
arr = (int *)calloc(10, sizeof(int));

The same functionality as calloc() can be achieved using malloc() and memset():

// allocate memory for 10 integers with garbage values   
arr= (int *)malloc(10 * sizeof(int));
// set all of them to 0
memset(arr, 0, 10 * sizeof(int)); 

Note that malloc() is preferably used over calloc() since it's faster. If zero-initializing the values is wanted, use calloc() instead.

Converting a Java Keystore into PEM Format

Converting a Java Keystore into PEM Format

The most precise answer of all must be that this is NOT possible.

A Java keystore is merely a storage facility for cryptographic keys and certificates while PEM is a file format for X.509 certificates only.

Save the console.log in Chrome to a file

There is an open-source javascript plugin that does just that, but for any browser - debugout.js

Debugout.js records and save console.logs so your application can access them. Full disclosure, I wrote it. It formats different types appropriately, can handle nested objects and arrays, and can optionally put a timestamp next to each log. You can also toggle live-logging in one place, and without having to remove all your logging statements.

How to for each the hashmap?

Use entrySet,

/**
 *Output: 
D: 99.22
A: 3434.34
C: 1378.0
B: 123.22
E: -19.08

B's new balance: 1123.22
 */

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class MainClass {
  public static void main(String args[]) {

    HashMap<String, Double> hm = new HashMap<String, Double>();

    hm.put("A", new Double(3434.34));
    hm.put("B", new Double(123.22));
    hm.put("C", new Double(1378.00));
    hm.put("D", new Double(99.22));
    hm.put("E", new Double(-19.08));

    Set<Map.Entry<String, Double>> set = hm.entrySet();

    for (Map.Entry<String, Double> me : set) {
      System.out.print(me.getKey() + ": ");
      System.out.println(me.getValue());
    }

    System.out.println();

    double balance = hm.get("B");
    hm.put("B", balance + 1000);

    System.out.println("B's new balance: " + hm.get("B"));
  }
}

see complete example here:

What is the difference between user and kernel modes in operating systems?

I'm going to take a stab in the dark and guess you're talking about Windows. In a nutshell, kernel mode has full access to hardware, but user mode doesn't. For instance, many if not most device drivers are written in kernel mode because they need to control finer details of their hardware.

See also this wikibook.

Is there a reason for C#'s reuse of the variable in a foreach?

The compiler declares the variable in a way that makes it highly prone to an error that is often difficult to find and debug, while producing no perceivable benefits.

Your criticism is entirely justified.

I discuss this problem in detail here:

Closing over the loop variable considered harmful

Is there something you can do with foreach loops this way that you couldn't if they were compiled with an inner-scoped variable? or is this just an arbitrary choice that was made before anonymous methods and lambda expressions were available or common, and which hasn't been revised since then?

The latter. The C# 1.0 specification actually did not say whether the loop variable was inside or outside the loop body, as it made no observable difference. When closure semantics were introduced in C# 2.0, the choice was made to put the loop variable outside the loop, consistent with the "for" loop.

I think it is fair to say that all regret that decision. This is one of the worst "gotchas" in C#, and we are going to take the breaking change to fix it. In C# 5 the foreach loop variable will be logically inside the body of the loop, and therefore closures will get a fresh copy every time.

The for loop will not be changed, and the change will not be "back ported" to previous versions of C#. You should therefore continue to be careful when using this idiom.

Is there a way to list open transactions on SQL Server 2000 database?

For all databases query sys.sysprocesses

SELECT * FROM sys.sysprocesses WHERE open_tran = 1

For the current database use:

DBCC OPENTRAN

"Insufficient Storage Available" even there is lot of free space in device memory

The same problem was coming for my phone and this resolved the problem:

  • Go to Application Manager/ Apps from Settings.

  • Select Google Play Services.

Enter image description here

  • Click Uninstall Updates button to the right of the Force Stop button.

  • Once the updates are uninstalled, you should see Disable button which means you are done.

Enter image description here

You will see lots of free space available now.

Java 8 lambdas, Function.identity() or t->t

As of the current JRE implementation, Function.identity() will always return the same instance while each occurrence of identifier -> identifier will not only create its own instance but even have a distinct implementation class. For more details, see here.

The reason is that the compiler generates a synthetic method holding the trivial body of that lambda expression (in the case of x->x, equivalent to return identifier;) and tell the runtime to create an implementation of the functional interface calling this method. So the runtime sees only different target methods and the current implementation does not analyze the methods to find out whether certain methods are equivalent.

So using Function.identity() instead of x -> x might save some memory but that shouldn’t drive your decision if you really think that x -> x is more readable than Function.identity().

You may also consider that when compiling with debug information enabled, the synthetic method will have a line debug attribute pointing to the source code line(s) holding the lambda expression, therefore you have a chance of finding the source of a particular Function instance while debugging. In contrast, when encountering the instance returned by Function.identity() during debugging an operation, you won’t know who has called that method and passed the instance to the operation.

How to insert TIMESTAMP into my MySQL table?

If you have a specific integer timestamp to insert/update, you can use PHP date() function with your timestamp as second arg :

date("Y-m-d H:i:s", $myTimestamp)

How to unit test abstract classes: extend with stubs?

To make an unit test specifically on the abstract class, you should derive it for testing purpose, test base.method() results and intended behaviour when inheriting.

You test a method by calling it so test an abstract class by implementing it...

What is a Windows Handle?

A handle is like a primary key value of a record in a database.

edit 1: well, why the downvote, a primary key uniquely identifies a database record, and a handle in the Windows system uniquely identifies a window, an opened file, etc, That's what I'm saying.

How to send a JSON object using html form data

Get complete form data as array and json stringify it.

var formData = JSON.stringify($("#myForm").serializeArray());

You can use it later in ajax. Or if you are not using ajax; put it in hidden textarea and pass to server. If this data is passed as json string via normal form data then you have to decode it using json_decode. You'll then get all data in an array.

$.ajax({
  type: "POST",
  url: "serverUrl",
  data: formData,
  success: function(){},
  dataType: "json",
  contentType : "application/json"
});

Fatal error: Call to undefined function imap_open() in PHP

if you are on linux, edit the /etc/php/php.ini (or you will have to create a new extension import file at /etc/php5/cli/conf.d) file so that you add the imap shared object file and then, restart the apache server. Uncomment

;extension=imap.so

so that it becomes like this:

extension=imap.so

Then, restart the apache by

# /etc/rc.d/httpd restart

How to check if array element is null to avoid NullPointerException in Java

You have more going on than you said. I ran the following expanded test from your example:

public class test {

    public static void main(String[] args) {
        Object[][] someArray = new Object[5][];
        someArray[0] = new Object[10];
        someArray[1] = null;
        someArray[2] = new Object[1];
        someArray[3] = null;
        someArray[4] = new Object[5];

        for (int i=0; i<=someArray.length-1; i++) {
            if (someArray[i] != null) {
                System.out.println("not null");
            } else {
                System.out.println("null");
            }
        }
    }
}

and got the expected output:

$ /cygdrive/c/Program\ Files/Java/jdk1.6.0_03/bin/java -cp . test
not null
null
not null
null
not null

Are you possibly trying to check the lengths of someArray[index]?

How to resolve Error listenerStart when deploying web-app in Tomcat 5.5?

Answered provided by Tom Saleeba is very helpful. Today I also struggled with the same error

Apr 28, 2015 7:53:27 PM org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

I followed the suggestion and added the logging.properties file. And below was my reason of failure:

java.lang.IllegalStateException: Cannot set web app root system property when WAR file is not expanded

The root cause of the issue was a listener (Log4jConfigListener) that I added into the web.xml. And as per the link SEVERE: Exception org.springframework.web.util.Log4jConfigListener , this listener cannot be added within a WAR that is not expanded.

It may be helpful for someone to know that this was happening on OpenShift JBoss gear.

Execute command without keeping it in history

There are several ways you can achieve this. This sets the size of the history file to 0:

export HISTFILESIZE=0

This sets the history file to /dev/null, effectively disabling it:

export HISTFILE=/dev/null

For individual commands, you can prefix the command with a space and it won't be saved in the history file. Note that this requires you have the ignorespace value included in the $HISTCONTROL environment variable (man bash and search for ignorespace for more details).

Is it possible to get the index you're sorting over in Underscore.js?

I think it's worth mentioning how the Underscore's _.each() works internally. The _.each(list, iteratee) checks if the passed list is an array object, or an object.

In the case that the list is an array, iteratee arguments will be a list element and index as in the following example:

var a = ['I', 'like', 'pancakes', 'a', 'lot', '.'];
_.each( a, function(v, k) { console.log( k + " " + v); });

0 I
1 like
2 pancakes
3 a
4 lot
5 .

On the other hand, if the list argument is an object the iteratee will take a list element and a key:

var o = {name: 'mike', lastname: 'doe', age: 21};
_.each( o, function(v, k) { console.log( k + " " + v); });

name mike
lastname doe
age 21

For reference this is the _.each() code from Underscore.js 1.8.3

_.each = _.forEach = function(obj, iteratee, context) {
   iteratee = optimizeCb(iteratee, context);
   var i, length;
   if (isArrayLike(obj)) {
      for (i = 0, length = obj.length; i < length; i++) {
         iteratee(obj[i], i, obj);
      }
   } else {
      var keys = _.keys(obj);
      for (i = 0, length = keys.length; i < length; i++) {
         iteratee(obj[keys[i]], keys[i], obj);
      }
   }
   return obj;
};

How can I fix "Design editor is unavailable until a successful build" error?

Simply restart the Android Studio. In my case, I was offline before starting the Android Studio, but online when I did restart.

How does OkHttp get Json string?

Below code is for getting data from online server using GET method and okHTTP library for android kotlin...

Log.e("Main",response.body!!.string())

in above line !! is the thing using which you can get the json from response body

val client = OkHttpClient()
            val request: Request = Request.Builder()
                .get()
                .url("http://172.16.10.126:8789/test/path/jsonpage")
                .addHeader("", "")
                .addHeader("", "")
                .build()
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    // Handle this
                    Log.e("Main","Try again latter!!!")
                }

                override fun onResponse(call: Call, response: Response) {
                    // Handle this
                    Log.e("Main",response.body!!.string())
                }
            })

Laravel - Form Input - Multiple select for a one to many relationship

I agree with user3158900, and I only differ slightly in the way I use it:

{{Form::label('sports', 'Sports')}}
{{Form::select('sports',$aSports,null,array('multiple'=>'multiple','name'=>'sports[]'))}}

However, in my experience the 3rd parameter of the select is a string only, so for repopulating data for a multi-select I have had to do something like this:

<select multiple="multiple" name="sports[]" id="sports">
@foreach($aSports as $aKey => $aSport)
    @foreach($aItem->sports as $aItemKey => $aItemSport)
        <option value="{{$aKey}}" @if($aKey == $aItemKey)selected="selected"@endif>{{$aSport}}</option>
    @endforeach
@endforeach
</select>

How do I retrieve query parameters in Spring Boot?

Use @RequestParam

@RequestMapping(value="user", method = RequestMethod.GET)
public @ResponseBody Item getItem(@RequestParam("data") String itemid){

    Item i = itemDao.findOne(itemid);              
    String itemName = i.getItemName();
    String price = i.getPrice();
    return i;
}

Cross-platform way of getting temp directory in Python

I use:

from pathlib import Path
import platform
import tempfile

tempdir = Path("/tmp" if platform.system() == "Darwin" else tempfile.gettempdir())

This is because on MacOS, i.e. Darwin, tempfile.gettempdir() and os.getenv('TMPDIR') return a value such as '/var/folders/nj/269977hs0_96bttwj2gs_jhhp48z54/T'; it is one that I do not always want.

MongoError: connect ECONNREFUSED 127.0.0.1:27017

For Windows users.

This happens because the MondgDB server is stopped. to fix this you can,

  1. 1 search for Services ,for that search using the left bottom corner search option.

    2 then there is a gear icon named with 'Services'.

    3 after clicking that you will get a window with lot of services

    4 scroll down and you will find 'MongoDB server (MongoDB)'.

    5 so you will see that there is an option to start the service.

    6 start it.

  2. 1 then open your command prompt.

    2 type mongod

now you can connect to your server.

this steps also working fine if your sql server service down. (find sql server services)

Using an authorization header with Fetch in React Native

I had this identical problem, I was using django-rest-knox for authentication tokens. It turns out that nothing was wrong with my fetch method which looked like this:

...
    let headers = {"Content-Type": "application/json"};
    if (token) {
      headers["Authorization"] = `Token ${token}`;
    }
    return fetch("/api/instruments/", {headers,})
      .then(res => {
...

I was running apache.

What solved this problem for me was changing WSGIPassAuthorization to 'On' in wsgi.conf.

I had a Django app deployed on AWS EC2, and I used Elastic Beanstalk to manage my application, so in the django.config, I did this:

container_commands:
  01wsgipass:
    command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf'

Enable tcp\ip remote connections to sql server express already installed database with code or script(query)

I recommend to use SMO (Enable TCP/IP Network Protocol for SQL Server). However, it was not available in my case.

I rewrote the WMI commands from Krzysztof Kozielczyk to PowerShell.

# Enable TCP/IP

Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocol -Filter "InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'" |
Invoke-CimMethod -Name SetEnable

# Open the right ports in the firewall
New-NetFirewallRule -DisplayName 'MSSQL$SQLEXPRESS' -Direction Inbound -Action Allow -Protocol TCP -LocalPort 1433

# Modify TCP/IP properties to enable an IP address

$properties = Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocolProperty -Filter "InstanceName='SQLEXPRESS' and ProtocolName = 'Tcp' and IPAddressName='IPAll'"
$properties | ? { $_.PropertyName -eq 'TcpPort' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '1433' }
$properties | ? { $_.PropertyName -eq 'TcpPortDynamic' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '' }

# Restart SQL Server

Restart-Service 'MSSQL$SQLEXPRESS'

Removing character in list of strings

Beside using loop and for comprehension, you could also use map

lst = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")]
mylst = map(lambda each:each.strip("8"), lst)
print mylst

Difference between @Before, @BeforeClass, @BeforeEach and @BeforeAll

The code marked @Before is executed before each test, while @BeforeClass runs once before the entire test fixture. If your test class has ten tests, @Before code will be executed ten times, but @BeforeClass will be executed only once.

In general, you use @BeforeClass when multiple tests need to share the same computationally expensive setup code. Establishing a database connection falls into this category. You can move code from @BeforeClass into @Before, but your test run may take longer. Note that the code marked @BeforeClass is run as static initializer, therefore it will run before the class instance of your test fixture is created.

In JUnit 5, the tags @BeforeEach and @BeforeAll are the equivalents of @Before and @BeforeClass in JUnit 4. Their names are a bit more indicative of when they run, loosely interpreted: 'before each tests' and 'once before all tests'.

remove / reset inherited css from an element

Try this: Create a plain div without any style or content outside of the red div. Now you can use a loop over all styles of the plain div and assign then to your inner div to reset all styles.

Of course this doesn't work if someone assigns styles to all divs (i.e. without using a class. CSS would be div { ... }).

The usual solution for problems like this is to give your div a distinct class. That way, web designers of the sites can adjust the styling of your div to fit into the rest of the design.

How To Set A JS object property name from a variable

Use a variable as an object key

let key = 'myKey';

let data = {[key] : 'name1'; }

See How to iterete on your object here

How to generate a random number between 0 and 1?

In your version rand() % 10000 will yield an integer between 0 and 9999. Since RAND_MAX may be as little as 32767, and since this is not exactly divisible by 10000 and not large relative to 10000, there will be significant bias in the 'randomness' of the result, moreover, the maximum value will be 0.9999, not 1.0, and you have unnecessarily restricted your values to four decimal places.

It is simple arithmetic, a random number divided by the maximum possible random number will yield a number from 0 to 1 inclusive, while utilising the full resolution and distribution of the RNG

double r2()
{
    return (double)rand() / (double)RAND_MAX ;
}

Use (double)rand() / (double)((unsigned)RAND_MAX + 1) if exclusion of 1.0 was intentional.

PHP ternary operator vs null coalescing operator

The major difference is that

  1. Ternary Operator expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE but on the other hand Null Coalescing Operator expression (expr1) ?? (expr2) evaluates to expr1 if expr1 is not NULL

  2. Ternary Operator expr1 ?: expr3 emit a notice if the left-hand side value (expr1) does not exist but on the other hand Null Coalescing Operator (expr1) ?? (expr2) In particular, does not emit a notice if the left-hand side value (expr1) does not exist, just like isset().

  3. TernaryOperator is left associative

    ((true ? 'true' : false) ? 't' : 'f');
    

    Null Coalescing Operator is right associative

    ($a ?? ($b ?? $c));
    

Now lets explain the difference between by example :

Ternary Operator (?:)

$x='';
$value=($x)?:'default';
var_dump($value);

// The above is identical to this if/else statement
if($x){
  $value=$x;
}
else{
  $value='default';
}
var_dump($value);

Null Coalescing Operator (??)

$value=($x)??'default';
var_dump($value);

// The above is identical to this if/else statement
if(isset($x)){
  $value=$x;
}
else{
  $value='default';
}
var_dump($value);

Here is the table that explain the difference and similarity between '??' and ?:

enter image description here

Special Note : null coalescing operator and ternary operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. This is important to know if you want to return a variable by reference. The statement return $foo ?? $bar; and return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued.

How to add buttons at top of map fragment API v2 layout

extending de Almeida's answer I am editing code little bit here. since previous code was hiding gps location icon I did following way which worked better.

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"

>

<RadioGroup 
    android:id="@+id/radio_group_list_selector"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:orientation="horizontal" 
    android:background="#80000000"
    android:padding="4dp" >

    <RadioButton
        android:id="@+id/radioPopular"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:text="@string/Popular"
        android:gravity="center_horizontal|center_vertical"
        android:layout_weight="1"
        android:button="@null"
        android:background="@drawable/shape_radiobutton"
        android:textColor="@drawable/textcolor_radiobutton" />
    <View
        android:id="@+id/VerticalLine"
        android:layout_width="1dip"
        android:layout_height="match_parent"
        android:background="#aaa" />

    <RadioButton
        android:id="@+id/radioAZ"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center_horizontal|center_vertical"
        android:text="@string/AZ"
        android:layout_weight="1"
        android:button="@null"
        android:background="@drawable/shape_radiobutton2"
        android:textColor="@drawable/textcolor_radiobutton" />

    <View
        android:id="@+id/VerticalLine"
        android:layout_width="1dip"
        android:layout_height="match_parent"
        android:background="#aaa" />

    <RadioButton
        android:id="@+id/radioCategory"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center_horizontal|center_vertical"
        android:text="@string/Category"
        android:layout_weight="1"
        android:button="@null"
        android:background="@drawable/shape_radiobutton2"
        android:textColor="@drawable/textcolor_radiobutton" />
    <View
        android:id="@+id/VerticalLine"
        android:layout_width="1dip"
        android:layout_height="match_parent"
        android:background="#aaa" />

    <RadioButton
        android:id="@+id/radioNearBy"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center_horizontal|center_vertical"
        android:text="@string/NearBy"
        android:layout_weight="1"
        android:button="@null"
        android:background="@drawable/shape_radiobutton3"
        android:textColor="@drawable/textcolor_radiobutton" />
</RadioGroup>

<fragment
    xmlns:map="http://schemas.android.com/apk/res-auto"
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.google.android.gms.maps.SupportMapFragment"
    android:scrollbars="vertical" />

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

I just used the following:

import unicodedata
message = unicodedata.normalize("NFKD", message)

Check what documentation says about it:

unicodedata.normalize(form, unistr) Return the normal form form for the Unicode string unistr. Valid values for form are ‘NFC’, ‘NFKC’, ‘NFD’, and ‘NFKD’.

The Unicode standard defines various normalization forms of a Unicode string, based on the definition of canonical equivalence and compatibility equivalence. In Unicode, several characters can be expressed in various way. For example, the character U+00C7 (LATIN CAPITAL LETTER C WITH CEDILLA) can also be expressed as the sequence U+0043 (LATIN CAPITAL LETTER C) U+0327 (COMBINING CEDILLA).

For each character, there are two normal forms: normal form C and normal form D. Normal form D (NFD) is also known as canonical decomposition, and translates each character into its decomposed form. Normal form C (NFC) first applies a canonical decomposition, then composes pre-combined characters again.

In addition to these two forms, there are two additional normal forms based on compatibility equivalence. In Unicode, certain characters are supported which normally would be unified with other characters. For example, U+2160 (ROMAN NUMERAL ONE) is really the same thing as U+0049 (LATIN CAPITAL LETTER I). However, it is supported in Unicode for compatibility with existing character sets (e.g. gb2312).

The normal form KD (NFKD) will apply the compatibility decomposition, i.e. replace all compatibility characters with their equivalents. The normal form KC (NFKC) first applies the compatibility decomposition, followed by the canonical composition.

Even if two unicode strings are normalized and look the same to a human reader, if one has combining characters and the other doesn’t, they may not compare equal.

Solves it for me. Simple and easy.

Textarea to resize based on content length

Alciende's answer didn't quite work for me in Safari for whatever reason just now, but did after a minor modification:

function textAreaAdjust(o) {
    o.style.height = "1px";
    setTimeout(function() {
        o.style.height = (o.scrollHeight)+"px";
    }, 1);
}

Hope this helps someone

Is it possible in Java to catch two exceptions in the same catch block?

http://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html covers catching multiple exceptions in the same block.

 try {
     // your code
} catch (Exception1 | Exception2 ex) {
     // Handle 2 exceptions in Java 7
}

I'm making study cards, and this thread was helpful, just wanted to put in my two cents.

Proper way to assert type of variable in Python

The isinstance built-in is the preferred way if you really must, but even better is to remember Python's motto: "it's easier to ask forgiveness than permission"!-) (It was actually Grace Murray Hopper's favorite motto;-). I.e.:

def my_print(text, begin, end):
    "Print 'text' in UPPER between 'begin' and 'end' in lower"
    try:
      print begin.lower() + text.upper() + end.lower()
    except (AttributeError, TypeError):
      raise AssertionError('Input variables should be strings')

This, BTW, lets the function work just fine on Unicode strings -- without any extra effort!-)

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

Try below code,

$cookieFile = "cookies.txt";
if(!file_exists($cookieFile)) {
    $fh = fopen($cookieFile, "w");
    fwrite($fh, "");
    fclose($fh);
}


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiCall);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_VERBOSE, true);
if(!curl_exec($ch)){
    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}
else{
    $response = curl_exec($ch); 
}
curl_close($ch);
$result = json_decode($response, true);

echo '<pre>';
var_dump($result);
echo'</pre>';

I hope this will help you.

Best regards, Dasitha.

AngularJS dynamic routing

Ok solved it.

Added the solution to GitHub - http://gregorypratt.github.com/AngularDynamicRouting

In my app.js routing config:

$routeProvider.when('/pages/:name', {
    templateUrl: '/pages/home.html', 
    controller: CMSController 
});

Then in my CMS controller:

function CMSController($scope, $route, $routeParams) {

    $route.current.templateUrl = '/pages/' + $routeParams.name + ".html";

    $.get($route.current.templateUrl, function (data) {
        $scope.$apply(function () {
            $('#views').html($compile(data)($scope));
        });
    });
    ...
}
CMSController.$inject = ['$scope', '$route', '$routeParams'];

With #views being my <div id="views" ng-view></div>

So now it works with standard routing and dynamic routing.

To test it I copied about.html called it portfolio.html, changed some of it's contents and entered /#/pages/portfolio into my browser and hey presto portfolio.html was displayed....

Updated Added $apply and $compile to the html so that dynamic content can be injected.

How do I move a redis database from one server to another?

I also want to do the same thing: migrate a db from a standalone redis instance to a another redis instances(redis sentinel).

Because the data is not critical(session data), i will give https://github.com/yaauie/redis-copy a try.

How to list files in a directory in a C program?

One tiny addition to JB Jansen's answer - in the main readdir() loop I'd add this:

  if (dir->d_type == DT_REG)
  {
     printf("%s\n", dir->d_name);
  }

Just checking if it's really file, not (sym)link, directory, or whatever.

NOTE: more about struct dirent in libc documentation.

Googlemaps API Key for Localhost

Where it says "Accept requests from these HTTP referrers (websites) (Optional)" you don't need to have any referrer listed. So click the X beside localhost on this page but continue to use your key.

It should then work after a few minutes.

Changes made can sometimes take a few minutes to take effect so wait a few minutes before testing again.

XAMPP Start automatically on Windows 7 startup

In addition to MR Chandru"s answer above, do these steps after configuring XAMPP:

  • open the directory where XAMPP is installed. By default it's installed at C:\xampp
  • Create Shortcut to the file xampp-control.exe, the XAMPP Control Panel
  • Paste it in

C:\Users\User-Name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

or

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp

The XAMPP Control Panel should now auto-start whenever you reboot Windows.

How Big can a Python List Get?

As the Python documentation says:

sys.maxsize

The largest positive integer supported by the platform’s Py_ssize_t type, and thus the maximum size lists, strings, dicts, and many other containers can have.

In my computer (Linux x86_64):

>>> import sys
>>> print sys.maxsize
9223372036854775807

Sqlite: CURRENT_TIMESTAMP is in GMT, not the timezone of the machine

I think this might help.

SELECT datetime(strftime('%s','now'), 'unixepoch', 'localtime');

AngularJS - convert dates in controller

create a filter.js and you can make this as reusable

angular.module('yourmodule').filter('date', function($filter)
{
    return function(input)
    {
        if(input == null){ return ""; }
        var _date = $filter('date')(new Date(input), 'dd/MM/yyyy');
        return _date.toUpperCase();
    };
});

view

<span>{{ d.time | date }}</span>

or in controller

var filterdatetime = $filter('date')( yourdate );

Date filtering and formatting in Angular js.

Python safe method to get value of nested dictionary

You could use get twice:

example_dict.get('key1', {}).get('key2')

This will return None if either key1 or key2 does not exist.

Note that this could still raise an AttributeError if example_dict['key1'] exists but is not a dict (or a dict-like object with a get method). The try..except code you posted would raise a TypeError instead if example_dict['key1'] is unsubscriptable.

Another difference is that the try...except short-circuits immediately after the first missing key. The chain of get calls does not.


If you wish to preserve the syntax, example_dict['key1']['key2'] but do not want it to ever raise KeyErrors, then you could use the Hasher recipe:

class Hasher(dict):
    # https://stackoverflow.com/a/3405143/190597
    def __missing__(self, key):
        value = self[key] = type(self)()
        return value

example_dict = Hasher()
print(example_dict['key1'])
# {}
print(example_dict['key1']['key2'])
# {}
print(type(example_dict['key1']['key2']))
# <class '__main__.Hasher'>

Note that this returns an empty Hasher when a key is missing.

Since Hasher is a subclass of dict you can use a Hasher in much the same way you could use a dict. All the same methods and syntax is available, Hashers just treat missing keys differently.

You can convert a regular dict into a Hasher like this:

hasher = Hasher(example_dict)

and convert a Hasher to a regular dict just as easily:

regular_dict = dict(hasher)

Another alternative is to hide the ugliness in a helper function:

def safeget(dct, *keys):
    for key in keys:
        try:
            dct = dct[key]
        except KeyError:
            return None
    return dct

So the rest of your code can stay relatively readable:

safeget(example_dict, 'key1', 'key2')

What is the use of the @ symbol in PHP?

Suppose we haven't used the "@" operator then our code would look like this:

$fileHandle = fopen($fileName, $writeAttributes);

And what if the file we are trying to open is not found? It will show an error message.

To suppress the error message we are using the "@" operator like:

$fileHandle = @fopen($fileName, $writeAttributes);

How to find largest objects in a SQL Server database?

If you are using Sql Server Management Studio 2008 there are certain data fields you can view in the object explorer details window. Simply browse to and select the tables folder. In the details view you are able to right-click the column titles and add fields to the "report". Your mileage may vary if you are on SSMS 2008 express.

How to make VS Code to treat other file extensions as certain language?

Hold down Ctrl+Shift+P (or cmd on Mac), select "Change Language Mode" and there it is.

But I still can't find a way to make VS Code recognized files with specific extension as some certain language.

Excel VBA Run-time error '13' Type mismatch

Sub HighlightSpecificValue()

'PURPOSE: Highlight all cells containing a specified values


Dim fnd As String, FirstFound As String
Dim FoundCell As Range, rng As Range
Dim myRange As Range, LastCell As Range

'What value do you want to find?
  fnd = InputBox("I want to hightlight cells containing...", "Highlight")

    'End Macro if Cancel Button is Clicked or no Text is Entered
      If fnd = vbNullString Then Exit Sub

Set myRange = ActiveSheet.UsedRange
Set LastCell = myRange.Cells(myRange.Cells.Count)

enter code here
Set FoundCell = myRange.Find(what:=fnd, after:=LastCell)

'Test to see if anything was found
  If Not FoundCell Is Nothing Then
    FirstFound = FoundCell.Address

  Else
    GoTo NothingFound
  End If

Set rng = FoundCell

'Loop until cycled through all unique finds
  Do Until FoundCell Is Nothing
    'Find next cell with fnd value
      Set FoundCell = myRange.FindNext(after:=FoundCell)







    'Add found cell to rng range variable
      Set rng = Union(rng, FoundCell)

    'Test to see if cycled through to first found cell
      If FoundCell.Address = FirstFound Then Exit Do


  Loop

'Highlight Found cells yellow

  rng.Interior.Color = RGB(255, 255, 0)

  Dim fnd1 As String
  fnd1 = "Rah"
  'Condition highlighting

  Set FoundCell = myRange.FindNext(after:=FoundCell)



  If FoundCell.Value("rah") Then
      rng.Interior.Color = RGB(255, 0, 0)

  ElseIf FoundCell.Value("Nav") Then

    rng.Interior.Color = RGB(0, 0, 255)



    End If





'Report Out Message
  MsgBox rng.Cells.Count & " cell(s) were found containing: " & fnd

Exit Sub

'Error Handler
NothingFound:
  MsgBox "No cells containing: " & fnd & " were found in this worksheet"

End Sub

Java: Array with loop

Here's how:

// Create an array with room for 100 integers
int[] nums = new int[100];

// Fill it with numbers using a for-loop
for (int i = 0; i < nums.length; i++)
    nums[i] = i + 1;  // +1 since we want 1-100 and not 0-99

// Compute sum
int sum = 0;
for (int n : nums)
    sum += n;

// Print the result (5050)
System.out.println(sum);

How to do date/time comparison

For comparison between two times use time.Sub()

// utc life
loc, _ := time.LoadLocation("UTC")

// setup a start and end time
createdAt := time.Now().In(loc).Add(1 * time.Hour)
expiresAt := time.Now().In(loc).Add(4 * time.Hour)

// get the diff
diff := expiresAt.Sub(createdAt)
fmt.Printf("Lifespan is %+v", diff)

The program outputs:

Lifespan is 3h0m0s

http://play.golang.org/p/bbxeTtd4L6

How to use a jQuery plugin inside Vue

Step 1 We place ourselves with the terminal in the folder of our project and install JQuery through npm or yarn.

npm install jquery --save

Step 2 Within our file where we want to use JQuery, for example app.js (resources/js/app.js), in the script section we include the following code.

// We import JQuery
const $ = require('jquery');
// We declare it globally
window.$ = $;

// You can use it now
$('body').css('background-color', 'orange');

// Here you can add the code for different plugins

Class file for com.google.android.gms.internal.zzaja not found

I solved this exact problem today and stumbled onto this unanswered question by chance during the process.

First, ensure you've properly setup Firebase for Android as documented here: https://firebase.google.com/docs/android/setup. Then, make sure you are compiling the latest version of the Firebase APIs (9.2.0) and the Google Play Services APIs (9.2.0) that you are using. My gradle dependencies look something like this:

dependencies {
    ...
    compile 'com.google.android.gms:play-services-location:9.2.0'
    compile 'com.google.firebase:firebase-core:9.2.0'
    compile 'com.google.firebase:firebase-auth:9.2.0'
    compile 'com.google.firebase:firebase-messaging:9.2.0'
}

Hope this helps!

How to send image to PHP file using Ajax?

Jquery code which contains simple ajax :

   $("#product").on("input", function(event) {
      var data=$("#nameform").serialize();
    $.post("./__partails/search-productbyCat.php",data,function(e){
       $(".result").empty().append(e);

     });


    });

Html elements you can use any element:

     <form id="nameform">
     <input type="text" name="product" id="product">
     </form>

php Code:

  $pdo=new PDO("mysql:host=localhost;dbname=onlineshooping","root","");
  $Catagoryf=$_POST['product'];

 $pricef=$_POST['price'];
  $colorf=$_POST['color'];

  $stmtcat=$pdo->prepare('SELECT * from products where Catagory =?');
  $stmtcat->execute(array($Catagoryf));

  while($result=$stmtcat->fetch(PDO::FETCH_ASSOC)){
  $iddb=$result['ID'];
     $namedb=$result['Name'];
    $pricedb=$result['Price'];
     $colordb=$result['Color'];

   echo "<tr>";
   echo "<td><a href=./pages/productsinfo.php?id=".$iddb."> $namedb</a> </td>".'<br>'; 
   echo "<td><pre>$pricedb</pre></td>";
   echo "<td><pre>    $colordb</pre>";
   echo "</tr>";

The easy way

How can I get current location from user in iOS

In Swift (for iOS 8+).

Info.plist

First things first. You need to add your descriptive string in the info.plist file for the keys NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription depending on what kind of service you are requesting

Code

import Foundation
import CoreLocation

class LocationManager: NSObject, CLLocationManagerDelegate {
    
    let manager: CLLocationManager
    var locationManagerClosures: [((userLocation: CLLocation) -> ())] = []
    
    override init() {
        self.manager = CLLocationManager()
        super.init()
        self.manager.delegate = self
    }
    
    //This is the main method for getting the users location and will pass back the usersLocation when it is available
    func getlocationForUser(userLocationClosure: ((userLocation: CLLocation) -> ())) {
        
        self.locationManagerClosures.append(userLocationClosure)
        
        //First need to check if the apple device has location services availabel. (i.e. Some iTouch's don't have this enabled)
        if CLLocationManager.locationServicesEnabled() {
            //Then check whether the user has granted you permission to get his location
            if CLLocationManager.authorizationStatus() == .NotDetermined {
                //Request permission
                //Note: you can also ask for .requestWhenInUseAuthorization
                manager.requestWhenInUseAuthorization()
            } else if CLLocationManager.authorizationStatus() == .Restricted || CLLocationManager.authorizationStatus() == .Denied {
                //... Sorry for you. You can huff and puff but you are not getting any location
            } else if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
                // This will trigger the locationManager:didUpdateLocation delegate method to get called when the next available location of the user is available
                manager.startUpdatingLocation()
            }
        }
        
    }
    
    //MARK: CLLocationManager Delegate methods
    
    @objc func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        if status == .AuthorizedAlways || status == .AuthorizedWhenInUse {
            manager.startUpdatingLocation()
        }
    }
    
    func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
        //Because multiple methods might have called getlocationForUser: method there might me multiple methods that need the users location.
        //These userLocation closures will have been stored in the locationManagerClosures array so now that we have the users location we can pass the users location into all of them and then reset the array.
        let tempClosures = self.locationManagerClosures
        for closure in tempClosures {
            closure(userLocation: newLocation)
        }
        self.locationManagerClosures = []
    }
}

Usage

self.locationManager = LocationManager()
self.locationManager.getlocationForUser { (userLocation: CLLocation) -> () in
            print(userLocation)
        }

How to pass an ArrayList to a varargs method parameter?

In Java 8:

List<WorldLocation> locations = new ArrayList<>();

.getMap(locations.stream().toArray(WorldLocation[]::new));

What is the difference between int, Int16, Int32 and Int64?

Each type of integer has a different range of storage capacity

   Type      Capacity

   Int16 -- (-32,768 to +32,767)

   Int32 -- (-2,147,483,648 to +2,147,483,647)

   Int64 -- (-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807)

As stated by James Sutherland in his answer:

int and Int32 are indeed synonymous; int will be a little more familiar looking, Int32 makes the 32-bitness more explicit to those reading your code. I would be inclined to use int where I just need 'an integer', Int32 where the size is important (cryptographic code, structures) so future maintainers will know it's safe to enlarge an int if appropriate, but should take care changing Int32 variables in the same way.

The resulting code will be identical: the difference is purely one of readability or code appearance.

Powershell folder size of folders without listing Subdirectories

This is something I wind up looking for repeatedly, even though I wrote myself a nice little function a while ago. So, I figured others might benefit from having it and maybe I'll even find it here, myself. hahaha

It's pretty simple to paste into your script and use. Just pass it a folder object.

I think it requires PowerShell 3 just because of the -directory flag on the Get-ChildItem command, but I'm sure it can be easily adapted, if need be.

function Get-TreeSize ($folder = $null)
{
    #Function to get recursive folder size
    $result = @()
    $folderResult = "" | Select-Object FolderPath, FolderName, SizeKB, SizeMB, SizeGB, OverThreshold

    $contents  = Get-ChildItem $folder.FullName -recurse -force -erroraction SilentlyContinue -Include * | Where-Object {$_.psiscontainer -eq $false} | Measure-Object -Property length -sum | Select-Object sum
    $sizeKB = [math]::Round($contents.sum / 1000,3)   #.ToString("#.##")
    $sizeMB = [math]::Round($contents.sum / 1000000,3)   #.ToString("#.##")
    $sizeGB = [math]::Round($contents.sum / 1000000000,3)   #.ToString("#.###")

    $folderResult.FolderPath = $folder.FullName
    $folderResult.FolderName = $folder.BaseName
    $folderResult.SizeKB = $sizeKB
    $folderresult.SizeMB = $sizeMB
    $folderresult.SizeGB = $sizeGB
    $result += $folderResult

    return $result
} 


#Use the function like this for a single directory
$topDir = get-item "C:\test"
Get-TreeSize ($topDir)

#Use the function like this for all top level folders within a direcotry
#$topDir = gci -directory "\\server\share\folder"
$topDir = Get-ChildItem -directory "C:\test"
foreach ($folderPath in $topDir) {Get-TreeSize $folderPath}  

how to make password textbox value visible when hover an icon

You will need to get the textbox via javascript when moving the mouse over it and change its type to text. And when moving it out, you will want to change it back to password. No chance of doing this in pure CSS.

HTML:

<input type="password" name="password" id="myPassword" size="30" />
<img src="theicon" onmouseover="mouseoverPass();" onmouseout="mouseoutPass();" />

JS:

function mouseoverPass(obj) {
  var obj = document.getElementById('myPassword');
  obj.type = "text";
}
function mouseoutPass(obj) {
  var obj = document.getElementById('myPassword');
  obj.type = "password";
}

How to: "Separate table rows with a line"

If you don't want to use CSS try this one between your rows:

    <tr>
    <td class="divider"><hr /></td>
    </tr>

Cheers!!

CodeIgniter: How to use WHERE clause and OR clause

$where = "name='Joe' AND status='boss' OR status='active'";

$this->db->where($where);

Though I am 3/4 of a month late, you still execute the following after your where clauses are defined... $this->db->get("tbl_name");

Solve error javax.mail.AuthenticationFailedException

Just in case anyone comes looking a solution for this problem.

The Authentication problems can be alleviated by activating the google 2-step verification for the account in use and creating an app specific password. I had the same problem as the OP. Enabling 2-step worked.

What are the special dollar sign shell variables?

  • $1, $2, $3, ... are the positional parameters.
  • "$@" is an array-like construct of all positional parameters, {$1, $2, $3 ...}.
  • "$*" is the IFS expansion of all positional parameters, $1 $2 $3 ....
  • $# is the number of positional parameters.
  • $- current options set for the shell.
  • $$ pid of the current shell (not subshell).
  • $_ most recent parameter (or the abs path of the command to start the current shell immediately after startup).
  • $IFS is the (input) field separator.
  • $? is the most recent foreground pipeline exit status.
  • $! is the PID of the most recent background command.
  • $0 is the name of the shell or shell script.

Most of the above can be found under Special Parameters in the Bash Reference Manual. There are all the environment variables set by the shell.

For a comprehensive index, please see the Reference Manual Variable Index.

Java List.contains(Object with field value equal to x)

Google Guava

If you're using Guava, you can take a functional approach and do the following

FluentIterable.from(list).find(new Predicate<MyObject>() {
   public boolean apply(MyObject input) {
      return "John".equals(input.getName());
   }
}).Any();

which looks a little verbose. However the predicate is an object and you can provide different variants for different searches. Note how the library itself separates the iteration of the collection and the function you wish to apply. You don't have to override equals() for a particular behaviour.

As noted below, the java.util.Stream framework built into Java 8 and later provides something similar.

How do I use the includes method in lodash to check if an object is in the collection?

The includes (formerly called contains and include) method compares objects by reference (or more precisely, with ===). Because the two object literals of {"b": 2} in your example represent different instances, they are not equal. Notice:

({"b": 2} === {"b": 2})
> false

However, this will work because there is only one instance of {"b": 2}:

var a = {"a": 1}, b = {"b": 2};
_.includes([a, b], b);
> true

On the other hand, the where(deprecated in v4) and find methods compare objects by their properties, so they don't require reference equality. As an alternative to includes, you might want to try some (also aliased as any):

_.some([{"a": 1}, {"b": 2}], {"b": 2})
> true

How to get the first 2 letters of a string in Python?

All previous examples will raise an exception in case your string is not long enough.

Another approach is to use 'yourstring'.ljust(100)[:100].strip().

This will give you first 100 chars. You might get a shorter string in case your string last chars are spaces.

Measuring text height to be drawn on Canvas ( Android )

You must use Rect.width() and Rect.Height() which returned from getTextBounds() instead. That works for me.

Multiple file extensions in OpenFileDialog

Based on First answer here is the complete image selection options:

Filter = @"|All Image Files|*.BMP;*.bmp;*.JPG;*.JPEG*.jpg;*.jpeg;*.PNG;*.png;*.GIF;*.gif;*.tif;*.tiff;*.ico;*.ICO
           |PNG|*.PNG;*.png
           |JPEG|*.JPG;*.JPEG*.jpg;*.jpeg
           |Bitmap(.BMP,.bmp)|*.BMP;*.bmp                                    
           |GIF|*.GIF;*.gif
           |TIF|*.tif;*.tiff
           |ICO|*.ico;*.ICO";

Retrieving Dictionary Value Best Practices

I imagine that trygetvalue is doing something more like:

if(myDict.ReallyOptimisedVersionofContains(someKey))
{ 
  someVal = myDict[someKey];
  return true;
}
return false;

So hopefully no try/catch anywhere.

I think it is just a method of convenience really. I generally use it as it saves a line of code or two.

position fixed header in html

I assume your header is fixed because you want it to stay at the top of the page even when the user scrolls down, but you dont want it covering the container. Setting position: fixed removes the element from the linear layout of the page however, so you would need to either set the top margin of the "next" element to be the same as the height of the header, or (if for whatever reason you don't want to do that), put a placeholder element which takes up space in the page flow, but would appear underneath where the header shows up.

Auto-increment primary key in SQL tables

Although the following is not way to do it in GUI but you can get autoincrementing simply using the IDENTITY datatype(start, increment):

CREATE TABLE "dbo"."TableName"
(
   id int IDENTITY(1,1) PRIMARY KEY NOT NULL,
   name varchar(20),
);

the insert statement should list all columns except the id column (it will be filled with autoincremented value):

INSERT INTO "dbo"."TableName" (name) VALUES ('alpha');
INSERT INTO "dbo"."TableName" (name) VALUES ('beta');

and the result of

SELECT id, name FROM "dbo"."TableName";

will be

id    name
--------------------------
1     alpha
2     beta

How do I handle too long index names in a Ruby on Rails ActiveRecord migration?

I have a project that uses generators a lot and needed this to be automatic, so I copied the index_name function from the rails source to override it. I added this in config/initializers/generated_index_name.rb:

# make indexes shorter for postgres
require "active_record/connection_adapters/abstract/schema_statements"
module ActiveRecord
  module ConnectionAdapters # :nodoc:
    module SchemaStatements
      def index_name(table_name, options) #:nodoc:
        if Hash === options
          if options[:column]
            "ix_#{table_name}_on_#{Array(options[:column]) * '__'}".slice(0,63)
          elsif options[:name]
            options[:name]
          else
            raise ArgumentError, "You must specify the index name"
          end
        else
          index_name(table_name, index_name_options(options))
        end
      end
    end
  end
end

It creates indexes like ix_assignments_on_case_id__project_id and just truncates it to 63 characters if it's still too long. That's still going to be non-unique if the table name is very long, but you can add complications like shortening the table name separately from the column names or actually checking for uniqueness.

Note, this is from a Rails 5.2 project; if you decide to do this, copy the source from your version.

ReactJS: setTimeout() not working?

Try to use ES6 syntax of set timeout. Normal javascript setTimeout() won't work in react js

setTimeout(
      () => this.setState({ position: 100 }), 
      5000
    );

How to break out from foreach loop in javascript

Use a for loop instead of .forEach()

var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false

for(var call of myObj) {
    console.log(call)
    
    var a = call['a'], b = call['b']
     
    if(a == null || b == null) {
        result = false
        break
    }
}

Ruby on Rails form_for select field with class

You can see in here: http://apidock.com/rails/ActionView/Helpers/FormBuilder/select

Or here: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select

Select tag has maximun 4 agrument, and last agrument is html option, it mean you can put class, require, selection option in here.

= f.select :sms_category_id, @sms_category_collect, {}, {class: 'form-control', required: true, selected: @set}

jQuery Date Picker - disable past dates

I have created function to disable previous date, disable flexible weekend days (Like Saturday, Sunday)

We are using beforeShowDay method of jQuery UI datepicker plugin.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
var NotBeforeToday = function(date) {_x000D_
  var now = new Date(); //this gets the current date and time_x000D_
  if (date.getFullYear() == now.getFullYear() && date.getMonth() == now.getMonth() && date.getDate() >= now.getDate() && (date.getDay() > 0 && date.getDay() < 6) )_x000D_
   return [true,""];_x000D_
  if (date.getFullYear() >= now.getFullYear() && date.getMonth() > now.getMonth() && (date.getDay() > 0 && date.getDay() < 6))_x000D_
   return [true,""];_x000D_
  if (date.getFullYear() > now.getFullYear() && (date.getDay() > 0 && date.getDay() < 6))_x000D_
   return [true,""];_x000D_
  return [false,""];_x000D_
 }_x000D_
_x000D_
_x000D_
jQuery("#datepicker").datepicker({_x000D_
  beforeShowDay: NotBeforeToday_x000D_
    });
_x000D_
_x000D_
_x000D_

enter image description here

Here today's date is 15th Sept. I have disabled Saturday and Sunday.

How does Java handle integer underflows and overflows and how would you check for it?

There are libraries that provide safe arithmetic operations, which check integer overflow/underflow . For example, Guava's IntMath.checkedAdd(int a, int b) returns the sum of a and b, provided it does not overflow, and throws ArithmeticException if a + b overflows in signed int arithmetic.

How to convert 2D float numpy array to 2D int numpy array?

you can use np.int_:

>>> x = np.array([[1.0, 2.3], [1.3, 2.9]])
>>> x
array([[ 1. ,  2.3],
       [ 1.3,  2.9]])
>>> np.int_(x)
array([[1, 2],
       [1, 2]])

Installing OpenCV on Windows 7 for Python 2.7

open command prompt and run the following commands (assuming python 2.7):

cd c:\Python27\scripts\
pip install opencv-python

the above works for me for python 2.7 on windows 10 64 bit

How to change the color of progressbar in C# .NET 3.5?

Since the previous answers don't appear to work in with Visual Styles. You'll probably need to create your own class or extend the progress bar:

public class NewProgressBar : ProgressBar
{
    public NewProgressBar()
    {
        this.SetStyle(ControlStyles.UserPaint, true);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        Rectangle rec = e.ClipRectangle;

        rec.Width = (int)(rec.Width * ((double)Value / Maximum)) - 4;
        if(ProgressBarRenderer.IsSupported)
           ProgressBarRenderer.DrawHorizontalBar(e.Graphics, e.ClipRectangle);
        rec.Height = rec.Height - 4;
        e.Graphics.FillRectangle(Brushes.Red, 2, 2, rec.Width, rec.Height);
    }
}

EDIT: Updated code to make the progress bar use the visual style for the background

How to set Java SDK path in AndroidStudio?

I tried updating all of my SDKs by just going into the Project Structure > Platform Settings > SDKs and changing the Java SDK, but that didn't work, so I had to recreate the configurations from scratch.

Here's how to create your SDKs with the latest Java:

  1. In Project Structure > Platform Settings > SDKs, click the "+" button to add a new SDK.
  2. In the pop-up, go into your Android SDK folder and click "Choose"
  3. Another pop-up will appear asking for which SDK and JDK you want to use. Choose any Android SDK and the 1.7 JDK.
  4. Go to Project Structure > Project Settings > Project and change your Project SDK to the one you just created. You should see the name of the SDK contain the new Java version that you installed.

How do I check if an HTML element is empty using jQuery?

In resume, there are many options to find out if an element is empty:

1- Using html:

if (!$.trim($('p#element').html())) {
    // paragraph with id="element" is empty, your code goes here
}

2- Using text:

if (!$.trim($('p#element').text())) {
    // paragraph with id="element" is empty, your code goes here
}

3- Using is(':empty'):

if ($('p#element').is(':empty')) {
    // paragraph with id="element" is empty, your code goes here
}

4- Using length

if (!$('p#element').length){
    // paragraph with id="element" is empty, your code goes here
}

In addiction if you are trying to find out if an input element is empty you can use val:

if (!$.trim($('input#element').val())) {
    // input with id="element" is empty, your code goes here
}

How can I convert a cv::Mat to a gray scale in OpenCv?

Using the C++ API, the function name has slightly changed and it writes now:

#include <opencv2/imgproc/imgproc.hpp>

cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, CV_BGR2GRAY);

The main difficulties are that the function is in the imgproc module (not in the core), and by default cv::Mat are in the Blue Green Red (BGR) order instead of the more common RGB.

OpenCV 3

Starting with OpenCV 3.0, there is yet another convention. Conversion codes are embedded in the namespace cv:: and are prefixed with COLOR. So, the example becomes then:

#include <opencv2/imgproc/imgproc.hpp>

cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, cv::COLOR_BGR2GRAY);

As far as I have seen, the included file path hasn't changed (this is not a typo).

How to store NULL values in datetime fields in MySQL?

Specifically relating to the error you're getting, you can't do something like this in PHP for a nullable field in MySQL:

$sql = 'INSERT INTO table (col1, col2) VALUES(' . $col1 . ', ' . null . ')';

Because null in PHP will equate to an empty string which is not the same as a NULL value in MysQL. Instead you want to do this:

$sql = 'INSERT INTO table (col1, col2) VALUES(' . $col1 . ', ' . (is_null($col2) ? 'NULL' : $col2). ')';

Of course you don't have to use is_null but I figure that it demonstrates the point a little better. Probably safer to use empty() or something like that. And if $col2 happens to be a string which you would enclose in double quotes in the query, don't forget not to include those around the 'NULL' string, otherwise it wont work.

Hope that helps!

How do I count cells that are between two numbers in Excel?

=COUNTIFS(H5:H21000,">=100", H5:H21000,"<999")

How to use <sec:authorize access="hasRole('ROLES)"> for checking multiple Roles?

There is a special security expression in spring security:

hasAnyRole(list of roles) - true if the user has been granted any of the roles specified (given as a comma-separated list of strings).

I have never used it but I think it is exactly what you are looking for.

Example usage:

<security:authorize access="hasAnyRole('ADMIN', 'DEVELOPER')">
    ...
</security:authorize>

Here is a link to the reference documentation where the standard spring security expressions are described. Also, here is a discussion where I described how to create custom expression if you need it.

Find Item in ObservableCollection without using a loop

You're looking for a hash based collection (like a Dictionary or Hashset) which the ObservableCollection is not. The best solution might be to derive from a hash based collection and implement INotifyCollectionChanged which will give you the same behavior as an ObservableCollection.

How do you debug React Native?

You can use Safari to debug the iOS version of your app without having to enable "Debug JS Remotely", Just follow the following steps:

1. Enable Develop menu in Safari: Preferences ? Advanced ? Select "Show Develop menu in menu bar"
2. Select your app's JSContext: Develop ? {Your Simulator} ? Automatically Show Web Inspector for JS JSContext
3. Safari's Web Inspector should open which has a Console and a Debugger

Show row number in row header of a DataGridView

just enhancing above solution.. so header it self resize its width in order to accommodate lengthy string like 12345

private void advancedDataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
    var grid = sender as DataGridView;
    var rowIdx = (e.RowIndex + 1).ToString();

    var centerFormat = new StringFormat()
    {
        // right alignment might actually make more sense for numbers
        Alignment = StringAlignment.Center,

        LineAlignment = StringAlignment.Center
    };
    //get the size of the string
    Size textSize = TextRenderer.MeasureText(rowIdx, this.Font);
    //if header width lower then string width then resize
    if (grid.RowHeadersWidth < textSize.Width + 40)
    {
        grid.RowHeadersWidth = textSize.Width + 40;
    }
    var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
    e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat);
}

How to exit if a command failed?

You can also use, if you want to preserve exit error status, and have a readable file with one command per line:

my_command1 || exit $?
my_command2 || exit $?

This, however will not print any additional error message. But in some cases, the error will be printed by the failed command anyway.

How to adjust an UIButton's imageSize?

Updated for Swift 3

yourButtonName.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10)

How to send FormData objects with Ajax-requests in jQuery?

Instead of - fd.append( 'userfile', $('#userfile')[0].files[0]);

Use - fd.append( 'file', $('#userfile')[0].files[0]);

getch and arrow codes

for a solution that uses ncurses with working code and initialization of ncurses see getchar() returns the same value (27) for up and down arrow keys

When saving, how can you check if a field has changed?

Very late to the game, but this is a version of Chris Pratt's answer that protects against race conditions while sacrificing performance, by using a transaction block and select_for_update()

@receiver(pre_save, sender=MyModel)
@transaction.atomic
def do_something_if_changed(sender, instance, **kwargs):
    try:
        obj = sender.objects.select_for_update().get(pk=instance.pk)
    except sender.DoesNotExist:
        pass # Object is new, so field hasn't technically changed, but you may want to do something else here.
    else:
        if not obj.some_field == instance.some_field: # Field has changed
            # do something

How to select <td> of the <table> with javascript?

var t = document.getElementById("table"),
    d = t.getElementsByTagName("tr"),
    r = d.getElementsByTagName("td");

needs to be:

var t = document.getElementById("table"),
    tableRows = t.getElementsByTagName("tr"),
    r = [], i, len, tds, j, jlen;

for ( i =0, len = tableRows.length; i<len; i++) {
    tds = tableRows[i].getElementsByTagName('td');
    for( j = 0, jlen = tds.length; j < jlen; j++) {
        r.push(tds[j]);
    }
}

Because getElementsByTagName returns a NodeList an Array-like structure. So you need to loop through the return nodes and then populate you r like above.

Add a column in a table in HIVE QL

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

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

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

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

python: NameError:global name '...‘ is not defined

You need to call self.a() to invoke a from b. a is not a global function, it is a method on the class.

You may want to read through the Python tutorial on classes some more to get the finer details down.

Access parent URL from iframe

You're correct. Subdomains are still considered separate domains when using iframes. It's possible to pass messages using postMessage(...), but other JS APIs are intentionally made inaccessible.

It's also still possible to get the URL depending on the context. See other answers for more details.

How can I add additional PHP versions to MAMP

The easiest solution I found is to just rename the php folder version as such:

  1. Shut down the servers
  2. Rename the folder containing the php version that you don't need in /Applications/MAMP/bin/php. php7.3.9 --> _php7.3.9

That way only two of them will be read by MAMP. Done!

A weighted version of random.choice

Since version 1.7.0, NumPy has a choice function that supports probability distributions.

from numpy.random import choice
draw = choice(list_of_candidates, number_of_items_to_pick,
              p=probability_distribution)

Note that probability_distribution is a sequence in the same order of list_of_candidates. You can also use the keyword replace=False to change the behavior so that drawn items are not replaced.

How to scale images to screen size in Pygame

You can scale the image with pygame.transform.scale:

import pygame
picture = pygame.image.load(filename)
picture = pygame.transform.scale(picture, (1280, 720))

You can then get the bounding rectangle of picture with

rect = picture.get_rect()

and move the picture with

rect = rect.move((x, y))
screen.blit(picture, rect)

where screen was set with something like

screen = pygame.display.set_mode((1600, 900))

To allow your widgets to adjust to various screen sizes, you could make the display resizable:

import os
import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((500, 500), HWSURFACE | DOUBLEBUF | RESIZABLE)
pic = pygame.image.load("image.png")
screen.blit(pygame.transform.scale(pic, (500, 500)), (0, 0))
pygame.display.flip()
while True:
    pygame.event.pump()
    event = pygame.event.wait()
    if event.type == QUIT:
        pygame.display.quit()
    elif event.type == VIDEORESIZE:
        screen = pygame.display.set_mode(
            event.dict['size'], HWSURFACE | DOUBLEBUF | RESIZABLE)
        screen.blit(pygame.transform.scale(pic, event.dict['size']), (0, 0))
        pygame.display.flip()

border-radius not working

Now I am using the browser kit like this:

{
border-radius: 7px;
-webkit-border-radius: 7px;
-moz-border-radius: 7px;
}

How to draw border on just one side of a linear layout?

To get a border on just one side of a drawable, apply a negative inset to the other 3 sides (causing those borders to be drawn off-screen).

<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:insetTop="-2dp" 
    android:insetBottom="-2dp"
    android:insetLeft="-2dp">

    <shape android:shape="rectangle">
        <stroke android:width="2dp" android:color="#FF0000" />
        <solid android:color="#000000" />
    </shape>

</inset>

enter image description here

This approach is similar to naykah's answer, but without the use of a layer-list.

How to manage startActivityForResult on Android?

I will post the new "way" with androidx in a short answer (because in some case you does not need custom registry or contract). If you want more informations see : https://developer.android.com/training/basics/intents/result

Important : there is actually a bug with the backward compatibility of androidx so you have to add fragment_version in your gradle file. Otherwise you will get an exception "New result API error : Can only use lower 16 bits for requestCode".

dependencies {

    def activity_version = "1.2.0-beta01"
    // Java language implementation
    implementation "androidx.activity:activity:$activity_version"
    // Kotlin
    implementation "androidx.activity:activity-ktx:$activity_version"

    def fragment_version = "1.3.0-beta02"
    // Java language implementation
    implementation "androidx.fragment:fragment:$fragment_version"
    // Kotlin
    implementation "androidx.fragment:fragment-ktx:$fragment_version"
    // Testing Fragments in Isolation
    debugImplementation "androidx.fragment:fragment-testing:$fragment_version"
}

Now you just have to add this member variable of your activity. This use a predefined registry and generic contract.

public class MyActivity extends AppCompatActivity{

   ...

    /**
     * Activity callback API.
     */
    // https://developer.android.com/training/basics/intents/result
    private ActivityResultLauncher<Intent> mStartForResult = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),

            new ActivityResultCallback<ActivityResult>() {

                @Override
                public void onActivityResult(ActivityResult result) {
                    switch (result.getResultCode()) {
                        case Activity.RESULT_OK:
                            Intent intent = result.getData();
                            // Handle the Intent
                            Toast.makeText(MyActivity.this, "Activity returned ok", Toast.LENGTH_SHORT).show();
                            break;
                        case Activity.RESULT_CANCELED:
                            Toast.makeText(MyActivity.this, "Activity canceled", Toast.LENGTH_SHORT).show();
                            break;
                    }
                }
            });

Before new API you had :

btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyActivity .this, EditActivity.class);
                startActivityForResult(intent, Constants.INTENT_EDIT_REQUEST_CODE);
            }
        });

You may notice that the request code is now generated (and holded) by the google framework. Your code become.

 btn.setOnClickListener(new View.OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MyActivity .this, EditActivity.class);
                    mStartForResult.launch(intent);
                }
            });

Hope my answer will help some people !

How can I get a random number in Kotlin?

Generate a random integer between from(inclusive) and to(exclusive)

import java.util.Random

val random = Random()

fun rand(from: Int, to: Int) : Int {
    return random.nextInt(to - from) + from
}

How to clear the interpreter console?

You have number of ways doing it on Windows:

1. Using Keyboard shortcut:

Press CTRL + L

2. Using system invoke method:

import os
cls = lambda: os.system('cls')
cls()

3. Using new line print 100 times:

cls = lambda: print('\n'*100)
cls()

PHP Parse error: syntax error, unexpected T_PUBLIC

The public keyword is used only when declaring a class method.

Since you're declaring a simple function and not a class you need to remove public from your code.