Programs & Examples On #Ziparchive

ZipArchive is a PHP extension for manipulating zip compressed archives

Creating a ZIP archive in memory using System.IO.Compression

Working solution for MVC

    public ActionResult Index()
    {
        string fileName = "test.pdf";
        string fileName1 = "test.vsix";
        string fileNameZip = "Export_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".zip";

        byte[] fileBytes = System.IO.File.ReadAllBytes(@"C:\test\test.pdf");
        byte[] fileBytes1 = System.IO.File.ReadAllBytes(@"C:\test\test.vsix");
        byte[] compressedBytes;
        using (var outStream = new MemoryStream())
        {
            using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
            {
                var fileInArchive = archive.CreateEntry(fileName, CompressionLevel.Optimal);
                using (var entryStream = fileInArchive.Open())
                using (var fileToCompressStream = new MemoryStream(fileBytes))
                {
                    fileToCompressStream.CopyTo(entryStream);
                }

                var fileInArchive1 = archive.CreateEntry(fileName1, CompressionLevel.Optimal);
                using (var entryStream = fileInArchive1.Open())
                using (var fileToCompressStream = new MemoryStream(fileBytes1))
                {
                    fileToCompressStream.CopyTo(entryStream);
                }


            }
            compressedBytes = outStream.ToArray();
        }
        return File(compressedBytes, "application/zip", fileNameZip);
    }

Fatal error: Class 'ZipArchive' not found in

I'm not seeing it here, so I'd like to add that on Debian/Ubuntu you may need to enable the extension after installing the relative package. So:

sudo apt-get install php-zip
sudo phpenmod zip
sudo service apache2 restart

How do I format date in jQuery datetimepicker?

Newer versions of datetimepicker (I'm using is use 2.3.7) use format:"Y/m/d" not dateFormat...

so

jQuery('#timePicker').datetimepicker({
    format: 'd-m-y',
    value: new Date()
});

See http://xdsoft.net/jqplugins/datetimepicker/

Converting pfx to pem using openssl

You can use the OpenSSL Command line tool. The following commands should do the trick

openssl pkcs12 -in client_ssl.pfx -out client_ssl.pem -clcerts

openssl pkcs12 -in client_ssl.pfx -out root.pem -cacerts

If you want your file to be password protected etc, then there are additional options.

You can read the entire documentation here.

Can't install nuget package because of "Failed to initialize the PowerShell host"

Had the same problem and this solved it for me (Powershell as admin):

Set-ItemProperty -Path HKLM:\Software\Policies\Microsoft\Windows\PowerShell -Name ExecutionPolicy -Value ByPass 

PowerShell try/catch/finally

That is very odd.

I went through ItemNotFoundException's base classes and tested the following multiple catches to see what would catch it:

try {
  remove-item C:\nonexistent\file.txt -erroraction stop
}
catch [System.Management.Automation.ItemNotFoundException] {
  write-host 'ItemNotFound'
}
catch [System.Management.Automation.SessionStateException] {
  write-host 'SessionState'
}
catch [System.Management.Automation.RuntimeException] {
  write-host 'RuntimeException'
}
catch [System.SystemException] {
  write-host 'SystemException'
}
catch [System.Exception] {
  write-host 'Exception'
}
catch {
  write-host 'well, darn'
}

As it turns out, the output was 'RuntimeException'. I also tried it with a different exception CommandNotFoundException:

try {
  do-nonexistent-command
}
catch [System.Management.Automation.CommandNotFoundException] {
  write-host 'CommandNotFoundException'
}
catch {
  write-host 'well, darn'
}

That output 'CommandNotFoundException' correctly.

I vaguely remember reading elsewhere (though I couldn't find it again) of problems with this. In such cases where exception filtering didn't work correctly, they would catch the closest Type they could and then use a switch. The following just catches Exception instead of RuntimeException, but is the switch equivalent of my first example that checks all base types of ItemNotFoundException:

try {
  Remove-Item C:\nonexistent\file.txt -ErrorAction Stop
}
catch [System.Exception] {
  switch($_.Exception.GetType().FullName) {
    'System.Management.Automation.ItemNotFoundException' {
      write-host 'ItemNotFound'
    }
    'System.Management.Automation.SessionStateException' {
      write-host 'SessionState'
    }
    'System.Management.Automation.RuntimeException' {
      write-host 'RuntimeException'
    }
    'System.SystemException' {
      write-host 'SystemException'
    }
    'System.Exception' {
      write-host 'Exception'
    }
    default {'well, darn'}
  }
}

This writes 'ItemNotFound', as it should.

Convert JS date time to MySQL datetime

I think the solution can be less clunky by using method toISOString(), it has a wide browser compatibility.

So your expression will be a one-liner:

new Date().toISOString().slice(0, 19).replace('T', ' ');

The generated output:

"2017-06-29 17:54:04"

How to concatenate string variables in Bash

The way I'd solve the problem is just

$a$b

For example,

a="Hello"
b=" World"
c=$a$b
echo "$c"

which produces

Hello World

If you try to concatenate a string with another string, for example,

a="Hello"
c="$a World"

then echo "$c" will produce

Hello World

with an extra space.

$aWorld

doesn't work, as you may imagine, but

${a}World

produces

HelloWorld

Can I install/update WordPress plugins without providing FTP access?

Yes you can do it.

You need to add

define('METHOD','direct');

in your wpconfig. But this method won't be preferable because it has security voilances.

Thanks,

Custom li list-style with font-awesome icon

I did two things inspired by @OscarJovanny comment, with some hacks.

Step 1:

  • Download icons file as svg from Here, as I only need only this icon from font awesome

Step 2:

<style>
ul {
    list-style-type: none;
    margin-left: 10px;
}

ul li {
    margin-bottom: 12px;
    margin-left: -10px;
    display: flex;
    align-items: center;
}

ul li::before {
    color: transparent;
    font-size: 1px;
    content: " ";
    margin-left: -1.3em;
    margin-right: 15px;
    padding: 10px;
    background-color: orange;
    -webkit-mask-image: url("./assets/img/check-circle-solid.svg");
    -webkit-mask-size: cover;
}
</style>

Results

enter image description here

Number of visitors on a specific page

Go to Behavior > Site Content > All Pages and put your URI into the search box.enter image description here

I can pass a variable from a JSP scriptlet to JSTL but not from JSTL to a JSP scriptlet without an error

@skaffman nailed it down. They live each in its own context. However, I wouldn't consider using scriptlets as the solution. You'd like to avoid them. If all you want is to concatenate strings in EL and you discovered that the + operator fails for strings in EL (which is correct), then just do:

<c:out value="abc${test}" />

Or if abc is to obtained from another scoped variable named ${resp}, then do:

<c:out value="${resp}${test}" />

Use Expect in a Bash script to provide a password to an SSH command

A simple Expect script:

File Remotelogin.exp

    #!/usr/bin/expect
    set user [lindex $argv 1]
    set ip [lindex $argv 0]
    set password [lindex $argv 2]
    spawn ssh $user@$ip
    expect "password"
    send "$password\r"
    interact

Example:

./Remotelogin.exp <ip> <user name> <password>

How to run a shell script in OS X by double-clicking?

Alternatively, you could create a regular Mac OS X application from your script using Platypus

angular-cli where is webpack.config.js file - new angular6 does not support ng eject

With Angular CLI 6 you need to use builders as ng eject is deprecated and will soon be removed in 8.0. That's what it says when I try to do an ng eject

enter image description here

You can use angular-builders package (https://github.com/meltedspark/angular-builders) to provide your custom webpack config.

I have tried to summarize all in a single blog post on my blog - How to customize build configuration with custom webpack config in Angular CLI 6

but essentially you add following dependencies -

  "devDependencies": {
    "@angular-builders/custom-webpack": "^7.0.0",
    "@angular-builders/dev-server": "^7.0.0",
    "@angular-devkit/build-angular": "~0.11.0",

In angular.json make following changes -

  "architect": {
    "build": {
      "builder": "@angular-builders/custom-webpack:browser",
      "options": {
        "customWebpackConfig": {"path": "./custom-webpack.config.js"},

Notice change in builder and new option customWebpackConfig. Also change

    "serve": {
      "builder": "@angular-builders/dev-server:generic",

Notice the change in builder again for serve target. Post these changes you can create a file called custom-webpack.config.js in your same root directory and add your webpack config there.

However, unlike ng eject configuration provided here will be merged with default config so just add stuff you want to edit/add.

How often should Oracle database statistics be run?

At my last job we ran statistics once a week. If I remember correctly, we scheduled them on a Thursday night, and on Friday the DBAs were very careful to monitor the longest running queries for anything unexpected. (Friday was picked because it was often just after a code release, and tended to be a fairly low traffic day.) When they saw a bad query they would find a better query plan and save that one so it wouldn't change again unexpectedly. (Oracle has tools to do this for you automatically, you tell it the query to optimize and it does.)

Many organizations avoid running statistics out of fear of bad query plans popping up unexpectedly. But this usually means that their query plans get worse and worse over time. And when they do run statistics then they encounter a number of problems. The resulting scramble to fix those issues confirms their fears about the dangers of running statistics. But if they ran statistics regularly, used the monitoring tools as they are supposed to, and fixed issues as they came up then they would have fewer headaches, and they wouldn't encounter them all at once.

VBA Runtime Error 1004 "Application-defined or Object-defined error" when Selecting Range

I also had a similar issue. After copying and pasting to a sheet I wanted the cursor/ selected cell to be A1 not the range that I just pasted into.

Dim wkSheet as Worksheet
Set wkSheet = Worksheets(<sheetname>)

wkSheet("A1").Select

but got a 400 error which was actually a 1004 error

You need to activate the sheet before changing the selected cell this worked

Dim wkSheet as Worksheet
Set wkSheet = Worksheets(<sheetname>)

wkSheet.Activate
wkSheet("A1").Select

Firebase: how to generate a unique numeric ID for key?

As explained above, you can use the Firebase default push id.

If you want something numeric you can do something based on the timestamp to avoid collisions

f.e. something based on date,hour,second,ms, and some random int at the end

01612061353136799031

Which translates to:

016-12-06 13:53:13:679 9031

It all depends on the precision you need (social security numbers do the same with some random characters at the end of the date). Like how many transactions will be expected during the day, hour or second. You may want to lower precision to favor ease of typing.

You can also do a transaction that increments the number id, and on success you will have a unique consecutive number for that user. These can be done on the client or server side.

(https://firebase.google.com/docs/database/android/read-and-write)

Display unescaped HTML in Vue.js

Before using v-html, you have to make sure that the element which you escape is sanitized in case you allow user input, otherwise you expose your app to xss vulnerabilities.

More info here: https://vuejs.org/v2/guide/security.html

I highly encourage you that instead of using v-html to use this npm package

How to set image on QPushButton?

You can also use:

button.setStyleSheet("qproperty-icon: url(:/path/to/images.png);");

Note: This is a little hacky. You should use this only as last resort. Icons should be set from C++ code or Qt Designer.

What is the simplest way to get indented XML with line breaks from XmlDocument?

A more simplified approach based on the accepted answer:

static public string Beautify(this XmlDocument doc) {
    StringBuilder sb = new StringBuilder();
    XmlWriterSettings settings = new XmlWriterSettings
    {
        Indent = true
    };

    using (XmlWriter writer = XmlWriter.Create(sb, settings)) {
        doc.Save(writer);
    }

    return sb.ToString(); 
}

Setting the new line is not necessary. Indent characters also has the default two spaces so I preferred not to set it as well.

mean() warning: argument is not numeric or logical: returning NA

The same error appears if you do not use the correct (numeric) format of your data in your data.frame column using mean() function. Therefore, check your data using str(data.frame&column) function to see what data type you have, and convert it to numeric format if necessary. For example, if your data is Character convert it with as.numeric(data.frame$column), or as a factor with as.numeric(as.character(data.frame$column)). The mean function does not work with types other than numeric.

git submodule tracking latest

Edit (2020.12.28): GitHub change default master branch to main branch since October 2020. See https://github.com/github/renaming


Update March 2013

Git 1.8.2 added the possibility to track branches.

"git submodule" started learning a new mode to integrate with the tip of the remote branch (as opposed to integrating with the commit recorded in the superproject's gitlink).

# add submodule to track master branch
git submodule add -b master [URL to Git repo];

# update your submodule
git submodule update --remote 

If you had a submodule already present you now wish would track a branch, see "how to make an existing submodule track a branch".

Also see Vogella's tutorial on submodules for general information on submodules.

Note:

git submodule add -b . [URL to Git repo];
                    ^^^

See git submodule man page:

A special value of . is used to indicate that the name of the branch in the submodule should be the same name as the current branch in the current repository.


See commit b928922727d6691a3bdc28160f93f25712c565f6:

submodule add: If --branch is given, record it in .gitmodules

This allows you to easily record a submodule.<name>.branch option in .gitmodules when you add a new submodule. With this patch,

$ git submodule add -b <branch> <repository> [<path>]
$ git config -f .gitmodules submodule.<path>.branch <branch>

reduces to

$ git submodule add -b <branch> <repository> [<path>]

This means that future calls to

$ git submodule update --remote ...

will get updates from the same branch that you used to initialize the submodule, which is usually what you want.

Signed-off-by: W. Trevor King [email protected]


Original answer (February 2012):

A submodule is a single commit referenced by a parent repo.
Since it is a Git repo on its own, the "history of all commits" is accessible through a git log within that submodule.

So for a parent to track automatically the latest commit of a given branch of a submodule, it would need to:

  • cd in the submodule
  • git fetch/pull to make sure it has the latest commits on the right branch
  • cd back in the parent repo
  • add and commit in order to record the new commit of the submodule.

gitslave (that you already looked at) seems to be the best fit, including for the commit operation.

It is a little annoying to make changes to the submodule due to the requirement to check out onto the correct submodule branch, make the change, commit, and then go into the superproject and commit the commit (or at least record the new location of the submodule).

Other alternatives are detailed here.

PHP - Get bool to echo false when false

var_export provides the desired functionality.

This will always print a value rather than printing nothing for null or false. var_export prints a PHP representation of the argument it's passed, the output could be copy/pasted back into PHP.

var_export(true);    // true
var_export(false);   // false
var_export(1);       // 1
var_export(0);       // 0
var_export(null);    // NULL
var_export('true');  // 'true'   <-- note the quotes
var_export('false'); // 'false'

If you want to print strings "true" or "false", you can cast to a boolean as below, but beware of the peculiarities:

var_export((bool) true);   // true
var_export((bool) false);  // false
var_export((bool) 1);      // true
var_export((bool) 0);      // false
var_export((bool) '');     // false
var_export((bool) 'true'); // true
var_export((bool) null);   // false

// !! CAREFUL WITH CASTING !!
var_export((bool) 'false'); // true
var_export((bool) '0');     // false

MySQL Error 1215: Cannot add foreign key constraint

I'm guessing that Clients.Case_Number and/or Staff.Emp_ID are not exactly the same data type as Clients_has_Staff.Clients_Case_Number and Clients_has_Staff.Staff_Emp_ID.

Perhaps the columns in the parent tables are INT UNSIGNED?

They need to be exactly the same data type in both tables.

How to fix div on scroll

On jQuery for designers there's a well written post about this, this is the jQuery snippet that does the magic. just replace #comment with the selector of the div that you want to float.

Note: To see the whole article go here: http://jqueryfordesigners.com/fixed-floating-elements/

$(document).ready(function () {
  var $obj = $('#comment');
  var top = $obj.offset().top - parseFloat($obj.css('marginTop').replace(/auto/, 0));

  $(window).scroll(function (event) {
    // what the y position of the scroll is
    var y = $(this).scrollTop();

    // whether that's below the form
    if (y >= top) {
      // if so, ad the fixed class
      $obj.addClass('fixed');
    } else {
      // otherwise remove it
      $obj.removeClass('fixed');
    }
  });
});

What is the Gradle artifact dependency graph command?

Ah, since I had no dependencies in my master project, "gradle dependencies" only lists those and not subproject dependencies so the correct command ended up being

 gradle :<subproject>:dependencies

so for me this was

 gradle :master:dependencies

How do I find which process is leaking memory?

if the program leaks over a long time, top might not be practical. I would write a simple shell scripts that appends the result of "ps aux" to a file every X seconds, depending on how long it takes to leak significant amounts of memory. Something like:

while true
do
echo "---------------------------------" >> /tmp/mem_usage
date >> /tmp/mem_usage
ps aux >> /tmp/mem_usage
sleep 60
done

Check if object exists in JavaScript

if (n === Object(n)) {
   // code
}

Printing Even and Odd using two Threads in Java

public class Solution {

 static class NumberGenerator{

     private static volatile boolean printEvenNumber = false;


     public  void printEvenNumber(int i) {
         synchronized (this) {
             if(!printEvenNumber) {
                 try {
                     wait();
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
             }
             System.out.println(i);
             printEvenNumber = !printEvenNumber;
             notify();
         }
     }

     public  void printOddNumber(int i ) {
            synchronized (this) {
                if(printEvenNumber) {
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                System.out.println(i);
                printEvenNumber = !printEvenNumber;
                notify();
            }
     }

}

static  class OddNumberGenerator implements Runnable{
    private NumberGenerator numberGenerator;

    public OddNumberGenerator(NumberGenerator numberGenerator) {
        this.numberGenerator = numberGenerator;
    }

    @Override
    public void run() {
        for(int i  = 1; i <100; i = i + 2) {
            numberGenerator.printOddNumber(i);
        }
    }
}

static class EvenNumberGenerator implements Runnable {
    private NumberGenerator numberGenerator;

    public EvenNumberGenerator(NumberGenerator numberGenerator) {
        this.numberGenerator = numberGenerator;
    }

    @Override
    public void run() {
        for (int i = 2; i <= 100; i =  i + 2) {
           numberGenerator.printEvenNumber(i);
        }
    }
}


public static void main(String[] args) {
    NumberGenerator ng = new NumberGenerator();
    OddNumberGenerator oddNumberGenerator = new OddNumberGenerator(ng);
    EvenNumberGenerator evenNumberGenerator = new EvenNumberGenerator(ng);
    new Thread(oddNumberGenerator).start();
    new Thread(evenNumberGenerator).start();

}

}

What are "res" and "req" parameters in Express functions?

I noticed one error in Dave Ward's answer (perhaps a recent change?): The query string paramaters are in request.query, not request.params. (See https://stackoverflow.com/a/6913287/166530 )

request.params by default is filled with the value of any "component matches" in routes, i.e.

app.get('/user/:id', function(request, response){
  response.send('user ' + request.params.id);
});

and, if you have configured express to use its bodyparser (app.use(express.bodyParser());) also with POST'ed formdata. (See How to retrieve POST query parameters? )

Wait until an HTML5 video loads

you can use preload="none" in the attribute of video tag so the video will be displayed only when user clicks on play button.

_x000D_
_x000D_
<video preload="none">
_x000D_
_x000D_
_x000D_

Google maps responsive resize

After few years, I moved to leaflet map and I have fixed this issue completely, the following could be applied to google maps too:

    var headerHeight = $("#navMap").outerHeight();
    var footerHeight = $("footer").outerHeight();
    var windowHeight = window.innerHeight;
    var mapContainerHeight = headerHeight + footerHeight;
    var totalMapHeight = windowHeight - mapContainerHeight;
    $("#map").css("margin-top", headerHeight);
    $("#map").height(totalMapHeight);

    $(window).resize(function(){
        var headerHeight = $("#navMap").outerHeight();
        var footerHeight = $("footer").outerHeight();
        var windowHeight = window.innerHeight;
        var mapContainerHeight = headerHeight + footerHeight;
        var totalMapHeight = windowHeight - mapContainerHeight;
        $("#map").css("margin-top", headerHeight);
        $("#map").height(totalMapHeight);
        map.fitBounds(group1.getBounds());
    });

How do I navigate to another page when PHP script is done?

if ($done)
{
    header("Location: /url/to/the/other/page");
    exit;
}

How to pass extra variables in URL with WordPress

<?php
$edit_post = add_query_arg('c', '123', 'news' );

?>

<a href="<?php echo $edit_post; ?>">Go to New page</a>

You can add any page inplace of "news".

How does one capture a Mac's command key via JavaScript?

var element = //the DOM element to listen for the key on.
element.onkeyup = function(e) {
   if(e.metaKey) {
      //command key was pressed
   }
}

Convert Unicode data to int in python

In python, integers and strings are immutable and are passed by value. You cannot pass a string, or integer, to a function and expect the argument to be modified.

So to convert string limit="100" to a number, you need to do

limit = int(limit) # will return new object (integer) and assign to "limit"

If you really want to go around it, you can use a list. Lists are mutable in python; when you pass a list, you pass it's reference, not copy. So you could do:

def int_in_place(mutable):
    mutable[0] = int(mutable[0])

mutable = ["1000"]
int_in_place(mutable)
# now mutable is a list with a single integer

But you should not need it really. (maybe sometimes when you work with recursions and need to pass some mutable state).

hasOwnProperty in JavaScript

hasOwnProperty() is a nice property to validate object keys. Example:

var obj = {a:1, b:2};

obj.hasOwnProperty('a') // true

XSLT getting last element

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

(//element[@name='D'])[last()]

How to obtain a QuerySet of all rows, with specific fields for each one of them?

Daniel answer is right on the spot. If you want to query more than one field do this:

Employee.objects.values_list('eng_name','rank')

This will return list of tuples. You cannot use named=Ture when querying more than one field.

Moreover if you know that only one field exists with that info and you know the pk id then do this:

Employee.objects.values_list('eng_name','rank').get(pk=1)

installing JDK8 on Windows XP - advapi32.dll error

This happens because Oracle dropped support for Windows XP (which doesn't have RegDeleteKeyExA used by the installer in its ADVAPI32.DLL by the way) as described in http://mail.openjdk.java.net/pipermail/openjfx-dev/2013-July/009005.html. Yet while the official support for XP has ended, the Java binaries are still (as of Java 8u20 EA b05 at least) XP-compatible - only the installer isn't...

Because of that, the solution is actually quite easy:

  1. get 7-Zip (or any other good unpacker), unpack the distribution .exe manually, it has one .zip file inside of it (tools.zip), extract it too,

  2. use unpack200 from JDK8 to unpack all .pack files to .jar files (older unpacks won't work properly); JAVA_HOME environment variable should be set to your Java unpack root, e.g. "C:\Program Files\Java\jdk8" - you can specify it implicitly by e.g.

    SET JAVA_HOME=C:\Program Files\Java\jdk8
    
    • Unpack all files with a single command (in batch file):

      FOR /R %%f IN (*.pack) DO "%JAVA_HOME%\bin\unpack200.exe" -r -v "%%f" "%%~pf%%~nf.jar"
      
    • Unpack all files with a single command (command line from JRE root):

      FOR /R %f IN (*.pack) DO "bin\unpack200.exe" -r -v "%f" "%~pf%~nf.jar"
      
    • Unpack by manually locating the files and unpacking them one-by-one:

      %JAVA_HOME%\bin\unpack200 -r packname.pack packname.jar
      

    where packname is for example rt

  3. point the tool you want to use (e.g. Netbeans) to the %JAVA_HOME% and you're good to go.

Note: you probably shouldn't do this just to use Java 8 in your web browser or for any similar reason (installing JRE 8 comes to mind); security flaws in early updates of major Java version releases are (mind me) legendary, and adding to that no real support for neither XP nor Java 8 on XP only makes matters much worse. Not to mention you usually don't need Java in your browser (see e.g. http://nakedsecurity.sophos.com/2013/01/15/disable-java-browsers-homeland-security/ - the topic is already covered on many pages, just Google it if you require further info). In any case, AFAIK the only thing required to apply this procedure to JRE is to change some of the paths specified above from \bin\ to \lib\ (the file placement in installer directory tree is a bit different) - yet I strongly advise against doing it.

See also: How can I get the latest JRE / JDK as a zip file rather than EXE or MSI installer?, JRE 1.7 - java version - returns: java/lang/NoClassDefFoundError: java/lang/Object

how to hide keyboard after typing in EditText in android?

I found this because my EditText wasn't automatically getting dismissed on enter.

This was my original code.

editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if ( (actionId == EditorInfo.IME_ACTION_DONE) || ((event.getKeyCode() == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN ))) {

            // Do stuff when user presses enter

            return true;

        }

        return false;
    }
});

I solved it by removing the line

return true;

after doing stuff when user presses enter.

Hope this helps someone.

How can I use a batch file to write to a text file?

@echo off Title Writing using Batch Files color 0a

echo Example Text > Filename.txt echo Additional Text >> Filename.txt

@ECHO OFF
Title Writing Using Batch Files
color 0a

echo Example Text > Filename.txt
echo Additional Text >> Filename.txt

Get the string within brackets in Python

You can use

import re

s = re.search(r"\[.*?]", string)
if s:
    print(s.group(0))

size of NumPy array

This is called the "shape" in NumPy, and can be requested via the .shape attribute:

>>> a = zeros((2, 5))
>>> a.shape
(2, 5)

If you prefer a function, you could also use numpy.shape(a).

Any way to write a Windows .bat file to kill processes?

Here I wrote an example command that you can paste in your cmd command line prompt and is written for chrome.exe.

FOR /F "tokens=2 delims= " %P IN ('tasklist /FO Table /M "chrome*" /NH') DO (TASKKILL /PID %P)

The for just takes all the PIDs listed on the below tasklist command and executes TASKKILL /PID on every PID

tasklist /FO Table /M "chrome*" /NH

If you use the for in a batch file just use %%P instead of %P

Splitting String with delimiter

split doesn't work that way in groovy. you have to use tokenize...

See the docs:

http://groovy-lang.org/gdk.html#split()

Sending event when AngularJS finished loading

Angular hasn't provided a way to signal when a page finished loading, maybe because "finished" depends on your application. For example, if you have hierarchical tree of partials, one loading the others. "Finish" would mean that all of them have been loaded. Any framework would have a hard time analyzing your code and understanding that everything is done, or still waited upon. For that, you would have to provide application-specific logic to check and determine that.

SQL Server JOIN missing NULL values

Try using additional condition in join:

SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
FROM Table1 
INNER JOIN Table2
ON (Table1.Col1 = Table2.Col1 
    OR (Table1.Col1 IS NULL AND Table2.Col1 IS NULL)
   )

How to check whether a str(variable) is empty or not?

element = random.choice(myList)
if element:
    # element contains text
else:
    # element is empty ''

Convert string to int if string is a number

To put it on one line:

currentLoad = IIf(IsNumeric(oXLSheet2.Cells(4, 6).Value), CInt(oXLSheet2.Cells(4, 6).Value), 0)

Convert dictionary to bytes and back again python?

If you need to convert the dictionary to binary, you need to convert it to a string (JSON) as described in the previous answer, then you can convert it to binary.

For example:

my_dict = {'key' : [1,2,3]}

import json
def dict_to_binary(the_dict):
    str = json.dumps(the_dict)
    binary = ' '.join(format(ord(letter), 'b') for letter in str)
    return binary


def binary_to_dict(the_binary):
    jsn = ''.join(chr(int(x, 2)) for x in the_binary.split())
    d = json.loads(jsn)  
    return d

bin = dict_to_binary(my_dict)
print bin

dct = binary_to_dict(bin)
print dct

will give the output

1111011 100010 1101011 100010 111010 100000 1011011 110001 101100 100000 110010 101100 100000 110011 1011101 1111101

{u'key': [1, 2, 3]}

How to make clang compile to llvm IR

If you have multiple files and you don't want to have to type each file, I would recommend that you follow these simple steps (I am using clang-3.8 but you can use any other version):

  1. generate all .ll files

    clang-3.8 -S -emit-llvm *.c
    
  2. link them into a single one

    llvm-link-3.8 -S -v -o single.ll *.ll
    
  3. (Optional) Optimise your code (maybe some alias analysis)

    opt-3.8 -S -O3 -aa -basicaaa -tbaa -licm single.ll -o optimised.ll
    
  4. Generate assembly (generates a optimised.s file)

    llc-3.8 optimised.ll
    
  5. Create executable (named a.out)

    clang-3.8 optimised.s
    

The simplest way to comma-delimit a list?

I usually use something similar to version 3. It works well c/c++/bash/... :P

Bootstrap control with multiple "data-toggle"

When you opening modal on a tag and want show tooltip and if you implement tooltip inside tag it will show tooltip nearby tag. like this

enter image description here

I will suggest that use div outside a tag and use "display: inline-block;"

<div data-toggle="tooltip" title="" data-original-title="Add" style=" display inline-block;">
    <a class="btn btn-primary" data-toggle="modal" data-target="#myModal" onclick="setSelectedRoleId(6)">
     <span class="fa fa-plus"></span>
    </a>
</div>

enter image description here

Chrome javascript debugger breakpoints don't do anything?

Make sure that you're using the same host in the URL that you were when you set up the mapping. E.g. if you were at http://127.0.0.1/my-app when you set up and mapped the workspace then breakpoints won't work if you view the page via http://localhost/my-app. Also, thanks for reading this far. See my answer to the Chromium issue here.

Multiple models in a view

My advice is to make a big view model:

public BigViewModel
{
    public LoginViewModel LoginViewModel{get; set;}
    public RegisterViewModel RegisterViewModel {get; set;}
}

In your Index.cshtml, if for example you have 2 partials:

@addTagHelper *,Microsoft.AspNetCore.Mvc.TagHelpers
@model .BigViewModel

@await Html.PartialAsync("_LoginViewPartial", Model.LoginViewModel)

@await Html.PartialAsync("_RegisterViewPartial ", Model.RegisterViewModel )

and in controller:

model=new BigViewModel();
model.LoginViewModel=new LoginViewModel();
model.RegisterViewModel=new RegisterViewModel(); 

error: command 'gcc' failed with exit status 1 on CentOS

Is gcc installed?

sudo yum install gcc

Javascript loop through object array?

To loop through an object array or just array in javascript, you can do the following:

var cars = [{name: 'Audi'}, {name: 'BMW'}, {name: 'Ferrari'}, {name: 'Mercedes'}, {name: 'Maserati'}];

for(var i = 0; i < cars.length; i++) {
    console.log(cars[i].name);
}

There is also the forEach() function, which is more "javascript-ish" and also less code but more complicated for its syntax:

cars.forEach(function (car) {
    console.log(car.name);
});

And both of them are outputting the following:

// Audi
// BMW
// Ferrari
// Mercedes
// Maserati

How to check if a file exists in the Documents directory in Swift?

An alternative/recommended Code Pattern in Swift 3 would be:

  1. Use URL instead of FileManager
  2. Use of exception handling

    func verifyIfSqliteDBExists(){
        let docsDir     : URL       = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let dbPath      : URL       = docsDir.appendingPathComponent("database.sqlite")
    
        do{
            let sqliteExists : Bool = try dbPath.checkResourceIsReachable()
            print("An sqlite database exists at this path :: \(dbPath.path)")
    
        }catch{
            print("SQLite NOT Found at :: \(strDBPath)")
        }
    }
    

how to open Jupyter notebook in chrome on windows

  • Run the jupyter notebook --generate-config command on the anaconda prompt.
  • Then edit the jupyter_notebook_config.py file.

Find the c.NotebookApp.Browser like this:

c.NotebookApp.browser = 'c:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'

Works on mine.

Android Whatsapp/Chat Examples

If you are looking to create an instant messenger for Android, this code should get you started somewhere.

Excerpt from the source :

This is a simple IM application runs on Android, application makes http request to a server, implemented in php and mysql, to authenticate, to register and to get the other friends' status and data, then it communicates with other applications in other devices by socket interface.

EDIT : Just found this! Maybe it's not related to WhatsApp. But you can use the source to understand how chat applications are programmed.

There is a website called Scringo. These awesome people provide their own SDK which you can integrate in your existing application to exploit cool features like radaring, chatting, feedback, etc. So if you are looking to integrate chat in application, you could just use their SDK. And did I say the best part? It's free!

*UPDATE : * Scringo services will be closed down on 15 February, 2015.

Tomcat request timeout

For anyone who doesn't like none of the solutions posted above like me then you can simply implement a timer yourself and stop the request execution by throwing a runtime exception. Something like below:

                  try 
                 {
                     timer.schedule(new TimerTask() {
                       @Override
                       public void run() {
                         timer.cancel();
                       }
                     }, /* specify time of the requst */ 1000);
                 }
                 catch(Exception e)
                 {
                   throw new RuntimeException("the request is taking longer than usual");
                 }

   

or preferably use the java guava timeLimiter here

CocoaPods Errors on Project Build

Had the same issue saying /Pods/Pods-resources.sh: No such file or directory even after files etc related to pods were removed.

Got rid of it by going to target->Build phases and then removing the build phase "Copy Pod Resources".

unix - count of columns in file

If you have python installed you could try:

python -c 'import sys;f=open(sys.argv[1]);print len(f.readline().split("|"))' \
    stores.dat

check null,empty or undefined angularjs

You can use angular's function called angular.isUndefined(value) returns boolean.

You may read more about angular's functions here: AngularJS Functions (isUndefined)

How do I allow HTTPS for Apache on localhost?

In order to protect the security of information being sent to and from your web server, it's a good idea to enable encryption of the communication between clients and the server. This is often called SSL.

So let's set up HTTPS with a self-signed certificate on Apache2. I am going to list the steps which you should follow:

  • Install apache2 web-server on your machine. For linux machine open the terminal and type

sudo apt-get install apache2

  • After successful installation check the status of apache2 service by executing command

sudo service apache2 status

It should output

apache2 service status

  • Navigate to browser and type

http://localhost:80

Verify that you get default page for apache2 like this.

default output of apache2

  • For encrypting a web connection we need certificate from CA (certificate authority) or we can use self signed certificates. Let's create a self signed certificate using the following command.

openssl req -x509 -newkey rsa:2048 -keyout mykey.key -out mycert.pem -days 365 -nodes

Please fill the information accordingly as shown below.

create self signed certificate using openssl

mykey.key and mycert.pem should be created in your present working directory.

  • It would be nice we if move certificates and keys at a common place and it will be easy for apache2 web server to find them. So let's execute the following commands

sudo cp mycert.pem /etc/ssl/certs

sudo cp mykey.key /etc/ssl/private

  • Let's enable the SSL mode on your server

sudo a2enmod ssl

It should output like this

enable ssl

  • Let's configure apache2 to use self signed certificate and key which we have generated above.

sudo vi /etc/apache2/sites-available/default-ssl.conf

Please find these two lines and replace them with your cert and key paths.

Initial

default-conf

Final

after config changes

  • Enable the site

cd /etc/apache2/sites-available/

sudo a2ensite default-ssl.conf

  • Restart the apache2 service

sudo service apache2 restart

  • Verify the apache2 web-server on HTTPS. Open your browser again and type

https://localhost:443

It should output something like this with a warning that page you are about to view is not secure because we have configured the server with self-signed certificate.

enter image description here

  • Congratulations you have configured your apache2 with HTTPS endpoint , now click on advanced --> add exception --> confirm security exception , you will see the default page again.

page after adding exception

Environment Specific application.properties file in Spring Boot application

we can do like this:

in application.yml:

spring:
  profiles:
    active: test //modify here to switch between environments
    include:  application-${spring.profiles.active}.yml

in application-test.yml:

server:
  port: 5000

and in application-local.yml:

server:
  address: 0.0.0.0
  port: 8080

then spring boot will start our app as we wish to.

Try catch statements in C

Ok, I couldn't resist replying to this. Let me first say I don't think it's a good idea to simulate this in C as it really is a foreign concept to C.

We can use abuse the preprocessor and local stack variables to give use a limited version of C++ try/throw/catch.

Version 1 (local scope throws)

#include <stdbool.h>

#define try bool __HadError=false;
#define catch(x) ExitJmp:if(__HadError)
#define throw(x) __HadError=true;goto ExitJmp;

Version 1 is a local throw only (can't leave the function's scope). It does rely on C99's ability to declare variables in code (it should work in C89 if the try is first thing in the function).

This function just makes a local var so it knows if there was an error and uses a goto to jump to the catch block.

For example:

#include <stdio.h>
#include <stdbool.h>

#define try bool __HadError=false;
#define catch(x) ExitJmp:if(__HadError)
#define throw(x) __HadError=true;goto ExitJmp;

int main(void)
{
    try
    {
        printf("One\n");
        throw();
        printf("Two\n");
    }
    catch(...)
    {
        printf("Error\n");
    }
    return 0;
}

This works out to something like:

int main(void)
{
    bool HadError=false;
    {
        printf("One\n");
        HadError=true;
        goto ExitJmp;
        printf("Two\n");
    }
ExitJmp:
    if(HadError)
    {
        printf("Error\n");
    }
    return 0;
}

Version 2 (scope jumping)

#include <stdbool.h>
#include <setjmp.h>

jmp_buf *g__ActiveBuf;

#define try jmp_buf __LocalJmpBuff;jmp_buf *__OldActiveBuf=g__ActiveBuf;bool __WasThrown=false;g__ActiveBuf=&__LocalJmpBuff;if(setjmp(__LocalJmpBuff)){__WasThrown=true;}else
#define catch(x) g__ActiveBuf=__OldActiveBuf;if(__WasThrown)
#define throw(x) longjmp(*g__ActiveBuf,1);

Version 2 is a lot more complex but basically works the same way. It uses a long jump out of the current function to the try block. The try block then uses an if/else to skip the code block to the catch block which check the local variable to see if it should catch.

The example expanded again:

jmp_buf *g_ActiveBuf;

int main(void)
{
    jmp_buf LocalJmpBuff;
    jmp_buf *OldActiveBuf=g_ActiveBuf;
    bool WasThrown=false;
    g_ActiveBuf=&LocalJmpBuff;

    if(setjmp(LocalJmpBuff))
    {
        WasThrown=true;
    }
    else
    {
        printf("One\n");
        longjmp(*g_ActiveBuf,1);
        printf("Two\n");
    }
    g_ActiveBuf=OldActiveBuf;
    if(WasThrown)
    {
        printf("Error\n");
    }
    return 0;
}

This uses a global pointer so the longjmp() knows what try was last run. We are using abusing the stack so child functions can also have a try/catch block.

Using this code has a number of down sides (but is a fun mental exercise):

  • It will not free allocated memory as there are no deconstructors being called.
  • You can't have more than 1 try/catch in a scope (no nesting)
  • You can't actually throw exceptions or other data like in C++
  • Not thread safe at all
  • You are setting up other programmers for failure because they will likely not notice the hack and try using them like C++ try/catch blocks.

How to reduce the image size without losing quality in PHP

If you are looking to reduce the size using coding itself, you can follow this code in php.

<?php 
function compress($source, $destination, $quality) {

    $info = getimagesize($source);

    if ($info['mime'] == 'image/jpeg') 
        $image = imagecreatefromjpeg($source);

    elseif ($info['mime'] == 'image/gif') 
        $image = imagecreatefromgif($source);

    elseif ($info['mime'] == 'image/png') 
        $image = imagecreatefrompng($source);

    imagejpeg($image, $destination, $quality);

    return $destination;
}

$source_img = 'source.jpg';
$destination_img = 'destination .jpg';

$d = compress($source_img, $destination_img, 90);
?>

$d = compress($source_img, $destination_img, 90);

This is just a php function that passes the source image ( i.e., $source_img ), destination image ( $destination_img ) and quality for the image that will take to compress ( i.e., 90 ).

$info = getimagesize($source);

The getimagesize() function is used to find the size of any given image file and return the dimensions along with the file type.

Swift's guard keyword

Unlike if, guard creates the variable that can be accessed from outside its block. It is useful to unwrap a lot of Optionals.

Should each and every table have a primary key?

It is a good practice to have a PK on every table, but it's not a MUST. Most probably you will need a unique index, and/or a clustered index (which is PK or not) depending on your need.

Check out the Primary Keys and Clustered Indexes sections on Books Online (for SQL Server)

"PRIMARY KEY constraints identify the column or set of columns that have values that uniquely identify a row in a table. No two rows in a table can have the same primary key value. You cannot enter NULL for any column in a primary key. We recommend using a small, integer column as a primary key. Each table should have a primary key. A column or combination of columns that qualify as a primary key value is referred to as a candidate key."

But then check this out also: http://www.aisintl.com/case/primary_and_foreign_key.html

Flutter - Layout a Grid

Use whichever suits your need.

  1. GridView.count(...)

    GridView.count(
      crossAxisCount: 2,
      children: <Widget>[
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
      ],
    )
    
  2. GridView.builder(...)

    GridView.builder(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
      itemBuilder: (_, index) => FlutterLogo(),
      itemCount: 4,
    )
    
  3. GridView(...)

    GridView(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
      children: <Widget>[
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
      ],
    )
    
  4. GridView.custom(...)

    GridView.custom(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
      childrenDelegate: SliverChildListDelegate(
        [
          FlutterLogo(),
          FlutterLogo(),
          FlutterLogo(),
          FlutterLogo(),
        ],
      ),
    )
    
  5. GridView.extent(...)

    GridView.extent(
      maxCrossAxisExtent: 400,
      children: <Widget>[
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
      ],
    )
    

Output (same for all):

enter image description here

What is an application binary interface (ABI)?

The term ABI is used to refer to two distinct but related concepts.

When talking about compilers it refers to the rules used to translate from source-level constructs to binary constructs. How big are the data types? how does the stack work? how do I pass parameters to functions? which registers should be saved by the caller vs the callee?

When talking about libraries it refers to the binary interface presented by a compiled library. This interface is the result of a number of factors including the source code of the library, the rules used by the compiler and in some cases definitions picked up from other libraries.

Changes to a library can break the ABI without breaking the API. Consider for example a library with an interface like.

void initfoo(FOO * foo)
int usefoo(FOO * foo, int bar)
void cleanupfoo(FOO * foo)

and the application programmer writes code like

int dostuffwithfoo(int bar) {
  FOO foo;
  initfoo(&foo);
  int result = usefoo(&foo,bar)
  cleanupfoo(&foo);
  return result;
}

The application programmer doesn't care about the size or layout of FOO, but the application binary ends up with a hardcoded size of foo. If the library programmer adds an extra field to foo and someone uses the new library binary with the old application binary then the library may make out of bounds memory accesses.

OTOH if the library author had designed their API like.

FOO * newfoo(void)
int usefoo(FOO * foo, int bar)
void deletefoo((FOO * foo, int bar))

and the application programmer writes code like

int dostuffwithfoo(int bar) {
  FOO * foo;
  foo = newfoo();
  int result = usefoo(foo,bar)
  deletefoo(foo);
  return result;
}

Then the application binary does not need to know anything about the structure of FOO, that can all be hidden inside the library. The price you pay for that though is that heap operations are involved.

First letter capitalization for EditText

To capitalize, you can do the following with edit text:

To make first letter capital of every word:

android:inputType="textCapWords"

To make first letter capital of every sentence:

android:inputType="textCapSentences"

To make every letter capital:

android:inputType="textCapCharacters"

But this will only make changes to keyboard and user can change the mode to write letter in small case.

So this approach is not much appreciated if you really want the data in capitalize format, add following class first:

public class CapitalizeFirstLetter {
    public static String capitaliseName(String name) {
        String collect[] = name.split(" ");
        String returnName = "";
        for (int i = 0; i < collect.length; i++) {
            collect[i] = collect[i].trim().toLowerCase();
            if (collect[i].isEmpty() == false) {
                returnName = returnName + collect[i].substring(0, 1).toUpperCase() + collect[i].substring(1) + " ";
            }
        }
        return returnName.trim();
    }
    public static String capitaliseOnlyFirstLetter(String data)
    {
        return data.substring(0,1).toUpperCase()+data.substring(1);
    }
}

And then,

Now to capitalize every word:

CapitalizeFirstLetter.capitaliseName(name);

To capitalize only first word:

CapitalizeFirstLetter.capitaliseOnlyFirstLetter(data);

How to search if dictionary value contains certain string with Python

Klaus solution has less overhead, on the other hand this one may be more readable

myDict = {'age': ['12'], 'address': ['34 Main Street, 212 First Avenue'],
          'firstName': ['Alan', 'Mary-Ann'], 'lastName': ['Stone', 'Lee']}

def search(myDict, lookup):
    for key, value in myDict.items():
        for v in value:
            if lookup in v:
                return key

search(myDict, 'Mary')

Date Comparison using Java

Date#equals() and Date#after()

If there is a possibility that the hour and minute fields are != 0, you'd have to set them to 0.

I can't forget to mention that using java.util.Date is considered a bad practice, and most of its methods are deprecated. Use java.util.Calendar or JodaTime, if possible.

How to find index of list item in Swift?

Just use firstIndex method.

array.firstIndex(where: { $0 == searchedItem })

How do I change the text size in a label widget, python tkinter

Try passing width=200 as additional paramater when creating the Label.

This should work in creating label with specified width.

If you want to change it later, you can use:

label.config(width=200)

As you want to change the size of font itself you can try:

label.config(font=("Courier", 44))

Less than or equal to

There is no => for if.
Use if %energy% GEQ %m2enc%

See if /? for some other details.

How to get a reversed list view on a list in Java?

You can also do this:

static ArrayList<String> reverseReturn(ArrayList<String> alist)
{
   if(alist==null || alist.isEmpty())
   { 
       return null;
   }

   ArrayList<String> rlist = new ArrayList<>(alist);

   Collections.reverse(rlist);
   return rlist;
}

Java regular expression OR operator

You can just use the pipe on its own:

"string1|string2"

for example:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|string2", "blah"));

Output:

blah, blah, string3

The main reason to use parentheses is to limit the scope of the alternatives:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(1|2)", "blah"));

has the same output. but if you just do this:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|2", "blah"));

you get:

blah, stringblah, string3

because you've said "string1" or "2".

If you don't want to capture that part of the expression use ?::

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(?:1|2)", "blah"));

Rename specific column(s) in pandas

Use the pandas.DataFrame.rename funtion. Check this link for description.

data.rename(columns = {'gdp': 'log(gdp)'}, inplace = True)

If you intend to rename multiple columns then

data.rename(columns = {'gdp': 'log(gdp)', 'cap': 'log(cap)', ..}, inplace = True)

HTML5 Video Autoplay not working correctly

Try autoplay="autoplay" instead of the "true" value. That's the documented way to enable autoplay. That sounds weirdly redundant, I know.

How to force link from iframe to be opened in the parent window

<a target="parent"> will open links in a new tab/window ... <a target="_parent"> will open links in the parent/current window, without opening new tabs/windows. Don't_forget_that_underscore!

How to call Stored Procedure in a View?

You would have to script the View like below. You would essentially write the results of your proc to a table var or temp table, then select into the view.

Edit - If you can change your stored procedure to a Table Value function, it would eliminate the step of selecting to a temp table.

**Edit 2 ** - Comments are correct that a sproc cannot be read into a view like I suggested. Instead, convert your proc to a table-value function as mentioned in other posts and select from that:

create view sampleView
as select field1, field2, ... 
from dbo.MyTableValueFunction

I apologize for the confusion

How do I create a chart with multiple series using different X values for each series?

You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.

catch forEach last iteration

The 2018 ES6+ ANSWER IS:

    const arr = [1, 2, 3];

    arr.forEach((val, key, arr) => {
      if (Object.is(arr.length - 1, key)) {
        // execute last item logic
        console.log(`Last callback call at index ${key} with value ${val}` ); 
      }
    });

Listing only directories using ls in Bash?

A plain list of the current directory, it'd be:

ls -1d */

If you want it sorted and clean:

ls -1d */ | cut -c 1- | rev | cut -c 2- | rev | sort

Remember: capitalized characters have different behavior in the sort

How to add a custom CA Root certificate to the CA Store used by pip in Windows?

I think nt86's solution is the most appropriate because it leverages the underlying Windows infrastructure (certificate store). But it doesn't explain how to install python-certifi-win32 to start with since pip is non functional.

The trick is to use --trustedhost to install python-certifi-win32 and then after that, pip will automatically use the windows certificate store to load the certificate used by the proxy.

So in a nutshell, you should do:

pip install python-certifi-win32 -trustedhost pypi.org

and after that you should be good to go

Random alpha-numeric string in JavaScript?

var randomString = function(length) {
  var str = '';
  var chars ='0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split(
      '');
  var charsLen = chars.length;
  if (!length) {
    length = ~~(Math.random() * charsLen);
  }
  for (var i = 0; i < length; i++) {
    str += chars[~~(Math.random() * charsLen)];
  }
  return str;
};

How to send a PUT/DELETE request in jQuery?

You could use the ajax method:

$.ajax({
    url: '/script.cgi',
    type: 'DELETE',
    success: function(result) {
        // Do something with the result
    }
});

Android Studio: Gradle - build fails -- Execution failed for task ':dexDebug'

If you are also using Dagger or Butterknife you should to add guava as a dependency to your build.gradle main file like classpath :

com.google.guava:guava:20.0

In other hand, if you are having problems with larger heap for the Gradle daemon you can increase adding to your radle file:

 dexOptions {
        javaMaxHeapSize "4g"
    } 

Increase Tomcat memory settings

try setting this

CATALINA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8 
-server -Xms1536m -Xmx1536m
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m 
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"

in {$tomcat-folder}\bin\setenv.sh (create it if necessary).

See http://www.mkyong.com/tomcat/tomcat-javalangoutofmemoryerror-permgen-space/ for more details.

Why can't Visual Studio find my DLL?

To add to Oleg's answer:

I was able to find the DLL at runtime by appending Visual Studio's $(ExecutablePath) to the PATH environment variable in Configuration Properties->Debugging. This macro is exactly what's defined in the Configuration Properties->VC++ Directories->Executable Directories field*, so if you have that setup to point to any DLLs you need, simply adding this to your PATH makes finding the DLLs at runtime easy!

* I actually don't know if the $(ExecutablePath) macro uses the project's Executable Directories setting or the global Property Pages' Executable Directories setting. Since I have all of my libraries that I often use configured through the Property Pages, these directories show up as defaults for any new projects I create.

Difference between const reference and normal parameter

Since none of you mentioned nothing about the const keyword...

The const keyword modifies the type of a type declaration or the type of a function parameter, preventing the value from varying. (Source: MS)

In other words: passing a parameter by reference exposes it to modification by the callee. Using the const keyword prevents the modification.

Add to python path mac os x

Setting the $PYTHONPATH environment variable does not seem to affect the Spyder IDE's iPython terminals on a Mac. However, Spyder's application menu contains a "PYTHONPATH manager." Adding my path here solved my problem. The "PYTHONPATH manager" is also persistent across application restarts.

This is specific to a Mac, because setting the PYTHONPATH environment variable on my Windows PC gives the expected behavior (modules are found) without using the PYTHONPATH manager in Spyder.

Best/Most Comprehensive API for Stocks/Financial Data

Some of the brokerage firms like TDAmeritrade have APIs you can use to get streaming data from their servers:

http://www.tdameritrade.com/tradingtools/partnertools/api_dev.html

Can you delete data from influxdb?

I am adding this commands as reference for altering retention inside of InfluxDB container in kubernetes k8s. wget is used so as container doesn't have curl and influx CLI

wget 'localhost:8086/query?pretty=true' --post-data="db=k8s;q=ALTER RETENTION POLICY \"default\" on \"k8s\" duration 5h shard duration 4h default" -O-

Verification

wget 'localhost:8086/query?pretty=true' --post-data="db=k8s;q=SHOW RETENTION POLICIES" -O-

How to make audio autoplay on chrome

You may simply use (.autoplay = true;) as following (tested on Chrome Desktop):

<audio id="audioID" loop> <source src="path/audio.mp3"  type="audio/mp3"></audio>

<script>
var myaudio = document.getElementById("audioID").autoplay = true;
</script>

If you need to add stop/play buttons:

<button onclick="play()" type="button">playbutton</button>
<button onclick="stop()" type="button">stopbutton</button>

<audio id="audioID" autoplay loop> <source src="path/audio.mp3"  type="audio/mp3"> 
</audio>

<script>
var myaudio = document.getElementById("audioID");

function play() { 
return myaudio.play(); 
};

function stop() {
return myaudio.pause(); 
};
</script>

If you want stop/play to be one single button:

<button onclick="PlayStop()" type="button">button</button>


<audio id="audioID" autoplay loop> <source src="path/audio.mp3"  type="audio/mp3"> 
</audio>

<script>
var myaudio = document.getElementById("audioID");

function PlayStop() { 
return myaudio.paused ? myaudio.play() : myaudio.pause();
};
</script>

If you want to display stop/play on the same button:

<button onclick="PlayStop()" type="button">Play</button>


<audio id="audioID" autoplay loop> <source src="path/audio.mp3"  type="audio/mp3"> 
</audio>

<script>
var myaudio = document.getElementById("audioID");

function PlayStop() { 
if (elem.innerText=="Play") {
    elem.innerText = "Stop";
}
else {
    elem.innerText = "Play";
}
return myaudio.paused ? myaudio.play() : myaudio.pause();
};`
</script>

In some browsers audio may doesn't work correctly, so as a trick try adding iframe before your code:

<iframe src="dummy.mp3" allow="autoplay" id="audio" style="display:none"></iframe>

<button onclick="PlayStop()" type="button">Play</button>


<audio id="audioID" autoplay loop> <source src="path/audio.mp3"  type="audio/mp3"> 
</audio>

<script>
var myaudio = document.getElementById("audioID");

function button() { 
if (elem.innerText=="Play") {
    elem.innerText = "Stop";
}
else {
    elem.innerText = "Play";
}
return myaudio.paused ? myaudio.play() : myaudio.pause();
};
</script>

Changing a specific column name in pandas DataFrame

Since inplace argument is available, you don't need to copy and assign the original data frame back to itself, but do as follows:

df.rename(columns={'two':'new_name'}, inplace=True)

What is tempuri.org?

http://en.wikipedia.org/wiki/Tempuri

tempuri.org is the default namespace URI used by Microsoft development products, like Visual Studio.

Windows Scipy Install: No Lapack/Blas Resources Found

I was also getting same error while installing scikit-fuzzy. I resolved error as follows:

  1. Install Numpy, a whl file
  2. Install Scipy, again a whl file

choose file according to python version like amd64 for python3 and other win32 file for the python27

  1. then pip install --user skfuzzy

I hope, It will work for you

Split text with '\r\n'

This worked for me.

string stringSeparators = "\r\n";
string text = sr.ReadToEnd();
string lines = text.Replace(stringSeparators, "");
lines = lines.Replace("\\r\\n", "\r\n");
Console.WriteLine(lines);

The first replace replaces the \r\n from the text file's new lines, and the second replaces the actual \r\n text that is converted to \\r\\n when the files is read. (When the file is read \ becomes \\).

Selecting a row in DataGridView programmatically

 <GridViewName>.ClearSelection(); ----------------------------------------------------1
 foreach(var item in itemList) -------------------------------------------------------2
 {
    rowHandle =<GridViewName>.LocateByValue("UniqueProperty_Name", item.unique_id );--3
    if (rowHandle != GridControl.InvalidRowHandle)------------------------------------4
    {
        <GridViewName>.SelectRow(rowHandle);------------------------------------ -----5
    }
  }
  1. Clear all previous selection.
  2. Loop through rows needed to be selected in your grid.
  3. Get their row handles from grid (Note here grid is already updated with new rows)
  4. Checking if the row handle is valid or not.
  5. When valid row handle then select it.

Where itemList is list of rows to be selected in the grid view.

CodeIgniter: Unable to connect to your database server using the provided settings Error Message

If you used this to secure your server: http://www.thonky.com/how-to/prevent-base-64-decode-hack/

And then got the error: Code Igniter needs mysql_pconnect() in order to run.

I figured it out once I realized all the Code Igniter websites on the server were broken, so it wasn't a localized connection issue.

How to change color of SVG image using CSS (jQuery SVG image replacement)?

@Drew Baker gave a great solution to solve the problem. The code works properly. However, those who uses AngularJs may find lots of dependency on jQuery. Consequently, I thought it is a good idea to paste for AngularJS users, a code following @Drew Baker's solution.

AngularJs way of the same code

1. Html: use the bellow tag in you html file:

<svg-image src="/icons/my.svg" class="any-class-you-wish"></svg-image>

2. Directive: this will be the directive that you will need to recognise the tag:

'use strict';
angular.module('myApp')
  .directive('svgImage', ['$http', function($http) {
    return {
      restrict: 'E',
      link: function(scope, element) {
        var imgURL = element.attr('src');
        // if you want to use ng-include, then
        // instead of the above line write the bellow:
        // var imgURL = element.attr('ng-include');
        var request = $http.get(
          imgURL,
          {'Content-Type': 'application/xml'}
        );

        scope.manipulateImgNode = function(data, elem){
          var $svg = angular.element(data)[4];
          var imgClass = elem.attr('class');
          if(typeof(imgClass) !== 'undefined') {
            var classes = imgClass.split(' ');
            for(var i = 0; i < classes.length; ++i){
              $svg.classList.add(classes[i]);
            }
          }
          $svg.removeAttribute('xmlns:a');
          return $svg;
        };

        request.success(function(data){
          element.replaceWith(scope.manipulateImgNode(data, element));
        });
      }
    };
  }]);

3. CSS:

.any-class-you-wish{
    border: 1px solid red;
    height: 300px;
    width:  120px
}

4. Unit-test with karma-jasmine:

'use strict';

describe('Directive: svgImage', function() {

  var $rootScope, $compile, element, scope, $httpBackend, apiUrl, data;

  beforeEach(function() {
    module('myApp');

    inject(function($injector) {
      $rootScope = $injector.get('$rootScope');
      $compile = $injector.get('$compile');
      $httpBackend = $injector.get('$httpBackend');
      apiUrl = $injector.get('apiUrl');
    });

    scope = $rootScope.$new();
    element = angular.element('<svg-image src="/icons/icon-man.svg" class="svg"></svg-image>');
    element = $compile(element)(scope);

    spyOn(scope, 'manipulateImgNode').andCallThrough();
    $httpBackend.whenGET(apiUrl + 'me').respond(200, {});

    data = '<?xml version="1.0" encoding="utf-8"?>' +
      '<!-- Generator: Adobe Illustrator 17.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->' +
      '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">' +
      '<!-- Obj -->' +
      '<!-- Obj -->' +
      '<svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"' +
      'width="64px" height="64px" viewBox="0 0 64 64" enable-background="new 0 0 64 64" xml:space="preserve">' +
        '<g>' +
          '<path fill="#F4A902" d=""/>' +
          '<path fill="#F4A902" d=""/>' +
        '</g>' +
      '</svg>';
    $httpBackend.expectGET('/icons/icon-man.svg').respond(200, data);
  });

  afterEach(function() {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  });

  it('should call manipulateImgNode atleast once', function () {
    $httpBackend.flush();
    expect(scope.manipulateImgNode.callCount).toBe(1);
  });

  it('should return correct result', function () {
    $httpBackend.flush();
    var result = scope.manipulateImgNode(data, element);
    expect(result).toBeDefined();
  });

  it('should define classes', function () {
    $httpBackend.flush();
    var result = scope.manipulateImgNode(data, element);
    var classList = ["svg"];
    expect(result.classList[0]).toBe(classList[0]);
  });
});

what is the use of annotations @Id and @GeneratedValue(strategy = GenerationType.IDENTITY)? Why the generationtype is identity?

In a Object Relational Mapping context, every object needs to have a unique identifier. You use the @Id annotation to specify the primary key of an entity.

The @GeneratedValue annotation is used to specify how the primary key should be generated. In your example you are using an Identity strategy which

Indicates that the persistence provider must assign primary keys for the entity using a database identity column.

There are other strategies, you can see more here.

Can I install Python 3.x and 2.x on the same Windows computer?

Easy-peasy ,after installing both the python versions add the paths to the environment variables ;seeenvironment variable settings. Then go to python 2 and python 3 folders and rename them to python2 and python3 respectively as shown here for python2 and here for python3. Now in cmd type python2 or python3 to use your required version see here.

How to fix libeay32.dll was not found error

Please check if the dll in application is of the same version as that in the sys32 or wow64 folder depending on your version of windows.

You can check that from the filesize of the dlls.

Eg: I faced this issue because my libeay32.dll and ssleay32.dll file in system32 had a different dll than my libeay32.dll and ssleay32.dll file in openssl application.

I copied the one in sys32 into openssl and everything worked well.

Find size of an array in Perl

All three give the same result if we modify the second one a bit:

my @arr = (2, 4, 8, 10);

print "First result:\n";
print scalar @arr; 

print "\n\nSecond result:\n";
print $#arr + 1; # Shift numeration with +1 as it shows last index that starts with 0.

print "\n\nThird result:\n";
my $arrSize = @arr;
print $arrSize;

JPA: how do I persist a String into a database field, type MYSQL Text

With @Lob I always end up with a LONGTEXTin MySQL.

To get TEXT I declare it that way (JPA 2.0):

@Column(columnDefinition = "TEXT")
private String text

Find this better, because I can directly choose which Text-Type the column will have in database.

For columnDefinition it is also good to read this.

EDIT: Please pay attention to Adam Siemions comment and check the database engine you are using, before applying columnDefinition = "TEXT".

File URL "Not allowed to load local resource" in the Internet Browser

Follow the below steps,

  1. npm install -g http-server, install the http-server in angular project.
  2. Go to file location which needs to be accessed and open cmd prompt, use cmd http-server ./
  3. Access any of the paths with port number in browser(ex: 120.0.0.1:8080) 4.now in your angular application use the path "http://120.0.0.1:8080/filename" Worked fine for me

Interview Question: Merge two sorted singly linked lists without creating new nodes

Here is a complete working example that uses the linked list implemented java.util. You can just copy paste the code below inside a main() method.

        LinkedList<Integer> dList1 = new LinkedList<Integer>();
        LinkedList<Integer> dList2 = new LinkedList<Integer>();
        LinkedList<Integer> dListMerged = new LinkedList<Integer>();

        dList1.addLast(1);
        dList1.addLast(8);
        dList1.addLast(12);
        dList1.addLast(15);
        dList1.addLast(85);

        dList2.addLast(2);
        dList2.addLast(3);
        dList2.addLast(12);
        dList2.addLast(24);
        dList2.addLast(85);
        dList2.addLast(185);

        int i = 0;
        int y = 0;
        int dList1Size = dList1.size();
        int dList2Size = dList2.size();
        int list1Item = dList1.get(i);
        int list2Item = dList2.get(y);
        while (i < dList1Size || y < dList2Size) {

            if (i < dList1Size) {

                if (list1Item <= list2Item || y >= dList2Size) {
                    dListMerged.addLast(list1Item);
                    i++;
                    if (i < dList1Size) {
                        list1Item = dList1.get(i);
                    }
                }
            }


            if (y < dList2Size) {

                if (list2Item <= list1Item || i >= dList1Size) {
                    dListMerged.addLast(list2Item);
                    y++;
                    if (y < dList2Size) {
                        list2Item = dList2.get(y);
                    }
                }
            }

        }

        for(int x:dListMerged)
        {
            System.out.println(x);
        }

Exporting to .xlsx using Microsoft.Office.Interop.Excel SaveAs Error

This is how you save the relevant file as a Excel12 (.xlsx) file... It is not as you would intuitively think i.e. using Excel.XlFileFormat.xlExcel12 but Excel.XlFileFormat.xlOpenXMLWorkbook. The actual C# command was

excelWorkbook.SaveAs(strFullFilePathNoExt, Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value,
    Missing.Value, false, false, Excel.XlSaveAsAccessMode.xlNoChange, 
    Excel.XlSaveConflictResolution.xlUserResolution, true, 
    Missing.Value, Missing.Value, Missing.Value);

I hope this helps someone else in the future.


Missing.Value is found in the System.Reflection namespace.

How do I change the UUID of a virtual disk?

Same solution as @Al3x for Windows x64, in cmd.exe:

cd %programfiles%\Oracle\VirtualBox

VBoxManage internalcommands sethduuid "full/path/to/.vdi"

This randomizes the UUID of the disk. Pro tip: Right click the .vdi file while holding shift and select "Copy as path" to obtain "full/path/to/.vdi" and enable quick edit in cmd.exe, then right click to paste.

How to change column width in DataGridView?

In my Visual Studio 2019 it worked only after I set the AutoSizeColumnsMode property to None.

Can a background image be larger than the div itself?

No, you can't.

But as a solid workaround, I would suggest to classify that first div as position:relative and use div::before to create an underlying element containing your image. Classified as position:absolute you can move it anywhere relative to your initial div.

Don't forget to add content to that new element. Here's some example:

div {
  position: relative;
}    

div::before {
  content: ""; /* empty but necessary */
  position: absolute;
  background: ...
}

Note: if you want it to be 'on top' of the parent div, use div::after instead.

Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"

I've faced this error, That was because the value you want to filter in the _id field is not in an ID format, one "if" should solve your error.

const mongoose = require('mongoose');

console.log(mongoose.Types.ObjectId.isValid('53cb6b9b4f4ddef1ad47f943'));
// true
console.log(mongoose.Types.ObjectId.isValid('whatever'));
// false

To solve it, always validate if the criteria value for search is a valid ObjectId

const criteria = {};
criteria.$or = [];

if(params.q) {
  if(mongoose.Types.ObjectId.isValid(params.id)) {
    criteria.$or.push({ _id: params.q })
  }
  criteria.$or.push({ name: { $regex: params.q, $options: 'i' }})
  criteria.$or.push({ email: { $regex: params.q, $options: 'i' }})
  criteria.$or.push({ password: { $regex: params.q, $options: 'i' }})
}

return UserModule.find(criteria).exec(() => {
  // do stuff
})

How to insert a row in an HTML table body in JavaScript

Basic approach:

This should add HTML-formatted content and show the newly added row.

var myHtmlContent = "<h3>hello</h3>"
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];

var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.innerHTML = myHtmlContent;

How to sort a data frame by alphabetic order of a character variable in R?

The order() function fails when the column has levels or factor. It works properly when stringsAsFactors=FALSE is used in data.frame creation.

Regular Expression for matching parentheses

The solution consists in a regex pattern matching open and closing parenthesis

String str = "Your(String)";
// parameter inside split method is the pattern that matches opened and closed parenthesis, 
// that means all characters inside "[ ]" escaping parenthesis with "\\" -> "[\\(\\)]"
String[] parts = str.split("[\\(\\)]");
for (String part : parts) {
   // I print first "Your", in the second round trip "String"
   System.out.println(part);
}

Writing in Java 8's style, this can be solved in this way:

Arrays.asList("Your(String)".split("[\\(\\)]"))
    .forEach(System.out::println);

I hope it is clear.

Aligning label and textbox on same line (left and right)

You should use CSS to align the textbox. The reason your code above does not work is because by default a div's width is the same as the container it's in, therefore in your example it is pushed below.

The following would work.

<td  colspan="2" class="cell">
                <asp:Label ID="Label6" runat="server" Text="Label"></asp:Label>        
                <asp:TextBox ID="TextBox3" runat="server" CssClass="righttextbox"></asp:TextBox>       
</td>

In your CSS file:

.cell
{
text-align:left;
}

.righttextbox
{
float:right;
}

Instance member cannot be used on type

Another example is, you have class like :

@obc class Album: NSObject {
    let name:String
    let singer:Singer
    let artwork:URL
    let playingSong:Song


    // ...

    class func getCurrentlyPlayingSongLyric(duration: Int = 0) -> String {
        // ...
       return playingSong.lyric
    }
}

you will also get the same type of error like :

instance member x cannot be used on type x. 

It's because you assign your method with "class" keyword (which makes your method a type method) and using like :

Album.getCurrentlyPlayingSongLyric(duration: 5)

but who set the playingSong variable before? Ok. You shouldn't use class keyword for that case :

 // ...

 func getCurrentlyPlayingSongLyric(duration: Int = 0) -> String {
        // ...
       return playingSong.lyric
 }

 // ...

Now you're free to go.

How do I redirect to the previous action in ASP.NET MVC?

In Mvc using plain html in View Page with java script onclick

<input type="button" value="GO BACK" class="btn btn-primary" 
onclick="location.href='@Request.UrlReferrer'" />

This works great. hope helps someone.

@JuanPieterse has already answered using @Html.ActionLink so if possible someone can comment or answer using @Url.Action

How to check if a string is numeric?

If you are allowed to use third party libraries, suggest the following.

https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/math/NumberUtils.html

NumberUtils.isDigits(str:String):boolean
NumberUtils.isNumber(str:String):boolean

How to prevent tensorflow from allocating the totality of a GPU memory?

config = tf.ConfigProto()
config.gpu_options.allow_growth=True
sess = tf.Session(config=config)

https://github.com/tensorflow/tensorflow/issues/1578

Display more Text in fullcalendar

With the modification of a single line you could alter the fullcalendar.js script to allow a line break and put multiple information on the same line.

In FullCalendar.js on line ~3922 find htmlEscape(s) function and add .replace(/<br\s?/?>/g, '
') to the end of it.

function htmlEscape(s) {
    return s.replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/'/g, '&#039;')
    .replace(/"/g, '&quot;')
    .replace(/\n/g, '<br />')
    .replace(/&lt;br\s?\/?&gt;/g, '<br />');
}

This will allow you to have multiple lines for the title, separating the information. Example replace the event.title with title: 'All Day Event' + '<br />' + 'Other Description'

Trim a string in C

Not the best way but it works

char* Trim(char* str)
{
    int len = strlen(str);
    char* buff = new char[len];
    int i = 0;
    memset(buff,0,len*sizeof(char));
    do{
        if(isspace(*str)) continue;
        buff[i] = *str; ++i;
    } while(*(++str) != '\0');
    return buff;
}

How to run batch file from network share without "UNC path are not supported" message?

Instead of launching the batch directly from explorer - create a shortcut to the batch and set the starting directory in the properties of the shortcut to a local path like %TEMP% or something.

To delete the symbolic link, use the rmdir command.

fork() and wait() with two child processes

It looks to me as though the basic problem is that you have one wait() call rather than a loop that waits until there are no more children. You also only wait if the last fork() is successful rather than if at least one fork() is successful.

You should only use _exit() if you don't want normal cleanup operations - such as flushing open file streams including stdout. There are occasions to use _exit(); this is not one of them. (In this example, you could also, of course, simply have the children return instead of calling exit() directly because returning from main() is equivalent to exiting with the returned status. However, most often you would be doing the forking and so on in a function other than main(), and then exit() is often appropriate.)


Hacked, simplified version of your code that gives the diagnostics I'd want. Note that your for loop skipped the first element of the array (mine doesn't).

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

int main(void)
{
    pid_t child_pid, wpid;
    int status = 0;
    int i;
    int a[3] = {1, 2, 1};

    printf("parent_pid = %d\n", getpid());
    for (i = 0; i < 3; i++)
    {
        printf("i = %d\n", i);
        if ((child_pid = fork()) == 0)
        {
            printf("In child process (pid = %d)\n", getpid());
            if (a[i] < 2)
            {
                printf("Should be accept\n");
                exit(1);
            }
            else
            {
                printf("Should be reject\n");
                exit(0);
            }
            /*NOTREACHED*/
        }
    }

    while ((wpid = wait(&status)) > 0)
    {
        printf("Exit status of %d was %d (%s)\n", (int)wpid, status,
               (status > 0) ? "accept" : "reject");
    }
    return 0;
}

Example output (MacOS X 10.6.3):

parent_pid = 15820
i = 0
i = 1
In child process (pid = 15821)
Should be accept
i = 2
In child process (pid = 15822)
Should be reject
In child process (pid = 15823)
Should be accept
Exit status of 15823 was 256 (accept)
Exit status of 15822 was 0 (reject)
Exit status of 15821 was 256 (accept)

Performing a query on a result from another query?

Note that your initial query is probably not returning what you want:

SELECT availables.bookdate AS Date, DATEDIFF(now(),availables.updated_at) as Age 
FROM availables INNER JOIN rooms ON availables.room_id=rooms.id 
WHERE availables.bookdate BETWEEN  '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094 GROUP BY availables.bookdate

You are grouping by book date, but you are not using any grouping function on the second column of your query.

The query you are probably looking for is:

SELECT availables.bookdate AS Date, count(*) as subtotal, sum(DATEDIFF(now(),availables.updated_at) as Age)
FROM availables INNER JOIN rooms ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
GROUP BY availables.bookdate

Remove a folder from git tracking

I know this is an old thread but I just wanted to add a little as the marked solution didn't solve the problem for me (although I tried many times).

The only way I could actually stop git form tracking the folder was to do the following:

  1. Make a backup of the local folder and put in a safe place.
  2. Delete the folder from your local repo
  3. Make sure cache is cleared git rm -r --cached your_folder/
  4. Add your_folder/ to .gitignore
  5. Commit changes
  6. Add the backup back into your repo

You should now see that the folder is no longer tracked.

Don't ask me why just clearing the cache didn't work for me, I am not a Git super wizard but this is how I solved the issue.

Modify the legend of pandas bar plot

To change the labels for Pandas df.plot() use ax.legend([...]):

import pandas as pd
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
df.plot(kind='bar', ax=ax)
#ax = df.plot(kind='bar') # "same" as above
ax.legend(["AAA", "BBB"]);

enter image description here

Another approach is to do the same by plt.legend([...]):

import matplotlib.pyplot as plt
df.plot(kind='bar')
plt.legend(["AAA", "BBB"]);

enter image description here

Remove HTML Tags from an NSString on the iPhone

Take a look at NSXMLParser. It's a SAX-style parser. You should be able to use it to detect tags or other unwanted elements in the XML document and ignore them, capturing only pure text.

Replace a string in shell script using a variable

Not related to question but in case if someone is passing the string as an argument to bash script this might help.

Use:

./bash_script.sh "path\to\file"

Instead of:

./bash_script.sh path\to\file

For your reference.

Difference between UTF-8 and UTF-16?

Simple way to differentiate UTF-8 and UTF-16 is to identify commonalities between them.

Other than sharing same unicode number for given character, each one is their own format.

UTF-8 try to represent, every unicode number given to character with one byte(If it is ASCII), else 2 two bytes, else 4 bytes and so on...

UTF-16 try to represent, every unicode number given to character with two byte to start with. If two bytes are not sufficient, then uses 4 bytes. IF that is also not sufficient, then uses 6 bytes.

Theoretically, UTF-16 is more space efficient, but in practical UTF-8 is more space efficient as most of the characters(98% of data) for processing are ASCII and UTF-8 try to represent them with single byte and UTF-16 try to represent them with 2 bytes.

Also, UTF-8 is superset of ASCII encoding. So every app that expects ASCII data would also accepted by UTF-8 processor. This is not true for UTF-16. UTF-16 could not understand ASCII, and this is big hurdle for UTF-16 adoption.

Another point to note is, all UNICODE as of now could be fit in 4 bytes of UTF-8 maximum(Considering all languages of world). This is same as UTF-16 and no real saving in space compared to UTF-8 ( https://stackoverflow.com/a/8505038/3343801 )

So, people use UTF-8 where ever possible.

Coerce multiple columns to factors at once

It appears that the use of SAPPLY on a data.frame to convert variables to factors at once does not work as it produces a matrix/ array. My approach is to use LAPPLY instead, as follows.

## let us create a data.frame here

class <- c("7", "6", "5", "3")

cash <- c(100, 200, 300, 150)

height <- c(170, 180, 150, 165)

people <- data.frame(class, cash, height)

class(people) ## This is a dataframe 

## We now apply lapply to the data.frame as follows.

bb <- lapply(people, as.factor) %>% data.frame() 

## The lapply part returns a list which we coerce back to a data.frame

class(bb) ## A data.frame

##Now let us check the classes of the variables 

class(bb$class)

class(bb$height)

class(bb$cash) ## as expected, are all factors. 

How to run a cron job on every Monday, Wednesday and Friday?

Use this command to add job

crontab -e

In this format:

0 19 * * 1,3,5 /path to your file/file.php

What's wrong with foreign keys?

To me, if you want to go by the ACID standards, it is critical to have foreign keys to ensure referential integrity.

Errors in pom.xml with dependencies (Missing artifact...)

I somehow had this issue after I lost internet connection. I was able to fix it by updating the Maven indexes in Eclipse and then selecting my project and updating the Snapshots/releases.

AngularJS- Login and Authentication in each route and controller

All have suggested big solution why you are worrying of session on client side. I mean when state/url changes I suppose you are doing an ajax call to load the data for tempelate.

Note :- To Save user's data you may use `resolve` feature of `ui-router`.
 Check cookie if it exist load template , if even cookies doesn't exist than 
there is no chance of logged in , simply redirect to login template/page.

Now the ajax data is returned by server using any api. Now the point came into play , return standard return types using server according to logged in status of user. Check those return codes and process your request in controller. Note:- For controller which doesn't require an ajax call natively , you can call a blank request to server like this server.location/api/checkSession.php and this is checkSession.php

<?php/ANY_LANGUAGE
session_start();//You may use your language specific function if required
if(isset($_SESSION["logged_in"])){
set_header("200 OK");//this is not right syntax , it is just to hint
}
else{
set_header("-1 NOT LOGGED_IN");//you may set any code but compare that same       
//code on client side to check if user is logged in or not.
}
//thanks.....

On client side inside controller or through any service as shown in other answers

    $http.get(dataUrl)
    .success(function (data){
        $scope.templateData = data;
    })
    .error(function (error, status){
        $scope.data.error = { message: error, status: status};
        console.log($scope.data.error.status);
if(status == CODE_CONFIGURED_ON_SERVER_SIDE_FOR_NON_LOGGED_IN){
//redirect to login
  });

Note :- I will update more tomorrow or in future

SQLAlchemy insert or update example

I try lots of ways and finally try this:

def db_persist(func):
    def persist(*args, **kwargs):
        func(*args, **kwargs)
        try:
            session.commit()
            logger.info("success calling db func: " + func.__name__)
            return True
        except SQLAlchemyError as e:
            logger.error(e.args)
            session.rollback()
            return False

    return persist

and :

@db_persist
def insert_or_update(table_object):
    return session.merge(table_object)

Using CSS to affect div style inside iframe

A sort of hack-ish way of doing things is like Eugene said. I ended up following his code and linking to my custom Css for the page. The problem for me was that, With a twitter timeline you have to do some sidestepping of twitter to override their code a smidgen. Now we have a rolling timeline with our css to it, I.E. Larger font, proper line height and making the scrollbar hidden for heights larger than their limits.

var c = document.createElement('link');
setTimeout(frames[0].document.body.appendChild(c),500); // Mileage varies by connection. Bump 500 a bit higher if necessary

Search for string and get count in vi editor

:%s/string/string/g will give the answer.

Could not load file or assembly ... An attempt was made to load a program with an incorrect format (System.BadImageFormatException)

In my case the error was System.BadImageFormatException: Could not load file or assembly 'vjslib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies.

It was solved by installing vjredist 64 from here.

Xampp localhost/dashboard

Here's what's actually happening localhost means that you want to open htdocs. First it will search for any file named index.php or index.html. If one of those exist it will open the file. If neither of those exist then it will open all folder/file inside htdocs directory which is what you want.

So, the simplest solution is to rename index.php or index.html to index2.php etc.

MySQL Update Column +1?

update table_name set field1 = field1 + 1;

How to call a function from a string stored in a variable?

Solution: Use PHP7

Note: For a summarized version, see TL;DR at the end of the answer.

Old Methods

Update: One of the old methods explained here has been removed. Refer to other answers for explanation on other methods, it is not covered here. By the way, if this answer doesn't help you, you should return upgrading your stuff. PHP 5.6 support has ended in January 2019 (now even PHP 7.1 and 7.2 are not being supported). See supported versions for more information.

As others mentioned, in PHP5 (and also in newer versions like PHP7) we could use variables as function names, use call_user_func() and call_user_func_array() (which, personally, I hate those functions), etc.

New Methods

As of PHP7, there are new ways introduced:

Note: Everything inside <something> brackets means one or more expressions to form something, e.g. <function_name> means expressions forming a function name.

Dynamic Function Call: Function Name On-the-fly

We can use one or more expressions inside parentheses as the function name in just one go, in the form of:

(<function_name>)(arguments);

For example:

function something(): string
{
    return "something";
}

$bar = "some_thing";

(str_replace("_", "", $bar))(); // something

// Possible, too; but generally, not recommended, because makes your code more complicated
(str_replace("_", "", $bar))()(); 

Note: Although removing the parentheses around str_replace() is not an error, putting parentheses makes code more readable. However, you cannot do that sometimes, e.g. while using . operator. To be consistent, I recommend you to put the parentheses always.

Dynamic Method Call: Method Name On-the-fly

Just like dynamic function calls, we can do the same way with method calls, surrounded by curly braces instead of parentheses (for extra forms, navigate to TL;DR section):

$object->{<method_name>}(arguments);
$object::{<method_name>}(arguments);

See it in an example:

class Foo
{
    public function another(): string
    {
        return "something";
    }
}

$bar = "another thing";

(new Something())->{explode(" ", $bar)[0]}(); // something

Dynamic Method Call: The Array Syntax

A more elegant way added in PHP7 is the following:

[<object>, <method_name>](arguments);
[<class_name>, <method_name>](arguments); // Static calls only

As an example:

class Foo
{
    public function nonStaticCall()
    {
        echo "Non-static call";
    }
    public static function staticCall()
    {
        echo "Static call";
    }
}

$x = new X();

[$x, "non" . "StaticCall"](); // Non-static call
[$x, "static" . "Call"](); // Static call

Note: The benefit of using this method over the previous one is that, you don't care about the call type (i.e. whether it's static or not).

Note: If you care about performance (and micro-optimizations), don't use this method. As I tested, this method is really slower than other methods (more than 10 times).

Extra Example: Using Anonymous Classes

Making things a bit complicated, you could use a combination of anonymous classes and the features above:

$bar = "SomeThing";

echo (new class {
    public function something()
    {
        return 512;
    }
})->{strtolower($bar)}(); // 512

TL;DR (Conclusion)

Generally, in PHP7, using the following forms are all possible:

// Everything inside `<something>` brackets means one or more expressions
// to form something

// Dynamic function call
(<function_name>)(arguments)

// Dynamic method call on an object
$object->{<method_name>}(arguments)
$object::{<method_name>}(arguments)

// Dynamic method call on a dynamically-generated object
(<object>)->{<method_name>}(arguments)
(<object>)::{<method_name>}(arguments)

// Dynamic method call, statically
ClassName::{<method_name>}(arguments)
(<class_name>)::{<method_name>}(arguments)

// Dynamic method call, array-like (no different between static and non-static calls
[<object>, <method_name>](arguments)

// Dynamic method call, array-like, statically
[<class_name>, <method_name>](arguments)

Special thanks to this PHP talk.

AngularJs ReferenceError: $http is not defined

I have gone through the same problem when I was using

    myApp.controller('mainController', ['$scope', function($scope,) {
        //$http was not working in this
    }]);

I have changed the above code to given below. Remember to include $http(2 times) as given below.

 myApp.controller('mainController', ['$scope','$http', function($scope,$http) {
      //$http is working in this
 }]);

and It has worked well.

How to open the terminal in Atom?

I didn't want to install a package just for that purpose so I ended up using this in my init.coffee:

spawn = require('child_process').spawn
atom.commands.add 'atom-text-editor', 'open-terminal', ->
  file = atom.workspace.getActiveTextEditor().getPath()
  dir = atom.project.getDirectoryForProjectPath(file).path
  spawn 'mate-terminal', ["--working-directory=#{dir}"], {
    detached: true
  }

With that, I could map ctrl-shift-t to the open-terminal command and it opens a mate-terminal.

PHP Accessing Parent Class Variable

Just echo it since it's inherited

echo $this->bb;

Set height of chart in Chart.js

You can wrap your canvas element in a parent div, relatively positioned, then give that div the height you want, setting maintainAspectRatio: false in your options

//HTML
<div id="canvasWrapper" style="position: relative; height: 80vh/500px/whatever">
<canvas id="chart"></canvas>
</div>

<script>
new Chart(somechart, {
options: {
    responsive: true,
    maintainAspectRatio: false

/*, your other options*/

}
});
</script>

How to use Ajax.ActionLink?

Sure, a very similar question was asked before. Set the controller for ajax requests:

public ActionResult Show()
{
    if (Request.IsAjaxRequest()) 
    {
        return PartialView("Your_partial_view", new Model());
    }
    else 
    {
        return View();
    }
}

Set the action link as wanted:

@Ajax.ActionLink("Show", 
                 "Show", 
                 null, 
                 new AjaxOptions { HttpMethod = "GET", 
                 InsertionMode = InsertionMode.Replace, 
                 UpdateTargetId = "dialog_window_id", 
                 OnComplete = "your_js_function();" })

Note that I'm using Razor view engine, and that your AjaxOptions may vary depending on what you want. Finally display it on a modal window. The jQuery UI dialog is suggested.

Chrome Fullscreen API

The API only works during user interaction, so it cannot be used maliciously. Try the following code:

addEventListener("click", function() {
    var el = document.documentElement,
      rfs = el.requestFullscreen
        || el.webkitRequestFullScreen
        || el.mozRequestFullScreen
        || el.msRequestFullscreen 
    ;

    rfs.call(el);
});

Javascript Debugging line by line using Google Chrome

...How can I step through my javascript code line by line using Google Chromes developer tools without it going into javascript libraries?...


For the record: At this time (Feb/2015) both Google Chrome and Firefox have exactly what you (and I) need to avoid going inside libraries and scripts, and go beyond the code that we are interested, It's called Black Boxing:

enter image description here

When you blackbox a source file, the debugger will not jump into that file when stepping through code you're debugging.

More info:

Conversion failed when converting the varchar value 'simple, ' to data type int

Given that you're only converting to ints to then perform a comparison, I'd just switch the table definition around to using varchar also:

Create table #myTempTable
(
num varchar(12)
)
insert into #myTempTable (num) values (1),(2),(3),(4),(5)

and remove all of the attempted CONVERTs from the rest of the query.

 SELECT a.name, a.value AS value, COUNT(*) AS pocet   
 FROM 
 (SELECT item.name, value.value 
  FROM mdl_feedback AS feedback 
  INNER JOIN mdl_feedback_item AS item 
       ON feedback.id = item.feedback
  INNER JOIN mdl_feedback_value AS value 
       ON item.id = value.item 
   WHERE item.typ = 'multichoicerated' AND item.feedback IN (43)
 ) AS a 
 INNER JOIN #myTempTable 
     on a.value = #myTempTable.num
 GROUP BY a.name, a.value ORDER BY a.name

How to print jquery object/array

_x000D_
_x000D_
var arrofobject = [{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}];_x000D_
var data = arrofobject.map(arrofobject => arrofobject);_x000D_
console.log(data)
_x000D_
_x000D_
_x000D_

for more details please look at jQuery.map()

type checking in javascript

These days, ECMAScript 6 (ECMA-262) is "in the house". Use Number.isInteger(x) to ask the question you want to ask with respect to the type of x:

js> var x = 3
js> Number.isInteger(x)
true
js> var y = 3.1
js> Number.isInteger(y)
false

Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

 extension UITextField {  
  func setBottomBorder(color:String) {
    self.borderStyle = UITextBorderStyle.None
    let border = CALayer()
    let width = CGFloat(1.0)
    border.borderColor = UIColor(hexString: color)!.cgColor
    border.frame = CGRect(x: 0, y: self.frame.size.height - width,   width:  self.frame.size.width, height: self.frame.size.height)
    border.borderWidth = width
    self.layer.addSublayer(border)
    self.layer.masksToBounds = true
   }
}

and then just do this:

yourTextField.setBottomBorder(color: "#3EFE46")

How do I see if Wi-Fi is connected on Android?

You should be able to use the ConnectivityManager to get the state of the Wi-Fi adapter. From there you can check if it is connected or even available.

ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

if (mWifi.isConnected()) {
    // Do whatever
}

NOTE: It should be noted (for us n00bies here) that you need to add

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

to your

AndroidManifest.xml for this to work.

NOTE2: public NetworkInfo getNetworkInfo (int networkType) is now deprecated:

This method was deprecated in API level 23. This method does not support multiple connected networks of the same type. Use getAllNetworks() and getNetworkInfo(android.net.Network) instead.

NOTE3: public static final int TYPE_WIFI is now deprecated:

This constant was deprecated in API level 28. Applications should instead use NetworkCapabilities.hasTransport(int) or requestNetwork(NetworkRequest, NetworkCallback) to request an appropriate network. for supported transports.

how to hide <li> bullets in navigation menu and footer links BUT show them for listing items

The example bellow explains how to remove bullets using a css style class. You can use , similar to css class, by identifier (#id), by parent tag, etc. The same way you can use to define a css to remove bullets from the page footer.

I've used this site as a starting point.

<html>
<head>
<style type="text/css">
div.ui-menu li {
    list-style:none;
    background-image:none;
    background-repeat:none;
    background-position:0; 
}
ul
{
    list-style-type:none;
    padding:0px;
    margin:0px;
}
li
{
    background-image:url(sqpurple.gif);
    background-repeat:no-repeat;
    background-position:0px 5px; 
    padding-left:14px;
}
</style>
</head>

<body>

<div class="ui-menu">
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ul>
</div>

<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ul>
</body>

</html>

UnicodeEncodeError: 'latin-1' codec can't encode character

Use the below snippet to convert the text from Latin to English

import unicodedata
def strip_accents(text):
    return "".join(char for char in
                   unicodedata.normalize('NFKD', text)
                   if unicodedata.category(char) != 'Mn')

strip_accents('áéíñóúü')

output:

'aeinouu'

How to subtract days from a plain Date?

get moment.js. All the cool kids use it. It has more formatting options, etc. Where

var n = 5;
var dateMnsFive = moment(<your date>).subtract(n , 'day');

Optional! Convert to JS Date obj for Angular binding.

var date = new Date(dateMnsFive.toISOString());

Optional! Format

var date = dateMnsFive.format("YYYY-MM-DD");

javascript how to create a validation error message without using alert

JavaScript

<script language="javascript">
        var flag=0;
        function username()
        {
            user=loginform.username.value;
            if(user=="")
            {
                document.getElementById("error0").innerHTML="Enter UserID";
                flag=1;
            }
        }   
        function password()
        {
            pass=loginform.password.value;
            if(pass=="")
            {
                document.getElementById("error1").innerHTML="Enter password";   
                flag=1;
            }
        }

        function check(form)
        {
            flag=0;
            username();
            password();
            if(flag==1)
                return false;
            else
                return true;
        }

    </script>

HTML

<form name="loginform" action="Login" method="post" class="form-signin" onSubmit="return check(this)">



                    <div id="error0"></div>
                    <input type="text" id="inputEmail" name="username" placeholder="UserID" onBlur="username()">
               controls">
                    <div id="error1"></div>
                    <input type="password" id="inputPassword" name="password" placeholder="Password" onBlur="password()" onclick="make_blank()">

                    <button type="submit" class="btn">Sign in</button>
                </div>
            </div>
        </form>

Using the HTML5 "required" attribute for a group of checkboxes?

Inspired by the answers from @thegauraw and @Brian Woodward, here's a bit I pulled together for JQuery users, including a custom validation error message:

$cbx_group = $("input:checkbox[name^='group']");
$cbx_group.on("click", function() {
    if ($cbx_group.is(":checked")) {
        // checkboxes become unrequired as long as one is checked
        $cbx_group.prop("required", false).each(function() {
            this.setCustomValidity("");
        });
    } else {
        // require checkboxes and set custom validation error message
        $cbx_group.prop("required", true).each(function() {
            this.setCustomValidity("Please select at least one checkbox.");
        });
    }
});

Note that my form has some checkboxes checked by default.

Maybe some of you JavaScript/JQuery wizards could tighten that up even more?

How do I find an element that contains specific text in Selenium WebDriver (Python)?

Try this. It's very easy:

driver.getPageSource().contains("text to search");

This really worked for me in Selenium WebDriver.

Thymeleaf: how to use conditionals to dynamically add/remove a CSS class

What @Nilsi mentioned is perfectly correct. However, adminclass and user class need to be wrapped in single quotes as this might fail due to Thymeleaf looking for adminClass or userclass variables which should be strings. That said,

it should be: -

 <a href="" class="baseclass" th:classappend="${isAdmin} ? 'adminclass' : 
 'userclass'"> 
 </a>

or just:

<a href="" th:class="${isAdmin} ? 'newclass' : 
  'baseclass'"> 
 </a>

Save PL/pgSQL output from PostgreSQL to a CSV file

I tried several things but few of them were able to give me the desired CSV with header details.

Here is what worked for me.

psql -d dbame -U username \
  -c "COPY ( SELECT * FROM TABLE ) TO STDOUT WITH CSV HEADER " > \
  OUTPUT_CSV_FILE.csv

How do I use a pipe to redirect the output of one command to the input of another?

This should work:

for /F "tokens=*" %i in ('temperature') do prismcom.exe usb %i

If running in a batch file, you need to use %%i instead of just %i (in both places).

How do I split a string, breaking at a particular character?

If Spliter is found then only

Split it

else return the same string

function SplitTheString(ResultStr) {
    if (ResultStr != null) {
        var SplitChars = '~';
        if (ResultStr.indexOf(SplitChars) >= 0) {
            var DtlStr = ResultStr.split(SplitChars);
            var name  = DtlStr[0];
            var street = DtlStr[1];
        }
    }
}

Converting data frame column from character to numeric

If we need only one column to be numeric

yyz$b <- as.numeric(as.character(yyz$b))

But, if all the columns needs to changed to numeric, use lapply to loop over the columns and convert to numeric by first converting it to character class as the columns were factor.

yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))

Both the columns in the OP's post are factor because of the string "n/a". This could be easily avoided while reading the file using na.strings = "n/a" in the read.table/read.csv or if we are using data.frame, we can have character columns with stringsAsFactors=FALSE (the default is stringsAsFactors=TRUE)


Regarding the usage of apply, it converts the dataset to matrix and matrix can hold only a single class. To check the class, we need

lapply(yyz, class)

Or

sapply(yyz, class)

Or check

str(yyz)

How do I sort strings alphabetically while accounting for value when a string is numeric?

You say you cannot convert the numbers into int because the array can contain elements that cannot be converted to int, but there is no harm in trying:

string[] things = new string[] { "105", "101", "102", "103", "90", "paul", "bob", "lauren", "007", "90" };
Array.Sort(things, CompareThings);

foreach (var thing in things)
    Debug.WriteLine(thing);

Then compare like this:

private static int CompareThings(string x, string y)
{
    int intX, intY;
    if (int.TryParse(x, out intX) && int.TryParse(y, out intY))
        return intX.CompareTo(intY);

    return x.CompareTo(y);
}

Output: 007, 90, 90, 101, 102, 103, 105, bob, lauren, paul

How to delete all instances of a character in a string in python?

Strings are immutable in Python, which means once a string is created, you cannot alter the contents of the strings. If at all, you need to change it, a new instance of the string will be created with the alterations.

Having that in mind, we have so many ways to solve this

  1. Using str.replace,

    >>> "it is icy".replace("i", "")
    't s cy'
    
  2. Using str.translate,

    >>> "it is icy".translate(None, "i")
    't s cy'
    
  3. Using Regular Expression,

    >>> import re
    >>> re.sub(r'i', "", "it is icy")
    't s cy'
    
  4. Using comprehension as a filter,

    >>> "".join([char for char in "it is icy" if char != "i"])
    't s cy'
    
  5. Using filter function

    >>> "".join(filter(lambda char: char != "i", "it is icy"))
    't s cy'
    

Timing comparison

def findreplace(m_string, char):
    m_string = list(m_string)
    for k in m_string:
        if k == char:
            del(m_string[m_string.index(k)])
    return "".join(m_string)

def replace(m_string, char):
    return m_string.replace("i", "")

def translate(m_string, char):
    return m_string.translate(None, "i")

from timeit import timeit

print timeit("findreplace('it is icy','i')", "from __main__ import findreplace")
print timeit("replace('it is icy','i')", "from __main__ import replace")
print timeit("translate('it is icy','i')", "from __main__ import translate")

Result

1.64474582672
0.29278588295
0.311302900314

str.replace and str.translate methods are 8 and 5 times faster than the accepted answer.

Note: Comprehension method and filter methods are expected to be slower, for this case, since they have to create list and then they have to be traversed again to construct a string. And re is a bit overkill for a single character replacement. So, they all are excluded from the timing comparison.

Maven: add a folder or jar file into current classpath

From docs and example it is not clear that classpath manipulation is not allowed.

<configuration>
 <compilerArgs>
  <arg>classpath=${basedir}/lib/bad.jar</arg>
 </compilerArgs>
</configuration>

But see Java docs (also https://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/tooldocs/solaris/javac.html)

-classpath path Specifies the path javac uses to look up classes needed to run javac or being referenced by other classes you are compiling. Overrides the default or the CLASSPATH environment variable if it is set.

Maybe it is possible to get current classpath and extend it,
see in maven, how output the classpath being used?

    <properties>
      <cpfile>cp.txt</cpfile>
    </properties>

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>2.9</version>
    <executions>
      <execution>
        <id>build-classpath</id>
        <phase>generate-sources</phase>
        <goals>
          <goal>build-classpath</goal>
        </goals>
        <configuration>
          <outputFile>${cpfile}</outputFile>
        </configuration>
      </execution>
    </executions>
  </plugin>

Read file (Read a file into a Maven property)

<plugin>
  <groupId>org.codehaus.gmaven</groupId>
  <artifactId>gmaven-plugin</artifactId>
  <version>1.4</version>
  <executions>
    <execution>
      <phase>generate-resources</phase>
      <goals>
        <goal>execute</goal>
      </goals>
      <configuration>
        <source>
          def file = new File(project.properties.cpfile)
          project.properties.cp = file.getText()
        </source>
      </configuration>
    </execution>
  </executions>
</plugin>

and finally

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.6.1</version>
    <configuration>
      <compilerArgs>
         <arg>classpath=${cp}:${basedir}/lib/bad.jar</arg>
      </compilerArgs>
    </configuration>
   </plugin>

Convert seconds into days, hours, minutes and seconds

Based on the answer by Julian Moreno, but changed to give the response as a string (not an array), only include the time intervals required and not assume the plural.

The difference between this and the highest voted answer is:

For 259264 seconds, this code would give

3 days, 1 minute, 4 seconds

For 259264 seconds, the highest voted answer (by Glavic) would give

3 days, 0 hours, 1 minutes and 4 seconds

function secondsToTime($inputSeconds) {
    $secondsInAMinute = 60;
    $secondsInAnHour = 60 * $secondsInAMinute;
    $secondsInADay = 24 * $secondsInAnHour;

    // Extract days
    $days = floor($inputSeconds / $secondsInADay);

    // Extract hours
    $hourSeconds = $inputSeconds % $secondsInADay;
    $hours = floor($hourSeconds / $secondsInAnHour);

    // Extract minutes
    $minuteSeconds = $hourSeconds % $secondsInAnHour;
    $minutes = floor($minuteSeconds / $secondsInAMinute);

    // Extract the remaining seconds
    $remainingSeconds = $minuteSeconds % $secondsInAMinute;
    $seconds = ceil($remainingSeconds);

    // Format and return
    $timeParts = [];
    $sections = [
        'day' => (int)$days,
        'hour' => (int)$hours,
        'minute' => (int)$minutes,
        'second' => (int)$seconds,
    ];

    foreach ($sections as $name => $value){
        if ($value > 0){
            $timeParts[] = $value. ' '.$name.($value == 1 ? '' : 's');
        }
    }

    return implode(', ', $timeParts);
}

I hope this helps someone.

How to disable registration new users in Laravel

Set Register route false in your web.php.

Auth::routes(['register' => false]);

HTML Table cellspacing or padding just top / bottom

Cellspacing is all around the cell and cannot be changed (i.e. if it's set to one, there will be 1 pixel of space on all sides). Padding can be specified discreetly (e.g. padding-top, padding-bottom, padding-left, and padding-right; or padding: [top] [right] [bottom] [left];).

The simplest way to resize an UIImage?

Trevor Howard has some UIImage categories that handle resize quite nicely. If nothing else you can use the code as examples.

Note: As of iOS 5.1, this answer maybe invalid. See comment below.

Maven project version inheritance - do I have to specify the parent version?

As Yanflea mentioned, there is a way to go around this.

In Maven 3.5.0 you can use the following way of transferring the version down from the parent project:

Parent POM.xml

<project ...>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mydomain</groupId>
    <artifactId>myprojectparent</artifactId>
    <packaging>pom</packaging>
    <version>${myversion}</version>
    <name>MyProjectParent</name>

    <properties>
        <myversion>0.1-SNAPSHOT</myversion>
    </properties>

    <modules>
        <module>modulefolder</module>
    </modules>
    ...
</project>

Module POM.xml

<project ...>
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.mydomain</groupId>
        <artifactId>myprojectmodule</artifactId>
        <version>${myversion}</version> <!-- This still needs to be set, but you can use properties from parent -->
    </parent>

    <groupId>se.car_o_liner</groupId>
    <artifactId>vinno</artifactId>
    <packaging>war</packaging>
    <name>Vinno</name>
    <!-- Note that there's no version specified; it's inherited from parent -->
    ...
</project>

You are free to change myversion to whatever you want that isn't a reserved property.

Joda DateTime to Timestamp conversion

I've solved this problem in this way.

String dateUTC = rs.getString("date"); //UTC
DateTime date;
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS").withZoneUTC();
date = dateTimeFormatter.parseDateTime(dateUTC);

In this way you ignore the server TimeZone forcing your chosen TimeZone.

Xcode 6 Bug: Unknown class in Interface Builder file

Don't use spaces in the project name, otherwise the Custom Class will not find your own classes.

Adding ID's to google map markers

I have a simple Location class that I use to handle all of my marker-related things. I'll paste my code below for you to take a gander at.

The last line(s) is what actually creates the marker objects. It loops through some JSON of my locations, which look something like this:

{"locationID":"98","name":"Bergqvist Järn","note":null,"type":"retail","address":"Smidesvägen 3","zipcode":"69633","city":"Askersund","country":"Sverige","phone":"0583-120 35","fax":null,"email":null,"url":"www.bergqvist-jb.com","lat":"58.891079","lng":"14.917371","contact":null,"rating":"0","distance":"45.666885421019"}

Here is the code:

If you look at the target() method in my Location class, you'll see that I keep references to the infowindow's and can simply open() and close() them because of a reference.

See a live demo: http://ww1.arbesko.com/en/locator/ (type in a Swedish city, like stockholm, and hit enter)

var Location = function() {
    var self = this,
        args = arguments;

    self.init.apply(self, args);
};

Location.prototype = {
    init: function(location, map) {
        var self = this;

        for (f in location) { self[f] = location[f]; }

        self.map = map;
        self.id = self.locationID;

        var ratings = ['bronze', 'silver', 'gold'],
            random = Math.floor(3*Math.random());

        self.rating_class = 'blue';

        // this is the marker point
        self.point = new google.maps.LatLng(parseFloat(self.lat), parseFloat(self.lng));
        locator.bounds.extend(self.point);

        // Create the marker for placement on the map
        self.marker = new google.maps.Marker({
            position: self.point,
            title: self.name,
            icon: new google.maps.MarkerImage('/wp-content/themes/arbesko/img/locator/'+self.rating_class+'SmallMarker.png'),
            shadow: new google.maps.MarkerImage(
                                        '/wp-content/themes/arbesko/img/locator/smallMarkerShadow.png',
                                        new google.maps.Size(52, 18),
                                        new google.maps.Point(0, 0),
                                        new google.maps.Point(19, 14)
                                    )
        });

        google.maps.event.addListener(self.marker, 'click', function() {
            self.target('map');
        });

        google.maps.event.addListener(self.marker, 'mouseover', function() {
            self.sidebarItem().mouseover();
        });

        google.maps.event.addListener(self.marker, 'mouseout', function() {
            self.sidebarItem().mouseout();
        });

        var infocontent = Array(
            '<div class="locationInfo">',
                '<span class="locName br">'+self.name+'</span>',
                '<span class="locAddress br">',
                    self.address+'<br/>'+self.zipcode+' '+self.city+' '+self.country,
                '</span>',
                '<span class="locContact br">'
        );

        if (self.phone) {
            infocontent.push('<span class="item br locPhone">'+self.phone+'</span>');
        }

        if (self.url) {
            infocontent.push('<span class="item br locURL"><a href="http://'+self.url+'">'+self.url+'</a></span>');
        }

        if (self.email) {
            infocontent.push('<span class="item br locEmail"><a href="mailto:'+self.email+'">Email</a></span>');
        }

        // Add in the lat/long
        infocontent.push('</span>');

        infocontent.push('<span class="item br locPosition"><strong>Lat:</strong> '+self.lat+'<br/><strong>Lng:</strong> '+self.lng+'</span>');

        // Create the infowindow for placement on the map, when a marker is clicked
        self.infowindow = new google.maps.InfoWindow({
            content: infocontent.join(""),
            position: self.point,
            pixelOffset: new google.maps.Size(0, -15) // Offset the infowindow by 15px to the top
        });

    },

    // Append the marker to the map
    addToMap: function() {
        var self = this;

        self.marker.setMap(self.map);
    },

    // Creates a sidebar module for the item, connected to the marker, etc..
    sidebarItem: function() {
        var self = this;

        if (self.sidebar) {
            return self.sidebar;
        }

        var li = $('<li/>').attr({ 'class': 'location', 'id': 'location-'+self.id }),
            name = $('<span/>').attr('class', 'locationName').html(self.name).appendTo(li),
            address = $('<span/>').attr('class', 'locationAddress').html(self.address+' <br/> '+self.zipcode+' '+self.city+' '+self.country).appendTo(li);

        li.addClass(self.rating_class);

        li.bind('click', function(event) {
            self.target();
        });

        self.sidebar = li;

        return li;
    },

    // This will "target" the store. Center the map and zoom on it, as well as 
    target: function(type) {
        var self = this;

        if (locator.targeted) {
            locator.targeted.infowindow.close();
        }

        locator.targeted = this;

        if (type != 'map') {
            self.map.panTo(self.point);
            self.map.setZoom(14);
        };

        // Open the infowinfow
        self.infowindow.open(self.map);
    }
};

for (var i=0; i < locations.length; i++) {
    var location = new Location(locations[i], self.map);
    self.locations.push(location);

    // Add the sidebar item
    self.location_ul.append(location.sidebarItem());

    // Add the map!
    location.addToMap();
};

Difference between object and class in Scala

tl;dr

  • class C defines a class, just as in Java or C++.
  • object O creates a singleton object O as instance of some anonymous class; it can be used to hold static members that are not associated with instances of some class.
  • object O extends T makes the object O an instance of trait T; you can then pass O anywhere, a T is expected.
  • if there is a class C, then object C is the companion object of class C; note that the companion object is not automatically an instance of C.

Also see Scala documentation for object and class.

object as host of static members

Most often, you need an object to hold methods and values/variables that shall be available without having to first instantiate an instance of some class. This use is closely related to static members in Java.

object A {
  def twice(i: Int): Int = 2*i
}

You can then call above method using A.twice(2).

If twice were a member of some class A, then you would need to make an instance first:

class A() {
  def twice(i: Int): Int = 2 * i
}

val a = new A()
a.twice(2)

You can see how redundant this is, as twice does not require any instance-specific data.

object as a special named instance

You can also use the object itself as some special instance of a class or trait. When you do this, your object needs to extend some trait in order to become an instance of a subclass of it.

Consider the following code:

object A extends B with C {
  ...
}

This declaration first declares an anonymous (inaccessible) class that extends both B and C, and instantiates a single instance of this class named A.

This means A can be passed to functions expecting objects of type B or C, or B with C.

Additional Features of object

There also exist some special features of objects in Scala. I recommend to read the official documentation.

  • def apply(...) enables the usual method name-less syntax of A(...)
  • def unapply(...) allows to create custom pattern matching extractors
  • if accompanying a class of the same name, the object assumes a special role when resolving implicit parameters

Location Services not working in iOS 8

Solution with backward compatibility which doesn't produce Xcode warnings:

SEL requestSelector = NSSelectorFromString(@"requestWhenInUseAuthorization");
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined &&
  [self.locationManager respondsToSelector:requestSelector]) {
((void (*)(id, SEL))[self.locationManager methodForSelector:requestSelector])(self.locationManager, requestSelector);
  [self.locationManager startUpdatingLocation];
} else {
  [self.locationManager startUpdatingLocation];
}

Setup NSLocationWhenInUseUsageDescription key in your Info.plist.

For iOS version 11.0+ : Setup NSLocationAlwaysAndWhenInUseUsageDescription key in your Info.plist. along with other 2 keys.

How can I convert a .py to .exe for Python?

Python 3.6 is supported by PyInstaller.

Open a cmd window in your Python folder (open a command window and use cd or while holding shift, right click it on Windows Explorer and choose 'Open command window here'). Then just enter

pip install pyinstaller

And that's it.

The simplest way to use it is by entering on your command prompt

pyinstaller file_name.py

For more details on how to use it, take a look at this question.

Strip HTML from Text JavaScript

As an extension to the jQuery method, if your string might not contain HTML (eg if you are trying to remove HTML from a form field)

jQuery(html).text();

will return an empty string if there is no HTML

Use:

jQuery('<p>' + html + '</p>').text();

instead.

Update: As has been pointed out in the comments, in some circumstances this solution will execute javascript contained within html if the value of html could be influenced by an attacker, use a different solution.

What is Bootstrap?

Bootstrap, as I know it, is a well defined CSS. Although using Bootstrap you could also use JavaScript, jQuery etc. But the main difference is that, using Bootstrap you can just call the class name and then you get the output on the HTML form. for eg. coloring of buttons shaping of text, using layouts. For all this you do not have to write a CSS file rather you just have to use the correct class name for shaping your HTML form.

How can I determine if an image has loaded, using Javascript/jQuery?

Using the jquery data store you can define a 'loaded' state.

<img id="myimage" onload="$(this).data('loaded', 'loaded');" src="lolcats.jpg" />

Then elsewhere you can do:

if ($('#myimage').data('loaded')) {
    // loaded, so do stuff
}

In C# check that filename is *possibly* valid (not that it exists)

Think it's too late to answer but... :) in case of path with volume name you could write something like this:

using System;
using System.Linq;
using System.IO;

// ...

var drives = Environment.GetLogicalDrives();
var invalidChars = Regex.Replace(new string(Path.GetInvalidFileNameChars()), "[\\\\/]", "");
var drive = drives.FirstOrDefault(d => filePath.StartsWith(d));
if (drive != null) {
    var fileDirPath = filePath.Substring(drive.Length);
    if (0 < fileDirPath.Length) {
        if (fileDirPath.IndexOfAny(invalidChars.ToCharArray()) == -1) {
            if (Path.Combine(drive, fileDirPath) != drive) {
                // path correct and we can proceed
            }
        }
    }
}

How to store phone numbers on MySQL databases?

  • All as varchar (they aren't numbers but "collections of digits")
  • Country + area + number separately
  • Not all countries have area code (eg Malta where I am)
  • Some countries drop the leading zero from the area code when dialling internal (eg UK)
  • Format in the client code

Calling Python in Java?

It depends on what do you mean by python functions? if they were written in cpython you can not directly call them you will have to use JNI, but if they were written in Jython you can easily call them from java, as jython ultimately generates java byte code.

Now when I say written in cpython or jython it doesn't make much sense because python is python and most code will run on both implementations unless you are using specific libraries which relies on cpython or java.

see here how to use Python interpreter in Java.

Matplotlib connect scatterplot points with line - Python

I think @Evert has the right answer:

plt.scatter(dates,values)
plt.plot(dates, values)
plt.show()

Which is pretty much the same as

plt.plot(dates, values, '-o')
plt.show()

or whatever linestyle you prefer.

How do I get the width and height of a HTML5 canvas?

Here's a CodePen that uses canvas.height/width, CSS height/width, and context to correctly render any canvas at any size.

HTML:

<button onclick="render()">Render</button>
<canvas id="myCanvas" height="100" width="100" style="object-fit:contain;"></canvas>

CSS:

canvas {
  width: 400px;
  height: 200px;
  border: 1px solid red;
  display: block;
}

Javascript:

const myCanvas = document.getElementById("myCanvas");
const originalHeight = myCanvas.height;
const originalWidth = myCanvas.width;
render();
function render() {
  let dimensions = getObjectFitSize(
    true,
    myCanvas.clientWidth,
    myCanvas.clientHeight,
    myCanvas.width,
    myCanvas.height
  );
  myCanvas.width = dimensions.width;
  myCanvas.height = dimensions.height;

  let ctx = myCanvas.getContext("2d");
  let ratio = Math.min(
    myCanvas.clientWidth / originalWidth,
    myCanvas.clientHeight / originalHeight
  );
  ctx.scale(ratio, ratio); //adjust this!
  ctx.beginPath();
  ctx.arc(50, 50, 50, 0, 2 * Math.PI);
  ctx.stroke();
}

// adapted from: https://www.npmjs.com/package/intrinsic-scale
function getObjectFitSize(
  contains /* true = contain, false = cover */,
  containerWidth,
  containerHeight,
  width,
  height
) {
  var doRatio = width / height;
  var cRatio = containerWidth / containerHeight;
  var targetWidth = 0;
  var targetHeight = 0;
  var test = contains ? doRatio > cRatio : doRatio < cRatio;

  if (test) {
    targetWidth = containerWidth;
    targetHeight = targetWidth / doRatio;
  } else {
    targetHeight = containerHeight;
    targetWidth = targetHeight * doRatio;
  }

  return {
    width: targetWidth,
    height: targetHeight,
    x: (containerWidth - targetWidth) / 2,
    y: (containerHeight - targetHeight) / 2
  };
}

Basically, canvas.height/width sets the size of the bitmap you are rendering to. The CSS height/width then scales the bitmap to fit the layout space (often warping it as it scales it). The context can then modify it's scale to draw, using vector operations, at different sizes.

How to select the first row of each group?

A nice way of doing this with the dataframe api is using the argmax logic like so

  val df = Seq(
    (0,"cat26",30.9), (0,"cat13",22.1), (0,"cat95",19.6), (0,"cat105",1.3),
    (1,"cat67",28.5), (1,"cat4",26.8), (1,"cat13",12.6), (1,"cat23",5.3),
    (2,"cat56",39.6), (2,"cat40",29.7), (2,"cat187",27.9), (2,"cat68",9.8),
    (3,"cat8",35.6)).toDF("Hour", "Category", "TotalValue")

  df.groupBy($"Hour")
    .agg(max(struct($"TotalValue", $"Category")).as("argmax"))
    .select($"Hour", $"argmax.*").show

 +----+----------+--------+
 |Hour|TotalValue|Category|
 +----+----------+--------+
 |   1|      28.5|   cat67|
 |   3|      35.6|    cat8|
 |   2|      39.6|   cat56|
 |   0|      30.9|   cat26|
 +----+----------+--------+

jquery .live('click') vs .click()

Always use click if you not dynamically add elements.

live works by adding an event listener to the document root and listens for bubbled up events. An alternative is delegate, which works the same, but binds the event handler to the specified element.
This way, the event has not to bubble up the whole DOM and is caught earlier.

Pandas (python): How to add column to dataframe for index?

I stumbled on this question while trying to do the same thing (I think). Here is how I did it:

df['index_col'] = df.index

You can then sort on the new index column, if you like.

.NET Console Application Exit Event

For the CTRL+C case, you can use this:

// Tell the system console to handle CTRL+C by calling our method that
// gracefully shuts down.
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);


static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
            Console.WriteLine("Shutting down...");
            // Cleanup here
            System.Threading.Thread.Sleep(750);
}