Programs & Examples On #Safearray

Is there an eval() function in Java?

With Java 9, we get access to jshell, so one can write something like this:

import jdk.jshell.JShell;
import java.lang.StringBuilder;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Eval {
    public static void main(String[] args) throws IOException {
        try(JShell js = JShell.create(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {

            js.onSnippetEvent(snip -> {
                if (snip.status() == jdk.jshell.Snippet.Status.VALID) {
                    System.out.println("? " + snip.value());
                }
            });

            System.out.print("> ");
            for (String line = br.readLine(); line != null; line = br.readLine()) {
                js.eval(js.sourceCodeAnalysis().analyzeCompletion(line).source());
                System.out.print("> ");
            }
        }
    }
}

Sample run:

> 1 + 2 / 4 * 3
? 1
> 32 * 121
? 3872
> 4 * 5
? 20
> 121 * 51
? 6171
>

Slightly op, but that's what Java currently has to offer

Add floating point value to android resources/values

As described in this link http://droidista.blogspot.in/2012/04/adding-float-value-to-your-resources.html

Declare in dimen.xml

<item name="my_float_value" type="dimen" format="float">9.52</item>

Referencing from xml

@dimen/my_float_value

Referencing from java

TypedValue typedValue = new TypedValue();
getResources().getValue(R.dimen.my_float_value, typedValue, true);
float myFloatValue = typedValue.getFloat();

Android emulator failed to allocate memory 8

This error fires if you set the AVD RAM to anything that is larger then the single largest block of continuous memory the emulator is able to allocate. Close anything RAM heavy, start your emulator, start everything else you need. In a previous answer I have limited this to x86 images with IntelHAXM, but this actually is the case for all types of emulator instances.

Show week number with Javascript?

With that code you can simply;

document.write(dayNames[now.getDay()] + " (" + now.getWeek() + ").");

(You will need to paste the getWeek function above your current script)

Why is vertical-align:text-top; not working in CSS

The vertical-align attribute is for inline elements only. It will have no effect on block level elements, like a div. Also text-top only moves the text to the top of the current font size. If you would like to vertically align an inline element to the top just use this.

vertical-align: top;

The paragraph tag is not outdated. Also, the vertical-align attribute applied to a span element may not display as intended in some mozilla browsers.

RichTextBox (WPF) does not have string property "Text"

"Extended WPF Toolkit" now provides a richtextbox with the Text property.

You can get or set the text in different formats (XAML, RTF and plaintext).

Here is the link: Extended WPF Toolkit RichTextBox

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

In case Translate works locally but not remotly e.i group.Translate(typeof(NTAccount)

If you want to have the application code executes using the LOGGED IN USER identity, then enable impersonation. Impersonation can be enabled thru IIS or by adding the following element in the web.config.

<system.web>
<identity impersonate="true"/>

If impersonation is enabled, the application executes using the permissions found in your user account. So if the logged in user has access, to a specific network resource, only then will he be able to access that resource thru the application.

Thank PRAGIM tech for this information from his diligent video

Windows authentication in asp.net Part 87:

https://www.youtube.com/watch?v=zftmaZ3ySMc

But impersonation creates a lot of overhead on the server

The best solution to allow users of certain network groups is to deny anonymous in the web config <authorization><deny users="?"/><authentication mode="Windows"/>

and in your code behind, preferably in the global.asax, use the HttpContext.Current.User.IsInRole :

Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
If HttpContext.Current.User.IsInRole("TheDomain\TheGroup") Then
//code to do when user is in group
End If

NOTE: The Group must be written with a backslash \ i.e. "TheDomain\TheGroup"

Why are empty catch blocks a bad idea?

It's probably never the right thing because you're silently passing every possible exception. If there's a specific exception you're expecting, then you should test for it, rethrow if it's not your exception.

try
{
    // Do some processing.
}
catch (FileNotFound fnf)
{
    HandleFileNotFound(fnf);
}
catch (Exception e)
{
    if (!IsGenericButExpected(e))
        throw;
}

public bool IsGenericButExpected(Exception exception)
{
    var expected = false;
    if (exception.Message == "some expected message")
    {
        // Handle gracefully ... ie. log or something.
        expected = true;
    }

    return expected;
}

How to check undefined in Typescript

Late to the story but I think some details are overlooked?

if you use

if (uemail !== undefined) {
  //some function
}

You are, technically, comparing variable uemail with variable undefined and, as the latter is not instantiated, it will give both type and value of 'undefined' purely by default, hence the comparison returns true. But it overlooks the potential that a variable by the name of undefined may actually exist -however unlikely- and would therefore then not be of type undefined. In that case, the comparison will return false.

To be correct one would have to declare a constant of type undefined for example:

const _undefined: undefined

and then test by:

if (uemail === _undefined) {
  //some function
}

This test will return true as uemail now equals both value & type of _undefined as _undefined is now properly declared to be of type undefined.

Another way would be

if (typeof(uemail) === 'undefined') {
  //some function
}

In which case the boolean return is based on comparing the two strings on either end of the comparison. This is, from a technical point of view, NOT testing for undefined, although it achieves the same result.

OpenJDK availability for Windows OS

Only OpenJDK 7. OpenJDK6 is basically the same code base as SUN's version, that's why it redirects you to the official Oracle site.

How to close a GUI when I push a JButton?

You may use Window#dispose() method to release all of the native screen resources, subcomponents, and all of its owned children.

The System.exit(0) will terminates the currently running Java Virtual Machine.

Reading a List from properties file and load with spring annotation @Value

if using property placeholders then ser1702544 example would become

@Value("#{myConfigProperties['myproperty'].trim().replaceAll(\"\\s*(?=,)|(?<=,)\\s*\", \"\").split(',')}") 

With placeholder xml:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">   
    <property name="properties" ref="myConfigProperties" />
    <property name="placeholderPrefix"><value>$myConfigProperties{</value></property>
</bean>    

<bean id="myConfigProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
     <property name="locations">
         <list>
                <value>classpath:myprops.properties</value>
         </list>
     </property>
</bean> 

Refresh Excel VBA Function Results

This refreshes the calculation better than Range(A:B).Calculate:

Public Sub UpdateMyFunctions()
    Dim myRange As Range
    Dim rng As Range

    ' Assume the functions are in this range A1:B10.
    Set myRange = ActiveSheet.Range("A1:B10")

    For Each rng In myRange
        rng.Formula = rng.Formula
    Next
End Sub

What is the best way to get all the divisors of a number?

Although there are already many solutions to this, I really have to post this :)

This one is:

  • readable
  • short
  • self contained, copy & paste ready
  • quick (in cases with a lot of prime factors and divisors, > 10 times faster than the accepted solution)
  • python3, python2 and pypy compliant

Code:

def divisors(n):
    # get factors and their counts
    factors = {}
    nn = n
    i = 2
    while i*i <= nn:
        while nn % i == 0:
            factors[i] = factors.get(i, 0) + 1
            nn //= i
        i += 1
    if nn > 1:
        factors[nn] = factors.get(nn, 0) + 1

    primes = list(factors.keys())

    # generates factors from primes[k:] subset
    def generate(k):
        if k == len(primes):
            yield 1
        else:
            rest = generate(k+1)
            prime = primes[k]
            for factor in rest:
                prime_to_i = 1
                # prime_to_i iterates prime**i values, i being all possible exponents
                for _ in range(factors[prime] + 1):
                    yield factor * prime_to_i
                    prime_to_i *= prime

    # in python3, `yield from generate(0)` would also work
    for factor in generate(0):
        yield factor

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

User.objects.filter(username='tom', groups__name='admin').exists()

That query will inform you user : "tom" whether belong to group "admin " or not

SQL INSERT INTO from multiple tables

If I'm understanding you correctly, you should be able to do this in one query, joining table1 and table2 together:

INSERT INTO table3 { name, age, sex, city, id, number}
SELECT p.name, p.age, p.sex, p.city, p.id, c.number
FROM table1 p
INNER JOIN table2 c ON c.Id = p.Id

Create web service proxy in Visual Studio from a WSDL file

save the file on your disk and then use the following as URL:

file://your_path/your_file.wsdl

python 2.7: cannot pip on windows "bash: pip: command not found"

On windows 7, you have to use this command: python -m pip install xxx. All above don't work for me.

How do I find duplicate values in a table in Oracle?

Simplest I can think of:

select job_number, count(*)
from jobs
group by job_number
having count(*) > 1;

Could not find the main class, program will exit

The classpath is the path that the system will follow when trying to find the classes that you're trying to run. In the batch file you're trying to execute it probably has a variable like CLASSPATH=blah;blah;etc or a java command that looks similar to

java -classpath "c:\directory\lib\squirrel-sql.jar" com.some.squirrel.package.file

If you can find or add that classpath setting, make sure that it includes a path to the squirrel-sql.jar and any other jar files that it may depend on separated by semicolons (or the root /lib directory that may be included with the installation).

Basically you just need to tell java where to find the class files that you're trying to execute. Wikipedia has a more indepth discussion about classpath and can offer you more insight. http://en.wikipedia.org/wiki/Classpath_(Java)

How do I list one filename per output line in Linux?

Ls is designed for human consumption, and you should not parse its output.

In shell scripts, there are a few cases where parsing the output of ls does work is the simplest way of achieving the desired effect. Since ls might mangle non-ASCII and control characters in file names, these cases are a subset of those that do not require obtaining a file name from ls.

In python, there is absolutely no reason to invoke ls. Python has all of ls's functionality built-in. Use os.listdir to list the contents of a directory and os.stat or os to obtain file metadata. Other functions in the os modules are likely to be relevant to your problem as well.


If you're accessing remote files over ssh, a reasonably robust way of listing file names is through sftp:

echo ls -1 | sftp remote-site:dir

This prints one file name per line, and unlike the ls utility, sftp does not mangle nonprintable characters. You will still not be able to reliably list directories where a file name contains a newline, but that's rarely done (remember this as a potential security issue, not a usability issue).

In python (beware that shell metacharacters must be escapes in remote_dir):

command_line = "echo ls -1 | sftp " + remote_site + ":" + remote_dir
remote_files = os.popen(command_line).read().split("\n")

For more complex interactions, look up sftp's batch mode in the documentation.

On some systems (Linux, Mac OS X, perhaps some other unices, but definitely not Windows), a different approach is to mount a remote filesystem through ssh with sshfs, and then work locally.

In Python, how do I loop through the dictionary and change the value if it equals something?

for k, v in mydict.iteritems():
    if v is None:
        mydict[k] = ''

In a more general case, e.g. if you were adding or removing keys, it might not be safe to change the structure of the container you're looping on -- so using items to loop on an independent list copy thereof might be prudent -- but assigning a different value at a given existing index does not incur any problem, so, in Python 2.any, it's better to use iteritems.

In Python3 however the code gives AttributeError: 'dict' object has no attribute 'iteritems' error. Use items() instead of iteritems() here.

Refer to this post.

Is there a command like "watch" or "inotifywait" on the Mac?

You might want to take a look at (and maybe expand) my little tool kqwait. Currently it just sits around and waits for a write event on a single file, but the kqueue architecture allows for hierarchical event stacking...

How to exit from Python without traceback?

# Pygame Example  

import pygame, sys  
from pygame.locals import *

pygame.init()  
DISPLAYSURF = pygame.display.set_mode((400, 300))  
pygame.display.set_caption('IBM Emulator')

BLACK = (0, 0, 0)  
GREEN = (0, 255, 0)

fontObj = pygame.font.Font('freesansbold.ttf', 32)  
textSurfaceObj = fontObj.render('IBM PC Emulator', True, GREEN,BLACK)  
textRectObj = textSurfaceObj.get_rect()  
textRectObj = (10, 10)

try:  
    while True: # main loop  
        DISPLAYSURF.fill(BLACK)  
        DISPLAYSURF.blit(textSurfaceObj, textRectObj)  
        for event in pygame.event.get():  
            if event.type == QUIT:  
                pygame.quit()  
                sys.exit()  
        pygame.display.update()  
except SystemExit:  
    pass

WordPress is giving me 404 page not found for all pages except the homepage

If the default behavior (example.com/?p=42) is working, you should:

  • Change to your preferred permalink style: Admin: Settings > Permalinks, and click Save. Sometime it fixes the issue. If it didn't:
  • Verify that the file /path/to/wordpress/.htaccess has been changed and now includes the line RewriteEngine On. If it doesn't include the line, it's a Wordpress permissions issue.
  • Verify that the 'rewrite' module is loaded: create a PHP file with

    <?php
      phpinfo()
    ?>
    

    in it, open it in the browser and search for mod_rewrite. It should be in the 'Loaded Modules' section. If it's not, enable it - Look at your apache default index.html file for details - in Ubuntu, you do it with the helper a2enmod.

  • Verify that apache server is looking at the .htaccess file. open httpd.conf - or it's Ubuntu's alternative, /etc/apache2/apache2.conf. In it, You should have something like

    <Directory /path/to/wordpress>
      Options Indexes FollowSymLinks
      AllowOverride All
      Require all granted
    </Directory>
    
  • After making these changes, don't forget to restart your apache server. sudo service apache2 restart

How to nicely format floating numbers to string without unnecessary decimal 0's

My two cents:

if(n % 1 == 0) {
    return String.format(Locale.US, "%.0f", n));
} else {
    return String.format(Locale.US, "%.1f", n));
}

Pass multiple arguments into std::thread

Had the same problem. I was passing a non-const reference of custom class and the constructor complained (some tuple template errors). Replaced the reference with pointer and it worked.

text-align:center won't work with form <label> tag (?)

label is an inline element so its width is equal to the width of the text it contains. The browser is actually displaying the label with text-align:center but since the label is only as wide as the text you don't notice.

The best thing to do is to apply a specific width to the label that is greater than the width of the content - this will give you the results you want.

Use dynamic variable names in `dplyr`

Here's another version, and it's arguably a bit simpler.

multipetal <- function(df, n) {
    varname <- paste("petal", n, sep=".")
    df<-mutate_(df, .dots=setNames(paste0("Petal.Width*",n), varname))
    df
}

for(i in 2:5) {
    iris <- multipetal(df=iris, n=i)
}

> head(iris)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species petal.2 petal.3 petal.4 petal.5
1          5.1         3.5          1.4         0.2  setosa     0.4     0.6     0.8       1
2          4.9         3.0          1.4         0.2  setosa     0.4     0.6     0.8       1
3          4.7         3.2          1.3         0.2  setosa     0.4     0.6     0.8       1
4          4.6         3.1          1.5         0.2  setosa     0.4     0.6     0.8       1
5          5.0         3.6          1.4         0.2  setosa     0.4     0.6     0.8       1
6          5.4         3.9          1.7         0.4  setosa     0.8     1.2     1.6       2

How to run Gulp tasks sequentially one after the other

I was searching for this answer for a while. Now I got it in the official gulp documentation.

If you want to perform a gulp task when the last one is complete, you have to return a stream:

_x000D_
_x000D_
gulp.task('wiredep', ['dev-jade'], function () {_x000D_
    var stream = gulp.src(paths.output + '*.html')_x000D_
        .pipe($.wiredep())_x000D_
        .pipe(gulp.dest(paths.output));_x000D_
_x000D_
    return stream; // execute next task when this is completed_x000D_
});_x000D_
_x000D_
// First will execute and complete wiredep task_x000D_
gulp.task('prod-jade', ['wiredep'], function() {_x000D_
    gulp.src(paths.output + '**/*.html')_x000D_
        .pipe($.minifyHtml())_x000D_
        .pipe(gulp.dest(paths.output));_x000D_
});
_x000D_
_x000D_
_x000D_

Windows service on Local Computer started and then stopped error

Not sure this will be helpful, but for debugging a service you could always use the following in the OnStart method:

protected override void OnStart(string[] args)
{
     System.Diagnostics.Debugger.Launch();
     ...
}

than you could attach your visual studio to the process and have better debug abilities.

hope this was helpful, good luck

Creating a DateTime in a specific Time Zone in c#

The DateTimeOffset structure was created for exactly this type of use.

See: http://msdn.microsoft.com/en-us/library/system.datetimeoffset.aspx

Here's an example of creating a DateTimeOffset object with a specific time zone:

DateTimeOffset do1 = new DateTimeOffset(2008, 8, 22, 1, 0, 0, new TimeSpan(-5, 0, 0));

ADB Android Device Unauthorized

Check if you have kies installed. That is one possible solution

Why number 9 in kill -9 command in unix?

Both are same as kill -sigkill processID, kill -9 processID. Its basically for forced termination of the process.

error: This is probably not a problem with npm. There is likely additional logging output above

Finally, I found a solution to this problem without reinstalling npm and I'm posting it because in future it will help someone, Most of the time this error occurs javascript heap went out of the memory. As the error says itself this is not a problem with npm. Only we have to do is

instead of,

npm  run build -prod

extend the javascript memory by following,

node --max_old_space_size=4096 node_modules/@angular/cli/bin/ng build --prod

if var == False

Since Python evaluates also the data type NoneType as False during the check, a more precise answer is:

var = False
if var is False:
    print('learnt stuff')

This prevents potentially unwanted behaviour such as:

var = []  # or None
if not var:
    print('learnt stuff') # is printed what may or may not be wanted

But if you want to check all cases where var will be evaluated to False, then doing it by using logical not keyword is the right thing to do.

What does the question mark and the colon (?: ternary operator) mean in objective-c?

Building on Barry Wark's excellent explanation...

What is so important about the ternary operator is that it can be used in places that an if-else cannot. ie: Inside a condition or method parameter.

[NSString stringWithFormat: @"Status: %@", (statusBool ? @"Approved" : @"Rejected")]

...which is a great use for preprocessor constants:

// in your pch file...
#define statusString (statusBool ? @"Approved" : @"Rejected")

// in your m file...
[NSString stringWithFormat: @"Status: %@", statusString]

This saves you from having to use and release local variables in if-else patterns. FTW!

@property retain, assign, copy, nonatomic in Objective-C

The article linked to by MrMage is no longer working. So, here is what I've learned in my (very) short time coding in Objective-C:

nonatomic vs. atomic - "atomic" is the default. Always use "nonatomic". I don't know why, but the book I read said there is "rarely a reason" to use "atomic". (BTW: The book I read is the BNR "iOS Programming" book.)

readwrite vs. readonly - "readwrite" is the default. When you @synthesize, both a getter and a setter will be created for you. If you use "readonly", no setter will be created. Use it for a value you don't want to ever change after the instantiation of the object.

retain vs. copy vs. assign

  • "assign" is the default. In the setter that is created by @synthesize, the value will simply be assigned to the attribute. My understanding is that "assign" should be used for non-pointer attributes.
  • "retain" is needed when the attribute is a pointer to an object. The setter generated by @synthesize will retain (aka add a retain count) the object. You will need to release the object when you are finished with it.
  • "copy" is needed when the object is mutable. Use this if you need the value of the object as it is at this moment, and you don't want that value to reflect any changes made by other owners of the object. You will need to release the object when you are finished with it because you are retaining the copy.

How to run python script on terminal (ubuntu)?

First create the file you want, with any editor like vi r gedit. And save with. Py extension.In that the first line should be

!/usr/bin/env python

Delaying AngularJS route change until model loaded to prevent flicker

I have had a complex multi-level sliding panel interface, with disabled screen layer. Creating directive on disable screen layer that would create click event to execute the state like

$state.go('account.stream.social.view');

were producing a flicking effect. history.back() instead of it worked ok, however its not always back in history in my case. SO what I find out is that if I simply create attribute href on my disable screen instead of state.go , worked like a charm.

<a class="disable-screen" back></a>

Directive 'back'

app.directive('back', [ '$rootScope', function($rootScope) {

    return {
        restrict : 'A',
        link : function(scope, element, attrs) {
            element.attr('href', $rootScope.previousState.replace(/\./gi, '/'));
        }
    };

} ]);

app.js I just save previous state

app.run(function($rootScope, $state) {      

    $rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams) {         

        $rootScope.previousState = fromState.name;
        $rootScope.currentState = toState.name;


    });
});

How can I add additional PHP versions to MAMP

Additional Version of PHP can be installed directly from the APP (using MAMP PRO v5 at least).

Here's how (All Steps):

MAMP PRO --> Preferences --> click [Check Now] to check for updates (even if you have automatic updates enabled!) --> click [Show PHP Versions] --> Install as needed!

Step-by-step screenshots:

MAMP PRO --> Preferences

enter image description here

enter image description here

enter image description here

Django: Calling .update() on a single model instance retrieved by .get()?

I am using the following code in such cases:

obj, created = Model.objects.get_or_create(id=some_id)

if not created:
   resp= "It was created"
else:
   resp= "OK"
   obj.save()

How to list all available Kafka brokers in a cluster?

Here are a couple of quick functions I use when bash scripting Kafka Data Load into Demo Environments. In this example I use HDP with no security, but it is easily modified to other environments and intended to be quick and functional rather than particularly robust.

The first retrieves the address of the first ZooKeeper node from the config:

ZKS1=$(cat /usr/hdp/current/zookeeper-client/conf/zoo.cfg | grep server.1)
[[ ${ZKS1} =~ server.1=(.*?):[0-9]*:[0-9]* ]]
export ZKADDR=${BASH_REMATCH[1]}:2181
echo "using ZooKeeper Server $ZKADDR"

The second retrieves the Broker IDs from ZooKeeper:

echo "Fetching list of Kafka Brokers"
export BROKERIDS=$(/usr/hdp/current/kafka-broker/bin/zookeeper-shell.sh ${ZKADDR} <<< 'ls /brokers/ids' | tail -1)
export BROKERIDS=${BROKERIDS//[!0-9 ]/}
echo "Found Kafka Broker IDS: $BROKERIDS"

The third parses ZooKeeper again to retrieve the list of Kafka Brokers Host:port ready for use in the command-line client:

unset BROKERS
for i in $BROKERIDS
do
DETAIL=$(/usr/hdp/current/kafka-broker/bin/zookeeper-shell.sh ${ZKADDR} <<< "get /brokers/ids/$i")
[[ $DETAIL =~ PLAINTEXT:\/\/(.*?)\"\] ]]
if [ -z ${BROKERS+x} ]; then BROKERS=${BASH_REMATCH[1]}; else 
BROKERS="${BROKERS},${BASH_REMATCH[1]}"; fi
done
echo "Found Brokerlist: $BROKERS"

Create, read, and erase cookies with jQuery

Use JavaScript Cookie plugin

Set a cookie

Cookies.set("example", "foo"); // Sample 1
Cookies.set("example", "foo", { expires: 7 }); // Sample 2
Cookies.set("example", "foo", { path: '/admin', expires: 7 }); // Sample 3

Get a cookie

alert( Cookies.get("example") );

Delete the cookie

Cookies.remove("example");
Cookies.remove('example', { path: '/admin' }) // Must specify path if used when setting.

IE11 Document mode defaults to IE7. How to reset?

Thanks to all the investigations of Lance, I could find a solution to my problem. It possibly had to do with my ISP.

To summarize:

  • Internet sites were displayed in the Intranet zone
  • Because of that the document mode was defaulted to 5 or 7 instead of Edge

I unchecked the "Automatically detect settings" in the Local Area Network Settings (found in "Internet Options" > Connections > LAN Settings.

Now the sites are correctly marked as Internet sites (instead of Intranet sites).

Xampp Access Forbidden php

if used ubuntu operating system then check chmod of /Practice folder change read write permission

Open terminal press shortcut key Ctrl+Alt+T Goto

$ cd /opt/lampp/htdocs/

and change folder read write and execute permission by using chmod command

e.g folder name is practice and path of folder /opt/lampp/htdocs/practice

Type command

$ sudo chmod 777 -R Practice

what is chmod and 777 ? visit this link http://linuxcommand.org/lts0070.php

Move existing, uncommitted work to a new branch in Git

The common scenario is the following: I forgot to create the new branch for the new feature, and was doing all the work in the old feature branch. I have commited all the "old" work to the master branch, and I want my new branch to grow from the "master". I have not made a single commit of my new work. Here is the branch structure: "master"->"Old_feature"

git stash 
git checkout master
git checkout -b "New_branch"
git stash apply

Appending an id to a list if not already present in a string

There are a couple things going on with your example. You have a list containing a string of numbers and newline characters:

list = ['350882 348521 350166\r\n']

And you are trying to find a number ID within this list:

id = 348521
if id not in list:
    ...

Your first conditional is always going to pass, because it will be looking for integer 348521 in list which has one element at index list[0] with the string value of '350882 348521 350166\r\n', so integer 348521 will be added to that list, making it a list of two elements: a string and an integer, as your output shows.

To reiterate: list is searched for id, not the string in list's first element.

If you were trying to find if the string representation of '348521' was contained within the larger string contained within your list, you could do the following, noting that you would need to do this for each element in list:

if str(id) not in list[0]: # list[0]: '350882 348521 350166\r\n'
    ...                    #                  ^^^^^^

However be aware that you would need to wrap str(id) with whitespace for the search, otherwise it would also match:

2348521999
 ^^^^^^

It is unclear whether you want your "list" to be a "string of integers separated by whitespace" or if you really want a list of integers.

If all you are trying to accomplish is to have a list of IDs, and to add IDs to that list only if they are not already contained, (and if the order of the elements in the list is not important,) then a set would be the best data structure to use.

ids = set(
    [int(id) for id in '350882 348521 350166\r\n'.strip().split(' ')]
)

# Adding an ID already in the set has no effect
ids.add(348521)

If the ordering of the IDs in the string is important then I would keep your IDs in a standard list and use your conditional check:

ids = [int(id) for id in '350882 348521 350166\r\n'.strip().split(' ')]

if 348521 not in ids:
    ...

c++ exception : throwing std::string

It works, but I wouldn't do it if I were you. You don't seem to be deleting that heap data when you're done, which means that you've created a memory leak. The C++ compiler takes care of ensuring that exception data is kept alive even as the stack is popped, so don't feel that you need to use the heap.

Incidentally, throwing a std::string isn't the best approach to begin with. You'll have a lot more flexibility down the road if you use a simple wrapper object. It may just encapsulate a string for now, but maybe in future you will want to include other information, like some data which caused the exception or maybe a line number (very common, that). You don't want to change all of your exception handling in every spot in your code-base, so take the high road now and don't throw raw objects.

Join between tables in two different databases?

Yes, assuming the account has appropriate permissions you can use:

SELECT <...>
FROM A.table1 t1 JOIN B.table2 t2 ON t2.column2 = t1.column1;

You just need to prefix the table reference with the name of the database it resides in.

Makefiles with source files in different directories

RC's post was SUPER useful. I never thought about using the $(dir $@) function, but it did exactly what I needed it to do.

In parentDir, have a bunch of directories with source files in them: dirA, dirB, dirC. Various files depend on the object files in other directories, so I wanted to be able to make one file from within one directory, and have it make that dependency by calling the makefile associated with that dependency.

Essentially, I made one Makefile in parentDir that had (among many other things) a generic rule similar to RC's:

%.o : %.cpp
        @mkdir -p $(dir $@)
        @echo "============="
        @echo "Compiling $<"
        @$(CC) $(CFLAGS) -c $< -o $@

Each subdirectory included this upper-level makefile in order to inherit this generic rule. In each subdirectory's Makefile, I wrote a custom rule for each file so that I could keep track of everything that each individual file depended on.

Whenever I needed to make a file, I used (essentially) this rule to recursively make any/all dependencies. Perfect!

NOTE: there's a utility called "makepp" that seems to do this very task even more intuitively, but for the sake of portability and not depending on another tool, I chose to do it this way.

Hope this helps!

How to use glOrtho() in OpenGL?

glOrtho describes a transformation that produces a parallel projection. The current matrix (see glMatrixMode) is multiplied by this matrix and the result replaces the current matrix, as if glMultMatrix were called with the following matrix as its argument:

OpenGL documentation (my bold)

The numbers define the locations of the clipping planes (left, right, bottom, top, near and far).

The "normal" projection is a perspective projection that provides the illusion of depth. Wikipedia defines a parallel projection as:

Parallel projections have lines of projection that are parallel both in reality and in the projection plane.

Parallel projection corresponds to a perspective projection with a hypothetical viewpoint—e.g., one where the camera lies an infinite distance away from the object and has an infinite focal length, or "zoom".

Reactjs - setting inline styles correctly

It's not immediately obvious from the documentation why the following does not work:

<span style={font-size: 1.7} class="glyphicon glyphicon-remove-sign"></span>

But when doing it entirely inline:

  • You need double curly brackets
  • You don't need to put your values in quotes
  • React will add some default if you omit "em"
  • Remember to camelCase style names that have dashes in CSS - e.g. font-size becomes fontSize:
  • class is className

The correct way looks like this:

<span style={{fontSize: 1.7 + "em"}} className="glyphicon glyphicon-remove-sign"></span>

Bootstrap button drop-down inside responsive table not visible because of scroll

Inside bootstrap.css search the next code:

.fixed-table-body {
  overflow-x: auto;
  overflow-y: auto;
  height: 100%;
}

...and update with this:

.fixed-table-body {
  overflow-x: visible;
  overflow-y: visible;
  height: 100%;
}

Display a view from another controller in ASP.NET MVC

Yes, you can. Return an Action like this :

return RedirectToAction("View", "Name of Controller");

An example:

return RedirectToAction("Details/" + id.ToString(), "FullTimeEmployees");

This approach will call the GET method

Also you could pass values to action like this:

return RedirectToAction("Details/" + id.ToString(), "FullTimeEmployees", new {id = id.ToString(), viewtype = "extended" });

How do I solve the "server DNS address could not be found" error on Windows 10?

Steps to manually configure DNS:

  1. You can access Network and Sharing center by right clicking on the Network icon on the taskbar.

  2. Now choose adapter settings from the side menu.

  3. This will give you a list of the available network adapters in the system . From them right click on the adapter you are using to connect to the internet now and choose properties option.

  4. In the networking tab choose ‘Internet Protocol Version 4 (TCP/IPv4)’.

  5. Now you can see the properties dialogue box showing the properties of IPV4. Here you need to change some properties.

    Select ‘use the following DNS address’ option. Now fill the following fields as given here.

    Preferred DNS server: 208.67.222.222

    Alternate DNS server : 208.67.220.220

    This is an available Open DNS address. You may also use google DNS server addresses.

    After filling these fields. Check the ‘validate settings upon exit’ option. Now click OK.

You have to add this DNS server address in the router configuration also (by referring the router manual for more information).

Refer : for above method & alternative

If none of this works, then open command prompt(Run as Administrator) and run these:

ipconfig /flushdns
ipconfig /registerdns
ipconfig /release
ipconfig /renew
NETSH winsock reset catalog
NETSH int ipv4 reset reset.log
NETSH int ipv6 reset reset.log
Exit

Hopefully that fixes it, if its still not fixed there is a chance that its a NIC related issue(driver update or h/w).

Also FYI, this has a thread on Microsoft community : Windows 10 - DNS Issue

If Cell Starts with Text String... Formula

I know this is a really old post, but I found it in searching for a solution to the same problem. I don't want a nested if-statement, and Switch is apparently newer than the version of Excel I'm using. I figured out what was going wrong with my code, so I figured I'd share here in case it helps someone else.

I remembered that VLOOKUP requires the source table to be sorted alphabetically/numerically for it to work. I was initially trying to do this...

=LOOKUP(LOWER(LEFT($T$3, 1)),  {"s","l","m"}, {-1,1,0})

and it started working when I did this...

=LOOKUP(LOWER(LEFT($T$3, 1)),  {"l","m","s"}, {1,0,-1})

I was initially thinking the last value might turn out to be a default, so I wanted the zero at the last place. That doesn't seem to be the behavior anyway, so I just put the possible matches in order, and it worked.

Edit: As a final note, I see that the example in the original post has letters in alphabetical order, but I imagine the real use case might have been different if the error was happening and the letters A, B, and C were just examples.

Use superscripts in R axis labels

It works the same way for axes: parse(text='70^o*N') will raise the o as a superscript (the *N is to make sure the N doesn't get raised too).

labelsX=parse(text=paste(abs(seq(-100, -50, 10)), "^o ", "*W", sep=""))
labelsY=parse(text=paste(seq(50,100,10), "^o ", "*N", sep=""))
plot(-100:-50, 50:100, type="n", xlab="", ylab="", axes=FALSE)
axis(1, seq(-100, -50, 10), labels=labelsX)
axis(2, seq(50, 100, 10), labels=labelsY)
box()

GitHub Error Message - Permission denied (publickey)

I was getting this error. Turns out I had just upgraded OSX to Sierra and my old key was no longer registered.

At first I thought it was "Upgrading to macOS Sierra will break your SSH keys and lock you out of your own servers"

But I had sidestepped that one. Turns out I just had to re-register my existing key:

ssh-add -K

And type the passphrase... done!

How to convert a byte array to Stream

In your case:

MemoryStream ms = new MemoryStream(buffer);

Difference between except: and except Exception as e: in Python

Another way to look at this. Check out the details of the exception:

In [49]: try: 
    ...:     open('file.DNE.txt') 
    ...: except Exception as  e: 
    ...:     print(dir(e)) 
    ...:                                                                                                                                    
['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', 'args', 'characters_written', 'errno', 'filename', 'filename2', 'strerror', 'with_traceback']

There are lots of "things" to access using the 'as e' syntax.

This code was solely meant to show the details of this instance.

Hide options in a select list using jQuery

Your best bet is to set disabled=true on the option items you want to disable, then in CSS set

option:disabled {
    display: none;
}

That way even if the browser doesn't support hiding the disabled item, it still can't be selected.. but on browsers that do support it, they will be hidden.

open link in iframe

Try this:

<iframe name="iframe1" src="target.html"></iframe>

<a href="link.html" target="iframe1">link</a>

The "target" attribute should open in the iframe.

DB2 SQL error: SQLCODE: -206, SQLSTATE: 42703

That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:

DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87

Double check your table definition. Maybe you just missed adding something.

I also tried google-ing this problem and saw this:

http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode

Reading an image file into bitmap from sdcard, why am I getting a NullPointerException?

The MediaStore API is probably throwing away the alpha channel (i.e. decoding to RGB565). If you have a file path, just use BitmapFactory directly, but tell it to use a format that preserves alpha:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
selected_photo.setImageBitmap(bitmap);

or

http://mihaifonoage.blogspot.com/2009/09/displaying-images-from-sd-card-in.html

Generating a PDF file from React Components

This may or may not be a sub-optimal way of doing things, but the simplest solution to the multi-page problem I found was to ensure all rendering is done before calling the jsPDFObj.save method.

As for rendering hidden articles, this is solved with a similar fix to css image text replacement, I position absolutely the element to be rendered -9999px off the page left, this doesn't affect layout and allows for the elem to be visible to html2pdf, especially when using tabs, accordions and other UI components that depend on {display: none}.

This method wraps the prerequisites in a promise and calls pdf.save() in the finally() method. I cannot be sure that this is foolproof, or an anti-pattern, but it would seem that it works in most cases I have thrown at it.

_x000D_
_x000D_
// Get List of paged elements._x000D_
let elems = document.querySelectorAll('.elemClass');_x000D_
let pdf = new jsPDF("portrait", "mm", "a4");_x000D_
_x000D_
// Fix Graphics Output by scaling PDF and html2canvas output to 2_x000D_
pdf.scaleFactor = 2;_x000D_
_x000D_
// Create a new promise with the loop body_x000D_
let addPages = new Promise((resolve,reject)=>{_x000D_
  elems.forEach((elem, idx) => {_x000D_
    // Scaling fix set scale to 2_x000D_
    html2canvas(elem, {scale: "2"})_x000D_
      .then(canvas =>{_x000D_
        if(idx < elems.length - 1){_x000D_
          pdf.addImage(canvas.toDataURL("image/png"), 0, 0, 210, 297);_x000D_
          pdf.addPage();_x000D_
        } else {_x000D_
          pdf.addImage(canvas.toDataURL("image/png"), 0, 0, 210, 297);_x000D_
          console.log("Reached last page, completing");_x000D_
        }_x000D_
  })_x000D_
  _x000D_
  setTimeout(resolve, 100, "Timeout adding page #" + idx);_x000D_
})_x000D_
_x000D_
addPages.finally(()=>{_x000D_
   console.log("Saving PDF");_x000D_
   pdf.save();_x000D_
});
_x000D_
_x000D_
_x000D_

Does JavaScript have a method like "range()" to generate a range within the supplied bounds?

I would like to add what I would think is a very adjustable version, which is very fast.

const range = (start, end) => {
    let all = [];
    if (typeof start === "string" && typeof end === "string") {
        // Return the range of characters using utf-8 least to greatest
        const s = start.charCodeAt(0);
        const e = end.charCodeAt(0);
        for (let i = s; i <= e; i++) {
            all.push(String.fromCharCode(i));
        }
    } else if (typeof start === "number" && typeof end === "number") {
        // Return the range of numbers from least to greatest
        for(let i = end; i >= start; i--) {
            all.push(i);
        }
    } else {
        throw new Error("Did not supply matching types number or string.");
    }
    return all;
}
// usage
const aTod = range("a", "d");

Also Typescript if you would like

const range = (start: string | number, end: string | number): string[] | number[] => {
    const all: string[] | number[] = [];
    if (typeof start === "string" && typeof end === "string") {
        const s: number = start.charCodeAt(0);
        const e: number = end.charCodeAt(0);
        for (let i = s; i <= e; i++) {
            all.push(String.fromCharCode(i));
        }
    } else if (typeof start === "number" && typeof end === "number") {
        for (let i = end; i >= start; i--) {
            all.push(i);
        }
    } else {
        throw new Error("Did not supply matching types number or string.");
    }
    return all;
}
// Usage
const negTenToten: number[] = range(-10, 10) as number[];

Made with some influence from other answers. User is gone now.

How can I solve "Either the parameter @objname is ambiguous or the claimed @objtype (COLUMN) is wrong."?

Nuts. I hit this same error weeks ago, and after a lot of wasted time figured out how to make it work--but I've since forgotten it. (Not much help, other than to say yes, it can be done.)

Have you tried different combinations of brackets, or of with and without brackest? e.g.

EXEC sp_rename 'ENG_TEst.ENG_Test_A/C_TYPE', 'ENG_Test_AC_TYPE', 'COLUMN';
EXEC sp_rename '[ENG_TEst].[ENG_Test_A/C_TYPE]', 'ENG_Test_AC_TYPE', 'COLUMN';
EXEC sp_rename '[ENG_TEst].[ENG_Test_A/C_TYPE]', '[ENG_Test_AC_TYPE]', 'COLUMN';
EXEC sp_rename '[ENG_TEst].ENG_Test_A/C_TYPE', 'ENG_Test_AC_TYPE', 'COLUMN';

If all else fails, there's always

  • Create new table (as "xENG_TEst") with proper names
  • Copy data over from old table
  • Drop old table
  • Rename new table to final name

File Upload in WebView

Ive actually managed to get the file picker to appear in Kitkat, to select a image and to get the filepath in activity result but the only thing that im not able to "fix" (cause this workaround) is to make the input filed to fill out with file data.

Does anyone know any way how to access the input-field from a activity ? Am using this example comment. Is just this last piece, the last brick in the wall that i just have to put into right place (tho i could trigger upload of image file directly from code.

UPDATE #1

Im no hardcore Android dev so i'll show code on newbie level. Im creating a new Activity in already existing Activity

Manifest part

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application android:label="TestApp">
 <activity android:name=".BrowseActivity"></activity>
</application>

Am creating my BrowseActivity class from this example answer. The WebChromeClient() instance basically looks the same, except last piece, triggering the picker UI part...

private final static int FILECHOOSER_RESULTCODE=1;  
private final static int KITKAT_RESULTCODE = 2;

...

// The new WebChromeClient() looks pretty much the same, except one piece...

WebChromeClient chromeClient = new WebChromeClient(){  
    // For Android 3.0+
    public void openFileChooser(ValueCallback<Uri> uploadMsg) { /* Default code */ }  

    // For Android 3.0+
    public void openFileChooser( ValueCallback uploadMsg, String acceptType ) { /* Default code */ }  

    //For Android 4.1, also default but it'll be as example
    public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
        mUploadMessage = uploadMsg;
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("*/*");
        BrowseActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), BrowseActivity.FILECHOOSER_RESULTCODE);

    }  

    // The new code
    public void showPicker( ValueCallback<Uri> uploadMsg ){  
        // Here is part of the issue, the uploadMsg is null since it is not triggered from Android
        mUploadMessage = uploadMsg; 
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("*/*");
        BrowseActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), BrowseActivity.KITKAT_RESULTCODE);
    }}

And some more stuff

web = new WebView(this);
// Notice this part, setting chromeClient as js interface is just lazy
web.getSettings().setJavaScriptEnabled(true);
web.addJavascriptInterface(chromeClient, "jsi" );
web.getSettings().setAllowFileAccess(true);
web.getSettings().setAllowContentAccess(true);
web.clearCache(true);
web.loadUrl( "http://as3breeze.com/upload.html" );
web.setWebViewClient(new myWebClient());
web.setWebChromeClient(chromeClient);


@Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) {  
  Log.d("Result", "("+requestCode+ ") - (" +resultCode  + ") - (" + intent + ") - " + mUploadMessage);  
    if (null == intent) return;  
    Uri result = null;  
    if(requestCode==FILECHOOSER_RESULTCODE)  
    {  
        Log.d("Result","Old android");  
        if (null == mUploadMessage) return;  
        result = intent == null || resultCode != RESULT_OK ? null  : intent.getData();  
        mUploadMessage.onReceiveValue(result);  
        mUploadMessage = null;  
    } else if (requestCode == KITKAT_RESULTCODE) {  
        Log.d("Result","Kitkat android");  
        result = intent.getData();  
        final int takeFlags = intent.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION  | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);  
        String path = getPath( this, result);  
        File selectedFile = new File(path); 
//I used you example with a bit of editing so thought i would share, here i added a method to upload the file to the webserver
File selectedFile = new File(path);  
            UploadFile(selectedFile);


        //mUploadMessage.onReceiveValue( Uri.parse(selectedFile.toString()) );  
        // Now we have the file but since mUploadMessage was null, it gets errors
    }  
}

 public void UploadFile(File selectedFile)
{
    Random rnd = new Random();
    String sName = "File" + rnd.nextInt(999999) + selectedFile.getAbsolutePath().substring(selectedFile.getAbsolutePath().lastIndexOf("."));
    UploadedFileName = sName;
    uploadFile = selectedFile;
    if (progressBar != null && progressBar.isShowing())
    {
        progressBar.dismiss();
    }
 // prepare for a progress bar dialog
    progressBar = new ProgressDialog(mContext);
    progressBar.setCancelable(true);
    progressBar.setMessage("Uploading File");
    progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);            
    progressBar.show();
    new Thread() {

        public void run() 
        {
            int serverResponseCode;
            String serverResponseMessage;
            HttpURLConnection connection = null;
            DataOutputStream outputStream = null;
            DataInputStream inputStream = null;
            String pathToOurFile = uploadFile.getAbsolutePath();
            String urlServer = "http://serveraddress/Scripts/UploadHandler.php?name" + UploadedFileName;
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary =  "*****";

            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1*1024*1024;

            try
            {
                FileInputStream fileInputStream = new FileInputStream(uploadFile);

                URL url = new URL(urlServer);
                connection = (HttpURLConnection) url.openConnection();
                Log.i("File", urlServer);

                // Allow Inputs &amp; Outputs.
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setUseCaches(false);

                // Set HTTP method to POST.
                connection.setRequestMethod("POST");

                connection.setRequestProperty("Connection", "Keep-Alive");
                connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
                Log.i("File", "Open conn");

                outputStream = new DataOutputStream( connection.getOutputStream() );

                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
                outputStream.writeBytes(lineEnd);
                Log.i("File", "write bytes");

                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
                Log.i("File", "available: " + fileInputStream.available());

                // Read file
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                Log.i("file", "Bytes Read: " + bytesRead);
                while (bytesRead > 0)
                {
                    outputStream.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                }

                outputStream.writeBytes(lineEnd);
                outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                // Responses from the server (code and message)
                serverResponseCode = connection.getResponseCode();
                serverResponseMessage = connection.getResponseMessage();
                Log.i("file repsonse", serverResponseMessage);

//once the file is uploaded call a javascript function to verify the user wants to save the image
                progressBar.dismiss();
                runOnUiThread(new Runnable() 
                {

                    @Override
                    public void run() 
                    {
                        Log.i("start", "File name: " + UploadedFileName);
                        WebView myWebView = (WebView) findViewById(R.id.webview);
                        myWebView.loadUrl("javascript:CheckImage('" + UploadedFileName + "')");
                    }
                });


                fileInputStream.close();
                outputStream.flush();
                outputStream.close();
            }
            catch (Exception ex)
            {
                Log.i("exception", "Error: " + ex.toString());
            }               
        }
    }.start();

}

Lastly, some more code to get the actual file path, code found on SO, ive added post url in comments as well so the author gets credits for his work.

/**
 * Get a file path from a Uri. This will get the the path for Storage Access
 * Framework Documents, as well as the _data field for the MediaStore and
 * other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @author paulburke
 * @source https://stackoverflow.com/a/20559175
 */
@TargetApi(Build.VERSION_CODES.KITKAT)
public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] {
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @param selection (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 * @source https://stackoverflow.com/a/20559175
 */
public static String getDataColumn(Context context, Uri uri, String selection,
                                   String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}


/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 * @source https://stackoverflow.com/a/20559175
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 * @source https://stackoverflow.com/a/20559175
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 * @source https://stackoverflow.com/a/20559175
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}  

Lastly, the HTML page needs to trigger that new method of showPicker (specificaly when on A4.4)

<form id="form-upload" method="post" enctype="multipart/form-data">
    <input id="fileupload" name="fileupload" type="file" onclick="javascript:prepareForPicker();"/>
</form>
<script type="text/javascript">
function getAndroidVersion() {
    var ua = navigator.userAgent; 
    var match = ua.match(/Android\s([0-9\.]*)/);
    return match ? match[1] : false;
};
function prepareForPicker(){
    if(getAndroidVersion().indexOf("4.4") != -1){
        window.jsi.showPicker();
        return false;
    }
}

function CheckImage(name)
{
//Check to see if user wants to save I used some ajax to save the file if necesarry
}
</script>

Python urllib2, basic HTTP authentication, and tr.im

Same solutions as Python urllib2 Basic Auth Problem apply.

see https://stackoverflow.com/a/24048852/1733117; you can subclass urllib2.HTTPBasicAuthHandler to add the Authorization header to each request that matches the known url.

class PreemptiveBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
    '''Preemptive basic auth.

    Instead of waiting for a 403 to then retry with the credentials,
    send the credentials if the url is handled by the password manager.
    Note: please use realm=None when calling add_password.'''
    def http_request(self, req):
        url = req.get_full_url()
        realm = None
        # this is very similar to the code from retry_http_basic_auth()
        # but returns a request object.
        user, pw = self.passwd.find_user_password(realm, url)
        if pw:
            raw = "%s:%s" % (user, pw)
            auth = 'Basic %s' % base64.b64encode(raw).strip()
            req.add_unredirected_header(self.auth_header, auth)
        return req

    https_request = http_request

"Undefined reference to" template class constructor

You will have to define the functions inside your header file.
You cannot separate definition of template functions in to the source file and declarations in to header file.

When a template is used in a way that triggers its intstantation, a compiler needs to see that particular templates definition. This is the reason templates are often defined in the header file in which they are declared.

Reference:
C++03 standard, § 14.7.2.4:

The definition of a non-exported function template, a non-exported member function template, or a non-exported member function or static data member of a class template shall be present in every translation unit in which it is explicitly instantiated.

EDIT:
To clarify the discussion on the comments:
Technically, there are three ways to get around this linking problem:

  • To move the definition to the .h file
  • Add explicit instantiations in the .cpp file.
  • #include the .cpp file defining the template at the .cpp file using the template.

Each of them have their pros and cons,

Moving the defintions to header files may increase the code size(modern day compilers can avoid this) but will increase the compilation time for sure.

Using the explicit instantiation approach is moving back on to traditional macro like approach.Another disadvantage is that it is necessary to know which template types are needed by the program. For a simple program this is easy but for complicated program this becomes difficult to determine in advance.

While including cpp files is confusing at the same time shares the problems of both above approaches.

I find first method the easiest to follow and implement and hence advocte using it.

Difference between "move" and "li" in MIPS assembly language

The move instruction copies a value from one register to another. The li instruction loads a specific numeric value into that register.

For the specific case of zero, you can use either the constant zero or the zero register to get that:

move $s0, $zero
li   $s0, 0

There's no register that generates a value other than zero, though, so you'd have to use li if you wanted some other number, like:

li $s0, 12345678

Returning JSON object as response in Spring Boot

More correct create DTO for API queries, for example entityDTO:

  1. Default response OK with list of entities:
@GetMapping(produces=MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public List<EntityDto> getAll() {
    return entityService.getAllEntities();
}

But if you need return different Map parameters you can use next two examples
2. For return one parameter like map:

@GetMapping(produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> getOneParameterMap() {
    return ResponseEntity.status(HttpStatus.CREATED).body(
            Collections.singletonMap("key", "value"));
}
  1. And if you need return map of some parameters(since Java 9):
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> getSomeParameters() {
    return ResponseEntity.status(HttpStatus.OK).body(Map.of(
            "key-1", "value-1",
            "key-2", "value-2",
            "key-3", "value-3"));
}

Why can't I see the "Report Data" window when creating reports?

Hi I faced the same issue in VS2008, I tried based on the post 8 (Thanks to the "Tricky part" section in that)

The (Ctrl+Alt+D) combo did not work there in VS2008, but after opening the Report file(rdlc) I browsed on the View menu and found out that View->Toolbars->Data Design is the solution for that.

Upon opening that we get around 4 icons of which the "Show Data Sources" section brings the "Website Data Sources" section which fetches all Entities, Typed DataSets etc.

The keybord shortcut is (Shift+Alt+D).

The twisty part here is the "Data Sources" section available with the Server Explorer toolbar doesnt bring up any stuff but the "Website Data Sources" brings all the needed., can somebody explain that to me.

What is the difference between json.dump() and json.dumps() in python?

In memory usage and speed.

When you call jsonstr = json.dumps(mydata) it first creates a full copy of your data in memory and only then you file.write(jsonstr) it to disk. So this is a faster method but can be a problem if you have a big piece of data to save.

When you call json.dump(mydata, file) -- without 's', new memory is not used, as the data is dumped by chunks. But the whole process is about 2 times slower.

Source: I checked the source code of json.dump() and json.dumps() and also tested both the variants measuring the time with time.time() and watching the memory usage in htop.

Pass a local file in to URL in Java

You can also use

[AnyClass].class.getResource(filePath)

Angular JS break ForEach

As the other answers state, Angular doesn't provide this functionality. jQuery does however, and if you have loaded jQuery as well as Angular, you can use

jQuery.each ( array, function ( index, value) {
    if(condition) return false; // this will cause a break in the iteration
})

See http://api.jquery.com/jquery.each/

JTable How to refresh table model after insert delete or update the data.

Would it not be better to use java.util.Observable and java.util.Observer that will cause the table to update?

How to read HDF5 files in Python

you can use Pandas.

import pandas as pd
pd.read_hdf(filename,key)

Why should C++ programmers minimize use of 'new'?

There are two widely-used memory allocation techniques: automatic allocation and dynamic allocation. Commonly, there is a corresponding region of memory for each: the stack and the heap.

Stack

The stack always allocates memory in a sequential fashion. It can do so because it requires you to release the memory in the reverse order (First-In, Last-Out: FILO). This is the memory allocation technique for local variables in many programming languages. It is very, very fast because it requires minimal bookkeeping and the next address to allocate is implicit.

In C++, this is called automatic storage because the storage is claimed automatically at the end of scope. As soon as execution of current code block (delimited using {}) is completed, memory for all variables in that block is automatically collected. This is also the moment where destructors are invoked to clean up resources.

Heap

The heap allows for a more flexible memory allocation mode. Bookkeeping is more complex and allocation is slower. Because there is no implicit release point, you must release the memory manually, using delete or delete[] (free in C). However, the absence of an implicit release point is the key to the heap's flexibility.

Reasons to use dynamic allocation

Even if using the heap is slower and potentially leads to memory leaks or memory fragmentation, there are perfectly good use cases for dynamic allocation, as it's less limited.

Two key reasons to use dynamic allocation:

  • You don't know how much memory you need at compile time. For instance, when reading a text file into a string, you usually don't know what size the file has, so you can't decide how much memory to allocate until you run the program.

  • You want to allocate memory which will persist after leaving the current block. For instance, you may want to write a function string readfile(string path) that returns the contents of a file. In this case, even if the stack could hold the entire file contents, you could not return from a function and keep the allocated memory block.

Why dynamic allocation is often unnecessary

In C++ there's a neat construct called a destructor. This mechanism allows you to manage resources by aligning the lifetime of the resource with the lifetime of a variable. This technique is called RAII and is the distinguishing point of C++. It "wraps" resources into objects. std::string is a perfect example. This snippet:

int main ( int argc, char* argv[] )
{
    std::string program(argv[0]);
}

actually allocates a variable amount of memory. The std::string object allocates memory using the heap and releases it in its destructor. In this case, you did not need to manually manage any resources and still got the benefits of dynamic memory allocation.

In particular, it implies that in this snippet:

int main ( int argc, char* argv[] )
{
    std::string * program = new std::string(argv[0]);  // Bad!
    delete program;
}

there is unneeded dynamic memory allocation. The program requires more typing (!) and introduces the risk of forgetting to deallocate the memory. It does this with no apparent benefit.

Why you should use automatic storage as often as possible

Basically, the last paragraph sums it up. Using automatic storage as often as possible makes your programs:

  • faster to type;
  • faster when run;
  • less prone to memory/resource leaks.

Bonus points

In the referenced question, there are additional concerns. In particular, the following class:

class Line {
public:
    Line();
    ~Line();
    std::string* mString;
};

Line::Line() {
    mString = new std::string("foo_bar");
}

Line::~Line() {
    delete mString;
}

Is actually a lot more risky to use than the following one:

class Line {
public:
    Line();
    std::string mString;
};

Line::Line() {
    mString = "foo_bar";
    // note: there is a cleaner way to write this.
}

The reason is that std::string properly defines a copy constructor. Consider the following program:

int main ()
{
    Line l1;
    Line l2 = l1;
}

Using the original version, this program will likely crash, as it uses delete on the same string twice. Using the modified version, each Line instance will own its own string instance, each with its own memory and both will be released at the end of the program.

Other notes

Extensive use of RAII is considered a best practice in C++ because of all the reasons above. However, there is an additional benefit which is not immediately obvious. Basically, it's better than the sum of its parts. The whole mechanism composes. It scales.

If you use the Line class as a building block:

 class Table
 {
      Line borders[4];
 };

Then

 int main ()
 {
     Table table;
 }

allocates four std::string instances, four Line instances, one Table instance and all the string's contents and everything is freed automagically.

Asp.net MVC ModelState.Clear

Well, this seemed to work on my Razor Page and never even did a round trip to the .cs file. This is old html way. It might be useful.

<input type="reset" value="Reset">

jQuery: print_r() display equivalent?

How about something like:

<script src='http://code.jquery.com/jquery-latest.js'></script>

function print_r(o){
return JSON.stringify(o,null,'\t').replace(/\n/g,'<br>').replace(/\t/g,'&nbsp;&nbsp;&nbsp;'); }

RegEx: How can I match all numbers greater than 49?

Try a conditional group matching 50-99 or any string of three or more digits:

var r = /^(?:[5-9]\d|\d{3,})$/

Apache won't run in xampp

None of the above worked for me. This is what finally worked for me:

1) Start Services (Type services in your start > search)
2) Look for Apache services.It was disabled in my case. Enabling it worked for me.

Some people have also reported duplicate listing of Apache services which has prevented it from starting. If that is the case, delete/disable one of the Apache services which corresponds to the wrong path.

A restart of XAMPP might be required.

How to add many functions in ONE ng-click?

A lot of people use (click) option so I will share this too.

<button (click)="function1()" (click)="function2()">Button</button>

Android Studio Emulator and "Process finished with exit code 0"

I was able to get past this by making sure all my SDKs were up to date. (Mac OS 10.13.3, Android Studio 3.0.1). I went to Android Studio -> Check for Updates... and let it run. Once my Android 5.0/5.1 (API level 21/22) SDKs were updated to revision 2: Preferences screen showing updated Android 5.0 and 5.1 SDKs

After doing this update, I was able to run the emulator without crashing out immediately with a "Emulator: Process finished with exit code 0" error.

C# getting the path of %AppData%

The BEST way to use the AppData directory, IS to use Environment.ExpandEnvironmentVariable method.

Reasons:

  • it replaces parts of your string with valid directories or whatever
  • it is case-insensitive
  • it is easy and uncomplicated
  • it is a standard
  • good for dealing with user input

Examples:

string path;
path = @"%AppData%\stuff";
path = @"%aPpdAtA%\HelloWorld";
path = @"%progRAMfiLES%\Adobe;%appdata%\FileZilla"; // collection of paths

path = Environment.ExpandEnvironmentVariables(path);
Console.WriteLine(path);

More info:

%ALLUSERSPROFILE%   C:\ProgramData
%APPDATA%   C:\Users\Username\AppData\Roaming
%COMMONPROGRAMFILES%    C:\Program Files\Common Files
%COMMONPROGRAMFILES(x86)%   C:\Program Files (x86)\Common Files
%COMSPEC%   C:\Windows\System32\cmd.exe
%HOMEDRIVE% C:
%HOMEPATH%  C:\Users\Username
%LOCALAPPDATA%  C:\Users\Username\AppData\Local
%PROGRAMDATA%   C:\ProgramData
%PROGRAMFILES%  C:\Program Files
%PROGRAMFILES(X86)% C:\Program Files (x86) (only in 64-bit version)
%PUBLIC%    C:\Users\Public
%SystemDrive%   C:
%SystemRoot%    C:\Windows
%TEMP% and %TMP%    C:\Users\Username\AppData\Local\Temp
%USERPROFILE%   C:\Users\Username
%WINDIR%    C:\Windows

Change WPF window background image in C# code

i just place one image in " d drive-->Data-->IMG". The image name is x.jpg:

And on c# code type

ImageBrush myBrush = new ImageBrush();

myBrush.ImageSource = new BitmapImage(new Uri(BaseUriHelper.GetBaseUri(this), "D:\\Data\\IMG\\x.jpg"));

(please put double slash in between path)

this.Background = myBrush;

finally i got the background.. enter image description here

Base 64 encode and decode example code

for android API byte[] to Base64String encoder

byte[] data=new byte[];
String Base64encodeString=android.util.Base64.encodeToString(data, android.util.Base64.DEFAULT);

How to set a value for a selectize.js input?

var $select = $(document.getElementById("selectTagName"));
var selectize = $select[0].selectize;
selectize.setValue(selectize.search("My Default Value").items[0]);

Integer division: How do you produce a double?

Best way to do this is

int i = 3;
Double d = i * 1.0;

d is 3.0 now.

cut or awk command to print first field of first row

try this:

head -1 /etc/*release | awk '{print $1}'

M_PI works with math.h but not with cmath in Visual Studio

Interestingly I checked this on an app of mine and I got the same error.

I spent a while checking through headers to see if there was anything undef'ing the _USE_MATH_DEFINES and found nothing.

So I moved the

#define _USE_MATH_DEFINES
#include <cmath>

to be the first thing in my file (I don't use PCHs so if you are you will have to have it after the #include "stdafx.h") and suddenly it compile perfectly.

Try moving it higher up the page. Totally unsure as to why this would cause issues though.

Edit: Figured it out. The #include <math.h> occurs within cmath's header guards. This means that something higher up the list of #includes is including cmath without the #define specified. math.h is specifically designed so that you can include it again with that define now changed to add M_PI etc. This is NOT the case with cmath. So you need to make sure you #define _USE_MATH_DEFINES before you include anything else. Hope that clears it up for you :)

Failing that just include math.h you are using non-standard C/C++ as already pointed out :)

Edit 2: Or as David points out in the comments just make yourself a constant that defines the value and you have something more portable anyway :)

How do I keep jQuery UI Accordion collapsed by default?

Add the active: false option (documentation)..

$("#accordion").accordion({ header: "h3", collapsible: true, active: false });

How to print an exception in Python?

(I was going to leave this as a comment on @jldupont's answer, but I don't have enough reputation.)

I've seen answers like @jldupont's answer in other places as well. FWIW, I think it's important to note that this:

except Exception as e:
    print(e)

will print the error output to sys.stdout by default. A more appropriate approach to error handling in general would be:

except Exception as e:
    print(e, file=sys.stderr)

(Note that you have to import sys for this to work.) This way, the error is printed to STDERR instead of STDOUT, which allows for the proper output parsing/redirection/etc. I understand that the question was strictly about 'printing an error', but it seems important to point out the best practice here rather than leave out this detail that could lead to non-standard code for anyone who doesn't eventually learn better.

I haven't used the traceback module as in Cat Plus Plus's answer, and maybe that's the best way, but I thought I'd throw this out there.

Best way to compare dates in Android

Kotlin supports operators overloading

In Kotlin you can easily compare dates with compare operators. Because Kotlin already support operators overloading. So to compare date objects :

firstDate: Date = // your first date
secondDate: Date = // your second date

if(firstDate < secondDate){
// fist date is before second date
}

and if you're using calendar objects, you can easily compare like this:

if(cal1.time < cal2.time){
// cal1 date is before cal2 date
}

Set bootstrap modal body height by percentage

You've no doubt solved this by now or decided to do something different, but as it has not been answered & I stumbled across this when looking for something similar I thought I'd share my method.

I've taken to using two div sets. One has hidden-xs and is for sm, md & lg device viewing. The other has hidden-sm, -md, -lg and is only for mobile. Now I have a lot more control over the display in my CSS.

You can see a rough idea in this js fiddle where I set the footer and buttons to be smaller when the resolution is of the -xs size.

  <div class="modal-footer">
      <div class="hidden-xs">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button type="button" class="btn btn-primary">Save changes</button>
      </div>
      <div class="hidden-sm hidden-md hidden-lg sml-footer">
    <button type="button" class="btn btn-xs btn-default" data-dismiss="modal">Close</button>
    <button type="button" class="btn btn-xs btn-primary">Save changes</button>
      </div>
  </div>

file_get_contents(): SSL operation failed with code 1, Failed to enable crypto

Had the same ssl-problem on my developer machine (php 7, xampp on windows) with a self signed certificate trying to fopen a "https://localhost/..."-file. Obviously the root-certificate-assembly (cacert.pem) didn't work. I just copied manually the code from the apache server.crt-File in the downloaded cacert.pem and did the openssl.cafile=path/to/cacert.pem entry in php.ini

How to sort Counter by value? - python

Use the Counter.most_common() method, it'll sort the items for you:

>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})
>>> x.most_common()
[('c', 7), ('a', 5), ('b', 3)]

It'll do so in the most efficient manner possible; if you ask for a Top N instead of all values, a heapq is used instead of a straight sort:

>>> x.most_common(1)
[('c', 7)]

Outside of counters, sorting can always be adjusted based on a key function; .sort() and sorted() both take callable that lets you specify a value on which to sort the input sequence; sorted(x, key=x.get, reverse=True) would give you the same sorting as x.most_common(), but only return the keys, for example:

>>> sorted(x, key=x.get, reverse=True)
['c', 'a', 'b']

or you can sort on only the value given (key, value) pairs:

>>> sorted(x.items(), key=lambda pair: pair[1], reverse=True)
[('c', 7), ('a', 5), ('b', 3)]

See the Python sorting howto for more information.

Quickest way to clear all sheet contents VBA

Technically, and from Comintern's accepted workaround, I believe you actually want to Delete all the Cells in the Sheet. Which removes Formatting (See footnote for exceptions), etc. as well as the Cells Contents. I.e. Sheets("Zeroes").Cells.Delete

Combined also with UsedRange, ScreenUpdating and Calculation skipping it should be nearly intantaneous:

Sub DeleteCells ()
    Application.Calculation = XlManual
    Application.ScreenUpdating = False
    Sheets("Zeroes").UsedRange.Delete
    Application.ScreenUpdating = True
    Application.Calculation = xlAutomatic
End Sub

Or if you prefer to respect the Calculation State Excel is currently in:

Sub DeleteCells ()
    Dim SaveCalcState
    SaveCalcState = Application.Calculation
    Application.Calculation = XlManual
    Application.ScreenUpdating = False
    Sheets("Zeroes").UsedRange.Delete
    Application.ScreenUpdating = True
    Application.Calculation = SaveCalcState
End Sub

Footnote: If formatting was applied for an Entire Column, then it is not deleted. This includes Font Colour, Fill Colour and Borders, the Format Category (like General, Date, Text, Etc.) and perhaps other properties too, but

Conditional formatting IS deleted, as is Entire Row formatting.

(Entire Column formatting is quite useful if you are importing raw data repeatedly to a sheet as it will conform to the Formats originally applied if a simple Paste-Values-Only type import is done.)

Save PHP array to MySQL?

As mentioned before - If you do not need to search for data within the array, you can use serialize - but this is "php only". So I would recommend to use json_decode / json_encode - not only for performance but also for readability and portability (other languages such as javascript can handle json_encoded data).

Fetching distinct values on a column using Spark DataFrame

This solution demonstrates how to transform data with Spark native functions which are better than UDFs. It also demonstrates how dropDuplicates which is more suitable than distinct for certain queries.

Suppose you have this DataFrame:

+-------+-------------+
|country|    continent|
+-------+-------------+
|  china|         asia|
| brazil|south america|
| france|       europe|
|  china|         asia|
+-------+-------------+

Here's how to take all the distinct countries and run a transformation:

df
  .select("country")
  .distinct
  .withColumn("country", concat(col("country"), lit(" is fun!")))
  .show()
+--------------+
|       country|
+--------------+
|brazil is fun!|
|france is fun!|
| china is fun!|
+--------------+

You can use dropDuplicates instead of distinct if you don't want to lose the continent information:

df
  .dropDuplicates("country")
  .withColumn("description", concat(col("country"), lit(" is a country in "), col("continent")))
  .show(false)
+-------+-------------+------------------------------------+
|country|continent    |description                         |
+-------+-------------+------------------------------------+
|brazil |south america|brazil is a country in south america|
|france |europe       |france is a country in europe       |
|china  |asia         |china is a country in asia          |
+-------+-------------+------------------------------------+

See here for more information about filtering DataFrames and here for more information on dropping duplicates.

Ultimately, you'll want to wrap your transformation logic in custom transformations that can be chained with the Dataset#transform method.

Flutter: Trying to bottom-center an item in a Column, but it keeps left-aligning

In addition of Stack: to avoid floating container on keyboard, use this

return Scaffold(
    appBar: getAppBar(title),
    resizeToAvoidBottomInset: false,
    body:

Submit button doesn't work

I faced this problem today, and the issue was I was preventing event default action in document onclick:

document.onclick = function(e) {
    e.preventDefault();
}

Document onclick usually is used for event delegation but it's wrong to prevent default for every event, you must do it only for required elements:

document.onclick = function(e) {
    if (e.target instanceof HTMLAnchorElement) e.preventDefault();
}

Get the index of the object inside an array, matching a condition

var list =  [
                {prop1:"abc",prop2:"qwe"},
                {prop1:"bnmb",prop2:"yutu"},
                {prop1:"zxvz",prop2:"qwrq"}
            ];

var findProp = p => {
    var index = -1;
    $.each(list, (i, o) => {
        if(o.prop2 == p) {
            index = i;
            return false; // break
        }
    });
    return index; // -1 == not found, else == index
}

Vba macro to copy row from table if value in table meets condition

That is exactly what you do with an advanced filter. If it's a one shot, you don't even need a macro, it is available in the Data menu.

Sheets("Sheet1").Range("A1:D17").AdvancedFilter Action:=xlFilterCopy, _
    CriteriaRange:=Sheets("Sheet1").Range("G1:G2"), CopyToRange:=Range("A1:D1") _
    , Unique:=False

Remove git mapping in Visual Studio 2015

The above answer did not work for me. The registry entries would just be automatically re-added when I opened the solution in Visual Studio. I found the resolution in one of the links in Matthews answer though so credit still goes to him for the correct answer.

Remove Git binding from Visual Studio 2013 solution?

Remove the hidden .git folder in your solutionfolder.

I also removed the .gitattributes and .gitignore files just to keep my folder clean.

How to prevent favicon.ico requests?

You can't. All you can do is to make that image as small as possible and set some cache invalidation headers (Expires, Cache-Control) far in the future. Here's what Yahoo! has to say about favicon.ico requests.

How to change link color (Bootstrap)

using bootstrap 4 and SCSS check out this link here for full details

https://getbootstrap.com/docs/4.0/getting-started/theming/

in a nutshell...

open up lib/bootstrap/scss/_navbar.scss and find the statements that create these variables

  .navbar-nav {
    .nav-link {
      color: $navbar-light-color;

      @include hover-focus() {
        color: $navbar-light-hover-color;
      }

      &.disabled {
        color: $navbar-light-disabled-color;
      }
    }

so now you need to override

$navbar-light-color
$navbar-light-hover-color
$navbar-light-disabled-color

create a new scss file _localVariables.scss and add the following (with your colors)

$navbar-light-color : #520b71
$navbar-light-hover-color: #F3EFE6;
$navbar-light-disabled-color: #F3EFE6;

@import "../lib/bootstrap/scss/functions";
@import "../lib/bootstrap/scss/variables";
@import "../lib/bootstrap/scss/mixins/_breakpoints";

and on your other scss pages just add

@import "_localVariables";

instead of

@import "../lib/bootstrap/scss/functions";
@import "../lib/bootstrap/scss/variables";
@import "../lib/bootstrap/scss/mixins/_breakpoints";

Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

For Docker users: In my case it was caused by excessive docker image size. You can remove unused data using prune command:

docker system prune --all --force --volumes

Warning: as per manual (docker system prune --help):

This will remove:

  • all stopped containers
  • all networks not used by at least one container
  • all dangling images
  • all dangling build cache

An example of how to use getopts in bash

The example packaged with getopt (my distro put it in /usr/share/getopt/getopt-parse.bash) looks like it covers all of your cases:

#!/bin/bash

# A small example program for using the new getopt(1) program.
# This program will only work with bash(1)
# An similar program using the tcsh(1) script language can be found
# as parse.tcsh

# Example input and output (from the bash prompt):
# ./parse.bash -a par1 'another arg' --c-long 'wow!*\?' -cmore -b " very long "
# Option a
# Option c, no argument
# Option c, argument `more'
# Option b, argument ` very long '
# Remaining arguments:
# --> `par1'
# --> `another arg'
# --> `wow!*\?'

# Note that we use `"$@"' to let each command-line parameter expand to a 
# separate word. The quotes around `$@' are essential!
# We need TEMP as the `eval set --' would nuke the return value of getopt.
TEMP=`getopt -o ab:c:: --long a-long,b-long:,c-long:: \
     -n 'example.bash' -- "$@"`

if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi

# Note the quotes around `$TEMP': they are essential!
eval set -- "$TEMP"

while true ; do
    case "$1" in
        -a|--a-long) echo "Option a" ; shift ;;
        -b|--b-long) echo "Option b, argument \`$2'" ; shift 2 ;;
        -c|--c-long) 
            # c has an optional argument. As we are in quoted mode,
            # an empty parameter will be generated if its optional
            # argument is not found.
            case "$2" in
                "") echo "Option c, no argument"; shift 2 ;;
                *)  echo "Option c, argument \`$2'" ; shift 2 ;;
            esac ;;
        --) shift ; break ;;
        *) echo "Internal error!" ; exit 1 ;;
    esac
done
echo "Remaining arguments:"
for arg do echo '--> '"\`$arg'" ; done

How can I get the SQL of a PreparedStatement?

I implemented the following code for printing SQL from PrepareStatement

public void printSqlStatement(PreparedStatement preparedStatement, String sql) throws SQLException{
        String[] sqlArrya= new String[preparedStatement.getParameterMetaData().getParameterCount()];
        try {
               Pattern pattern = Pattern.compile("\\?");
               Matcher matcher = pattern.matcher(sql);
               StringBuffer sb = new StringBuffer();
               int indx = 1;  // Parameter begin with index 1
               while (matcher.find()) {
             matcher.appendReplacement(sb,String.valueOf(sqlArrya[indx]));
               }
               matcher.appendTail(sb);
              System.out.println("Executing Query [" + sb.toString() + "] with Database[" + "] ...");
               } catch (Exception ex) {
                   System.out.println("Executing Query [" + sql + "] with Database[" +  "] ...");
            }

    }

How do you set the Content-Type header for an HttpClient request?

I find it most simple and easy to understand in the following way:

async Task SendPostRequest()
{
    HttpClient client = new HttpClient();
    var requestContent = new StringContent(<content>);
    requestContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    var response = await client.PostAsync(<url>, requestContent);
    var responseString = await response.Content.ReadAsStringAsync();
}
...

SendPostRequest().Wait();

Excel Formula: Count cells where value is date

Here is how I was able to trick Excel to count expired certifications in a list. I didn't have a set date, or date range, just current date. "TODAY()" doesn't work in these for Excel 2013. It sees it as text or condition, not the date value. So these previous didn't work for me. So the word problem/scenario: How many people are expired in this list?

Use: =IFERROR(D5-TODAY(),0) Where D5 is the date to be interrogated.

Then use: =IF(J5>=1,1,0) Where J5 is the cell where the first equation is producing either a positive or negative number. This set, I have hidden on the side of the visible sheet, then I just sum the total for the number of unexpired members.

Explanation of the UML arrows

Aggregations and compositions are a little bit confusing. However, think like compositions are a stronger version of aggregation. What does that mean? Let's take an example: (Aggregation) 1. Take a classroom and students: In this case, we try to analyze the relationship between them. A classroom has a relationship with students. That means classroom comprises of one or many students. Even if we remove the Classroom class, the Students class does not need to destroy, which means we can use Student class independently.

(Composition) 2. Take a look at pages and Book Class. In this case, pages is a book, which means collections of pages makes the book. If we remove the book class, the whole Page class will be destroyed. That means we cannot use the class of the page independently.

If you are still unclear about this topic, watch out this short wonderful video, which has explained the aggregation more clearly.

https://www.youtube.com/watch?v=d5ecYmyFZW0

What does "collect2: error: ld returned 1 exit status" mean?

Try running task manager to determine if your program is still running.

If it is running then stop it and run it again. the [Error] ld returned 1 exit status will not come back

Select2 open dropdown on focus

For Version 3.5.4 (Aug 30, 2015 and earlier)

The current answer is only applicable to versions 3.5.4 and before, where select2 fired blur and focus events (select2-focus & select2-blur). It attaches a one-time use handler using $.one to catch the initial focus, and then reattaches it during blur for subsequent uses.

$('.select2').select2({})
  .one('select2-focus', OpenSelect2)
  .on("select2-blur", function (e) {
    $(this).one('select2-focus', OpenSelect2)
  })

function OpenSelect2() {
  var $select2 = $(this).data('select2');
  setTimeout(function() {
    if (!$select2.opened()) { $select2.open(); }
  }, 0);  
}

I tried both of @irvin-dominin-aka-edward's answers, but also ran into both problems (having to click the dropdown twice, and that Firefox throws 'event is not defined').

I did find a solution that seems to solve the two problems and haven't run into other issue yet. This is based on @irvin-dominin-aka-edward's answers by modifying the select2Focus function so that instead of executing the rest of the code right away, wrap it in setTimeout.

Demo in jsFiddle & Stack Snippets

_x000D_
_x000D_
$('.select2').select2({})_x000D_
  .one('select2-focus', OpenSelect2)_x000D_
  .on("select2-blur", function (e) {_x000D_
    $(this).one('select2-focus', OpenSelect2)_x000D_
  })_x000D_
_x000D_
function OpenSelect2() {_x000D_
  var $select2 = $(this).data('select2');_x000D_
  setTimeout(function() {_x000D_
    if (!$select2.opened()) { $select2.open(); }_x000D_
  }, 0);  _x000D_
}
_x000D_
body {_x000D_
  margin: 2em;_x000D_
}_x000D_
_x000D_
.form-control {_x000D_
  width: 200px;  _x000D_
  margin-bottom: 1em;_x000D_
  padding: 5px;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
_x000D_
select {_x000D_
  border: 1px solid #aaa;_x000D_
  border-radius: 4px;_x000D_
  height: 28px;_x000D_
}
_x000D_
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.css">_x000D_
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.js"></script>_x000D_
_x000D_
  _x000D_
  <div class="form-control">_x000D_
    <label for="foods1" >Normal</label>_x000D_
    <select id="foods1" >_x000D_
      <option value=""></option>_x000D_
      <option value="1">Apple</option>_x000D_
      <option value="2">Banana</option>_x000D_
      <option value="3">Carrot</option>_x000D_
      <option value="4">Donut</option>_x000D_
    </select>_x000D_
</div>_x000D_
_x000D_
<div class="form-control">_x000D_
  <label for="foods2" >Select2</label>_x000D_
  <select id="foods2" class="select2" >_x000D_
    <option value=""></option>_x000D_
    <option value="1">Apple</option>_x000D_
    <option value="2">Banana</option>_x000D_
      <option value="3">Carrot</option>_x000D_
      <option value="4">Donut</option>_x000D_
    </select>_x000D_
  </div>
_x000D_
_x000D_
_x000D_

Get current time in milliseconds in Python?

time.time() may only give resolution to the second, the preferred approach for milliseconds is datetime.

from datetime import datetime
dt = datetime.now()
dt.microsecond

How to make layout with View fill the remaining space?

You can use set the layout_width or layout_width to 0dp (By the orientation you want to fill remaining space). Then use the layout_weight to make it fill remaining space.

Convert hex color value ( #ffffff ) to integer value

Answer is really simple guys, in android if you want to convert hex color in to int, just use android Color class, example shown as below

this is for light gray color

Color.parseColor("#a8a8a8");

Thats it and you will get your result.

Using "If cell contains" in VBA excel

Is this what you are looking for?

 If ActiveCell.Value == "Total" Then

    ActiveCell.offset(1,0).Value = "-"

 End If

Of you could do something like this

 Dim celltxt As String
 celltxt = ActiveSheet.Range("C6").Text
 If InStr(1, celltxt, "Total") Then
    ActiveCell.offset(1,0).Value = "-"
 End If

Which is similar to what you have.

Bootstrap NavBar with left, center or right aligned items

This is a dated question but I found an alternate solution to share right from the bootstrap github page. The documentation has not been updated and there are other questions on SO asking for the same solution albeit on slightly different questions. This solution is not specific to your case but as you can see the solution is the <div class="container"> right after <nav class="navbar navbar-default navbar-fixed-top"> but can also be replaced with <div class="container-fluid" as needed.

<!DOCTYPE html>
<html>

<head>
  <title>Navbar right padding broken </title>
  <script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</head>

<body>
  <nav class="navbar navbar-default navbar-fixed-top">
    <div class="container">
      <div class="navbar-header">
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
        <a href="#/" class="navbar-brand">Hello</a>
      </div>
      <div class="collapse navbar-collapse navbar-ex1-collapse">

        <ul class="nav navbar-nav navbar-right">
          <li>
            <div class="btn-group navbar-btn" role="group" aria-label="...">
              <button type="button" class="btn btn-default" data-toggle="modal" data-target="#modalLogin">Se connecter</button>
              <button type="button" class="btn btn-default" data-toggle="modal" data-target="#modalSignin">Créer un compte</button>
            </div>
          </li>
        </ul>
      </div>
    </div>
  </nav>
</body>

</html>

The solution was found on a fiddle on this page: https://github.com/twbs/bootstrap/issues/18362

and is listed as a won't fix in V3.

Regular expression for decimal number

As I tussled with this, TryParse in 3.5 does have NumberStyles: The following code should also do the trick without Regex to ignore thousands seperator.

double.TryParse(length, NumberStyles.AllowDecimalPoint,CultureInfo.CurrentUICulture, out lengthD))

Not relevant to the original question asked but confirming that TryParse() indeed is a good option.

Email Address Validation in Android on EditText

Try this:

if (!emailRegistration.matches("[a-zA-Z0-9._-]+@[a-z]+\.[a-z]+")) {
 editTextEmail.setError("Invalid Email Address");
}

Commenting out code blocks in Atom

You can use Ctrl + /. This works for me.

How do I create sql query for searching partial matches?

First of all, this approach won't scale in the large, you'll need a separate index from words to item (like an inverted index).

If your data is not large, you can do

SELECT DISTINCT(name) FROM mytable WHERE name LIKE '%mall%' OR description LIKE '%mall%'

using OR if you have multiple keywords.

Android "Only the original thread that created a view hierarchy can touch its views."

RunOnUIThread didn't seem to work for me but the following ended up solving my issues.

            _ = MainThread.InvokeOnMainThreadAsync(async () =>
           {
               this.LoadApplication(Startup.Init(this.ConfigureServices));

               var authenticationService = App.ServiceProvider.GetService<AuthenticationService>();
               if (authenticationService.AuthenticationResult == null)
               {
                   await authenticationService.AuthenticateAsync(AuthenticationUserFlow.SignUpSignIn, CrossCurrentActivity.Current.Activity).ConfigureAwait(false);
               }
           });

Within the Startup.Init method there is ReactiveUI routing and this needs to be invoked on the main thread. This Invoke method also accepts async/await better than RunOnUIThread.

So anywhere I need to invoke methods on the mainthread I use this.

Please comment on this if anyone knows something I don't and can help me improve my application.

Using Lato fonts in my css (@font-face)

Well, you're missing the letter 'd' in url("~/fonts/Lato-Bol.ttf"); - but assuming that's not it, I would open up your page with developer tools in Chrome and make sure there's no errors loading any of the files (you would probably see an issue in the JavaScript console, or you can check the Network tab and see if anything is red).

(I don't see anything obviously wrong with the code you have posted above)

Other things to check: 1) Are you including your CSS file in your html above the lines where you are trying to use the font-family style? 2) What do you see in the CSS panel in the developer tools for that div? Is font-family: lato crossed out?

How do you clone a Git repository into a specific folder?

If you are in the directory you want the contents of the git repository dumped to, run:

git clone [email protected]:origin .

The "." at the end specifies the current folder as the checkout folder.

jQuery AJAX cross domain

I had to load webpage from local disk "file:///C:/test/htmlpage.html", call "http://localhost/getxml.php" url, and do this in IE8+ and Firefox12+ browsers, use jQuery v1.7.2 lib to minimize boilerplate code. After reading dozens of articles finally figured it out. Here is my summary.

  • server script (.php, .jsp, ...) must return http response header Access-Control-Allow-Origin: *
  • before using jQuery ajax set this flag in javascript: jQuery.support.cors = true;
  • you may set flag once or everytime before using jQuery ajax function
  • now I can read .xml document in IE and Firefox. Other browsers I did not test.
  • response document can be plain/text, xml, json or anything else

Here is an example jQuery ajax call with some debug sysouts.

jQuery.support.cors = true;
$.ajax({
    url: "http://localhost/getxml.php",
    data: { "id":"doc1", "rows":"100" },
    type: "GET",
    timeout: 30000,
    dataType: "text", // "xml", "json"
    success: function(data) {
        // show text reply as-is (debug)
        alert(data);

        // show xml field values (debug)
        //alert( $(data).find("title").text() );

        // loop JSON array (debug)
        //var str="";
        //$.each(data.items, function(i,item) {
        //  str += item.title + "\n";
        //});
        //alert(str);
    },
    error: function(jqXHR, textStatus, ex) {
        alert(textStatus + "," + ex + "," + jqXHR.responseText);
    }
});

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

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

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

Salt and hash a password in Python

Here's my proposition:

for i in range(len(rserver.keys())):
    salt = uuid.uuid4().hex
    print(salt)
    mdp_hash = rserver.get(rserver.keys()[i])
    rserver.set(rserver.keys()[i], hashlib.sha256(salt.encode() + mdp_hash.encode()).hexdigest() + salt)
    rsalt.set(rserver.keys()[i], salt)

Extract a substring from a string in Ruby using a regular expression

"<name> <substring>"[/.*<([^>]*)/,1]
=> "substring"

No need to use scan, if we need only one result.
No need to use Python's match, when we have Ruby's String[regexp,#].

See: http://ruby-doc.org/core/String.html#method-i-5B-5D

Note: str[regexp, capture] ? new_str or nil

Getting the base url of the website and globally passing it to twig in Symfony 2

 <base href="{{ app.request.getSchemeAndHttpHost() }}"/>

or from controller

$this->container->get('router')->getContext()->getSchemeAndHttpHost()

HTTP Status 405 - Method Not Allowed Error for Rest API

In above code variable "ver" is assign to null, print "ver" before returning and see the value. As this "ver" having null service is send status as "204 No Content".

And about status code "405 - Method Not Allowed" will get this status code when rest controller or service only supporting GET method but from client side your trying with POST with valid uri request, during such scenario get status as "405 - Method Not Allowed"

Clicking HTML 5 Video element to play, pause video, breaks play button

Adding return false; worked for me:

jQuery version:

$(document).on('click', '#video-id', function (e) {
    var video = $(this).get(0);
    if (video.paused === false) {
        video.pause();
    } else {
        video.play();
    }

    return false;
});

Vanilla JavaScript version:

var v = document.getElementById('videoid');
v.addEventListener(
    'play', 
    function() { 
        v.play();
    }, 
    false);

v.onclick = function() {
    if (v.paused) {
        v.play();
    } else {
        v.pause();
    }

    return false;
};

Can I pass an array as arguments to a method with variable arguments in Java?

It's ok to pass an array - in fact it amounts to the same thing

String.format("%s %s", "hello", "world!");

is the same as

String.format("%s %s", new Object[] { "hello", "world!"});

It's just syntactic sugar - the compiler converts the first one into the second, since the underlying method is expecting an array for the vararg parameter.

See

how can I login anonymously with ftp (/usr/bin/ftp)?

Anonymous FTP usage is covered by RFC 1635: How to Use Anonymous FTP:

What is Anonymous FTP?

Anonymous FTP is a means by which archive sites allow general access to their archives of information. These sites create a special account called "anonymous".

Traditionally, this special anonymous user account accepts any string as a password, although it is common to use either the password "guest" or one's electronic mail (e-mail) address. Some archive sites now explicitly ask for the user's e-mail address and will not allow login with the "guest" password. Providing an e-mail address is a courtesy that allows archive site operators to get some idea of who is using their services.

These are general recommendations, though. Each FTP server may have its own guidelines.

For sample use of the ftp command on anonymous FTP access, see appendix A:

atlas.arc.nasa.gov% ftp naic.nasa.gov
Connected to naic.nasa.gov.
220 naic.nasa.gov FTP server (Wed May 4 12:15:15 PDT 1994) ready.
Name (naic.nasa.gov:amarine): anonymous
331 Guest login ok, send your complete e-mail address as password.
Password:
230-----------------------------------------------------------------
230-Welcome to the NASA Network Applications and Info Center Archive
230-
230-     Access to NAIC's online services is also available through:
230-
230-        Gopher         - naic.nasa.gov (port 70)
230-    World-Wide-Web - http://naic.nasa.gov/naic/naic-home.html
230-
230-        If you experience any problems please send email to
230-
230-                    [email protected]
230-
230-                 or call +1 (800) 858-9947
230-----------------------------------------------------------------
230-
230-Please read the file README
230-  it was last modified on Fri Dec 10 13:06:33 1993 - 165 days ago
230 Guest login ok, access restrictions apply.
ftp> cd files/rfc
250-Please read the file README.rfc
250-  it was last modified on Fri Jul 30 16:47:29 1993 - 298 days ago
250 CWD command successful.
ftp> get rfc959.txt
200 PORT command successful.
150 Opening ASCII mode data connection for rfc959.txt (147316 bytes).
226 Transfer complete.
local: rfc959.txt remote: rfc959.txt
151249 bytes received in 0.9 seconds (1.6e+02 Kbytes/s)
ftp> quit
221 Goodbye.
atlas.arc.nasa.gov%

See also the example session at the University of Edinburgh site.

Random state (Pseudo-random number) in Scikit learn

If there is no randomstate provided the system will use a randomstate that is generated internally. So, when you run the program multiple times you might see different train/test data points and the behavior will be unpredictable. In case, you have an issue with your model you will not be able to recreate it as you do not know the random number that was generated when you ran the program.

If you see the Tree Classifiers - either DT or RF, they try to build a try using an optimal plan. Though most of the times this plan might be the same there could be instances where the tree might be different and so the predictions. When you try to debug your model you may not be able to recreate the same instance for which a Tree was built. So, to avoid all this hassle we use a random_state while building a DecisionTreeClassifier or RandomForestClassifier.

PS: You can go a bit in depth on how the Tree is built in DecisionTree to understand this better.

randomstate is basically used for reproducing your problem the same every time it is run. If you do not use a randomstate in traintestsplit, every time you make the split you might get a different set of train and test data points and will not help you in debugging in case you get an issue.

From Doc:

If int, randomstate is the seed used by the random number generator; If RandomState instance, randomstate is the random number generator; If None, the random number generator is the RandomState instance used by np.random.

How to parse a query string into a NameValueCollection in .NET

Hit up Request.QueryString.Keys for a NameValueCollection of all query string parameters.

Interesting 'takes exactly 1 argument (2 given)' Python error

Yes, when you invoke e.extractAll(foo), Python munges that into extractAll(e, foo).

From http://docs.python.org/tutorial/classes.html

the special thing about methods is that the object is passed as the first argument of the function. In our example, the call x.f() is exactly equivalent to MyClass.f(x). In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s object before the first argument.

Emphasis added.

ByRef argument type mismatch in Excel VBA

While looping through your string one character at a time is a viable method, there's no need. VBA has built-in functions for this kind of thing:

Public Function ProcessString(input_string As String) As String
    ProcessString=Replace(input_string,"*","")
End Function

Why when I transfer a file through SFTP, it takes longer than FTP?

Yes, encryption add some load to your cpu, but if your cpu is not ancient that should not affect as much as you say.

If you enable compression for SSH, SCP is actually faster than FTP despite the SSH encryption (if I remember, twice as fast as FTP for the files I tried). I haven't actually used SFTP, but I believe it uses SCP for the actual file transfer. So please try this and let us know :-)

How to get size of mysql database?

It can be determined by using following MySQL command

SELECT table_schema AS "Database", SUM(data_length + index_length) / 1024 / 1024 AS "Size (MB)" FROM information_schema.TABLES GROUP BY table_schema

Result

Database    Size (MB)
db1         11.75678253
db2         9.53125000
test        50.78547382

Get result in GB

SELECT table_schema AS "Database", SUM(data_length + index_length) / 1024 / 1024 / 1024 AS "Size (GB)" FROM information_schema.TABLES GROUP BY table_schema

How do I use an image as a submit button?

<form id='formName' name='formName' onsubmit='redirect();return false;'>
        <div class="style7">
    <input type='text' id='userInput' name='userInput' value=''>
    <img src="BUTTON1.JPG" onclick="document.forms['formName'].submit();">
</div>
</form>

Building and running app via Gradle and Android Studio is slower than via Eclipse

You could make the process faster, if you use gradle from command line. There is a lot of optimization to do for the IDE developers. But it is just an early version.

For more information read this discussion on g+ with some of the devs.

Update Item to Revision vs Revert to Revision

To understand how the state of your working copy is different in both scenarios, you must understand the concept of the BASE revision:

BASE

The revision number of an item in a working copy. If the item has been locally modified, this refers to the way the item appears without those local modifications.

Your working copy contains a snapshot of each file (hidden in a .svn folder) in this BASE revision, meaning as it was when last retrieved from the repository. This explains why working copies take 2x the space and how it is possible that you can examine and even revert local modifications without a network connection.

Update item to Revision changes this base revision, making BASE out of date. When you try to commit local modifications, SVN will notice that your BASE does not match the repository HEAD. The commit will be refused until you do an update (and possibly a merge) to fix this.

Revert to revision does not change BASE. It is conceptually almost the same as manually editing the file to match an earlier revision.

How do I loop through items in a list box and then remove those item?

You have to go through the collection from the last item to the first. this code is in vb

for i as integer= list.items.count-1 to 0 step -1
....
list.items.removeat(i)
next

running multiple bash commands with subprocess

>>> command = "echo a; echo b"
>>> shlex.split(command);
    ['echo', 'a; echo', 'b']

so, the problem is shlex module do not handle ";"

How to deal with floating point number precision in JavaScript?

You are right, the reason for that is limited precision of floating point numbers. Store your rational numbers as a division of two integer numbers and in most situations you'll be able to store numbers without any precision loss. When it comes to printing, you may want to display the result as fraction. With representation I proposed, it becomes trivial.

Of course that won't help much with irrational numbers. But you may want to optimize your computations in the way they will cause the least problem (e.g. detecting situations like sqrt(3)^2).

Django: How can I call a view function from template?

For deleting all data:

HTML FILE

  class="btn btn-primary" href="{% url 'delete_product'%}">Delete

Put the above code in an anchor tag. (the a tag!)

url.py

path('delete_product', views.delete_product, name='delete_product')]

views.py

def delete_product(request):
    if request.method == "GET":
        dest = Racket.objects.all()
        dest.delete()
        return render(request, "admin_page.html")

What is object serialization?

Daring to answer the 6-year-old question, adding just a very high-level understanding for people new to Java

What is Serialization?

Converting an object to bytes

What is Deserialization?

Converting bytes back to an object (Deserialization).

When is serialization used?

When we want to Persist the Object. When we want the object to exist beyond the lifetime of the JVM.

Real World Example:

ATM: When the account holder tries to withdraw money from the server through ATM, the account holder information like withdrawal details will be serialized and sent to the server where the details are deserialized and used to perform operations.

How serialization is performed in java.

  1. Implement java.io.Serializable interface (marker interface so no method to implement).

  2. Persist the object: Use java.io.ObjectOutputStream class, a filter stream which is a wrapper around a lower-level byte stream (to write Object to file systems or transfer a flattened object across a network wire and rebuilt on the other side).

    • writeObject(<<instance>>) - to write an object
    • readObject() - to read an serialized Object

Remember:

When you serialize an object, only the object's state will be saved, not the object's class file or methods.

When you serialized a 2-byte object, you see 51 bytes serialized file.

Steps how the object is serialized and de-serialized.

Answer for: How did it convert to 51 bytes file?

  • First writes the serialization stream magic data (STREAM_MAGIC= "AC ED" and STREAM_VERSION=version of the JVM).
  • Then it writes out the metadata of the class associated with an instance (length of the class, the name of the class, serialVersionUID).
  • Then it recursively writes out the metadata of the superclass until it finds java.lang.Object.
  • Then starts with the actual data associated with the instance.
  • Finally writes the data of objects associated with the instance starting from metadata to the actual content.

If you are interested in more in-depth information about Java Serialization please check this link.

Edit : One more good link to read.

This will answer a few frequent questions:

  1. How not to serialize any field in class.
    Ans: use transient keyword

  2. When child class is serialized does parent class get serialized?
    Ans: No, If a parent is not extending the Serializable interface parents field don't get serialized.

  3. When a parent is serialized does child class get serialized?
    Ans: Yes, by default child class also gets serialized.

  4. How to avoid child class from getting serialized?
    Ans: a. Override writeObject and readObject method and throw NotSerializableException.

    b. also you can mark all fields transient in child class.

  5. Some system-level classes such as Thread, OutputStream, and its subclasses, and Socket are not serializable.

Bash script to calculate time elapsed

You are trying to execute the number in the ENDTIME as a command. You should also see an error like 1370306857: command not found. Instead use the arithmetic expansion:

echo "It takes $(($ENDTIME - $STARTTIME)) seconds to complete this task..."

You could also save the commands in a separate script, commands.sh, and use time command:

time commands.sh

How to insert data using wpdb

Just use wpdb->insert(tablename, coloumn, format) and wp will prepare that's query

<?php
global $wpdb;
$wpdb->insert("wp_submitted_form", array(
   "name" => $name,
   "email" => $email,
   "phone" => $phone,
   "country" => $country,
   "course" => $course,
   "message" => $message,
   "datesent" => $now ,
));
?>

Extracting jar to specified directory

This is what I ended up using inside my .bat file. Windows only of course.

set CURRENT_DIR=%cd%
mkdir ./directoryToExtractTo
cd ./directoryToExtractTo
jar xvf %CURRENT_DIR%\myJar.jar
cd %CURRENT_DIR%

How to make a JSONP request from Javascript without JQuery?

/**
 * Get JSONP data for cross-domain AJAX requests
 * @private
 * @link http://cameronspear.com/blog/exactly-what-is-jsonp/
 * @param  {String} url      The URL of the JSON request
 * @param  {String} callback The name of the callback to run on load
 */
var loadJSONP = function ( url, callback ) {

    // Create script with url and callback (if specified)
    var ref = window.document.getElementsByTagName( 'script' )[ 0 ];
    var script = window.document.createElement( 'script' );
    script.src = url + (url.indexOf( '?' ) + 1 ? '&' : '?') + 'callback=' + callback;

    // Insert script tag into the DOM (append to <head>)
    ref.parentNode.insertBefore( script, ref );

    // After the script is loaded (and executed), remove it
    script.onload = function () {
        this.remove();
    };

};

/** 
 * Example
 */

// Function to run on success
var logAPI = function ( data ) {
    console.log( data );
}

// Run request
loadJSONP( 'http://api.petfinder.com/shelter.getPets?format=json&key=12345&shelter=AA11', 'logAPI' );

How to define object in array in Mongoose schema correctly with 2d geo index

You can declare trk by the following ways : - either

trk : [{
    lat : String,
    lng : String
     }]

or

trk : { type : Array , "default" : [] }

In the second case during insertion make the object and push it into the array like

db.update({'Searching criteria goes here'},
{
 $push : {
    trk :  {
             "lat": 50.3293714,
             "lng": 6.9389939
           } //inserted data is the object to be inserted 
  }
});

or you can set the Array of object by

db.update ({'seraching criteria goes here ' },
{
 $set : {
          trk : [ {
                     "lat": 50.3293714,
                     "lng": 6.9389939
                  },
                  {
                     "lat": 50.3293284,
                     "lng": 6.9389634
                  }
               ]//'inserted Array containing the list of object'
      }
});

Display Back Arrow on Toolbar

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setNavigationIcon(R.drawable.back_arrow); // your drawable
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed(); // Implemented by activity
        }
    });

And for API 21+ android:navigationIcon

<android.support.v7.widget.Toolbar
    android:navigationIcon="@drawable/back_arrow"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"/>

How can I disable selected attribute from select2() dropdown Jquery?

To disable the complete select2 box, that is no deletion of already selected values and no new insertion, use:

$("id-select2").prop("disabled", true);

where id-select2 is the unique id of select2. you can also use any particular class if defined to address the dropdown.

"Large data" workflows using pandas

It is worth mentioning here Ray as well,
it's a distributed computation framework, that has it's own implementation for pandas in a distributed way.

Just replace the pandas import, and the code should work as is:

# import pandas as pd
import ray.dataframe as pd

#use pd as usual

can read more details here:

https://rise.cs.berkeley.edu/blog/pandas-on-ray/

How to use ArgumentCaptor for stubbing?

Assuming the following method to test:

public boolean doSomething(SomeClass arg);

Mockito documentation says that you should not use captor in this way:

when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);
assertThat(argumentCaptor.getValue(), equalTo(expected));

Because you can just use matcher during stubbing:

when(someObject.doSomething(eq(expected))).thenReturn(true);

But verification is a different story. If your test needs to ensure that this method was called with a specific argument, use ArgumentCaptor and this is the case for which it is designed:

ArgumentCaptor<SomeClass> argumentCaptor = ArgumentCaptor.forClass(SomeClass.class);
verify(someObject).doSomething(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), equalTo(expected));

How to check if a process id (PID) exists

I think that is a bad solution, that opens up for race conditions. What if the process dies between your test and your call to kill? Then kill will fail. So why not just try the kill in all cases, and check its return value to find out how it went?

How to make an embedded video not autoplay

fenomas's answer was really good...it got me off of looking into the HTML code. I know that jb was looking for something that works in Captivate, but the question is broad enough to include people working out of Flash (I'm using CS5), so I thought I'd throw in the specific answer to my situation here.

If you're using the stock Adobe FLVPlayback component in Flash (you probably are if you used File > Import > Import Video...), there's an option in the Properties panel, under Component Parameters. Look for 'autoPlay' and uncheck it. That'll stop autoplay when the page loads!

Linux: Which process is causing "device busy" when doing umount?

Just in case... sometimes happens that you are calling umount from the terminal, and your current directory belongs to the mounted filesystem.

Oracle query to fetch column names

On Several occasions, we would need comma separated list of all the columns from a table in a schema. In such cases we can use this generic function which fetches the comma separated list as a string.

CREATE OR REPLACE FUNCTION cols(
    p_schema_name IN VARCHAR2,
    p_table_name  IN VARCHAR2)
  RETURN VARCHAR2
IS
  v_string VARCHAR2(4000);
BEGIN
  SELECT LISTAGG(COLUMN_NAME , ',' ) WITHIN GROUP (
  ORDER BY ROWNUM )
  INTO v_string
  FROM ALL_TAB_COLUMNS
  WHERE OWNER    = p_schema_name
  AND table_name = p_table_name;
  RETURN v_string;
END;
/

So, simply calling the function from the query yields a row with all the columns.

select cols('HR','EMPLOYEES') FROM DUAL;

EMPLOYEE_ID,FIRST_NAME,LAST_NAME,EMAIL,PHONE_NUMBER,HIRE_DATE,JOB_ID,SALARY,COMMISSION_PCT,MANAGER_ID,DEPARTMENT_ID

Note: LISTAGG will fail if the combined length of all columns exceed 4000 characters which is rare. For most cases , this will work.

How do I get rid of an element's offset using CSS?

I had the same issue on our .NET based website, running on DotNetNuke (DNN) and what solved it for me was basically a simple margin reset of the form tag. .NET based websites are often wrapped in a form and without resetting the margin you can see the strange offset appearing sometimes, mostly when there are some scripts included.

So if you are trying to fix this issue on your site, try enter this into your CSS file:

form {
  margin: 0;
}

How to use Scanner to accept only valid int as input

  1. the condition num2 < num1 should be num2 <= num1 if num2 has to be greater than num1
  2. not knowing what the kb object is, I'd read a String and then trying Integer.parseInt() and if you don't catch an exception then it's a number, if you do, read a new one, maybe by setting num2 to Integer.MIN_VALUE and using the same type of logic in your example.

Android Studio how to run gradle sync manually?

I have a trouble may proof gradlew clean is not equal to ADT build clean. And Now I am struggling to get it fixed.

Here is what I got: I set a configProductID=11111 from my gradle.properties, from my build.gradle, I add

resValue "string", "ProductID", configProductID

If I do a build clean from ADT, the resource R.string.ProductID can be generated. Then I can do bellow command successfully.

gradlew assembleDebug

But, as I am trying to setup build server, I don't want help from ADT IDE, so I need to avoid using ADT build clean. Here comes my problem. Now I change my resource name from "ProductID" to "myProductID", I do:

gradlew clean

I get error

PS D:\work\wctposdemo> .\gradlew.bat clean

FAILURE: Build failed with an exception.

* Where:
Build file 'D:\work\wctposdemo\app\build.gradle'

* What went wrong:
Could not compile build file 'D:\work\wctposdemo\app\build.gradle'.
> startup failed:
  General error during semantic analysis: Unsupported class file major version 57

If I try with:

.\gradlew.bat --recompile-scripts

I just get error of

Unknown command-line option '--recompile-scripts'.

.c vs .cc vs. .cpp vs .hpp vs .h vs .cxx

Those extensions aren't really new, they are old. :-)

When C++ was new, some people wanted to have a .c++ extension for the source files, but that didn't work on most file systems. So they tried something close to that, like .cxx, or .cpp instead.

Others thought about the language name, and "incrementing" .c to get .cc or even .C in some cases. Didn't catch on that much.

Some believed that if the source is .cpp, the headers ought to be .hpp to match. Moderately successful.

Case-Insensitive List Search

I had a similar problem, I needed the index of the item but it had to be case insensitive, i looked around the web for a few minutes and found nothing, so I just wrote a small method to get it done, here is what I did:

private static int getCaseInvariantIndex(List<string> ItemsList, string searchItem)
{
    List<string> lowercaselist = new List<string>();

    foreach (string item in ItemsList)
    {
        lowercaselist.Add(item.ToLower());
    }

    return lowercaselist.IndexOf(searchItem.ToLower());
}

Add this code to the same file, and call it like this:

int index = getCaseInvariantIndexFromList(ListOfItems, itemToFind);

Hope this helps, good luck!

PHP preg_replace special characters

do this in two steps:

  1. replace not letter characters with this regex:

    [\/\&%#\$]

  2. replace quotes with this regex:

    [\"\']

and use preg_replace:

$stringWithoutNonLetterCharacters = preg_replace("/[\/\&%#\$]/", "_", $yourString);
$stringWithQuotesReplacedWithSpaces = preg_replace("/[\"\']/", " ", $stringWithoutNonLetterCharacters);

View a file in a different Git branch without changing branches

Add the following to your ~/.gitconfig file

[alias]
  cat = "!git show \"$1:$2\" #"

And then try this

git cat BRANCHNAME FILEPATH

Personally I prefer separate parameters without a colon. Why? This choice mirrors the parameters of the checkout command, which I tend to use rather frequently and I find it thus much easier to remember than the bizarro colon-separated parameter of the show command.

Delaying a jquery script until everything else has loaded

From here:

// Add jQuery 
var GM_JQ = document.createElement('script'); 
GM_JQ.src = 'http://jquery.com/src/jquery-latest.js';
GM_JQ.type = 'text/javascript'; 
document.getElementsByTagName('head')[0].appendChild(GM_JQ); 

// Check if jQuery's loaded 
function GM_wait() 
{ 
    if(typeof unsafeWindow.jQuery == 'undefined') 
    { 
        window.setTimeout(GM_wait,100); 
    } 
    else 
    { 
        $ = unsafeWindow.jQuery; 
        letsJQuery(); 
    } 
} 

GM_wait(); 

// All your GM code must be inside this function 
function letsJQuery() 
{
    // Do your jQuery stuff in here    
} 

This will wait until jQuery is loaded to use it, but you can use the same concept, setting variables in your other scripts (or checking them if they're not your script) to wait until they're loaded to use them.

For example, on my site, I use this for asynchronous JS loading and waiting until they're finished before doing anything with them using jQuery:

<script type="text/javascript" language="JavaScript"> 
    function js(url){
        s = document.createElement("script");
        s.type = "text/javascript";
        s.src = url;
        document.getElementsByTagName("head")[0].appendChild(s);
    }       

    js("/js/jquery-ui.js");
    js("/js/jrails.js");
    js("/js/jquery.jgrowl-min.js");
    js("/js/jquery.scrollTo-min.js");
    js("/js/jquery.corner-min.js");
    js("/js/jquery.cookie-min.js");
    js("/js/application-min.js");

    function JS_wait() {
        if (typeof $.cookie == 'undefined' || // set in jquery.cookie-min.js
            typeof getLastViewedAnchor == 'undefined' || // set in application-min.js
            typeof getLastViewedArchive == 'undefined' || // set in application-min.js 
            typeof getAntiSpamValue == 'undefined') // set in application-min.js
        { 
            window.setTimeout(JS_wait, 100); 
        }
        else 
        { 
            JS_ready(); 
        }
    }

    function JS_ready() {
        // snipped
    };

    $(document).ready(JS_wait);
</script> 

How to use background thread in swift?

You have to separate out the changes that you want to run in the background from the updates you want to run on the UI:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
    // do your task

    dispatch_async(dispatch_get_main_queue()) {
        // update some UI
    }
}

Custom CSS for <audio> tag?

There is not currently any way to style HTML5 <audio> players using CSS. Instead, you can leave off the control attribute, and implement your own controls using Javascript. If you don't want to implement them all on your own, I'd recommend using an existing themeable HTML5 audio player, such as jPlayer.

How to search for an element in an stl list?

No, not directly in the std::list template itself. You can however use std::find algorithm like that:

std::list<int> my_list;
//...
int some_value = 12;
std::list<int>::iterator iter = std::find (my_list.begin(), my_list.end(), some_value);
// now variable iter either represents valid iterator pointing to the found element,
// or it will be equal to my_list.end()

Fastest way to copy a file in Node.js

This is a good way to copy a file in one line of code using streams:

var fs = require('fs');
fs.createReadStream('test.log').pipe(fs.createWriteStream('newLog.log'));

In Node.js v8.5.0, copyFile was added.

const fs = require('fs');

// File destination.txt will be created or overwritten by default.
fs.copyFile('source.txt', 'destination.txt', (err) => {
  if (err) throw err;
  console.log('source.txt was copied to destination.txt');
});

How to compare type of an object in Python?

For other types, check out the types module:

>>> import types
>>> x = "mystring"
>>> isinstance(x, types.StringType)
True
>>> x = 5
>>> isinstance(x, types.IntType)
True
>>> x = None
>>> isinstance(x, types.NoneType)
True

P.S. Typechecking is a bad idea.

How to change PHP version used by composer

I found out that composer runs with the php-version /usr/bin/env finds first in $PATH, which is 7.1.33 in my case on MacOs. So shifting mamp's php to the beginning helped me here.

PHPVER=$(/usr/libexec/PlistBuddy -c "print phpVersion" ~/Library/Preferences/de.appsolute.mamppro.plist)

export PATH=/Applications/MAMP/bin/php/php${PHPVER}/bin:$PATH

What's wrong with nullable columns in composite primary keys?

NULL == NULL -> false (at least in DBMSs)

So you wouldn't be able to retrieve any relationships using a NULL value even with additional columns with real values.

Use PHP to create, edit and delete crontab jobs?

We recently prepared a mini project (PHP>=5.3) to manage the cron files for private and individual tasks. This tool connects and manages the cron files so you can use them, for example per project. Unit Tests available :-)

Sample from command line:

bin/cronman --enable /var/www/myproject/.cronfile --user www-data

Sample from API:

use php\manager\crontab\CrontabManager;

$crontab = new CrontabManager();
$crontab->enableOrUpdate('/tmp/my/crontab.txt');
$crontab->save();

Managing individual tasks from API:

use php\manager\crontab\CrontabManager;

$crontab = new CrontabManager();
$job = $crontab->newJob();
$job->on('* * * * *');
$job->onMinute('20-30')->doJob("echo foo");
$crontab->add($job);
$job->onMinute('35-40')->doJob("echo bar");
$crontab->add($job);
$crontab->save();

github: php-crontab-manager

Date format in dd/MM/yyyy hh:mm:ss

SELECT CONVERT(CHAR(10),GETDATE(),103) + ' ' + RIGHT(CONVERT(CHAR(26),GETDATE(),109),14)

maven error: package org.junit does not exist

Ok, you've declared junit dependency for test classes only (those that are in src/test/java but you're trying to use it in main classes (those that are in src/main/java).

Either do not use it in main classes, or remove <scope>test</scope>.

Why is my asynchronous function returning Promise { <pending> } instead of a value?

The then method returns a pending promise which can be resolved asynchronously by the return value of a result handler registered in the call to then, or rejected by throwing an error inside the handler called.

So calling AuthUser will not suddenly log the user in synchronously, but returns a promise whose then registered handlers will be called after the login succeeds ( or fails). I would suggest triggering all login processing by a then clause of the login promise. E.G. using named functions to highlight the sequence of flow:

let AuthUser = data => {   // just the login promise
  return google.login(data.username, data.password);
};

AuthUser(data).then( processLogin).catch(loginFail);

function processLogin( token) {
      // do logged in stuff:
      // enable, initiate, or do things after login
}
function loginFail( err) {
      console.log("login failed: " + err);
}

Notify ObservableCollection when Item changes

One simple solution to this is to replace the item being changed in the ObservableCollection which notifies the collection of the changed item. In the sample code snippet below Artists is the ObservableCollection and artist is an item of the type in the ObservableCollection:

    var index = Artists.IndexOf(artist);
    Artists.RemoveAt(index);
    artist.IsFollowed = true; // change something in the item
    Artists.Insert(index, artist);

How to convert a Datetime string to a current culture datetime string

DateTime dateValue;
CultureInfo culture = CultureInfo.CurrentCulture;
DateTimeStyles styles = DateTimeStyles.None;
DateTime.TryParse(datetimestring,culture, styles, out dateValue);

Using Gradle to build a jar with dependencies

Simple sulution

jar {
    manifest {
        attributes 'Main-Class': 'cova2.Main'
    } 
    doFirst {
        from { configurations.runtime.collect { it.isDirectory() ? it : zipTree(it) } }
    }
}

In Git, what is the difference between origin/master vs origin master?

origin is a name for remote git url. There can be many more remotes example below.

bangalore => bangalore.example.com:project.git

boston => boston.example.com:project.git

as far as origin/master (example bangalore/master) goes, it is pointer to "master" commit on bangalore site . You see it in your clone.

It is possible that remote bangalore has advanced since you have done "fetch" or "pull"

Update one MySQL table with values from another

It depends what is a use of those tables, but you might consider putting trigger on original table on insert and update. When insert or update is done, update the second table based on only one item from the original table. It will be quicker.

How to get the height of a body element

Simply use

$(document).height() // - $('body').offset().top

and / or

$(window).height()

instead of $('body').height();

iOS 10: "[App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction"

in your Xcode:

  • Click on your active scheme name right next to the Stop button
  • Click on Edit Scheme....
  • in Run (Debug) select the Arguments tab
  • in Environment Variables click +
  • add variable: OS_ACTIVITY_MODE = disable

screenshot

how to apply click event listener to image in android

ImageView img = (ImageView) findViewById(R.id.myImageId);
img.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
       // your code here
    }
});

combining two string variables

you need to take out the quotes:

soda = a + b

(You want to refer to the variables a and b, not the strings "a" and "b")

How to check if an alert exists using WebDriver?

I would suggest to use ExpectedConditions and alertIsPresent(). ExpectedConditions is a wrapper class that implements useful conditions defined in ExpectedCondition interface.

public boolean isAlertPresent(){
    boolean foundAlert = false;
    WebDriverWait wait = new WebDriverWait(driver, 0 /*timeout in seconds*/);
    try {
        wait.until(ExpectedConditions.alertIsPresent());
        foundAlert = true;
    } catch (TimeoutException eTO) {
        foundAlert = false;
    }
    return foundAlert;
}

Note: this is based on the answer by nilesh, but adapted to catch the TimeoutException which is thrown by the wait.until() method.

Is it possible to set a number to NaN or infinity?

Is it possible to set a number to NaN or infinity?

Yes, in fact there are several ways. A few work without any imports, while others require import, however for this answer I'll limit the libraries in the overview to standard-library and NumPy (which isn't standard-library but a very common third-party library).

The following table summarizes the ways how one can create a not-a-number or a positive or negative infinity float:

+-------------------------------------------------------------------+
¦   result ¦ NaN          ¦ Infinity           ¦ -Infinity          ¦
¦ module   ¦              ¦                    ¦                    ¦
¦----------+--------------+--------------------+--------------------¦
¦ built-in ¦ float("nan") ¦ float("inf")       ¦ -float("inf")      ¦
¦          ¦              ¦ float("infinity")  ¦ -float("infinity") ¦
¦          ¦              ¦ float("+inf")      ¦ float("-inf")      ¦
¦          ¦              ¦ float("+infinity") ¦ float("-infinity") ¦
+----------+--------------+--------------------+--------------------¦
¦ math     ¦ math.nan     ¦ math.inf           ¦ -math.inf          ¦
+----------+--------------+--------------------+--------------------¦
¦ cmath    ¦ cmath.nan    ¦ cmath.inf          ¦ -cmath.inf         ¦
+----------+--------------+--------------------+--------------------¦
¦ numpy    ¦ numpy.nan    ¦ numpy.PINF         ¦ numpy.NINF         ¦
¦          ¦ numpy.NaN    ¦ numpy.inf          ¦ -numpy.inf         ¦
¦          ¦ numpy.NAN    ¦ numpy.infty        ¦ -numpy.infty       ¦
¦          ¦              ¦ numpy.Inf          ¦ -numpy.Inf         ¦
¦          ¦              ¦ numpy.Infinity     ¦ -numpy.Infinity    ¦
+-------------------------------------------------------------------+

A couple remarks to the table:

  • The float constructor is actually case-insensitive, so you can also use float("NaN") or float("InFiNiTy").
  • The cmath and numpy constants return plain Python float objects.
  • The numpy.NINF is actually the only constant I know of that doesn't require the -.
  • It is possible to create complex NaN and Infinity with complex and cmath:

    +------------------------------------------------------------------------------------------+
    ¦   result ¦ NaN+0j         ¦ 0+NaNj          ¦ Inf+0j              ¦ 0+Infj               ¦
    ¦ module   ¦                ¦                 ¦                     ¦                      ¦
    ¦----------+----------------+-----------------+---------------------+----------------------¦
    ¦ built-in ¦ complex("nan") ¦ complex("nanj") ¦ complex("inf")      ¦ complex("infj")      ¦
    ¦          ¦                ¦                 ¦ complex("infinity") ¦ complex("infinityj") ¦
    +----------+----------------+-----------------+---------------------+----------------------¦
    ¦ cmath    ¦ cmath.nan ¹    ¦ cmath.nanj      ¦ cmath.inf ¹         ¦ cmath.infj           ¦
    +------------------------------------------------------------------------------------------+
    

    The options with ¹ return a plain float, not a complex.

is there any function to check whether a number is infinity or not?

Yes there is - in fact there are several functions for NaN, Infinity, and neither Nan nor Inf. However these predefined functions are not built-in, they always require an import:

+--------------------------------------------------------------+
¦      for ¦ NaN         ¦ Infinity or    ¦ not NaN and        ¦
¦          ¦             ¦ -Infinity      ¦ not Infinity and   ¦
¦ module   ¦             ¦                ¦ not -Infinity      ¦
¦----------+-------------+----------------+--------------------¦
¦ math     ¦ math.isnan  ¦ math.isinf     ¦ math.isfinite      ¦
+----------+-------------+----------------+--------------------¦
¦ cmath    ¦ cmath.isnan ¦ cmath.isinf    ¦ cmath.isfinite     ¦
+----------+-------------+----------------+--------------------¦
¦ numpy    ¦ numpy.isnan ¦ numpy.isinf    ¦ numpy.isfinite     ¦
+--------------------------------------------------------------+

Again a couple of remarks:

  • The cmath and numpy functions also work for complex objects, they will check if either real or imaginary part is NaN or Infinity.
  • The numpy functions also work for numpy arrays and everything that can be converted to one (like lists, tuple, etc.)
  • There are also functions that explicitly check for positive and negative infinity in NumPy: numpy.isposinf and numpy.isneginf.
  • Pandas offers two additional functions to check for NaN: pandas.isna and pandas.isnull (but not only NaN, it matches also None and NaT)
  • Even though there are no built-in functions, it would be easy to create them yourself (I neglected type checking and documentation here):

    def isnan(value):
        return value != value  # NaN is not equal to anything, not even itself
    
    infinity = float("infinity")
    
    def isinf(value):
        return abs(value) == infinity 
    
    def isfinite(value):
        return not (isnan(value) or isinf(value))
    

To summarize the expected results for these functions (assuming the input is a float):

+----------------------------------------------------------------------+
¦          input ¦ NaN   ¦ Infinity   ¦ -Infinity   ¦ something else   ¦
¦ function       ¦       ¦            ¦             ¦                  ¦
¦----------------+-------+------------+-------------+------------------¦
¦ isnan          ¦ True  ¦ False      ¦ False       ¦ False            ¦
+----------------+-------+------------+-------------+------------------¦
¦ isinf          ¦ False ¦ True       ¦ True        ¦ False            ¦
+----------------+-------+------------+-------------+------------------¦
¦ isfinite       ¦ False ¦ False      ¦ False       ¦ True             ¦
+----------------------------------------------------------------------+

Is it possible to set an element of an array to NaN in Python?

In a list it's no problem, you can always include NaN (or Infinity) there:

>>> [math.nan, math.inf, -math.inf, 1]  # python list
[nan, inf, -inf, 1]

However if you want to include it in an array (for example array.array or numpy.array) then the type of the array must be float or complex because otherwise it will try to downcast it to the arrays type!

>>> import numpy as np
>>> float_numpy_array = np.array([0., 0., 0.], dtype=float)
>>> float_numpy_array[0] = float("nan")
>>> float_numpy_array
array([nan,  0.,  0.])

>>> import array
>>> float_array = array.array('d', [0, 0, 0])
>>> float_array[0] = float("nan")
>>> float_array
array('d', [nan, 0.0, 0.0])

>>> integer_numpy_array = np.array([0, 0, 0], dtype=int)
>>> integer_numpy_array[0] = float("nan")
ValueError: cannot convert float NaN to integer

How to select specified node within Xpath node sets by index with Selenium?

There is no i in xpath is not entirely true. You can still use the count() to find the index.

Consider the following page

_x000D_
_x000D_
<html>_x000D_
_x000D_
 <head>_x000D_
  <title>HTML Sample table</title>_x000D_
 </head>_x000D_
_x000D_
 <style>_x000D_
 table, td, th {_x000D_
  border: 1px solid black;_x000D_
  font-size: 15px;_x000D_
  font-family: Trebuchet MS, sans-serif;_x000D_
 }_x000D_
 table {_x000D_
  border-collapse: collapse;_x000D_
  width: 100%;_x000D_
 }_x000D_
_x000D_
 th, td {_x000D_
  text-align: left;_x000D_
  padding: 8px;_x000D_
 }_x000D_
_x000D_
 tr:nth-child(even){background-color: #f2f2f2}_x000D_
_x000D_
 th {_x000D_
  background-color: #4CAF50;_x000D_
  color: white;_x000D_
 }_x000D_
 </style>_x000D_
_x000D_
 <body>_x000D_
 <table>_x000D_
  <thead>_x000D_
   <tr>_x000D_
    <th>Heading 1</th>_x000D_
    <th>Heading 2</th>_x000D_
    <th>Heading 3</th>_x000D_
    <th>Heading 4</th>_x000D_
    <th>Heading 5</th>_x000D_
    <th>Heading 6</th>_x000D_
   </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
   <tr>_x000D_
    <td>Data row 1 col 1</td>_x000D_
    <td>Data row 1 col 2</td>_x000D_
    <td>Data row 1 col 3</td>_x000D_
    <td>Data row 1 col 4</td>_x000D_
    <td>Data row 1 col 5</td>_x000D_
    <td>Data row 1 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 2 col 1</td>_x000D_
    <td>Data row 2 col 2</td>_x000D_
    <td>Data row 2 col 3</td>_x000D_
    <td>Data row 2 col 4</td>_x000D_
    <td>Data row 2 col 5</td>_x000D_
    <td>Data row 2 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 3 col 1</td>_x000D_
    <td>Data row 3 col 2</td>_x000D_
    <td>Data row 3 col 3</td>_x000D_
    <td>Data row 3 col 4</td>_x000D_
    <td>Data row 3 col 5</td>_x000D_
    <td>Data row 3 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 4 col 1</td>_x000D_
    <td>Data row 4 col 2</td>_x000D_
    <td>Data row 4 col 3</td>_x000D_
    <td>Data row 4 col 4</td>_x000D_
    <td>Data row 4 col 5</td>_x000D_
    <td>Data row 4 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 5 col 1</td>_x000D_
    <td>Data row 5 col 2</td>_x000D_
    <td>Data row 5 col 3</td>_x000D_
    <td>Data row 5 col 4</td>_x000D_
    <td>Data row 5 col 5</td>_x000D_
    <td>Data row 5 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
   </tr>_x000D_
  </tbody>_x000D_
 </table>_x000D_
_x000D_
 </br>_x000D_
_x000D_
 <table>_x000D_
  <thead>_x000D_
   <tr>_x000D_
    <th>Heading 7</th>_x000D_
    <th>Heading 8</th>_x000D_
    <th>Heading 9</th>_x000D_
    <th>Heading 10</th>_x000D_
    <th>Heading 11</th>_x000D_
    <th>Heading 12</th>_x000D_
   </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
   <tr>_x000D_
    <td>Data row 1 col 1</td>_x000D_
    <td>Data row 1 col 2</td>_x000D_
    <td>Data row 1 col 3</td>_x000D_
    <td>Data row 1 col 4</td>_x000D_
    <td>Data row 1 col 5</td>_x000D_
    <td>Data row 1 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 2 col 1</td>_x000D_
    <td>Data row 2 col 2</td>_x000D_
    <td>Data row 2 col 3</td>_x000D_
    <td>Data row 2 col 4</td>_x000D_
    <td>Data row 2 col 5</td>_x000D_
    <td>Data row 2 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 3 col 1</td>_x000D_
    <td>Data row 3 col 2</td>_x000D_
    <td>Data row 3 col 3</td>_x000D_
    <td>Data row 3 col 4</td>_x000D_
    <td>Data row 3 col 5</td>_x000D_
    <td>Data row 3 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 4 col 1</td>_x000D_
    <td>Data row 4 col 2</td>_x000D_
    <td>Data row 4 col 3</td>_x000D_
    <td>Data row 4 col 4</td>_x000D_
    <td>Data row 4 col 5</td>_x000D_
    <td>Data row 4 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 5 col 1</td>_x000D_
    <td>Data row 5 col 2</td>_x000D_
    <td>Data row 5 col 3</td>_x000D_
    <td>Data row 5 col 4</td>_x000D_
    <td>Data row 5 col 5</td>_x000D_
    <td>Data row 5 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
   </tr>_x000D_
  </tbody>_x000D_
 </table>_x000D_
_x000D_
 </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

The page has 2 tables and has 6 columns each with unique column names and 6 rows with variable data. The last row has the Modify button in both the tables.

Assuming that the user has to select the 4th Modify button from the first table based on the heading

Use the xpath //th[.='Heading 4']/ancestor::thead/following-sibling::tbody/tr/td[count(//tr/th[.='Heading 4']/preceding-sibling::th)+1]/button

The count() operator comes in handy in situations like these.

Logic:

  1. Find the header for the Modify button using //th[.='Heading 4']
  2. Find the index of the header column using count(//tr/th[.='Heading 4']/preceding-sibling::th)+1

Note: Index starts at 0

  1. Get the rows for the corresponding header using //th[.='Heading 4']/ancestor::thead/following-sibling::tbody/tr/td[count(//tr/th[.='Heading 4']/preceding-sibling::th)+1]

  2. Get the Modify button from the extracted node list using //th[.='Heading 4']/ancestor::thead/following-sibling::tbody/tr/td[count(//tr/th[.='Heading 4']/preceding-sibling::th)+1]/button

Get value of a specific object property in C# without knowing the class behind

Reflection can help you.

var someObject;
var propertyName = "PropertyWhichValueYouWantToKnow";
var propertyName = someObject.GetType().GetProperty(propertyName).GetValue(someObject, null);

How to extend an existing JavaScript array with another array, without creating a new array

I feel the most elegant these days is:

arr1.push(...arr2);

The MDN article on the spread operator mentions this nice sugary way in ES2015 (ES6):

A better push

Example: push is often used to push an array to the end of an existing array. In ES5 this is often done as:

var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
// Append all items from arr2 onto arr1
Array.prototype.push.apply(arr1, arr2);

In ES6 with spread this becomes:

var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
arr1.push(...arr2);

Do note that arr2 can't be huge (keep it under about 100 000 items), because the call stack overflows, as per jcdude's answer.