Programs & Examples On #Timespace

How to filter input type="file" dialog by specific file type?

You can use the accept attribute along with the . It doesn't work in IE and Safari.

Depending on your project scale and extensibility, you could use Struts. Struts offers two ways to limit the uploaded file type, declaratively and programmatically.

For more information: http://struts.apache.org/2.0.14/docs/file-upload.html#FileUpload-FileTypes

Regular expression for not allowing spaces in the input field

If you're using some plugin which takes string and use construct Regex to create Regex Object i:e new RegExp()

Than Below string will work

'^\\S*$'

It's same regex @Bergi mentioned just the string version for new RegExp constructor

How to find out which processes are using swap space in Linux?

Run top then press OpEnter. Now processes should be sorted by their swap usage.

Here is an update as my original answer does not provide an exact answer to the problem as pointed out in the comments. From the htop FAQ:

It is not possible to get the exact size of used swap space of a process. Top fakes this information by making SWAP = VIRT - RES, but that is not a good metric, because other stuff such as video memory counts on VIRT as well (for example: top says my X process is using 81M of swap, but it also reports my system as a whole is using only 2M of swap. Therefore, I will not add a similar Swap column to htop because I don't know a reliable way to get this information (actually, I don't think it's possible to get an exact number, because of shared pages).

How to configure SSL certificates with Charles Web Proxy and the latest Android Emulator on Windows?

What worked for me - should really be moved to iPhone:

Charles

  1. Enable transparent Http proxying
  2. Enable SSL proxying
  3. Right click on incoming request and select SSL proxying

Mac

  1. Download Charles CA Certificate bundle http://www.charlesproxy.com/ssl.zip
  2. Email yourself charles-proxy-ssl-proxying-certificate.crt

iPhone

  1. Enable http proxy for Charles on port 8888
  2. Select and install email attachment, yes trust it!

Voila, you can now view encrypted traffic from the domain added in the SSL proxying

Style jQuery autocomplete in a Bootstrap input field

The gap between the (bootstrap) input field and jquery-ui autocompleter seem to occur only in jQuery versions >= 3.2

When using jQuery version 3.1.1 it seem to not happen.

Possible reason is the notable update in v3.2.0 related to a bug fix on .width() and .height(). Check out the jQuery release notes for further details: v3.2.0 / v3.1.1

Bootstrap version 3.4.1 and jquery-ui version 1.12.0 used

How to get the last characters in a String in Java, regardless of String size

String inputstr = "abcd: efg: 1006746"
int startindex = inputstr.length() - 10;
String outputtendigitstr = inputstr.substring(startindex);

Make sure you check string length is more than 10.

Location of Django logs and errors

Add to your settings.py:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'debug.log',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

And it will create a file called debug.log in the root of your. https://docs.djangoproject.com/en/1.10/topics/logging/

ansible : how to pass multiple commands

I faced the same issue. In my case, part of my variables were in a dictionary i.e. with_dict variable (looping) and I had to run 3 commands on each item.key. This solution is more relevant where you have to use with_dict dictionary with running multiple commands (without requiring with_items)

Using with_dict and with_items in one task didn't help as it was not resolving the variables.

My task was like:

- name: Make install git source
  command: "{{ item }}"
  with_items:
    - cd {{ tools_dir }}/{{ item.value.artifact_dir }}
    - make prefix={{ tools_dir }}/{{ item.value.artifact_dir }} all
    - make prefix={{ tools_dir }}/{{ item.value.artifact_dir }} install
  with_dict: "{{ git_versions }}"

roles/git/defaults/main.yml was:

---
tool: git
default_git: git_2_6_3

git_versions:
  git_2_6_3:
    git_tar_name: git-2.6.3.tar.gz
    git_tar_dir: git-2.6.3
    git_tar_url: https://www.kernel.org/pub/software/scm/git/git-2.6.3.tar.gz

The above resulted in an error similar to the following for each {{ item }} (for 3 commands as mentioned above). As you see, the values of tools_dir is not populated (tools_dir is a variable which is defined in a common role's defaults/main.yml and also item.value.git_tar_dir value was not populated/resolved).

failed: [server01.poc.jenkins] => (item=cd {# tools_dir #}/{# item.value.git_tar_dir #}) => {"cmd": "cd '{#' tools_dir '#}/{#' item.value.git_tar_dir '#}'", "failed": true, "item": "cd {# tools_dir #}/{# item.value.git_tar_dir #}", "rc": 2}
msg: [Errno 2] No such file or directory

Solution was easy. Instead of using "COMMAND" module in Ansible, I used "Shell" module and created a a variable in roles/git/defaults/main.yml

So, now roles/git/defaults/main.yml looks like:

---
tool: git
default_git: git_2_6_3

git_versions:
  git_2_6_3:
    git_tar_name: git-2.6.3.tar.gz
    git_tar_dir: git-2.6.3
    git_tar_url: https://www.kernel.org/pub/software/scm/git/git-2.6.3.tar.gz

#git_pre_requisites_install_cmds: "cd {{ tools_dir }}/{{ item.value.git_tar_dir }} && make prefix={{ tools_dir }}/{{ item.value.git_tar_dir }} all && make prefix={{ tools_dir }}/{{ item.value.git_tar_dir }} install"

#or use this if you want git installation to work in ~/tools/git-x.x.x
git_pre_requisites_install_cmds: "cd {{ tools_dir }}/{{ item.value.git_tar_dir }} && make prefix=`pwd` all && make prefix=`pwd` install"

#or use this if you want git installation to use the default prefix during make 
#git_pre_requisites_install_cmds: "cd {{ tools_dir }}/{{ item.value.git_tar_dir }} && make all && make install"

and the task roles/git/tasks/main.yml looks like:

- name: Make install from git source
  shell: "{{ git_pre_requisites_install_cmds }}"
  become_user: "{{ build_user }}"
  with_dict: "{{ git_versions }}"
  tags:
    - koba

This time, the values got successfully substituted as the module was "SHELL" and ansible output echoed the correct values. This didn't require with_items: loop.

"cmd": "cd ~/tools/git-2.6.3 && make prefix=/home/giga/tools/git-2.6.3 all && make prefix=/home/giga/tools/git-2.6.3 install",

How to get row count in sqlite using Android?

Do you see what the DatabaseUtils.queryNumEntries() does? It's awful! I use this.

public int getRowNumberByArgs(Object... args) {
    String where = compileWhere(args);
    String raw = String.format("SELECT count(*) FROM %s WHERE %s;", TABLE_NAME, where);
    Cursor c = getWriteableDatabase().rawQuery(raw, null);
    try {
        return (c.moveToFirst()) ? c.getInt(0) : 0;
    } finally {
        c.close();
    }
}

Storing query results into a variable and modifying it inside a Stored Procedure

Try this example

CREATE PROCEDURE MyProc
BEGIN
    --Stored Procedure variables
    Declare @maxOr int; 
    Declare @maxCa int; 

    --Getting query result in the variable (first variant of syntax)
    SET @maxOr = (SELECT MAX(orId) FROM [order]); 

    --Another variant of seting variable from query
    SELECT @maxCa=MAX(caId) FROM [cart]; 

    --Updating record through the variable
    INSERT INTO [order_cart] (orId,caId)
    VALUES(@maxOr, @maxCa); 

    --return values to the program as dataset
    SELECT
       @maxOr AS maxOr,
       @maxCa AS maxCa

    -- return one int value as "return value"
    RETURN @maxOr
END
GO

SQL-command to call the stored procedure

EXEC MyProc

How to check empty object in angular 2 template using *ngIf

From the above answeres, following did not work or less preferable:

  • (previous_info | json) != '{}' works only for {} empty case, not for null or undefined case
  • Object.getOwnPropertyNames(previous_info).length also did not work, as Object is not accessible in the template
  • I would not like to create a dedicated variable this.objectLength = Object.keys(this.previous_info).length !=0;
  • I would not like to create a dedicated function

    isEmptyObject(obj) {
       return (obj && (Object.keys(obj).length === 0));
    }
    

Solution: keyvalue pipe along with ?. (safe navigation operator); and it seems simple.

It works well when previous_info = null or previous_info = undefined or previous_info = {} and treats as falsy value.

<div  *ngIf="(previous_info | keyvalue)?.length">

keyvalue - Transforms Object or Map into an array of key value pairs.

?. - The Angular safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined

DEMO: demo with angular 9, though it works for previous versions as well

How can I convert a file pointer ( FILE* fp ) to a file descriptor (int fd)?

The proper function is int fileno(FILE *stream). It can be found in <stdio.h>, and is a POSIX standard but not standard C.

Best practices to test protected methods with PHPUnit

I'm going to throw my hat into the ring here:

I've used the __call hack with mixed degrees of success. The alternative I came up with was to use the Visitor pattern:

1: generate a stdClass or custom class (to enforce type)

2: prime that with the required method and arguments

3: ensure that your SUT has an acceptVisitor method which will execute the method with the arguments specified in the visiting class

4: inject it into the class you wish to test

5: SUT injects the result of operation into the visitor

6: apply your test conditions to the Visitor's result attribute

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

I fixed it with adding the prefix (attr.) :

<create-report-card-form [attr.currentReportCardCount]="expression" ...

Unfortunately this haven't documented properly yet.

more detail here

Notice: Undefined variable: _SESSION in "" on line 9

Add

session_start();

at the beginning of your page before any HTML

You will have something like :

<?php session_start();
include("inc/incfiles/header.inc.php")?>
<html>
<head>
<meta http-equiv="Content-Type" conte...

Don't forget to remove the space you have before

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

Yes, it is possible to change a CSS class dynamically according to the situation, but not with th:if. This is done with the elvis operator.

<a href="lorem-ipsum.html" th:class="${isAdmin}? adminclass : userclass">Lorem Ipsum</a> 

How do I solve the INSTALL_FAILED_DEXOPT error?

I had changed my version of android version 4 support for sdk 21 and had this error. So I went back the version of support for the old version (before 21) and it worked. The error was occurring only in android 2.3

In Python, how to check if a string only contains certain characters?

This has already been answered satisfactorily, but for people coming across this after the fact, I have done some profiling of several different methods of accomplishing this. In my case I wanted uppercase hex digits, so modify as necessary to suit your needs.

Here are my test implementations:

import re

hex_digits = set("ABCDEF1234567890")
hex_match = re.compile(r'^[A-F0-9]+\Z')
hex_search = re.compile(r'[^A-F0-9]')

def test_set(input):
    return set(input) <= hex_digits

def test_not_any(input):
    return not any(c not in hex_digits for c in input)

def test_re_match1(input):
    return bool(re.compile(r'^[A-F0-9]+\Z').match(input))

def test_re_match2(input):
    return bool(hex_match.match(input))

def test_re_match3(input):
    return bool(re.match(r'^[A-F0-9]+\Z', input))

def test_re_search1(input):
    return not bool(re.compile(r'[^A-F0-9]').search(input))

def test_re_search2(input):
    return not bool(hex_search.search(input))

def test_re_search3(input):
    return not bool(re.match(r'[^A-F0-9]', input))

And the tests, in Python 3.4.0 on Mac OS X:

import cProfile
import pstats
import random

# generate a list of 10000 random hex strings between 10 and 10009 characters long
# this takes a little time; be patient
tests = [ ''.join(random.choice("ABCDEF1234567890") for _ in range(l)) for l in range(10, 10010) ]

# set up profiling, then start collecting stats
test_pr = cProfile.Profile(timeunit=0.000001)
test_pr.enable()

# run the test functions against each item in tests. 
# this takes a little time; be patient
for t in tests:
    for tf in [test_set, test_not_any, 
               test_re_match1, test_re_match2, test_re_match3,
               test_re_search1, test_re_search2, test_re_search3]:
        _ = tf(t)

# stop collecting stats
test_pr.disable()

# we create our own pstats.Stats object to filter 
# out some stuff we don't care about seeing
test_stats = pstats.Stats(test_pr)

# normally, stats are printed with the format %8.3f, 
# but I want more significant digits
# so this monkey patch handles that
def _f8(x):
    return "%11.6f" % x

def _print_title(self):
    print('   ncalls     tottime     percall     cumtime     percall', end=' ', file=self.stream)
    print('filename:lineno(function)', file=self.stream)

pstats.f8 = _f8
pstats.Stats.print_title = _print_title

# sort by cumulative time (then secondary sort by name), ascending
# then print only our test implementation function calls:
test_stats.sort_stats('cumtime', 'name').reverse_order().print_stats("test_*")

which gave the following results:

         50335004 function calls in 13.428 seconds

   Ordered by: cumulative time, function name
   List reduced from 20 to 8 due to restriction 

   ncalls     tottime     percall     cumtime     percall filename:lineno(function)
    10000    0.005233    0.000001    0.367360    0.000037 :1(test_re_match2)
    10000    0.006248    0.000001    0.378853    0.000038 :1(test_re_match3)
    10000    0.010710    0.000001    0.395770    0.000040 :1(test_re_match1)
    10000    0.004578    0.000000    0.467386    0.000047 :1(test_re_search2)
    10000    0.005994    0.000001    0.475329    0.000048 :1(test_re_search3)
    10000    0.008100    0.000001    0.482209    0.000048 :1(test_re_search1)
    10000    0.863139    0.000086    0.863139    0.000086 :1(test_set)
    10000    0.007414    0.000001    9.962580    0.000996 :1(test_not_any)

where:

ncalls
The number of times that function was called
tottime
the total time spent in the given function, excluding time made to sub-functions
percall
the quotient of tottime divided by ncalls
cumtime
the cumulative time spent in this and all subfunctions
percall
the quotient of cumtime divided by primitive calls

The columns we actually care about are cumtime and percall, as that shows us the actual time taken from function entry to exit. As we can see, regex match and search are not massively different.

It is faster not to bother compiling the regex if you would have compiled it every time. It is about 7.5% faster to compile once than every time, but only 2.5% faster to compile than to not compile.

test_set was twice as slow as re_search and thrice as slow as re_match

test_not_any was a full order of magnitude slower than test_set

TL;DR: Use re.match or re.search

SSL cert "err_cert_authority_invalid" on mobile chrome only

A decent way to check whether there is an issue in your certificate chain is to use this website:

https://www.digicert.com/help/

Plug in your test URL and it will tell you what may be wrong. We had an issue with the same symptom as you, and our issue was diagnosed as being due to intermediate certificates.

SSL Certificate is not trusted

The certificate is not signed by a trusted authority (checking against Mozilla's root store). If you bought the certificate from a trusted authority, you probably just need to install one or more Intermediate certificates. Contact your certificate provider for assistance doing this for your server platform.

Twitter Bootstrap Button Text Word Wrap

FWIW, in Boostrap 4.4, you can add .text-wrap style to things like buttons:

   <a href="#" class="btn btn-primary text-wrap">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</a>

https://getbootstrap.com/docs/4.4/utilities/text/#text-wrapping-and-overflow

How to get the number of characters in a string

There is a way to get count of runes without any packages by converting string to []rune as len([]rune(YOUR_STRING)):

package main

import "fmt"

func main() {
    russian := "??????? ? ??????"
    english := "Sputnik & pogrom"

    fmt.Println("count of bytes:",
        len(russian),
        len(english))

    fmt.Println("count of runes:",
        len([]rune(russian)),
        len([]rune(english)))

}

count of bytes 30 16

count of runes 16 16

Find string between two substrings

This seems much more straight forward to me:

import re

s = 'asdf=5;iwantthis123jasd'
x= re.search('iwantthis',s)
print(s[x.start():x.end()])

Apache is "Unable to initialize module" because of module's and PHP's API don't match after changing the PHP configuration

I had a similar issue after upgrading from PHP 5.5 to PHP 5.6. The phpize and php-config libraries being used to compile the phalcon extension were still the ones from PHP 5.5. I had to run the command below:

sudo apt-get install php5.6-dev

There will be a long stacktrace, the key information I saw was this:

update-alternatives: using /usr/bin/php-config5.6 to provide /usr/bin/php-config (php-config) in auto mode
update-alternatives: using /usr/bin/phpize5.6 to provide /usr/bin/phpize (phpize) in auto mode

I hope this helps someone.

Call to undefined method mysqli_stmt::get_result

I know this was already answered as to what the actual problem is, however I want to offer a simple workaround.

I wanted to use the get_results() method however I didn't have the driver, and I'm not somewhere I can get that added. So, before I called

$stmt->bind_results($var1,$var2,$var3,$var4...etc);

I created an empty array, and then just bound the results as keys in that array:

$result = array();
$stmt->bind_results($result['var1'],$result['var2'],$result['var3'],$result['var4']...etc);

so that those results could easily be passed into methods or cast to an object for further use.

Hope this helps anyone who's looking to do something similar.

8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE

If you are using linux system, use the below command.

fuser -k some_port_number/tcp - that will kill that process.

Sample:-

fuser -k 8080/tcp

Second Option: Configure the tomcat to use a new port

Uncaught SyntaxError: Unexpected token u in JSON at position 0

Try this in the console:

JSON.parse(undefined)

Here is what you will get:

Uncaught SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at <anonymous>:1:6

In other words, your app is attempting to parse undefined, which is not valid JSON.

There are two common causes for this. The first is that you may be referencing a non-existent property (or even a non-existent variable if not in strict mode).

window.foobar = '{"some":"data"}';
JSON.parse(window.foobarn)  // oops, misspelled!

The second common cause is failure to receive the JSON in the first place, which could be caused by client side scripts that ignore errors and send a request when they shouldn't.

Make sure both your server-side and client-side scripts are running in strict mode and lint them using ESLint. This will give you pretty good confidence that there are no typos.

Laravel password validation rule

A Custom Laravel Validation Rule will allow developers to provide a custom message with each use case for a better UX experience.

php artisan make:rule IsValidPassword

namespace App\Rules;

use Illuminate\Support\Str;
use Illuminate\Contracts\Validation\Rule;

class isValidPassword implements Rule
{
    /**
     * Determine if the Length Validation Rule passes.
     *
     * @var boolean
     */
    public $lengthPasses = true;

    /**
     * Determine if the Uppercase Validation Rule passes.
     *
     * @var boolean
     */
    public $uppercasePasses = true;

    /**
     * Determine if the Numeric Validation Rule passes.
     *
     * @var boolean
     */
    public $numericPasses = true;

    /**
     * Determine if the Special Character Validation Rule passes.
     *
     * @var boolean
     */
    public $specialCharacterPasses = true;

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $this->lengthPasses = (Str::length($value) >= 10);
        $this->uppercasePasses = (Str::lower($value) !== $value);
        $this->numericPasses = ((bool) preg_match('/[0-9]/', $value));
        $this->specialCharacterPasses = ((bool) preg_match('/[^A-Za-z0-9]/', $value));

        return ($this->lengthPasses && $this->uppercasePasses && $this->numericPasses && $this->specialCharacterPasses);
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        switch (true) {
            case ! $this->uppercasePasses
                && $this->numericPasses
                && $this->specialCharacterPasses:
                return 'The :attribute must be at least 10 characters and contain at least one uppercase character.';

            case ! $this->numericPasses
                && $this->uppercasePasses
                && $this->specialCharacterPasses:
                return 'The :attribute must be at least 10 characters and contain at least one number.';

            case ! $this->specialCharacterPasses
                && $this->uppercasePasses
                && $this->numericPasses:
                return 'The :attribute must be at least 10 characters and contain at least one special character.';

            case ! $this->uppercasePasses
                && ! $this->numericPasses
                && $this->specialCharacterPasses:
                return 'The :attribute must be at least 10 characters and contain at least one uppercase character and one number.';

            case ! $this->uppercasePasses
                && ! $this->specialCharacterPasses
                && $this->numericPasses:
                return 'The :attribute must be at least 10 characters and contain at least one uppercase character and one special character.';

            case ! $this->uppercasePasses
                && ! $this->numericPasses
                && ! $this->specialCharacterPasses:
                return 'The :attribute must be at least 10 characters and contain at least one uppercase character, one number, and one special character.';

            default:
                return 'The :attribute must be at least 10 characters.';
        }
    }
}

Then on your request validation:

$request->validate([
    'email'    => 'required|string|email:filter',
    'password' => [
        'required',
        'confirmed',
        'string',
        new isValidPassword(),
    ],
]);

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

The rule would be:

0 19 * * 1,3,5

I suggest that you use http://corntab.com for having a very convenient GUI to create your rules in the future :)

How to outline text in HTML / CSS

from: Outline effect to text

.strokeme
{
    color: white;
    text-shadow:
    -1px -1px 0 #000,
    1px -1px 0 #000,
    -1px 1px 0 #000,
    1px 1px 0 #000;  
}

cannot load such file -- bundler/setup (LoadError)

I ran into the same issue, but I think it was due to spring caching some gems and configurations. I fixed it by running gem pristine --all.

This restores installed gems to pristine condition from files located in the gem cache.

or you can just try for your gem like

gem pristine your_gem_name

How to Set RadioButtonFor() in ASp.net MVC 2 as Checked by default

This question on StackOverflow deals with RadioButtonListFor and the answer addresses your question too. You can set the selected property in the RadioButtonListViewModel.

SQL Server using wildcard within IN

SELECT c.* FROM(
SELECT '071235' AS token UNION ALL SELECT '07113' 
 UNION ALL SELECT '071343'
UNION ALL SELECT '0713SA'
UNION ALL SELECT '071443') AS c
JOIN (
SELECT '0712%' AS pattern UNION ALL SELECT '0711%' 
 UNION ALL SELECT '071343') AS d
ON c.token LIKE d.pattern

071235
07113
071343

Difference between socket and websocket?

WebSocket is just another application level protocol over TCP protocol, just like HTTP.

Some snippets < Spring in Action 4> quoted below, hope it can help you understand WebSocket better.

In its simplest form, a WebSocket is just a communication channel between two applications (not necessarily a browser is involved)...WebSocket communication can be used between any kinds of applications, but the most common use of WebSocket is to facilitate communication between a server application and a browser-based application.

Deep cloning objects

If you're already using a 3rd party application like ValueInjecter or Automapper, you can do something like this:

MyObject oldObj; // The existing object to clone

MyObject newObj = new MyObject();
newObj.InjectFrom(oldObj); // Using ValueInjecter syntax

Using this method you don't have to implement ISerializable or ICloneable on your objects. This is common with the MVC/MVVM pattern, so simple tools like this have been created.

see the ValueInjecter deep cloning sample on GitHub.

"ORA-01438: value larger than specified precision allowed for this column" when inserting 3

NUMBER (precision, scale) means precision number of total digits, of which scale digits are right of the decimal point.

NUMBER(2,2) in other words means a number with 2 digits, both of which are decimals. You may mean to use NUMBER(4,2) to get 4 digits, of which 2 are decimals. Currently you can just insert values with a zero integer part.

More info at the Oracle docs.

How do I pass along variables with XMLHTTPRequest

Following is correct way:

xmlhttp.open("GET","getuser.php?fname="+abc ,true);

Reload chart data via JSON with Highcharts

EDIT: The response down below is more correct!

https://stackoverflow.com/a/8408466/387285

http://www.highcharts.com/ref/#series-object

HTML:

<SELECT id="list">
<OPTION VALUE="A">Data Set A
<OPTION VALUE="B">Data Set B
</SELECT>
<button id="change">Refresh Table</button>

<div id="container" style="height: 400px"></div>

Javascript:

var options = {
    chart: {
        renderTo: 'container',
        defaultSeriesType: 'spline'
    },
    series: []
};

$("#change").click(function() {
    if ($("#list").val() == "A") {
        options.series = [{name: 'A', data: [1,2,3,2,1]}]
        // $.get('/dough/includes/live-chart.php?mode=month'
    } else {
        options.series = [{name: 'B', data: [3,2,1,2,3]}]
        // $.get('/dough/includes/live-chart.php?mode=newmode'
    } 

    var chart = new Highcharts.Chart(options);    
});

This is a very simple example since I don't have my files here with me but the basic idea is that every time the user selects new options for the stuff they want to see, you're going to have replace the .series data object with the new information from your server and then recreate the chart using the new Highcharts.Chart();.

Hope this helps! John

EDIT:

Check this out, its from something I've worked on in the past:

$("table#tblGeneralInfo2 > tbody > tr").each(function (index) {
    if (index != 0) {
        var chartnumbervalue = parseInt($(this).find("td:last").text());
        var charttextvalue = $(this).find("td:first").text();
        chartoptions.series[0].data.push([charttextvalue, chartnumbervalue]);
    }
});

I had a table with information in the first and last tds that I needed to add to the pie chart. I loop through each of the rows and push in the values. Note: I use chartoptions.series[0].data since pie charts only have 1 series.

Registry key Error: Java version has value '1.8', but '1.7' is required

I didn't delete any of the java.exe files, but changed the ordering of my System - "path" variable - so that it reflected %JAVA_HOME%\bin as the first entry. That did the trick.

Difference between __getattr__ vs __getattribute__

  • getattribute: Is used to retrieve an attribute from an instance. It captures every attempt to access an instance attribute by using dot notation or getattr() built-in function.
  • getattr: Is executed as the last resource when attribute is not found in an object. You can choose to return a default value or to raise AttributeError.

Going back to the __getattribute__ function; if the default implementation was not overridden; the following checks are done when executing the method:

  • Check if there is a descriptor with the same name (attribute name) defined in any class in the MRO chain (method object resolution)
  • Then looks into the instance’s namespace
  • Then looks into the class namespace
  • Then into each base’s namespace and so on.
  • Finally, if not found, the default implementation calls the fallback getattr() method of the instance and it raises an AttributeError exception as default implementation.

This is the actual implementation of the object.__getattribute__ method:

.. c:function:: PyObject* PyObject_GenericGetAttr(PyObject *o, PyObject *name) Generic attribute getter function that is meant to be put into a type object's tp_getattro slot. It looks for a descriptor in the dictionary of classes in the object's MRO as well as an attribute in the object's :attr:~object.dict (if present). As outlined in :ref:descriptors, data descriptors take preference over instance attributes, while non-data descriptors don't. Otherwise, an :exc:AttributeError is raised.

Access Controller method from another controller in Laravel 5

You can access the controller by instantiating it and calling doAction: (put use Illuminate\Support\Facades\App; before the controller class declaration)

$controller = App::make('\App\Http\Controllers\YouControllerName');
$data = $controller->callAction('controller_method', $parameters);

Also note that by doing this you will not execute any of the middlewares declared on that controller.

java.net.ConnectException :connection timed out: connect?

If you're pointing the config at a domain (eg fabrikam.com), do an NSLOOKUP to ensure all the responding IPs are valid, and can be connected to on port 389:

NSLOOKUP fabrikam.com

Test-NetConnection <IP returned from NSLOOKUP> -port 389

TypeError: 'str' does not support the buffer interface

For Python 3.x you can convert your text to raw bytes through:

bytes("my data", "encoding")

For example:

bytes("attack at dawn", "utf-8")

The object returned will work with outfile.write.

How to update only one field using Entity Framework?

Entity framework tracks your changes on objects that you queried from database via DbContext. For example if you DbContext instance name is dbContext

public void ChangePassword(int userId, string password){
     var user = dbContext.Users.FirstOrDefault(u=>u.UserId == userId);
     user.password = password;
     dbContext.SaveChanges();
}

How do you push a Git tag to a branch using a refspec?

For pushing a single tag: git push <reponame> <tagname>

For instance, git push production 1.0.0. Tags are not bound to branches, they are bound to commits.

When you want to have the tag's content in the master branch, do that locally on your machine. I would assume that you continued developing in your local master branch. Then just a git push origin master should suffice.

How to import spring-config.xml of one project into spring-config.xml of another project?

You have to add the jar/war of the module B in the module A and add the classpath in your new spring-module file. Just add this line

spring-moduleA.xml - is a file in module A under the resource folder. By adding this line, it imports all the bean definition from module A to module B.

MODULE B/ spring-moduleB.xml


import resource="classpath:spring-moduleA.xml"/>

<bean id="helloBeanB" class="basic.HelloWorldB">
  <property name="name" value="BMVNPrj" />
</bean>

Can't get Python to import from a different folder

After going through the answers given by these contributors above - Zorglub29, Tom, Mark, Aaron McMillin, lucasamaral, JoeyZhao, Kjeld Flarup, Procyclinsur, martin.zaenker, tooty44 and debugging the issue that I was facing I found out a different use case due to which I was facing this issue. Hence adding my observations below for anybody's reference.

In my code I had a cyclic import of classes. For example:

src
 |-- utilities.py (has Utilities class that uses Event class)  
 |-- consume_utilities.py (has Event class that uses Utilities class)
 |-- tests
      |-- test_consume_utilities.py (executes test cases that involves Event class)

I got following error when I tried to execute python -m pytest tests/test_utilities.py for executing UTs written in test_utilities.py.

ImportError while importing test module '/Users/.../src/tests/test_utilities.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests/test_utilities.py:1: in <module>
    from utilities import Utilities
...
...
E   ImportError: cannot import name 'Utilities'

The way I resolved the error was by re-factoring my code to move the functionality in cyclic import class so that I could remove the cyclic import of classes.

Note, I have __init__.py file in my 'src' folder as well as 'tests' folder and still was able to get rid of the 'ImportError' just by re-factoring the code.

Following stackoverflow link provides much more details on Circular dependency in Python.

'ssh' is not recognized as an internal or external command

Actually you have 2 problems here: First is that you don't have ssh installed, second is that you don't know how to deploy

Install SSH

It seems that ssh is not installed on your computer.

You can install openssh from here : http://openssh.en.softonic.com/download

Generate your key

Than you will have to geneate your ssh-key. There's a good tutorial about this here:

https://help.github.com/articles/generating-ssh-keys#platform-windows

Deploy

To deploy, you just have to push your code over git. Something like this:

git push fort master

If you get permission denied, be sure that you have put your public_key in the dashboard in the git tab.

SSH

The ssh command gives you access to your remote node. You should have received a password by email and now that you have ssh installed, you should be asked for a password when trying to connect. just input that password. If you want to use your private ssh key to connect to your server rather then typing that password, you can follow this : http://fortrabbit.com/docs/how-to/ssh-sftp/enable-public-key-authentication

node.js + mysql connection pooling

You will find this wrapper usefull :)

var pool = mysql.createPool(config.db);

exports.connection = {
    query: function () {
        var queryArgs = Array.prototype.slice.call(arguments),
            events = [],
            eventNameIndex = {};

        pool.getConnection(function (err, conn) {
            if (err) {
                if (eventNameIndex.error) {
                    eventNameIndex.error();
                }
            }
            if (conn) { 
                var q = conn.query.apply(conn, queryArgs);
                q.on('end', function () {
                    conn.release();
                });

                events.forEach(function (args) {
                    q.on.apply(q, args);
                });
            }
        });

        return {
            on: function (eventName, callback) {
                events.push(Array.prototype.slice.call(arguments));
                eventNameIndex[eventName] = callback;
                return this;
            }
        };
    }
};

Require it, use it like this:

db.connection.query("SELECT * FROM `table` WHERE `id` = ? ", row_id)
          .on('result', function (row) {
            setData(row);
          })
          .on('error', function (err) {
            callback({error: true, err: err});
          });

SQL join format - nested inner joins

For readability, I restructured the query... starting with the apparent top-most level being Table1, which then ties to Table3, and then table3 ties to table2. Much easier to follow if you follow the chain of relationships.

Now, to answer your question. You are getting a large count as the result of a Cartesian product. For each record in Table1 that matches in Table3 you will have X * Y. Then, for each match between table3 and Table2 will have the same impact... Y * Z... So your result for just one possible ID in table 1 can have X * Y * Z records.

This is based on not knowing how the normalization or content is for your tables... if the key is a PRIMARY key or not..

Ex:
Table 1       
DiffKey    Other Val
1          X
1          Y
1          Z

Table 3
DiffKey   Key    Key2  Tbl3 Other
1         2      6     V
1         2      6     X
1         2      6     Y
1         2      6     Z

Table 2
Key    Key2   Other Val
2      6      a
2      6      b
2      6      c
2      6      d
2      6      e

So, Table 1 joining to Table 3 will result (in this scenario) with 12 records (each in 1 joined with each in 3). Then, all that again times each matched record in table 2 (5 records)... total of 60 ( 3 tbl1 * 4 tbl3 * 5 tbl2 )count would be returned.

So, now, take that and expand based on your 1000's of records and you see how a messed-up structure could choke a cow (so-to-speak) and kill performance.

SELECT
      COUNT(*)
   FROM
      Table1 
         INNER JOIN Table3
            ON Table1.DifferentKey = Table3.DifferentKey
            INNER JOIN Table2
               ON Table3.Key =Table2.Key
               AND Table3.Key2 = Table2.Key2 

Reading data from XML

Alternatively, you can use XPathNavigator:

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XPathNavigator navigator = doc.CreateNavigator();

string books = GetStringValues("Books: ", navigator, "//Book/Title");
string authors = GetStringValues("Authors: ", navigator, "//Book/Author");

..

/// <summary>
/// Gets the string values.
/// </summary>
/// <param name="description">The description.</param>
/// <param name="navigator">The navigator.</param>
/// <param name="xpath">The xpath.</param>
/// <returns></returns>
private static string GetStringValues(string description,
                                      XPathNavigator navigator, string xpath) {
    StringBuilder sb = new StringBuilder();
    sb.Append(description);
    XPathNodeIterator bookNodesIterator = navigator.Select(xpath);
    while (bookNodesIterator.MoveNext())
       sb.Append(string.Format("{0} ", bookNodesIterator.Current.Value));
    return sb.ToString();
}

Maven build debug in Eclipse

The Run/Debug configuration you're using is meant to let you run Maven on your workspace as if from the command line without leaving Eclipse.

Assuming your tests are JUnit based you should be able to debug them by choosing a source folder containing tests with the right button and choose Debug as... -> JUnit tests.

Rethrowing exceptions in Java without losing the stack trace

Stack trace is prserved if you wrap the catched excetion into an other exception (to provide more info) or if you just rethrow the catched excetion.

try{ ... }catch (FooException e){ throw new BarException("Some usefull info", e); }

Redirect on Ajax Jquery Call

For ExpressJs router:

router.post('/login', async(req, res) => {
    return res.send({redirect: '/yoururl'});
})

Client-side:

    success: function (response) {
        if (response.redirect) {
            window.location = response.redirect
        }
    },

NPM clean modules

You can just delete the node_module directory

rm -rf node_modules/

Group list by values

Howard's answer is concise and elegant, but it's also O(n^2) in the worst case. For large lists with large numbers of grouping key values, you'll want to sort the list first and then use itertools.groupby:

>>> from itertools import groupby
>>> from operator import itemgetter
>>> seq = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]]
>>> seq.sort(key = itemgetter(1))
>>> groups = groupby(seq, itemgetter(1))
>>> [[item[0] for item in data] for (key, data) in groups]
[['A', 'C'], ['B'], ['D', 'E']]

Edit:

I changed this after seeing eyequem's answer: itemgetter(1) is nicer than lambda x: x[1].

Uncaught TypeError: Cannot read property 'msie' of undefined - jQuery tools

Use like blow

$(function (a) {

. . . . .then in your function you can using msie property like

if (a.browser.msie) 
{
}
else 
{
   $(settings.current).after(Uploadelement);
}

goodluck

Add comma to numbers every three digits

You can also look at the jquery FormatCurrency plugin (of which I am the author); it has support for multiple locales as well, but may have the overhead of the currency support that you don't need.

$(this).formatCurrency({ symbol: '', roundToDecimalPlace: 0 });

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

Scripts are raw java embedded in the page code, and if you declare variables in your scripts, then they become local variables embedded in the page.

In contrast, JSTL works entirely with scoped attributes, either at page, request or session scope. You need to rework your scriptlet to fish test out as an attribute:

<c:set var="test" value="test1"/>
<%
  String resp = "abc";
  String test = pageContext.getAttribute("test");
  resp = resp + test;
  pageContext.setAttribute("resp", resp);
%>
<c:out value="${resp}"/>

If you look at the docs for <c:set>, you'll see you can specify scope as page, request or session, and it defaults to page.

Better yet, don't use scriptlets at all: they make the baby jesus cry.

How do I get the file extension of a file in Java?

My dirty and may tiniest using String.replaceAll:

.replaceAll("^.*\\.(.*)$", "$1")

Note that first * is greedy so it will grab most possible characters as far as it can and then just last dot and file extension will be left.

How to convert a byte array to a hex string in Java?

Here is a java.util.Base64-like implementation, isn't it pretty?

import java.util.Arrays;

public class Base16/* a.k.a. Hex */ {
    public static class Encoder{
        private static char[] toLowerHex={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
        private static char[] toUpperHex={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        private boolean upper;
        public Encoder(boolean upper) {
            this.upper=upper;
        }
        public String encode(byte[] data){
            char[] value=new char[data.length*2];
            char[] toHex=upper?toUpperHex:toLowerHex;
            for(int i=0,j=0; i<data.length; i++){
                int octet=data[i]&0xFF;
                value[j++]=toHex[octet>>4];
                value[j++]=toHex[octet&0xF];
            }
            return new String(value);
        }
        static final Encoder LOWER_CASE=new Encoder(false);
        static final Encoder UPPER_CASE=new Encoder(true);
    }
    public static Encoder getEncoder(){
        return Encoder.LOWER_CASE;
    }
    public static Encoder getUpperEncoder(){
        return Encoder.UPPER_CASE;
    }

    public static class Decoder{
      private static int maxIndex=102;
      private static int[] toIndex;
      static {
        toIndex=new int[maxIndex+1];
        Arrays.fill(toIndex, -1);
        char[] chars={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','a','b','c','d','e','f'};
        for(int i=0; i<chars.length; i++) {
          toIndex[(int)chars[i]]=i;
        }
      }
      public Decoder() {
      }
      public byte[] decode(String str) {
          char[] value=str.toCharArray();
          int start=0;
          if(value.length>2 && value[0]=='0' && (value[1]=='x' || value[1]=='X')) {
            start=2;
          }
          int byteLength=(value.length-start)/2; // ignore trailing odd char if exists
          byte[] data=new byte[byteLength];
          for(int i=start,j=0;i<value.length;i+=2,j++){
              int i1;
              int i2;
              char c1=value[i];
              char c2=value[i+1];
              if(c1>maxIndex || (i1=toIndex[(int)c1])<0 || c2>maxIndex || (i2=toIndex[(int)c2])<0) {
                throw new IllegalArgumentException("Invalid character at "+i);
              }
              data[j]=(byte)((i1<<4)+i2);
          }
          return data;
      }
      static final Decoder IGNORE_CASE=new Decoder();
  }
  public static Decoder getDecoder(){
      return Decoder.IGNORE_CASE;
  }
}

How to download/upload files from/to SharePoint 2013 using CSOM?

Private Sub DownloadFile(relativeUrl As String, destinationPath As String, name As String)
    Try
        destinationPath = Replace(destinationPath + "\" + name, "\\", "\")
        Dim fi As FileInformation = Microsoft.SharePoint.Client.File.OpenBinaryDirect(Me.context, relativeUrl)
        Dim down As Stream = System.IO.File.Create(destinationPath)
        Dim a As Integer = fi.Stream.ReadByte()
        While a <> -1
            down.WriteByte(CType(a, Byte))
            a = fi.Stream.ReadByte()
        End While
    Catch ex As Exception
        ToLog(Type.ERROR, ex.Message)
    End Try
End Sub

To show error message without alert box in Java Script

You should place your script code after your HTML code and within your body tags. That way it doesn't run before the html code.

Why are only a few video games written in Java?

Actually, it is very possible for managed code to do 3d games, the problem is the back engines. With .Net, for a brief period, there was a Managed DirectX wrapper to DirectX 9 by Microsoft. This was before the abstraction that is now XNA.

Being given total access to DirectX api's, .Net games work a treat. The best example I know of is www.entombed.co.uk, which is written in VB.Net.

Unfortunately, on the Java side, it is seriously lacking - mainly for the reason that DirectX isn't available for Java, and games programmers know and understand the DirectX api - why learn yet another api when you will be returning to DirectX?

TypeError: $(...).DataTable is not a function

CAUSE

There could be multiple reasons for this error.

  • jQuery DataTables library is missing.
  • jQuery library is loaded after jQuery DataTables.
  • Multiple versions of jQuery library is loaded.

SOLUTION

Include only one version of jQuery library version 1.7 or newer before jQuery DataTables.

For example:

<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/jquery.dataTables.min.js" type="text/javascript"></script>

See jQuery DataTables: Common JavaScript console errors for more information on this and other common console errors.

Conda environments not showing up in Jupyter Notebook

Summary (tldr)

If you want the 'python3' kernel to always run the Python installation from the environment where it is launched, delete the User 'python3' kernel, which is taking precedence over whatever the current environment is with:

jupyter kernelspec remove python3

Full Solution

I am going to post an alternative and simpler solution for the following case:

  • You have created a conda environment
  • This environment has jupyter installed (which also installs ipykernel)
  • When you run the command jupyter notebook and create a new notebook by clicking 'python3' in the 'New' dropdown menu, that notebook executes python from the base environment and not from the current environment.
  • You would like it so that launching a new notebook with 'python3' within any environment executes the Python version from that environment and NOT the base

I am going to use the name 'test_env' for the environment for the rest of the solution. Also, note that 'python3' is the name of the kernel.

The currently top-voted answer does work, but there is an alternative. It says to do the following:

python -m ipykernel install --user --name test_env --display-name "Python (test_env)"

This will give you the option of using the test_env environment regardless of what environment you launch jupyter notebook from. But, launching a notebook with 'python3' will still use the Python installation from the base environment.

What likely is happening is that there is a user python3 kernel that exists. Run the command jupyter kernelspec list to list all of your environments. For instance, if you have a mac you will be returned the following (my user name is Ted).

python3       /Users/Ted/Library/Jupyter/kernels/python3

What Jupyter is doing here is searching through three different paths looking for kernels. It goes from User, to Env, to System. See this document for more details on the paths it searches for each operating system.

The two kernels above are both in the User path, meaning they will be available regardless of the environment that you launch a jupyter notebook from. This also means that if there is another 'python3' kernel at the environment level, then you will never be able to access it.

To me, it makes more sense that choosing the 'python3' kernel from the environment you launched the notebook from should execute Python from that environment.

You can check to see if you have another 'python3' environment by looking in the Env search path for your OS (see the link to the docs above). For me (on my mac), I issued the following command:

 ls /Users/Ted/anaconda3/envs/test_env/share/jupyter/kernels

And I indeed had a 'python3' kernel listed there.

Thanks to this GitHub issue comment (look at the first response), you can remove the User 'python3' environment with the following command:

jupyter kernelspec remove python3

Now when you run jupyter kernelspec list, assuming the test_env is still active, you will get the following:

python3       /Users/Ted/anaconda3/envs/test_env/share/jupyter/kernels/python3

Notice that this path is located within the test_env directory. If you create a new environment, install jupyter, activate it, and list the kernels, you will get another 'python3' kernel located in its environment path.

The User 'python3' kernel was taking precedence over any of the Env 'python3' kernels. By removing it, the active environment 'python3' kernel was exposed and able to be chosen every time. This eliminates the need to manually create kernels. It also makes more sense in terms of software development where one would want to isolate themselves into a single environment. Running a kernel that is different from the host environment doesn't seem natural.

It also seems that this User 'python3' is not installed for everyone by default, so not everyone is confronted by this issue.

How can I make all images of different height and width the same via CSS?

Set height and width parameters in CSS file

_x000D_
_x000D_
.ImageStyle{_x000D_
_x000D_
    max-height: 17vw;_x000D_
    min-height: 17vw;_x000D_
    max-width:17vw;_x000D_
    min-width: 17vw;_x000D_
    _x000D_
}
_x000D_
_x000D_
_x000D_

What are the minimum margins most printers can handle?

The margins vary depending on the printer. In Windows GDI, you call the following functions to get the built-in margins, the "no-print zone":

GetDeviceCaps(hdc, PHYSICALWIDTH);
GetDeviceCaps(hdc, PHYSICALHEIGHT);
GetDeviceCaps(hdc, PHYSICALOFFSETX);
GetDeviceCaps(hdc, PHYSICALOFFSETY);

Printing right to the edge is called a "bleed" in the printing industry. The only laser printer I ever knew to print right to the edge was the Xerox 9700: 120 ppm, $500K in 1980.

Generate a random number in the range 1 - 10

If you are using SQL Server then correct way to get integer is

SELECT Cast(RAND()*(b-a)+a as int);

Where

  • 'b' is the upper limit
  • 'a' is lower limit

Appending to an existing string

Here's another way:

fist_segment = "hello,"
second_segment = "world."
complete_string = "#{first_segment} #{second_segment}"

What is the best Java email address validation method?

Using the official java email package is the easiest:

public static boolean isValidEmailAddress(String email) {
   boolean result = true;
   try {
      InternetAddress emailAddr = new InternetAddress(email);
      emailAddr.validate();
   } catch (AddressException ex) {
      result = false;
   }
   return result;
}

COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?

I feel the performance characteristics change from one DBMS to another. It's all on how they choose to implement it. Since I have worked extensively on Oracle, I'll tell from that perspective.

COUNT(*) - Fetches entire row into result set before passing on to the count function, count function will aggregate 1 if the row is not null

COUNT(1) - Will not fetch any row, instead count is called with a constant value of 1 for each row in the table when the WHERE matches.

COUNT(PK) - The PK in Oracle is indexed. This means Oracle has to read only the index. Normally one row in the index B+ tree is many times smaller than the actual row. So considering the disk IOPS rate, Oracle can fetch many times more rows from Index with a single block transfer as compared to entire row. This leads to higher throughput of the query.

From this you can see the first count is the slowest and the last count is the fastest in Oracle.

How to count string occurrence in string?

For anyone that finds this thread in the future, note that the accepted answer will not always return the correct value if you generalize it, since it will choke on regex operators like $ and .. Here's a better version, that can handle any needle:

function occurrences (haystack, needle) {
  var _needle = needle
    .replace(/\[/g, '\\[')
    .replace(/\]/g, '\\]')
  return (
    haystack.match(new RegExp('[' + _needle + ']', 'g')) || []
  ).length
}

Get single row result with Doctrine NativeQuery

You can use $query->getSingleResult(), which will throw an exception if more than one result are found, or if no result is found. (see the related phpdoc here https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L791)

There's also the less famous $query->getOneOrNullResult() which will throw an exception if more than one result are found, and return null if no result is found. (see the related phpdoc here https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L752)

String.Format like functionality in T-SQL?

Here is my version. Can be extended to accommodate more number of parameters and can extend formatting based on type. Currently only date and datetime types are formatted.

Example:

select dbo.FormatString('some string %s some int %s date %s','"abcd"',100,cast(getdate() as date),DEFAULT,DEFAULT)
select dbo.FormatString('some string %s some int %s date time %s','"abcd"',100,getdate(),DEFAULT,DEFAULT)

Output:

some string "abcd" some int 100 date 29-Apr-2017
some string "abcd" some int 100 date time 29-Apr-2017 19:40

Functions:

create function dbo.FormatValue(@param sql_variant)
returns nvarchar(100)
begin
/*
Tejasvi Hegde, 29-April-2017
Can extend formatting here.
*/
    declare @result nvarchar(100)

    if (SQL_VARIANT_PROPERTY(@param,'BaseType') in ('date'))
    begin
       select @result = REPLACE(CONVERT(CHAR(11), @param, 106), ' ', '-')
    end
    else  if (SQL_VARIANT_PROPERTY(@param,'BaseType') in ('datetime','datetime2'))
    begin
       select @result = REPLACE(CONVERT(CHAR(11), @param, 106), ' ', '-')+' '+CONVERT(VARCHAR(5),@param,108)
    end
    else
    begin
       select @result = cast(@param as nvarchar(100))
    end
    return @result

/*
BaseType:
bigint
binary
char
date
datetime
datetime2
datetimeoffset
decimal
float
int
money
nchar
numeric
nvarchar
real
smalldatetime
smallint
smallmoney
time
tinyint
uniqueidentifier
varbinary
varchar
*/   

end;


create function dbo.FormatString(
    @format nvarchar(4000)
    ,@param1 sql_variant = null
    ,@param2 sql_variant = null
    ,@param3 sql_variant = null
    ,@param4 sql_variant = null
    ,@param5 sql_variant = null
    )
returns nvarchar(4000)
begin
/*
Tejasvi Hegde, 29-April-2017

select dbo.FormatString('some string value %s some int %s date %s','"abcd"',100,cast(getdate() as date),DEFAULT,DEFAULT)
select dbo.FormatString('some string value %s some int %s date time %s','"abcd"',100,getdate(),DEFAULT,DEFAULT)
*/

    declare @result nvarchar(4000)

    select @param1 = dbo.formatValue(@param1)
    ,@param2 = dbo.formatValue(@param2)
    ,@param3 = dbo.formatValue(@param3)
    ,@param4 = dbo.formatValue(@param4)
    ,@param5 = dbo.formatValue(@param5)

    select @param2 = cast(@param2 as nvarchar)
    EXEC xp_sprintf @result OUTPUT,@format , @param1, @param2, @param3, @param4, @param5

    return @result

end;

How to pause for specific amount of time? (Excel/VBA)

Just a cleaned up version of clemo's code - works in Access, which doesn't have the Application.Wait function.

Public Sub Pause(sngSecs As Single)
    Dim sngEnd As Single
    sngEnd = Timer + sngSecs
    While Timer < sngEnd
        DoEvents
    Wend
End Sub

Public Sub TestPause()
    Pause 1
    MsgBox "done"
End Sub

CodeIgniter activerecord, retrieve last insert id?

After your insert query, use this command $this->db->insert_id(); to return the last inserted id.

For example:

$this->db->insert('Your_tablename', $your_data);

$last_id =  $this->db->insert_id();

echo $last_id // assume that the last id from the table is 1, after the insert query this value will be 2.

Remove warning messages in PHP

There is already answer with Error Control Operator but it lacks of explanation. You can use @ operator with every expression and it hides errors (except of Fatal Errors).

@$test['test']; //PHP Notice:  Undefined variable: test

@(14/0); // PHP Warning:  Division by zero

//This is not working. You can't hide Fatal Errors this way.
@customFuntion(); // PHP Fatal error:  Uncaught Error: Call to undefined function customFuntion()

For debugging it's fast and perfect method. But you should never ever use it on production nor permanent include in your local version. It will give you a lot of unnecessary irritation.

You should consider instead:

1. Error reporting settings as mentioned in accepted answer.

error_reporting(E_ERROR | E_PARSE);

or from PHP INI settings

ini_set('display_errors','Off');

2. Catching exceptions

try {
    $var->method();
} catch (Error $e) {
    // Handle error
    echo $e->getMessage();
}

Copy Data from a table in one Database to another separate database

INSERT INTO DB1.dbo.TempTable
SELECT * FROM DB2.dbo.TempTable

If we use this query it will return Primary key error.... So better to choose which columns need to be moved, like

INSERT INTO db1.dbo.TempTable // (List of columns here)
SELECT (Same list of columns here)
FROM db2.dbo.TempTable

Using Excel VBA to export data to MS Access table

is it possible to export without looping through all records

For a range in Excel with a large number of rows you may see some performance improvement if you create an Access.Application object in Excel and then use it to import the Excel data into Access. The code below is in a VBA module in the same Excel document that contains the following test data

SampleData.png

Option Explicit

Sub AccImport()
    Dim acc As New Access.Application
    acc.OpenCurrentDatabase "C:\Users\Public\Database1.accdb"
    acc.DoCmd.TransferSpreadsheet _
            TransferType:=acImport, _
            SpreadSheetType:=acSpreadsheetTypeExcel12Xml, _
            TableName:="tblExcelImport", _
            Filename:=Application.ActiveWorkbook.FullName, _
            HasFieldNames:=True, _
            Range:="Folio_Data_original$A1:B10"
    acc.CloseCurrentDatabase
    acc.Quit
    Set acc = Nothing
End Sub

What are valid values for the id attribute in HTML?

In HTML

ID should start with {A-Z} or {a-z} you can Add Digits, period, hyphen, underscore, colons.

For example:

<span id="testID2"></span>
<span id="test-ID2"></span>
<span id="test_ID2"></span>
<span id="test:ID2"></span>
<span id="test.ID2"></span>

But Even Though You can Make ID with Colons(:) or period(.) It is hard for CSS to use these ID as Selector. Mainly when you want to Use Pseudo elements (:before,:after).

Also in JS it is Hard to select these ID's. So you should use first four ID's As preferred by many developer around and if it's necessary than you can use last two also.

Download file from web in Python 3

You can use wget which is popular downloading shell tool for that. https://pypi.python.org/pypi/wget This will be the simplest method since it does not need to open up the destination file. Here is an example.

import wget
url = 'https://i1.wp.com/python3.codes/wp-content/uploads/2015/06/Python3-powered.png?fit=650%2C350'  
wget.download(url, '/Users/scott/Downloads/cat4.jpg') 

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

You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

Pick an encoding and stick with it:

f.write(printinfo.encode('utf8') + '\n')

or use io.open() to create a file object that'll encode for you as you write to the file:

import io

f = io.open(filename, 'w', encoding='utf8')

You may want to read:

before continuing.

Internal vs. Private Access Modifiers

Private members are accessible only within the body of the class or the struct in which they are declared.

Internal types or members are accessible only within files in the same assembly

Can I change a column from NOT NULL to NULL without dropping it?

Sure you can.

ALTER TABLE myTable ALTER COLUMN myColumn int NULL

Just substitute int for whatever datatype your column is.

How can I create a memory leak in Java?

The interviewer might have be looking for a circular reference solution:

    public static void main(String[] args) {
        while (true) {
            Element first = new Element();
            first.next = new Element();
            first.next.next = first;
        }
    }

This is a classic problem with reference counting garbage collectors. You would then politely explain that JVMs use a much more sophisticated algorithm that doesn't have this limitation.

-Wes Tarle

Make div 100% Width of Browser Window

Set the margin for body at 0 and that will fix it.

body {
   margin: 0;
}

How can I remove time from date with Moment.js?

Whenever I use the moment.js library I specify the desired format this way:

moment(<your Date goes here>).format("DD-MMM-YYYY")

or

moment(<your Date goes here>).format("DD/MMM/YYYY")

... etc I hope you get the idea

Inside the format function, you put the desired format. The example above will get rid of all unwanted elements from the date such as minutes and seconds

How can I process each letter of text using Javascript?

You can simply iterate it as in an array:

for(var i in txt){
    console.log(txt[i]);
}

'and' (boolean) vs '&' (bitwise) - Why difference in behavior with lists vs numpy arrays?

  1. In Python an expression of X and Y returns Y, given that bool(X) == True or any of X or Y evaluate to False, e.g.:

    True and 20 
    >>> 20
    
    False and 20
    >>> False
    
    20 and []
    >>> []
    
  2. Bitwise operator is simply not defined for lists. But it is defined for integers - operating over the binary representation of the numbers. Consider 16 (01000) and 31 (11111):

    16 & 31
    >>> 16
    
  3. NumPy is not a psychic, it does not know, whether you mean that e.g. [False, False] should be equal to True in a logical expression. In this it overrides a standard Python behaviour, which is: "Any empty collection with len(collection) == 0 is False".

  4. Probably an expected behaviour of NumPy's arrays's & operator.

Printing out all the objects in array list

Override toString() method in Student class as below:

   @Override
   public String toString() {
        return ("StudentName:"+this.getStudentName()+
                    " Student No: "+ this.getStudentNo() +
                    " Email: "+ this.getEmail() +
                    " Year : " + this.getYear());
   }

Array vs ArrayList in performance

From here:

ArrayList is internally backed by Array in Java, any resize operation in ArrayList will slow down performance as it involves creating new Array and copying content from old array to new array.


In terms of performance Array and ArrayList provides similar performance in terms of constant time for adding or getting element if you know index. Though automatic resize of ArrayList may slow down insertion a bit Both Array and ArrayList is core concept of Java and any serious Java programmer must be familiar with these differences between Array and ArrayList or in more general Array vs List.

Using Custom Domains With IIS Express

On my WebMatrix IIS Express install changing from "*:80:localhost" to "*:80:custom.hostname" didn't work ("Bad Hostname", even with proper etc\hosts mappings), but "*:80:" did work--and with none of the additional steps required by the other answers here. Note that "*:80:*" won't do it; leave off the second asterisk.

Oracle: If Table Exists

You could always catch the error yourself.

begin
execute immediate 'drop table mytable';
exception when others then null;
end;

It is considered bad practice to overuse this, similar to empty catch()'es in other languages.

Regards
K

Using SSH keys inside docker container

If you are using docker compose an easy choice is to forward SSH agent like that:

something:
    container_name: something
    volumes:
        - $SSH_AUTH_SOCK:/ssh-agent # Forward local machine SSH key to docker
    environment:
        SSH_AUTH_SOCK: /ssh-agent

JavaScript Infinitely Looping slideshow with delays?

Perhps this is what you are looking for.

var pos = 0;
window.onload = function start() {
    setTimeout(slide, 3000);
}
function slide() {
   pos -= 600;
   if (pos === -2400)
     pos = 0;
   document.getElementById('container').style.marginLeft= pos + "px";
   setTimeout(slide, 3000);
}

Allow scroll but hide scrollbar

I know this is an oldie but here is a quick way to hide the scroll bar with pure CSS.

Just add

::-webkit-scrollbar {display:none;}

To your id or class of the div you're using the scroll bar with.

Here is a helpful link Custom Scroll Bar in Webkit

How to populate options of h:selectOneMenu from database?

Based on your question history, you're using JSF 2.x. So, here's a JSF 2.x targeted answer. In JSF 1.x you would be forced to wrap item values/labels in ugly SelectItem instances. This is fortunately not needed anymore in JSF 2.x.


Basic example

To answer your question directly, just use <f:selectItems> whose value points to a List<T> property which you preserve from the DB during bean's (post)construction. Here's a basic kickoff example assuming that T actually represents a String.

<h:selectOneMenu value="#{bean.name}">
    <f:selectItems value="#{bean.names}" />
</h:selectOneMenu>

with

@ManagedBean
@RequestScoped
public class Bean {

    private String name;
    private List<String> names; 

    @EJB
    private NameService nameService;

    @PostConstruct
    public void init() {
        names = nameService.list();
    }

    // ... (getters, setters, etc)
}

Simple as that. Actually, the T's toString() will be used to represent both the dropdown item label and value. So, when you're instead of List<String> using a list of complex objects like List<SomeEntity> and you haven't overridden the class' toString() method, then you would see com.example.SomeEntity@hashcode as item values. See next section how to solve it properly.

Also note that the bean for <f:selectItems> value does not necessarily need to be the same bean as the bean for <h:selectOneMenu> value. This is useful whenever the values are actually applicationwide constants which you just have to load only once during application's startup. You could then just make it a property of an application scoped bean.

<h:selectOneMenu value="#{bean.name}">
    <f:selectItems value="#{data.names}" />
</h:selectOneMenu>

Complex objects as available items

Whenever T concerns a complex object (a javabean), such as User which has a String property of name, then you could use the var attribute to get hold of the iteration variable which you in turn can use in itemValue and/or itemLabel attribtues (if you omit the itemLabel, then the label becomes the same as the value).

Example #1:

<h:selectOneMenu value="#{bean.userName}">
    <f:selectItems value="#{bean.users}" var="user" itemValue="#{user.name}" />
</h:selectOneMenu>

with

private String userName;
private List<User> users;

@EJB
private UserService userService;

@PostConstruct
public void init() {
    users = userService.list();
}

// ... (getters, setters, etc)

Or when it has a Long property id which you would rather like to set as item value:

Example #2:

<h:selectOneMenu value="#{bean.userId}">
    <f:selectItems value="#{bean.users}" var="user" itemValue="#{user.id}" itemLabel="#{user.name}" />
</h:selectOneMenu>

with

private Long userId;
private List<User> users;

// ... (the same as in previous bean example)

Complex object as selected item

Whenever you would like to set it to a T property in the bean as well and T represents an User, then you would need to bake a custom Converter which converts between User and an unique string representation (which can be the id property). Do note that the itemValue must represent the complex object itself, exactly the type which needs to be set as selection component's value.

<h:selectOneMenu value="#{bean.user}" converter="#{userConverter}">
    <f:selectItems value="#{bean.users}" var="user" itemValue="#{user}" itemLabel="#{user.name}" />
</h:selectOneMenu>

with

private User user;
private List<User> users;

// ... (the same as in previous bean example)

and

@ManagedBean
@RequestScoped
public class UserConverter implements Converter {

    @EJB
    private UserService userService;

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
        if (submittedValue == null || submittedValue.isEmpty()) {
            return null;
        }

        try {
            return userService.find(Long.valueOf(submittedValue));
        } catch (NumberFormatException e) {
            throw new ConverterException(new FacesMessage(String.format("%s is not a valid User ID", submittedValue)), e);
        }
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
        if (modelValue == null) {
            return "";
        }

        if (modelValue instanceof User) {
            return String.valueOf(((User) modelValue).getId());
        } else {
            throw new ConverterException(new FacesMessage(String.format("%s is not a valid User", modelValue)), e);
        }
    }

}

(please note that the Converter is a bit hacky in order to be able to inject an @EJB in a JSF converter; normally one would have annotated it as @FacesConverter(forClass=User.class), but that unfortunately doesn't allow @EJB injections)

Don't forget to make sure that the complex object class has equals() and hashCode() properly implemented, otherwise JSF will during render fail to show preselected item(s), and you'll on submit face Validation Error: Value is not valid.

public class User {

    private Long id;

    @Override
    public boolean equals(Object other) {
        return (other != null && getClass() == other.getClass() && id != null)
            ? id.equals(((User) other).id)
            : (other == this);
    }

    @Override
    public int hashCode() {
        return (id != null) 
            ? (getClass().hashCode() + id.hashCode())
            : super.hashCode();
    }

}

Complex objects with a generic converter

Head to this answer: Implement converters for entities with Java Generics.


Complex objects without a custom converter

The JSF utility library OmniFaces offers a special converter out the box which allows you to use complex objects in <h:selectOneMenu> without the need to create a custom converter. The SelectItemsConverter will simply do the conversion based on readily available items in <f:selectItem(s)>.

<h:selectOneMenu value="#{bean.user}" converter="omnifaces.SelectItemsConverter">
    <f:selectItems value="#{bean.users}" var="user" itemValue="#{user}" itemLabel="#{user.name}" />
</h:selectOneMenu>

See also:

Linking to a specific part of a web page

In case the target page is on the same domain (i.e. shares the same origin with your page) and you don't mind creation of new tabs (1), you can (ab)use some JavaScript:

<a href="javascript:void(window.open('./target.html').onload=function(){this.document.querySelector('p:nth-child(10)').scrollIntoView()})">see tenth paragraph on another page</a>

Trivia:

var w = window.open('some URL of the same origin');
w.onload = function(){
  // do whatever you want with `this.document`, like
  this.document.querySelecotor('footer').scrollIntoView()
}

Working example of such 'exploit' you can try right now could be:

javascript:(function(url,sel,w,el){w=window.open(url);w.addEventListener('load',function(){w.setTimeout(function(){el=w.document.querySelector(sel);el.scrollIntoView();el.style.backgroundColor='red'},1000)})})('https://stackoverflow.com/questions/45014240/link-to-a-specific-spot-on-a-page-i-cant-edit','footer')

If you enter this into location bar (mind that Chrome removes javascript: prefix when pasted from clipboard) or make it a href value of any link on this page (using Developer Tools) and click it, you will get another (duplicate) SO question page scrolled to the footer and footer painted red. (Delay added as a workaround for ajax-loaded content pushing footer down after load.)

Notes

  • Tested in current Chrome and Firefox, generally should work since it is based on defined standard behaviour.
  • Cannot be illustrated in interactive snippet here at SO, because they are isolated from the page origin-wise.
  • MDN: Window.open()
  • (1) window.open(url,'_self') seems to be breaking the load event; basically makes the window.open behave like a normal a href="" click navigation; haven't researched more yet.

Maven version with a property

I have two recommendation for you

  1. Use CI Friendly Revision for all your artifacts. You can add -Drevision=2.0.1 in .mvn/maven.config file. So basically you define your version only at one location.
  2. For all external dependency create a property in parent file. You can use Apache Camel Parent Pom as reference

Determine if string is in list in JavaScript

My solution results in a syntax like this:

// Checking to see if var 'column' is in array ['a', 'b', 'c']

if (column.isAmong(['a', 'b', 'c']) {
  // Do something
}

And I implement this by extending the basic Object prototype, like this:

Object.prototype.isAmong = function (MyArray){
   for (var a=0; a<MyArray.length; a++) {
      if (this === MyArray[a]) { 
          return true;
      }
   }
   return false;
}

We might alternatively name the method isInArray (but probably not inArray) or simply isIn.

Advantages: Simple, straightforward, and self-documenting.

How to do a simple file search in cmd

You can search in windows by DOS and explorer GUI.

DOS:

1) DIR

2) ICACLS (searches for files and folders to set ACL on them)

3) cacls ..................................................

2) example

icacls c:*ntoskrnl*.* /grant system:(f) /c /t ,then use PMON from sysinternals to monitor what folders are denied accesss. The result contains

access path contains your drive

process name is explorer.exe

those were filters youu must apply

scroll image with continuous scrolling using marquee tag

Marquee (<marquee>) is a deprecated and not a valid HTML tag. You can use many jQuery plugins to do. One of it, is jQuery News Ticker. There are many more!

How do you redirect HTTPS to HTTP?

It is better to avoid using mod_rewrite when you can.

In your case I would replace the Rewrite with this:

    <If "%{HTTPS} == 'on'" >
            Redirect permanent / http://production_server/
    </If>

The <If> directive is only available in Apache 2.4+ as per this blog here.

Vertical dividers on horizontal UL menu

I do it as Pekka says. Put an inline style on each <li>:

style="border-right: solid 1px #555; border-left: solid 1px #111;"

Take off first and last as appropriate.

Add column to SQL Server

Use this query:

ALTER TABLE tablename ADD columname DATATYPE(size);

And here is an example:

ALTER TABLE Customer ADD LastName VARCHAR(50);

VBA general way for pulling data out of SAP

This all depends on what sort of access you have to your SAP system. An ABAP program that exports the data and/or an RFC that your macro can call to directly get the data or have SAP create the file is probably best.

However as a general rule people looking for this sort of answer are looking for an immediate solution that does not require their IT department to spend months customizing their SAP system.

In that case you probably want to use SAP GUI Scripting. SAP GUI scripting allows you to automate the Windows SAP GUI in much the same way as you automate Excel. In fact you can call the SAP GUI directly from an Excel macro. Read up more on it here. The SAP GUI has a macro recording tool much like Excel does. It records macros in VBScript which is nearly identical to Excel VBA and can usually be copied and pasted into an Excel macro directly.

Example Code

Here is a simple example based on a SAP system I have access to.

Public Sub SimpleSAPExport()
  Set SapGuiAuto  = GetObject("SAPGUI") 'Get the SAP GUI Scripting object
  Set SAPApp = SapGuiAuto.GetScriptingEngine 'Get the currently running SAP GUI 
  Set SAPCon = SAPApp.Children(0) 'Get the first system that is currently connected
  Set session = SAPCon.Children(0) 'Get the first session (window) on that connection

  'Start the transaction to view a table
  session.StartTransaction "SE16"

  'Select table T001
  session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").Text = "T001"
  session.findById("wnd[0]/tbar[1]/btn[7]").Press

  'Set our selection criteria
  session.findById("wnd[0]/usr/txtMAX_SEL").text = "2"
  session.findById("wnd[0]/tbar[1]/btn[8]").press

  'Click the export to file button
  session.findById("wnd[0]/tbar[1]/btn[45]").press

  'Choose the export format
  session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").select
  session.findById("wnd[1]/tbar[0]/btn[0]").press

  'Choose the export filename
  session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "test.txt"
  session.findById("wnd[1]/usr/ctxtDY_PATH").text = "C:\Temp\"

  'Export the file
  session.findById("wnd[1]/tbar[0]/btn[0]").press
End Sub

Script Recording

To help find the names of elements such aswnd[1]/tbar[0]/btn[0] you can use script recording. Click the customize local layout button, it probably looks a bit like this: Customize Local Layout
Then find the Script Recording and Playback menu item.
Script Recording and Playback
Within that the More button allows you to see/change the file that the VB Script is recorded to. The output format is a bit messy, it records things like selecting text, clicking inside a text field, etc.

Edit: Early and Late binding

The provided script should work if copied directly into a VBA macro. It uses late binding, the line Set SapGuiAuto = GetObject("SAPGUI") defines the SapGuiAuto object.

If however you want to use early binding so that your VBA editor might show the properties and methods of the objects you are using, you need to add a reference to sapfewse.ocx in the SAP GUI installation folder.

Are nested try/except blocks in Python a good programming practice?

Your first example is perfectly fine. Even the official Python documentation recommends this style known as EAFP.

Personally, I prefer to avoid nesting when it's not necessary:

def __getattribute__(self, item):
    try:
        return object.__getattribute__(item)
    except AttributeError:
        pass  # Fallback to dict
    try:
        return self.dict[item]
    except KeyError:
        raise AttributeError("The object doesn't have such attribute") from None

PS. has_key() has been deprecated for a long time in Python 2. Use item in self.dict instead.

error::make_unique is not a member of ‘std’

In my case I was needed update the std=c++

I mean in my gradle file was this

android {
    ...

    defaultConfig {
        ...

        externalNativeBuild {
            cmake {
                cppFlags "-std=c++11", "-Wall"
                arguments "-DANDROID_STL=c++_static",
                        "-DARCORE_LIBPATH=${arcore_libpath}/jni",
                        "-DARCORE_INCLUDE=${project.rootDir}/app/src/main/libs"
            }
        }
       ....
    }

I changed this line

android {
    ...

    defaultConfig {
        ...

        externalNativeBuild {
            cmake {
                cppFlags "-std=c++17", "-Wall"   <-- this number from 11 to 17 (or 14)
                arguments "-DANDROID_STL=c++_static",
                        "-DARCORE_LIBPATH=${arcore_libpath}/jni",
                        "-DARCORE_INCLUDE=${project.rootDir}/app/src/main/libs"
            }
        }
       ....
    }

That's it...

Extract XML Value in bash script

I agree with Charles Duffy that a proper XML parser is the right way to go.

But as to what's wrong with your sed command (or did you do it on purpose?).

  • $data was not quoted, so $data is subject to shell's word splitting, filename expansion among other things. One of the consequences being that the spacing in the XML snippet is not preserved.

So given your specific XML structure, this modified sed command should work

title=$(sed -ne '/title/{s/.*<title>\(.*\)<\/title>.*/\1/p;q;}' <<< "$data")

Basically for the line that contains title, extract the text between the tags, then quit (so you don't extract the 2nd <title>)

How do I get the offset().top value of an element without using jQuery?

the accepted solution by Patrick Evans doesn't take scrolling into account. i've slightly changed his jsfiddle to demonstrate this:

css: add some random height to make sure we got some space to scroll

body{height:3000px;} 

js: set some scroll position

jQuery(window).scrollTop(100);

as a result the two reported values differ now: http://jsfiddle.net/sNLMe/66/

UPDATE Feb. 14 2015

there is a pull request for jqLite waiting, including its own offset method (taking care of current scroll position). have a look at the source in case you want to implement it yourself: https://github.com/angular/angular.js/pull/3799/files

How to pass parameters to $http in angularjs?

Here is a simple mathed to pass values from a route provider

//Route Provider
$routeProvider.when("/page/:val1/:val2/:val3",{controller:pageCTRL, templateUrl: 'pages.html'});


//Controller
$http.get( 'page.php?val1='+$routeParams.val1 +'&val2='+$routeParams.val2 +'&val3='+$routeParams.val3 , { cache: true})
        .then(function(res){
            //....
        })

BackgroundWorker vs background Thread

I knew how to use threads before I knew .NET, so it took some getting used to when I began using BackgroundWorkers. Matt Davis has summarized the difference with great excellence, but I would add that it's more difficult to comprehend exactly what the code is doing, and this can make debugging harder. It's easier to think about creating and shutting down threads, IMO, than it is to think about giving work to a pool of threads.

I still can't comment other people's posts, so forgive my momentary lameness in using an answer to address piers7

Don't use Thread.Abort(); instead, signal an event and design your thread to end gracefully when signaled. Thread.Abort() raises a ThreadAbortException at an arbitrary point in the thread's execution, which can do all kinds of unhappy things like orphan Monitors, corrupt shared state, and so on.
http://msdn.microsoft.com/en-us/library/system.threading.thread.abort.aspx

Duplicate and rename Xcode project & associated folders

I'm posting this since I have always been struggling when renaming a project in XCode.

Renaming the project is good and simple but this doesn't rename the source folder. Here is a step by step of what I have done that worked great in Xcode 4 and 5 thanks to the links below.

REF links:
Rename Project.
Rename Source Folder and other files.

1- Backup your project.

If you are using git, commit any changes, make a copy of the entire project folder and backup in time machine before making any changes (this step is not required but I highly recommended).

2- Open your project.

3- Slow double click or hit enter on the Project name (blue top icon) and rename it to whatever you like.

NOTE: After you rename the project and press ‘enter’ it will suggest to automatically change all project-name-related entries and will allow you to de-select some of them if you want. Select all of them and click ok.

4- Rename the Scheme

a) Click the menu right next to the stop button and select Manage Schemes.

b) Single-slow-click or hit enter on the old name scheme and rename it to whatever you like.

c) Click ok.

5 - Build and run to make sure it works.

NOTES: At this point all of the important project files should be renamed except the comments in the classes created when the project was created nor the source folder. Next we will rename the folder in the file system.

6- Close the project.

7- Rename the main and the source folder.

8- Right click the project bundle .xcodeproj file and select “Show Package Contents” from the context menu. Open the .pbxproj file with any text editor.

9- Search and replace any occurrence of the original folder name with the new folder name.

10- Save the file.

11- Open XCode project, test it.

12- Done.

EDIT 10/11/19:

There is a tool to rename projects in Xcode I haven't tried it enough to comment on it. https://github.com/appculture/xcode-project-renamer

Child inside parent with min-height: 100% not inheriting height

This is a reported webkit (chrome/safari) bug, children of parents with min-height can't inherit the height property: https://bugs.webkit.org/show_bug.cgi?id=26559

Apparently Firefox is affected too (can't test in IE at the moment)

Possible workaround:

  • add position:relative to #containment
  • add position:absolute to #containment-shadow-left

The bug doesn't show when the inner element has absolute positioning.

See http://jsfiddle.net/xrebB/

Edit on April 10, 2014

Since I'm currently working on a project for which I really need parent containers with min-height, and child elements inheriting the height of the container, I did some more research.

First: I'm not so sure anymore whether the current browser behaviour really is a bug. CSS2.1 specs say:

The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to 'auto'.

If I put a min-height on my container, I'm not explicitly specifying its height - so my element should get an auto height. And that's exactly what Webkit - and all other browsers - do.

Second, the workaround I found:

If I set my container element to display:table with height:inherit it acts exactly the same way as if I'd give it a min-height of 100%. And - more importantly - if I set the child element to display:table-cell it will perfectly inherit the height of the container element - whether it's 100% or more.

Full CSS:

html, body {
  height: 100%;
  margin: 0;
}

#container {
  background: green;
  display: table;
  height: inherit;
  width: 100%;
}

#content {
  background: red;
  display: table-cell;
}

The markup:

<div id="container">
  <div id="content">
      <p>content</p>
  </div>
</div>

See http://jsfiddle.net/xrebB/54/.

Callback function for JSONP with jQuery AJAX

delete this line:

jsonp: 'jsonp_callback',

Or replace this line:

url: 'http://url.of.my.server/submit?callback=json_callback',

because currently you are asking jQuery to create a random callback function name with callback=? and then telling jQuery that you want to use jsonp_callback instead.

WCF error: The caller was not authenticated by the service

if needed to specify domain(which authecticates username and password that client uses) in webconfig you can put this in system.serviceModel services service section:

<identity>          
<servicePrincipalName value="example.com" />
</identity>

and in client specify domain and username and password:

 client.ClientCredentials.Windows.ClientCredential.Domain = "example.com";
 client.ClientCredentials.Windows.ClientCredential.UserName = "UserName ";
 client.ClientCredentials.Windows.ClientCredential.Password = "Password";

Insert Data Into Temp Table with Query

This is possible. Try this way:

Create Global Temporary Table 
BossaDoSamba 
On Commit Preserve Rows 
As 
select ArtistName, sum(Songs) As NumberOfSongs 
 from Spotfy 
    where ArtistName = 'BossaDoSamba'
 group by ArtistName;

Combine two integer arrays

use ArrayUtils.addAll(T[], T...):

import org.apache.commons.lang3.ArrayUtils;

AnyObject[] array1 = ...;
AnyObject[] array2 = ...;
AnyObject[] mergedArray = ArrayUtils.addAll(array1, array2);

How to view .img files?

As you did not mention which OS you are running, here a solution for linux: use losetup

losetup /dev/loop0 /path/to/your/file.img

Then you can mount it.

Why is access to the path denied?

An UnauthorizedAccessException exception is thrown when the operating system denies access because of an I/O error or a security error.

If you are attempting to access a file or registry key, make sure it is not read-only.

How can I make visible an invisible control with jquery? (hide and show not work)

It's been more than 10 years and not sure if anyone still finding this question or answer relevant.

But a quick workaround is just to wrap the asp control within a html container

<div id="myElement" style="display: inline-block">
   <asp:TextBox ID="textBox1" runat="server"></asp:TextBox>
</div>

Whenever the Javascript Event is triggered, if it needs to be an event by the asp control, just wrap the asp control around the div container.

<div id="testG">  
   <asp:Button ID="Button2" runat="server" CssClass="btn" Text="Activate" />
</div>

The jQuery Code is below:

$(document).ready(function () {
    $("#testG").click(function () {
                $("#myElement").css("display", "none");
     });
});

How to detect lowercase letters in Python?

import re
s = raw_input('Type a word: ')
slower=''.join(re.findall(r'[a-z]',s))
supper=''.join(re.findall(r'[A-Z]',s))
print slower, supper

Prints:

Type a word: A Title of a Book
itleofaook ATB

Or you can use a list comprehension / generator expression:

slower=''.join(c for c in s if c.islower())
supper=''.join(c for c in s if c.isupper())
print slower, supper

Prints:

Type a word: A Title of a Book
itleofaook ATB

How to remove the bottom border of a box with CSS

You could just set the width to auto. Then the width of the div will equal 0 if it has no content.

width:auto;

Error Running React Native App From Terminal (iOS)

Problem is your Xcode version is not set on Command Line Tools, to solve this problem open Xcode>Menu>preferences> location> here for Command Line tools select your Xcode version, that's it. enter image description here

Enable binary mode while restoring a Database from an SQL dump

If you don't have enough space or don't want to waste time in decompressing it, Try this command.

gunzip < compressed-sqlfile.gz | mysql -u root -p

Don't forget to replace compressed-sqlfile.gz with your compressed file name.

.gz restore will not work without command I provided above.

JUnit test for System.out.println()

You don't want to redirect the system.out stream because that redirects for the ENTIRE JVM. Anything else running on the JVM can get messed up. There are better ways to test input/output. Look into stubs/mocks.

vertical alignment of text element in SVG

According to SVG spec, alignment-baseline only applies to <tspan>, <textPath>, <tref> and <altGlyph>. My understanding is that it is used to offset those from the <text> object above them. I think what you are looking for is dominant-baseline.

Possible values of dominant-baseline are:

auto | use-script | no-change | reset-size | ideographic | alphabetic | hanging | mathematical | central | middle | text-after-edge | text-before-edge | inherit

Check the W3C recommendation for the dominant-baseline property for more information about each possible value.

How to insert a value that contains an apostrophe (single quote)?

Because a single quote is used for indicating the start and end of a string; you need to escape it.

The short answer is to use two single quotes - '' - in order for an SQL database to store the value as '.

Look at using REPLACE to sanitize incoming values:

You want to check for '''', and replace them if they exist in the string with '''''' in order to escape the lone single quote.

Angular 2 Cannot find control with unspecified name attribute on formArrays

In my case I solved the issue by putting the name of the formControl in double and sinlge quotes so that it is interpreted as a string:

[formControlName]="'familyName'"

similar to below:

formControlName="familyName"

Python xml ElementTree from a string source?

You need the xml.etree.ElementTree.fromstring(text)

from xml.etree.ElementTree import XML, fromstring
myxml = fromstring(text)

Cannot find the declaration of element 'beans'

Use this to solve your problem:

<context:annotation-config/>

Generating a PDF file from React Components

I used jsPDF and html-to-image.

You can check out the code on the below git repo.

Link

If you like, you can drop a star there??

Uncaught TypeError: .indexOf is not a function

Basically indexOf() is a method belongs to string(array object also), But while calling the function you are passing a number, try to cast it to a string and pass it.

document.getElementById("oset").innerHTML = timeD2C(timeofday + "");

_x000D_
_x000D_
 var timeofday = new Date().getHours() + (new Date().getMinutes()) / 60;_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
 function timeD2C(time) { // Converts 11.5 (decimal) to 11:30 (colon)_x000D_
    var pos = time.indexOf('.');_x000D_
    var hrs = time.substr(1, pos - 1);_x000D_
    var min = (time.substr(pos, 2)) * 60;_x000D_
_x000D_
    if (hrs > 11) {_x000D_
        hrs = (hrs - 12) + ":" + min + " PM";_x000D_
    } else {_x000D_
        hrs += ":" + min + " AM";_x000D_
    }_x000D_
    return hrs;_x000D_
}_x000D_
alert(timeD2C(timeofday+""));
_x000D_
_x000D_
_x000D_


And it is good to do the string conversion inside your function definition,

function timeD2C(time) { 
  time = time + "";
  var pos = time.indexOf('.');

So that the code flow won't break at times when devs forget to pass a string into this function.

Does IE9 support console.log, and is it a real function?

How about...

console = { log : function(text) { alert(text); } }

How can I manually generate a .pyc file from a .py file

There is two way to do this

  1. Command line
  2. Using python program

If you are using command line use python -m compileall <argument> to compile python code to python binary code. Ex: python -m compileall -x ./*

Or, You can use this code to compile your library into byte-code.

import compileall
import os

lib_path = "your_lib_path"
build_path = "your-dest_path"

compileall.compile_dir(lib_path, force=True, legacy=True)

def moveToNewLocation(cu_path):
    for file in os.listdir(cu_path):
        if os.path.isdir(os.path.join(cu_path, file)):
            compile(os.path.join(cu_path, file))
        elif file.endswith(".pyc"):
            dest = os.path.join(build_path, cu_path ,file)
            os.makedirs(os.path.dirname(dest), exist_ok=True)
            os.rename(os.path.join(cu_path, file), dest)

moveToNewLocation(lib_path)

look at ? docs.python.org for detailed documentation

How can I convert a string to boolean in JavaScript?

You can use Function to return a Boolean value from string "true" or "false"

_x000D_
_x000D_
const TRUE_OR_FALSE = str => new Function(`return ${str}`)();_x000D_
_x000D_
const [TRUE, FALSE] = ["true", "false"];_x000D_
_x000D_
const [T, F] = [TRUE_OR_FALSE(TRUE), TRUE_OR_FALSE(FALSE)];_x000D_
_x000D_
console.log(T, typeof T); // `true` `"boolean"`_x000D_
_x000D_
console.log(F, typeof F); // `false` `"boolean"`
_x000D_
_x000D_
_x000D_

php pdo: get the columns name of a table

This will work for MySQL, Postgres, and probably any other PDO driver that uses the LIMIT clause.

Notice LIMIT 0 is added for improved performance:

$rs = $db->query('SELECT * FROM my_table LIMIT 0');
for ($i = 0; $i < $rs->columnCount(); $i++) {
    $col = $rs->getColumnMeta($i);
    $columns[] = $col['name'];
}
print_r($columns);

Error handling in Bash

I've used

die() {
        echo $1
        kill $$
}

before; i think because 'exit' was failing for me for some reason. The above defaults seem like a good idea, though.

Force IE10 to run in IE10 Compatibility View?

The X-UA-Compatible meta element only changes the Document mode, not the Browser mode. The Browser mode is chosen before the page is requested, so there is no way to include any markup, JavaScript or such to change this. While the Document mode falls back to older standards and quirks modes of the rendering engine, the Browser mode just changes things like how the browser identifies, such as the User Agent string.

If you’d like to change the Browser mode for all users (rather than changing it manually in the tools or through the settings), the only way (AFAICT) is to get your site added to Microsoft’s Copat View List. This is maintained by Microsoft to apply overrides to sites which break. There is information on how to remove your site from the compat view list, but none I can find to request that you're added.

The preferred method however is to try to fix any issues on the site first, as when you don’t run using the latest document and browser mode you can not take advantage of improvements in the browser, such as increased performance.

Generate table relationship diagram from existing schema (SQL Server)

Yes you can use SQL Server 2008 itself but you need to install SQL Server Management Studio Express (if not installed ) . Just right Click on Database Diagrams and create new diagram. Select the exisiting tables and if you have specified the references in your tables properly. You will be able to see the complete diagram of selected tables. For further reference see Getting started with SQL Server database diagrams

Deleting row from datatable in C#

There several different ways to do it. But You can use the following approach:

List<DataRow> RowsToDelete = new List<DataRow>();

for (int i = 0; i < drr.Length; i++) 
{     
   if(condition to delete the row) 
   {  
       RowsToDelete.Add(drr[i]);     
   } 
}

foreach(var dr in RowsToDelete) 
{     
   drr.Rows.Remove(dr); 
} 

invalid target release: 1.7

Other than setting JAVA_HOME environment variable, you got to make sure you are using the correct JDK in your Maven run configuration. Go to Run -> Run Configuration, select your Maven Build configuration, go to JRE tab and set the correct Runtime JRE.

Maven run configuration

Your content must have a ListView whose id attribute is 'android.R.id.list'

You should have one listview in your mainlist.xml file with id as @android:id/list

<ListView
    android:id="@android:id/list"
    android:layout_height="wrap_content"
    android:layout_height="fill_parent"/>

Convert dictionary to list collection in C#

If you want to pass the Dictionary keys collection into one method argument.

List<string> lstKeys = Dict.Keys;
Methodname(lstKeys);
-------------------
void MethodName(List<String> lstkeys)
{
    `enter code here`
    //Do ur task
}

If a folder does not exist, create it

Use the below code. I use this code for file copy and creating a new folder.

string fileToCopy = "filelocation\\file_name.txt";
String server = Environment.UserName;
string newLocation = "C:\\Users\\" + server + "\\Pictures\\Tenders\\file_name.txt";
string folderLocation = "C:\\Users\\" + server + "\\Pictures\\Tenders\\";
bool exists = System.IO.Directory.Exists(folderLocation);

if (!exists)
{
   System.IO.Directory.CreateDirectory(folderLocation);
   if (System.IO.File.Exists(fileToCopy))
   {
     MessageBox.Show("file copied");
     System.IO.File.Copy(fileToCopy, newLocation, true);
   }
   else
   {
      MessageBox.Show("no such files");
   }
}

Convert timestamp long to normal date format

java.time

    ZoneId usersTimeZone = ZoneId.of("Asia/Tashkent");
    Locale usersLocale = Locale.forLanguageTag("ga-IE");
    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
            .withLocale(usersLocale);

    long microsSince1970 = 1_512_345_678_901_234L;
    long secondsSince1970 = TimeUnit.MICROSECONDS.toSeconds(microsSince1970);
    long remainingMicros = microsSince1970 - TimeUnit.SECONDS.toMicros(secondsSince1970);
    ZonedDateTime dateTime = Instant.ofEpochSecond(secondsSince1970, 
                    TimeUnit.MICROSECONDS.toNanos(remainingMicros))
            .atZone(usersTimeZone);
    String dateTimeInUsersFormat = dateTime.format(formatter);
    System.out.println(dateTimeInUsersFormat);

The above snippet prints:

4 Noll 2017 05:01:18

“Noll” is Gaelic for December, so this should make your user happy. Except there may be very few Gaelic speaking people living in Tashkent, so please specify the user’s correct time zone and locale yourself.

I am taking seriously that you got microseconds from your database. If second precision is fine, you can do without remainingMicros and just use the one-arg Instant.ofEpochSecond(), which will make the code a couple of lines shorter. Since Instant and ZonedDateTime do support nanosecond precision, I found it most correct to keep the full precision of your timestamp. If your timestamp was in milliseconds rather than microseconds (which they often are), you may just use Instant.ofEpochMilli().

The answers using Date, Calendar and/or SimpleDateFormat were fine when this question was asked 7 years ago. Today those classes are all long outdated, and we have so much better in java.time, the modern Java date and time API.

For most uses I recommend you use the built-in localized formats as I do in the code. You may experiment with passing SHORT, LONG or FULL for format style. Yo may even specify format style for the date and for the time of day separately using an overloaded ofLocalizedDateTime method. If a specific format is required (this was asked in a duplicate question), you can have that:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss, dd/MM/uuuu");

Using this formatter instead we get

05:01:18, 04/12/2017

Link: Oracle tutorial: Date Time explaining how to use java.time.

What is the difference between a pandas Series and a single-column DataFrame?

from the pandas doc http://pandas.pydata.org/pandas-docs/stable/dsintro.html Series is a one-dimensional labeled array capable of holding any data type. To read data in form of panda Series:

import pandas as pd
ds = pd.Series(data, index=index)

DataFrame is a 2-dimensional labeled data structure with columns of potentially different types.

import pandas as pd
df = pd.DataFrame(data, index=index)

In both of the above index is list

for example: I have a csv file with following data:

,country,popuplation,area,capital
BR,Brazil,10210,12015,Brasile
RU,Russia,1025,457,Moscow
IN,India,10458,457787,New Delhi

To read above data as series and data frame:

import pandas as pd
file_data = pd.read_csv("file_path", index_col=0)
d = pd.Series(file_data.country, index=['BR','RU','IN'] or index =  file_data.index)

output:

>>> d
BR           Brazil
RU           Russia
IN            India

df = pd.DataFrame(file_data.area, index=['BR','RU','IN'] or index = file_data.index )

output:

>>> df
      area
BR   12015
RU     457
IN  457787

Class 'App\Http\Controllers\DB' not found and I also cannot use a new Model

The problem here are PHP namespaces. You need to learn how to use them. As your controller are in App\Http\Controllers namespace, if you refer any other class, you need to add leading backslash (or proper namespace) or add use statement at the beginning of file (before class definition).

So in your case you could use:

$headquote = \DB::table('quotation_texts')->find(176);
$headquote = \App\Quotation::find(176);

or add in your controller class use statement so the beginning of your controller class could look like this:

<?php

namespace App\Http\Controllers;

use DB;
use App\Quotation;

For more information about namespaces you could look at How to use objects from other namespaces and how to import namespaces in PHP or namespaces in PHP manual

How do I open a second window from the first window in WPF?

private void button1_Click(object sender, RoutedEventArgs e)
{
    window2 win2 = new window2();
    win2.Show();
}

Why can't Python find shared objects that are in directories in sys.path?

You can also set LD_RUN_PATH to /usr/local/lib in your user environment when you compile pycurl in the first place. This will embed /usr/local/lib in the RPATH attribute of the C extension module .so so that it automatically knows where to find the library at run time without having to have LD_LIBRARY_PATH set at run time.

Count the number of Occurrences of a Word in a String

This should be a faster non-regex solution.
(note - Not a Java programmer)

 String str = "i have a male cat. the color of male cat is Black";
 int found  = 0;
 int oldndx = 0;
 int newndx = 0;

 while ( (newndx=str.indexOf("male cat", oldndx)) > -1 )
 {
     found++;
     oldndx = newndx+8;
 }

Angularjs -> ng-click and ng-show to show a div

I implemented it something this way

Controller function:

app.controller("aboutController", function(){
this.selected = true;
this.toggle = function(){
  this.selected = this.selected?false:true;
}
});

HTML:

<div ng-controller="aboutController as about">
 <div ng-click="about.toggle()">Click Me to toggle the Fruits Name</div>
 <div ng-show ="about.selected">Apple is a delicious fruit</div>
</div>

How to force the input date format to dd/mm/yyyy?

To have a constant date format irrespective of the computer settings, you must use 3 different input elements to capture day, month, and year respectively. However, you need to validate the user input to ensure that you have a valid date as shown bellow

<input id="txtDay" type="text" placeholder="DD" />

<input id="txtMonth" type="text" placeholder="MM" />

<input id="txtYear" type="text" placeholder="YYYY" />
<button id="but" onclick="validateDate()">Validate</button>


  function validateDate() {
    var date = new Date(document.getElementById("txtYear").value, document.getElementById("txtMonth").value, document.getElementById("txtDay").value);

    if (date == "Invalid Date") {
        alert("jnvalid date");

    }
}

Split String by delimiter position using oracle SQL

Therefore, I would like to separate the string by the furthest delimiter.

I know this is an old question, but this is a simple requirement for which SUBSTR and INSTR would suffice. REGEXP are still slower and CPU intensive operations than the old subtsr and instr functions.

SQL> WITH DATA AS
  2    ( SELECT 'F/P/O' str FROM dual
  3    )
  4  SELECT SUBSTR(str, 1, Instr(str, '/', -1, 1) -1) part1,
  5         SUBSTR(str, Instr(str, '/', -1, 1) +1) part2
  6  FROM DATA
  7  /

PART1 PART2
----- -----
F/P   O

As you said you want the furthest delimiter, it would mean the first delimiter from the reverse.

You approach was fine, but you were missing the start_position in INSTR. If the start_position is negative, the INSTR function counts back start_position number of characters from the end of string and then searches towards the beginning of string.

How can I check if a value is of type Integer?

If you have a double/float/floating point number and want to see if it's an integer.

public boolean isDoubleInt(double d)
{
    //select a "tolerance range" for being an integer
    double TOLERANCE = 1E-5;
    //do not use (int)d, due to weird floating point conversions!
    return Math.abs(Math.floor(d) - d) < TOLERANCE;
}

If you have a string and want to see if it's an integer. Preferably, don't throw out the Integer.valueOf() result:

public boolean isStringInt(String s)
{
    try
    {
        Integer.parseInt(s);
        return true;
    } catch (NumberFormatException ex)
    {
        return false;
    }
}

If you want to see if something is an Integer object (and hence wraps an int):

public boolean isObjectInteger(Object o)
{
    return o instanceof Integer;
}

jQuery when element becomes visible

I just Improved ProllyGeek`s answer

Someone may find it useful. you can access displayChanged(event, state) event when .show(), .hide() or .toggle() is called on element

(function() {
  var eventDisplay = new $.Event('displayChanged'),
    origShow = $.fn.show,
    origHide = $.fn.hide;
  //
  $.fn.show = function() {
    origShow.apply(this, arguments);
    $(this).trigger(eventDisplay,['show']);
  };
  //
  $.fn.hide = function() {
    origHide.apply(this, arguments);
    $(this).trigger(eventDisplay,['hide']);
  };
  //
})();

$('#header').on('displayChanged', function(e,state) {
      console.log(state);
});

$('#header').toggle(); // .show() .hide() supported

Best practice for Django project working directory structure

Here is what I follow on My system.

  1. All Projects: There is a projects directory in my home folder i.e. ~/projects. All the projects rest inside it.

  2. Individual Project: I follow a standardized structure template used by many developers called django-skel for individual projects. It basically takes care of all your static file and media files and all.

  3. Virtual environment: I have a virtualenvs folder inside my home to store all virtual environments in the system i.e. ~/virtualenvs . This gives me flexibility that I know what all virtual environments I have and can look use easily

The above 3 are the main partitions of My working environment.

All the other parts you mentioned are mostly dependent on project to project basis (i.e. you might use different databases for different projects). So they should reside in their individual projects.

JPA With Hibernate Error: [PersistenceUnit: JPA] Unable to build EntityManagerFactory

Suppress the @JoinColumn(name="categoria") on the ID field of the Categoria class and I think it will work.

SQLite error 'attempt to write a readonly database' during insert?

I got this error when I tried to write to a database on an Android system.

Apparently sqlite3 not only needs write permissions to the database file and the containing directory (as @austin-hyde already said in his answer) but also the environment variable TMPDIR has to point to a (possibly writable) directory.

On my Android system I set it to TMPDIR="/data/local/tmp" and now my script runs as expected :)

Edit:

If you can't set environment variables you can use one of the other methods listed here: https://www.sqlite.org/tempfiles.html#temporary_file_storage_locations like PRAGMA temp_store_directory = 'directory-name';

How to add checkboxes to JTABLE swing

1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,

2) AbstractTableModel should be useful, where is in the JTable required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel,

3) consider using DefaultTableModel, (if you are not sure about how to works) instead of AbstractTableModel,

table_with_BooleanType_column

could be generated from simple code:

import javax.swing.*;
import javax.swing.table.*;

public class TableCheckBox extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTable table;

    public TableCheckBox() {
        Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
        Object[][] data = {
            {"Buy", "IBM", new Integer(1000), new Double(80.50), false},
            {"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
            {"Sell", "Apple", new Integer(3000), new Double(7.35), true},
            {"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
        };
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        table = new JTable(model) {

            private static final long serialVersionUID = 1L;

            /*@Override
            public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
            }*/
            @Override
            public Class getColumnClass(int column) {
                switch (column) {
                    case 0:
                        return String.class;
                    case 1:
                        return String.class;
                    case 2:
                        return Integer.class;
                    case 3:
                        return Double.class;
                    default:
                        return Boolean.class;
                }
            }
        };
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        getContentPane().add(scrollPane);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                TableCheckBox frame = new TableCheckBox();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocation(150, 150);
                frame.setVisible(true);
            }
        });
    }
}

slideToggle JQuery right to left

Please try this code

$(this).animate({'width': 'toggle'});

Does Visual Studio have code coverage for unit tests?

As already mentioned you can use Fine Code Coverage that visualize coverlet output. If you create a xunit test project (dotnet new xunit) you'll find coverlet reference already present in csproj file because Coverlet is the default coverage tool for every .NET Core and >= .NET 5 applications.

Microsoft has an example using ReportGenerator that converts coverage reports generated by coverlet, OpenCover, dotCover, Visual Studio, NCover, Cobertura, JaCoCo, Clover, gcov or lcov into human readable reports in various formats.

Example report:

enter image description here

While the article focuses on C# and xUnit as the test framework, both MSTest and NUnit would also work.

Guide:

https://docs.microsoft.com/en-us/dotnet/core/testing/unit-testing-code-coverage?tabs=windows#generate-reports

If you want code coverage in .xml files you can run any of these commands:

dotnet test --collect:"XPlat Code Coverage"

dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura

How to download a Nuget package without nuget.exe or Visual Studio extension?

I haven't tried it yet, but it looks like NuGet Package Explorer should be able to do it:

https://github.com/NuGetPackageExplorer/NuGetPackageExplorer

NuGet Package Explorer

(or like Colonel Panic says, 7-zip should probably do it)

py2exe - generate single executable file

As the other poster mention, py2exe, will generate an executable + some libraries to load. You can also have some data to add to your program.

Next step is to use an installer, to package all this into one easy-to-use installable/unistallable program.

I have used InnoSetup with delight for several years and for commercial programs, so I heartily recommend it.

Create a date time with month and day only, no year

Well, you can create your own type - but a DateTime always has a full date and time. You can't even have "just a date" using DateTime - the closest you can come is to have a DateTime at midnight.

You could always ignore the year though - or take the current year:

// Consider whether you want DateTime.UtcNow.Year instead
DateTime value = new DateTime(DateTime.Now.Year, month, day);

To create your own type, you could always just embed a DateTime within a struct, and proxy on calls like AddDays etc:

public struct MonthDay : IEquatable<MonthDay>
{
    private readonly DateTime dateTime;

    public MonthDay(int month, int day)
    {
        dateTime = new DateTime(2000, month, day);
    }

    public MonthDay AddDays(int days)
    {
        DateTime added = dateTime.AddDays(days);
        return new MonthDay(added.Month, added.Day);
    }

    // TODO: Implement interfaces, equality etc
}

Note that the year you choose affects the behaviour of the type - should Feb 29th be a valid month/day value or not? It depends on the year...

Personally I don't think I would create a type for this - instead I'd have a method to return "the next time the program should be run".

How to parse XML using vba

Often it is easier to parse without VBA, when you don't want to enable macros. This can be done with the replace function. Enter your start and end nodes into cells B1 and C1.

Cell A1: {your XML here}
Cell B1: <X>
Cell C1: </X>
Cell D1: =REPLACE(A1,1,FIND(A2,A1)+LEN(A2)-1,"")
Cell E1: =REPLACE(A4,FIND(A3,A4),LEN(A4)-FIND(A3,A4)+1,"")

And the result line E1 will have your parsed value:

Cell A1: {your XML here}
Cell B1: <X>
Cell C1: </X>
Cell D1: 24.365<X><Y>78.68</Y></PointN>
Cell E1: 24.365

Adding a splash screen to Flutter apps

You should try below code, worked for me

import 'dart:async';
import 'package:attendance/components/appbar.dart';
import 'package:attendance/homepage.dart';
import 'package:flutter/material.dart';

class _SplashScreenState extends State<SplashScreen>
with SingleTickerProviderStateMixin {


void handleTimeout() {
  Navigator.of(context).pushReplacement(new MaterialPageRoute(
    builder: (BuildContext context) => new MyHomePage()));
}

startTimeout() async {
  var duration = const Duration(seconds: 3);
  return new Timer(duration, handleTimeout);
}

@override
void initState() {
  // TODO: implement initState
  super.initState();

  _iconAnimationController = new AnimationController(
      vsync: this, duration: new Duration(milliseconds: 2000));

  _iconAnimation = new CurvedAnimation(
      parent: _iconAnimationController, curve: Curves.easeIn);
  _iconAnimation.addListener(() => this.setState(() {}));

  _iconAnimationController.forward();

  startTimeout();
}

@override
Widget build(BuildContext context) {
  return new Scaffold(
    body: new Scaffold(
      body: new Center(
        child: new Image(
        image: new AssetImage("images/logo.png"),
        width: _iconAnimation.value * 100,
        height: _iconAnimation.value * 100,
      )),
    ),
  );
}
}

Service Temporarily Unavailable Magento?

You need to follow these steps:

  1. Go to magento root directory via cPanel/FTP
  2. In case of Magento1, you will find maintenance.flag and delete it
  3. In case of Magento2, delete var/maintenance.flag

How to add one column into existing SQL Table

The syntax you need is

ALTER TABLE Products ADD LastUpdate  varchar(200) NULL

This is a metadata only operation

String replacement in Objective-C

You could use the method

- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target 
                                        withString:(NSString *)replacement

...to get a new string with a substring replaced (See NSString documentation for others)

Example use

NSString *str = @"This is a string";

str = [str stringByReplacingOccurrencesOfString:@"string"
                                     withString:@"duck"];

Map.Entry: How to use it?

Map.Entry interface helps us iterating a Map class

Check this simple example:

public class MapDemo {
    public static void main(String[] args) {
     Map<Integer,String> map=new HashMap();
     map.put(1, "Kamran");
        map.put(2, "Ali");
        map.put(3, "From");
        map.put(4, "Dir");
        map.put(5, "Lower");
        for(Map.Entry m:map.entrySet()){
        System.out.println(m.getKey()+"  "+m.getValue());
        }
    }
}

CSS table td width - fixed, not flexible

This workaround worked for me...

<td style="white-space: normal; width:300px;">

Converting Stream to String and back...what are we missing?

This is so common but so profoundly wrong. Protobuf data is not string data. It certainly isn't ASCII. You are using the encoding backwards. A text encoding transfers:

  • an arbitrary string to formatted bytes
  • formatted bytes to the original string

You do not have "formatted bytes". You have arbitrary bytes. You need to use something like a base-n (commonly: base-64) encode. This transfers

  • arbitrary bytes to a formatted string
  • a formatted string to the original bytes

look at Convert.ToBase64String and Convert. FromBase64String

.NET String.Format() to add commas in thousands place for a number

C# 7.1 (perhaps earlier?) makes this as easy and nice-looking as it should be, with string interpolation:

var jackpot = 1000000;
var niceNumberString = $"Jackpot is {jackpot:n}";
var niceMoneyString = $"Jackpot is {jackpot:C}";

Get HTML source of WebElement in Selenium WebDriver using Python

The other answers provide a lot of details about retrieving the markup of a WebElement. However, an important aspect is, modern websites are increasingly implementing JavaScript, ReactJS, jQuery, Ajax, Vue.js, Ember.js, GWT, etc. to render the dynamic elements within the DOM tree. Hence there is a necessity to wait for the element and its children to completely render before retrieving the markup.


Python

Hence, ideally you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • Using get_attribute("outerHTML"):

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#my-id")))
    print(element.get_attribute("outerHTML"))
    
  • Using execute_script():

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#my-id")))
    print(driver.execute_script("return arguments[0].outerHTML;", element))
    
  • Note: You have to add the following imports:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

Creating a .p12 file

The openssl documentation says that file supplied as the -in argument must be in PEM format.

Turns out that, contrary to the CA's manual, the certificate returned by the CA which I stored in myCert.cer is not PEM format rather it is PKCS7.

In order to create my .p12, I had to first convert the certificate to PEM:

openssl pkcs7 -in myCert.cer -print_certs -out certs.pem

and then execute

openssl pkcs12 -export -out keyStore.p12 -inkey myKey.pem -in certs.pem

how to remove only one style property with jquery

You can also replace "-moz-user-select:none" with "-moz-user-select:inherit". This will inherit the style value from any parent style or from the default style if no parent style was defined.

Awaiting multiple Tasks with different results

Use Task.WhenAll and then await the results:

var tCat = FeedCat();
var tHouse = SellHouse();
var tCar = BuyCar();
await Task.WhenAll(tCat, tHouse, tCar);
Cat cat = await tCat;
House house = await tHouse;
Tesla car = await tCar; 
//as they have all definitely finished, you could also use Task.Value.

C# list.Orderby descending

Sure:

var newList = list.OrderByDescending(x => x.Product.Name).ToList();

Doc: OrderByDescending(IEnumerable, Func).

In response to your comment:

var newList = list.OrderByDescending(x => x.Product.Name)
                  .ThenBy(x => x.Product.Price)
                  .ToList();

How to download a file from a URL in C#?

using (var client = new WebClient())
{
    client.DownloadFile("http://example.com/file/song/a.mpeg", "a.mpeg");
}

Passing an array using an HTML form hidden element

There are mainly two possible ways to achieve this:

  1. Serialize the data in some way:

    $postvalue = serialize($array); // Client side
    
    $array = unserialize($_POST['result']; // Server side
    

And then you can unserialize the posted values with unserialize($postvalue). Further information on this is here in the PHP manuals.

Alternativeley you can use the json_encode() and json_decode() functions to get a JSON formatted serialized string. You could even shrink the transmitted data with gzcompress() (note that this is performance intensive) and secure the transmitted data with base64_encode() (to make your data survive in non-8 bit clean transport layers) This could look like this:

    $postvalue = base64_encode(json_encode($array)); // Client side

    $array = json_decode(base64_decode($_POST['result'])); // Server side

A not recommended way to serialize your data (but very cheap in performance) is to simply use implode() on your array to get a string with all values separated by some specified character. On the server side you can retrieve the array with explode() then. But note that you shouldn't use a character for separation that occurs in the array values (or then escape it) and that you cannot transmit the array keys with this method.

  1. Use the properties of special named input elements:

    $postvalue = "";
    foreach ($array as $v) {
      $postvalue .= '<input type="hidden" name="result[]" value="' .$v. '" />';
    }
    

    Like this you get your entire array in the $_POST['result'] variable if the form is sent. Note that this doesn't transmit array keys. However you can achieve this by using result[$key] as name of each field.

Everyone of these methods got their own advantages and disadvantages. What you use is mainly depending on how large your array will be, since you should try to send a minimal amount of data with all of this methods.

Another way to achieve the same is to store the array in a server side session instead of transmitting it client side. Like this you can access the array over the $_SESSION variable and don't have to transmit anything over the form. For this have a look at a basic usage example of sessions on php.net.

How to change MySQL column definition?

This should do it:

ALTER TABLE test MODIFY locationExpert VARCHAR(120) 

Android SeekBar setOnSeekBarChangeListener

onProgressChanged is called every time you move the cursor.

@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
    textView.setText(String.valueOf(new Integer(progress)));        
}

so textView should show the progress and alter always if the seekbar is being moved.

Favicon dimensions?

Seems like your file should be .ico type.

Check this post about favicons:

http://www.html-kit.com/support/favicon/image-size/

Disable elastic scrolling in Safari

You can achieve this more universally by applying the following CSS:

html,
body {
  height: 100%;
  width: 100%;
  overflow: auto;
}

This allows your content, whatever it is, to become scrollable within body, but be aware that the scrolling context where scroll event is fired is now document.body, not window.

How to print a float with 2 decimal places in Java?

One issue that had me for an hour or more, on DecimalFormat- It handles double and float inputs differently. Even change of RoundingMode did not help. I am no expert but thought it may help someone like me. Ended up using Math.round instead. See below:

    DecimalFormat df = new DecimalFormat("#.##");
    double d = 0.7750;
    System.out.println(" Double 0.7750 -> " +Double.valueOf(df.format(d)));
    float f = 0.7750f;
    System.out.println(" Float 0.7750f -> "+Float.valueOf(df.format(f)));
    // change the RoundingMode
    df.setRoundingMode(RoundingMode.HALF_UP);
    System.out.println(" Rounding Up Double 0.7750 -> " +Double.valueOf(df.format(d)));
    System.out.println(" Rounding Up Float 0.7750f -> " +Float.valueOf(df.format(f)));

Output:

Double 0.7750 -> 0.78
Float 0.7750f -> 0.77

Rounding Up Double 0.7750 -> 0.78
Rounding Up Float 0.7750f -> 0.77

MongoDB relationships: embed or reference?

I know this is quite old but if you are looking for the answer to the OP's question on how to return only specified comment, you can use the $ (query) operator like this:

db.question.update({'comments.content': 'xxx'}, {'comments.$': true})

How to get a list of column names

The result set of a query in PHP offers a couple of functions allowing just that:

    numCols() 
    columnName(int $column_number )

Example

    $db = new SQLIte3('mysqlite.db');
    $table = 'mytable';

    $tableCol = getColName($db, $table);

    for ($i=0; $i<count($tableCol); $i++){
        echo "Column $i = ".$tableCol[$i]."\n";
    }           

    function getColName($db, $table){
        $qry = "SELECT * FROM $table LIMIT 1";
        $result = $db->query($qry);
        $nCols = $result->numCols();
        for ($i = 0; $i < $ncols; $i++) {
            $colName[$i] = $result->columnName($i);
        }
        return $colName;
    }

What does "opt" mean (as in the "opt" directory)? Is it an abbreviation?

OPTional

It holds optional software and packages that you install that are not required for the system to run.

What is the difference between 'SAME' and 'VALID' padding in tf.nn.max_pool of tensorflow?

Tensorflow 2.0 Compatible Answer: Detailed Explanations have been provided above, about "Valid" and "Same" Padding.

However, I will specify different Pooling Functions and their respective Commands in Tensorflow 2.x (>= 2.0), for the benefit of the community.

Functions in 1.x:

tf.nn.max_pool

tf.keras.layers.MaxPool2D

Average Pooling => None in tf.nn, tf.keras.layers.AveragePooling2D

Functions in 2.x:

tf.nn.max_pool if used in 2.x and tf.compat.v1.nn.max_pool_v2 or tf.compat.v2.nn.max_pool, if migrated from 1.x to 2.x.

tf.keras.layers.MaxPool2D if used in 2.x and

tf.compat.v1.keras.layers.MaxPool2D or tf.compat.v1.keras.layers.MaxPooling2D or tf.compat.v2.keras.layers.MaxPool2D or tf.compat.v2.keras.layers.MaxPooling2D, if migrated from 1.x to 2.x.

Average Pooling => tf.nn.avg_pool2d or tf.keras.layers.AveragePooling2D if used in TF 2.x and

tf.compat.v1.nn.avg_pool_v2 or tf.compat.v2.nn.avg_pool or tf.compat.v1.keras.layers.AveragePooling2D or tf.compat.v1.keras.layers.AvgPool2D or tf.compat.v2.keras.layers.AveragePooling2D or tf.compat.v2.keras.layers.AvgPool2D , if migrated from 1.x to 2.x.

For more information about Migration from Tensorflow 1.x to 2.x, please refer to this Migration Guide.

MySQL compare DATE string with string from DATETIME field

SELECT * FROM sample_table WHERE last_visit = DATE_FORMAT('2014-11-24 10:48:09','%Y-%m-%d %H:%i:%s')

this for datetime format in mysql using DATE_FORMAT(date,format).

Swift Error: Editor placeholder in source file

Sometimes, XCode does not forget the line which had an "Editor Placeholder" even if you have replaced it with a value. Cut the portion of the code where XCode is complaining and paste the code back to the same place to make the error message go away. This worked for me.

How to use paginator from material angular?

I'm struggling with the same here. But I can show you what I've got doing some research. Basically, you first start adding the page @Output event in the foo.template.ts:

 <md-paginator #paginator
                [length]="length"
                [pageIndex]="pageIndex"
                [pageSize]="pageSize"
                [pageSizeOptions]="[5, 10, 25, 100]"
                (page)="pageEvent = getServerData($event)"
                >
 </md-paginator>

And later, you have to add the pageEvent attribute in the foo.component.ts class and the others to handle paginator requirements:

pageEvent: PageEvent;
datasource: null;
pageIndex:number;
pageSize:number;
length:number;

And add the method that will fetch the server data:

ngOnInit() {
   getServerData(null) ...
}

public getServerData(event?:PageEvent){
  this.fooService.getdata(event).subscribe(
    response =>{
      if(response.error) {
        // handle error
      } else {
        this.datasource = response.data;
        this.pageIndex = response.pageIndex;
        this.pageSize = response.pageSize;
        this.length = response.length;
      }
    },
    error =>{
      // handle error
    }
  );
  return event;
}

So, basically every time you click the paginator, you'll activate getServerData(..) method that will call foo.service.ts getting all data required. In this case, you do not need to handle nextPage and nextXXX events because it will be automatically calculated upon view rendering.

Hope this can help you. Let me know if you had success. =]

Use sed to replace all backslashes with forward slashes

I had to use [\\] or [/] to be able to make this work, FYI.

awk '!/[\\]/' file > temp && mv temp file

and

awk '!/[/]/' file > temp && mv temp file

I was using awk to remove backlashes and forward slashes from a list.

How do I replace multiple spaces with a single space in C#?

I can remove whitespaces with this

while word.contains("  ")  //double space
   word = word.Replace("  "," "); //replace double space by single space.
word = word.trim(); //to remove single whitespces from start & end.

How to drop a PostgreSQL database if there are active connections to it?

You could kill all connections before dropping the database using the pg_terminate_backend(int) function.

You can get all running backends using the system view pg_stat_activity

I'm not entirely sure, but the following would probably kill all sessions:

select pg_terminate_backend(procpid)
from pg_stat_activity
where datname = 'doomed_database'

Of course you may not be connected yourself to that database