Programs & Examples On #Double underscore

Private Variables and Methods in Python

The double underscore. It mangles the name in such a way that it can't be accessed simply through __fieldName from outside the class, which is what you want to begin with if they're to be private. (Though it's still not very hard to access the field.)

class Foo:
    def __init__(self):
        self.__privateField = 4;
        print self.__privateField # yields 4 no problem

foo = Foo()
foo.__privateField
# AttributeError: Foo instance has no attribute '__privateField'

It will be accessible through _Foo__privateField instead. But it screams "I'M PRIVATE DON'T TOUCH ME", which is better than nothing.

Why do some functions have underscores "__" before and after the function name?

From the Python PEP 8 -- Style Guide for Python Code:

Descriptive: Naming Styles

The following special forms using leading or trailing underscores are recognized (these can generally be combined with any case convention):

  • _single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

  • single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g.

    Tkinter.Toplevel(master, class_='ClassName')

  • __double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo; see below).

  • __double_leading_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented.

Note that names with double leading and trailing underscores are essentially reserved for Python itself: "Never invent such names; only use them as documented".

What is the difference between "SMS Push" and "WAP Push"?

An SMS Push is a message to tell the terminal to initiate the session. This happens because you can't initiate an IP session simply because you don't know the IP Adress of the mobile terminal. Mostly used to send a few lines of data to end recipient, to the effect of sending information, or reminding of events.

WAP Push is an SMS within the header of which is included a link to a WAP address. On receiving a WAP Push, the compatible mobile handset automatically gives the user the option to access the WAP content on his handset. The WAP Push directs the end-user to a WAP address where content is stored ready for viewing or downloading onto the handset. This wap address may be a page or a WAP site.

The user may “take action” by using a developer-defined soft-key to immediately activate an application to accomplish a specific task, such as downloading a picture, making a purchase, or responding to a marketing offer.

Disable and later enable all table indexes in Oracle

If you are using non-parallel direct path loads then consider and benchmark not dropping the indexes at all, particularly if the indexes only cover a minority of the columns. Oracle has a mechanism for efficient maintenance of indexes on direct path loads.

Otherwise, I'd also advise making the indexes unusable instead of dropping them. Less chance of accidentally not recreating an index.

OpenVPN failed connection / All TAP-Win32 adapters on this system are currently in use

It seems to me you are using the wrong version...

TAP-Win32 should not be installed on the 64bit version. Download the right one and try again!

Remove padding or margins from Google Charts

I arrived here like most people with this same issue, and left shocked that none of the answer even remotely worked.

For anyone interested, here is the actual solution:

... //rest of options
width: '100%',
height: '350',
chartArea:{
    left:5,
    top: 20,
    width: '100%',
    height: '350',
}
... //rest of options

The key here has nothing to do with the "left" or "top" values. But rather that the:

Dimensions of both the chart and chart-area are SET and set to the SAME VALUE

As an amendment to my answer. The above will indeed solve the "excessive" padding/margin/whitespace problem. However, if you wish to include axes labels and/or a legend you will need to reduce the height & width of the chart area so something slightly below the outer width/height. This will "tell" the chart API that there is sufficient room to display these properties. Otherwise it will happily exclude them.

How to clear a notification in Android

From: http://developer.android.com/guide/topics/ui/notifiers/notifications.html

To clear the status bar notification when the user selects it from the Notifications window, add the "FLAG_AUTO_CANCEL" flag to your Notification object. You can also clear it manually with cancel(int), passing it the notification ID, or clear all your Notifications with cancelAll().

But Donal is right, you can only clear notifications that you created.

How to open a txt file and read numbers in Java

import java.io.*;  
public class DataStreamExample {  
     public static void main(String args[]){    
          try{    
            FileWriter  fin=new FileWriter("testout.txt");    
            BufferedWriter d = new BufferedWriter(fin);
            int a[] = new int[3];
            a[0]=1;
            a[1]=22;
            a[2]=3;
            String s="";
            for(int i=0;i<3;i++)
            {
                s=Integer.toString(a[i]);
                d.write(s);
                d.newLine();
            }

            System.out.println("Success");
            d.close();
            fin.close();    



            FileReader in=new FileReader("testout.txt");
            BufferedReader br=new BufferedReader(in);
            String i="";
            int sum=0;
            while ((i=br.readLine())!= null)
            {
                sum += Integer.parseInt(i);
            }
            System.out.println(sum);
          }catch(Exception e){System.out.println(e);}    
         }    
        }  

OUTPUT:: Success 26

Also, I used array to make it simple.... you can directly take integer input and convert it into string and send it to file. input-convert-Write-Process... its that simple.

maven command line how to point to a specific settings.xml for a single command?

You can simply use:

mvn --settings YourOwnSettings.xml clean install

or

mvn -s YourOwnSettings.xml clean install

Write to UTF-8 file in Python

I believe the problem is that codecs.BOM_UTF8 is a byte string, not a Unicode string. I suspect the file handler is trying to guess what you really mean based on "I'm meant to be writing Unicode as UTF-8-encoded text, but you've given me a byte string!"

Try writing the Unicode string for the byte order mark (i.e. Unicode U+FEFF) directly, so that the file just encodes that as UTF-8:

import codecs

file = codecs.open("lol", "w", "utf-8")
file.write(u'\ufeff')
file.close()

(That seems to give the right answer - a file with bytes EF BB BF.)

EDIT: S. Lott's suggestion of using "utf-8-sig" as the encoding is a better one than explicitly writing the BOM yourself, but I'll leave this answer here as it explains what was going wrong before.

View google chrome's cached pictures

You can make a bookmark with this as the url:

javascript:
var cached_anchors = $$('a');
for (var i in cached_anchors) {
    var ca = cached_anchors[i];
    if(ca.href.search('sprite') < 0 && ca.href.search('.png') > -1 || ca.href.search('.gif') > -1 || ca.href.search('.jpg') > -1) {
        var a = document.createElement('a');
        a.href = ca.innerHTML;
        a.target = '_blank';

        var img = document.createElement('img');
        img.src = ca.innerHTML;
        img.style.maxHeight = '100px';

        a.appendChild(img);
        document.getElementsByTagName('body')[0].appendChild(a);
    }
}
document.getElementsByTagName('body')[0].removeChild(document.getElementsByTagName('table')[0]);
void(0);

Then just go to chrome://cache and then click your bookmark and it'll show you all the images.

How to add new line in Markdown presentation?

If none of the solutions mentions here work for you, which is what happened with me, then you can do the following: Add an empty header (A hack that ruins semantics)

text
####
text

Just make sure that when the header is added it has no border in bottom of it in the markdown css, so you can try different variations of the headers.

How to sort a list of strings numerically?

You haven't actually converted your strings to ints. Or rather, you did, but then you didn't do anything with the results. What you want is:

list1 = ["1","10","3","22","23","4","2","200"]
list1 = [int(x) for x in list1]
list1.sort()

If for some reason you need to keep strings instead of ints (usually a bad idea, but maybe you need to preserve leading zeros or something), you can use a key function. sort takes a named parameter, key, which is a function that is called on each element before it is compared. The key function's return values are compared instead of comparing the list elements directly:

list1 = ["1","10","3","22","23","4","2","200"]
# call int(x) on each element before comparing it
list1.sort(key=int)

How to get diff between all files inside 2 folders that are on the web?

Once you have the source trees, e.g.

diff -ENwbur repos1/ repos2/ 

Even better

diff -ENwbur repos1/ repos2/  | kompare -o -

and have a crack at it in a good gui tool :)

  • -Ewb ignore the bulk of whitespace changes
  • -N detect new files
  • -u unified
  • -r recurse

Parser Error: '_Default' is not allowed here because it does not extend class 'System.Web.UI.Page' & MasterType declaration

Remember.. inherits is case sensitive for C# (not so for vb.net)

Found that out the hard way.

How do I convert the date from one format to another date object in another format without using any deprecated classes?

    //Convert input format 19-FEB-16 01.00.00.000000000 PM to 2016-02-19 01.00.000 PM
    SimpleDateFormat inFormat = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.SSSSSSSSS aaa");
    Date today = new Date();        

    Date d1 = inFormat.parse("19-FEB-16 01.00.00.000000000 PM");

    SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd hh.mm.ss.SSS aaa");

    System.out.println("Out date ="+outFormat.format(d1));

How to ignore parent css style

If I understood the question correctly: you can use auto in the CSS like this width: auto; and it will go back to default settings.

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

Same as AMIB answer, for soft delete error "Unknown column 'table_alias.deleted_at'", just add ->withTrashed() then handle it yourself like ->whereRaw('items_alias.deleted_at IS NULL')

How to create a JSON object

Usually, you would do something like this:

$post_data = json_encode(array('item' => $post_data));

But, as it seems you want the output to be with "{}", you better make sure to force json_encode() to encode as object, by passing the JSON_FORCE_OBJECT constant.

$post_data = json_encode(array('item' => $post_data), JSON_FORCE_OBJECT);

"{}" brackets specify an object and "[]" are used for arrays according to JSON specification.

Converting a String to a List of Words?

A regular expression for words would give you the most control. You would want to carefully consider how to deal with words with dashes or apostrophes, like "I'm".

Cast int to varchar

use :

SELECT cast(CHAR(50),id) as colI1 from t9;

LEFT JOIN vs. LEFT OUTER JOIN in SQL Server

What is the difference between left join and left outer join?

Nothing. LEFT JOIN and LEFT OUTER JOIN are equivalent.

Chaining multiple filter() in Django, is this a bug?

Sometimes you don't want to join multiple filters together like this:

def your_dynamic_query_generator(self, event: Event):
    qs \
    .filter(shiftregistrations__event=event) \
    .filter(shiftregistrations__shifts=False)

And the following code would actually not return the correct thing.

def your_dynamic_query_generator(self, event: Event):
    return Q(shiftregistrations__event=event) & Q(shiftregistrations__shifts=False)

What you can do now is to use an annotation count-filter.

In this case we count all shifts which belongs to a certain event.

qs: EventQuerySet = qs.annotate(
    num_shifts=Count('shiftregistrations__shifts', filter=Q(shiftregistrations__event=event))
)

Afterwards you can filter by annotation.

def your_dynamic_query_generator(self):
    return Q(num_shifts=0)

This solution is also cheaper on large querysets.

Hope this helps.

Turn off auto formatting in Visual Studio

VS2015 settings that helped me prevent auto formatting:

(and Tools > Options > Text Editor > Basic > Advanced, just like Tango91 suggested)

enter image description here

Force file download with php using header()

the htaccess solution

<filesmatch "\.(?i:doc|odf|pdf|cer|txt)$">
  Header set Content-Disposition attachment
</FilesMatch>

you can read this page: https://www.techmesto.com/force-files-to-download-using-htaccess/

How to SFTP with PHP?

PHP has ssh2 stream wrappers (disabled by default), so you can use sftp connections with any function that supports stream wrappers by using ssh2.sftp:// for protocol, e.g.

file_get_contents('ssh2.sftp://user:[email protected]:22/path/to/filename');

or - when also using the ssh2 extension

$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);
$stream = fopen("ssh2.sftp://$sftp/path/to/file", 'r');

See http://php.net/manual/en/wrappers.ssh2.php

On a side note, there is also quite a bunch of questions about this topic already:

Get all validation errors from Angular 2 FormGroup

You can iterate over this.form.errors property.

Using local makefile for CLion instead of CMake

Currently, only CMake is supported by CLion. Others build systems will be added in the future, but currently, you can only use CMake.

An importer tool has been implemented to help you to use CMake.

Edit:

Source : http://blog.jetbrains.com/clion/2014/09/clion-answers-frequently-asked-questions/

Set NA to 0 in R

Why not try this

  na.zero <- function (x) {
        x[is.na(x)] <- 0
        return(x)
    }
    na.zero(df)

Generate random numbers with a given (numerical) distribution

I wrote a solution for drawing random samples from a custom continuous distribution.

I needed this for a similar use-case to yours (i.e. generating random dates with a given probability distribution).

You just need the funtion random_custDist and the line samples=random_custDist(x0,x1,custDist=custDist,size=1000). The rest is decoration ^^.

import numpy as np

#funtion
def random_custDist(x0,x1,custDist,size=None, nControl=10**6):
    #genearte a list of size random samples, obeying the distribution custDist
    #suggests random samples between x0 and x1 and accepts the suggestion with probability custDist(x)
    #custDist noes not need to be normalized. Add this condition to increase performance. 
    #Best performance for max_{x in [x0,x1]} custDist(x) = 1
    samples=[]
    nLoop=0
    while len(samples)<size and nLoop<nControl:
        x=np.random.uniform(low=x0,high=x1)
        prop=custDist(x)
        assert prop>=0 and prop<=1
        if np.random.uniform(low=0,high=1) <=prop:
            samples += [x]
        nLoop+=1
    return samples

#call
x0=2007
x1=2019
def custDist(x):
    if x<2010:
        return .3
    else:
        return (np.exp(x-2008)-1)/(np.exp(2019-2007)-1)
samples=random_custDist(x0,x1,custDist=custDist,size=1000)
print(samples)

#plot
import matplotlib.pyplot as plt
#hist
bins=np.linspace(x0,x1,int(x1-x0+1))
hist=np.histogram(samples, bins )[0]
hist=hist/np.sum(hist)
plt.bar( (bins[:-1]+bins[1:])/2, hist, width=.96, label='sample distribution')
#dist
grid=np.linspace(x0,x1,100)
discCustDist=np.array([custDist(x) for x in grid]) #distrete version
discCustDist*=1/(grid[1]-grid[0])/np.sum(discCustDist)
plt.plot(grid,discCustDist,label='custom distribustion (custDist)', color='C1', linewidth=4)
#decoration
plt.legend(loc=3,bbox_to_anchor=(1,0))
plt.show()

Continuous custom distribution and discrete sample distribution

The performance of this solution is improvable for sure, but I prefer readability.

How to send json data in POST request using C#

You can do it with HttpWebRequest:

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://yourUrl");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(new
            {
                Username = "myusername",
                Password = "pass"
            });
    streamWriter.Write(json);
    streamWriter.Flush();
    streamWriter.Close();
}

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

Can one do a for each loop in java in reverse order?

You can use the Collections class to reverse the list then loop.

How can I convert an MDB (Access) file to MySQL (or plain SQL file)?

If you have access to a linux box with mdbtools installed, you can use this Bash shell script (save as mdbconvert.sh):

#!/bin/bash

TABLES=$(mdb-tables -1 $1)

MUSER="root"
MPASS="yourpassword"
MDB="$2"

MYSQL=$(which mysql)

for t in $TABLES
do
    $MYSQL -u $MUSER -p$MPASS $MDB -e "DROP TABLE IF EXISTS $t"
done

mdb-schema $1 mysql | $MYSQL -u $MUSER -p$MPASS $MDB

for t in $TABLES
do
    mdb-export -D '%Y-%m-%d %H:%M:%S' -I mysql $1 $t | $MYSQL -u $MUSER -p$MPASS $MDB
done

To invoke it simply call it like this:

./mdbconvert.sh accessfile.mdb mysqldatabasename

It will import all tables and all data.

How To Change DataType of a DataColumn in a DataTable?

Consider also altering the return type:

select cast(columnName as int) columnName from table

Is it possible to specify a different ssh port when using rsync?

When calling rsync within java (and perhaps other languages), I found that setting

-e ssh -p 22

resulting in rsync complaining it could not execute the binary:

ssh -p 22

because that path ssh -p 22 did not exist (the -p and 22 are no longer arguments for some reason and now make up part of the path to the binary rsync should call).

To workaround this problem I was able to use this environment variable:

export "RSYNC_RSH=ssh -p 2222"

(Programmatically set within java using env.put("RSYNC_RSH", "ssh -p " + port);)

Perl - If string contains text?

if ($string =~ m/something/) {
   # Do work
}

Where something is a regular expression.

how to read all files inside particular folder

using System.IO;

//...

  string[] files;

  if (Directory.Exists(Path)) {
    files = Directory.GetFiles(Path, @"*.xml", SearchOption.TopDirectoryOnly);
    //...

How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null)

        combo1.DisplayMember = "Text";
        combo1.ValueMember = "Value";   
        combo1.Items.Add(new { Text = "someText"), Value = "someValue") });
        dynamic item = combo1.Items[combo1.SelectedIndex];
        var itemValue = item.Value;
        var itemText = item.Text;

Unfortunatly "combo1.SelectedValue" does not work, i did not want to bind my combobox with any source, so i came up with this solution. Maybe it will help someone.

Remove first Item of the array (like popping from stack)

The easiest way is using shift(). If you have an array, the shift function shifts everything to the left.

var arr = [1, 2, 3, 4]; 
var theRemovedElement = arr.shift(); // theRemovedElement == 1
console.log(arr); // [2, 3, 4]

phpMyAdmin - config.inc.php configuration?

for phpMyAdmin-4.8.5-all-languages copy content from config.sample.inc.php into new file config.inc.php and instead of

/* Authentication type */
$cfg['Servers'][$i]['auth_type'] = 'cookie';
/* Server parameters */
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['AllowNoPassword'] = false;

put the folowing content:

/* Authentication type */
$cfg['Servers'][$i]['auth_type'] = 'config';
/* Server parameters */
$cfg['Servers'][$i]['host'] = 'localhost}';
$cfg['Servers'][$i]['user'] = '{your root mysql username';
$cfg['Servers'][$i]['password'] = '{your pasword for root user to login into mysql}';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['AllowNoPassword'] = true;

the rest remain commented an un-changed...

Forward host port to docker container

Your docker host exposes an adapter to all the containers. Assuming you are on recent ubuntu, you can run

ip addr

This will give you a list of network adapters, one of which will look something like

3: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP
link/ether 22:23:6b:28:6b:e0 brd ff:ff:ff:ff:ff:ff
inet 172.17.42.1/16 scope global docker0
inet6 fe80::a402:65ff:fe86:bba6/64 scope link
   valid_lft forever preferred_lft forever

You will need to tell rabbit/mongo to bind to that IP (172.17.42.1). After that, you should be able to open connections to 172.17.42.1 from within your containers.

Responsive bootstrap 3 timepicker?

As an update to the OP's question, I can confirm that the timepicker found at http://jdewit.github.io/bootstrap-timepicker/ does in fact work with Bootstrap 3 now with no problems at all.

What is the C# Using block and why should I use it?

Using calls Dispose() after the using-block is left, even if the code throws an exception.

So you usually use using for classes that require cleaning up after them, like IO.

So, this using block:

using (MyClass mine = new MyClass())
{
  mine.Action();
}

would do the same as:

MyClass mine = new MyClass();
try
{
  mine.Action();
}
finally
{
  if (mine != null)
    mine.Dispose();
}

Using using is way shorter and easier to read.

Get table name by constraint name

ALL_CONSTRAINTS describes constraint definitions on tables accessible to the current user.

DBA_CONSTRAINTS describes all constraint definitions in the database.

USER_CONSTRAINTS describes constraint definitions on tables in the current user's schema

Select CONSTRAINT_NAME,CONSTRAINT_TYPE ,TABLE_NAME ,STATUS from 
USER_CONSTRAINTS;

How to set <iframe src="..."> without causing `unsafe value` exception?

I ran into this issue as well, but in order to use a safe pipe in my angular module, I installed the safe-pipe npm package, which you can find here. FYI, this worked in Angular 9.1.3, I haven't tried this in any other versions of Angular. Here's how you add it step by step:

  1. Install the package via npm install safe-pipe or yarn add safe-pipe. This will store a reference to it in your dependencies in the package.json file, which you should already have from starting a new Angular project.

  2. Add SafePipeModule module to NgModule.imports in your Angular module file like so:

    import { SafePipeModule } from 'safe-pipe';
    
    @NgModule({
        imports: [ SafePipeModule ]
    })
    export class AppModule { }
    
    
  3. Add the safe pipe to an element in the template for the Angular component you are importing into your NgModule this way:

<element [property]="value | safe: sanitizationType"></element>
  1. Here are some specific examples of the safePipe in an html element:
<div [style.background-image]="'url(' + pictureUrl + ')' | safe: 'style'" class="pic bg-pic"></div>
<img [src]="pictureUrl | safe: 'url'" class="pic" alt="Logo">
<iframe [src]="catVideoEmbed | safe: 'resourceUrl'" width="640" height="390"></iframe>
<pre [innerHTML]="htmlContent | safe: 'html'"></pre>

No log4j2 configuration file found. Using default configuration: logging only errors to the console

Stuffs I check to verify logging,

1) Check that there're no older log4j versions.

mvn dependency:tree | grep log ## ./gradlew dependencies | grep log
[INFO] +- com.prayagupd:log-service:jar:1.0:compile
[INFO] +- org.apache.logging.log4j:log4j-api:jar:2.6.2:compile
[INFO] +- org.apache.logging.log4j:log4j-core:jar:2.6.2:compile
[INFO] |  \- commons-logging:commons-logging:jar:1.1.1:compile

2) make sure I'm setting log4j2.json properly, which is done with -Dlog4j.configurationFile=???

val logConfig: PropertiesConfiguration = new PropertiesConfiguration("application.properties")
System.setProperty("log4j.configurationFile", logConfig.getString("log4j.config.file"))

println("log4j.configurationFile :: " + System.getProperty("log4j.configurationFile"))

or

Configurator.initialize(null, logConfig.getString("log4j.config.file"));

Also if auto detection is happening make sure the file name is log4j2.* not log4j.*

3) Another check is for parser for log4j2.json. Thanks log4j team for not providing parser within the API.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.4.0</version>
</dependency>

This might throw an exception if can not find the json parser

[Fatal Error] log4j2.json:1:1: Content is not allowed in prolog.

Run Excel Macro from Outside Excel Using VBScript From Command Line

If you are trying to run the macro from your personal workbook it might not work as opening an Excel file with a VBScript doesnt automatically open your PERSONAL.XLSB. you will need to do something like this:

Dim oFSO
Dim oShell, oExcel, oFile, oSheet
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oShell = CreateObject("WScript.Shell")
Set oExcel = CreateObject("Excel.Application")
Set wb2 = oExcel.Workbooks.Open("C:\..\PERSONAL.XLSB") 'Specify foldername here

oExcel.DisplayAlerts = False


For Each oFile In oFSO.GetFolder("C:\Location\").Files
    If LCase(oFSO.GetExtensionName(oFile)) = "xlsx" Then
        With oExcel.Workbooks.Open(oFile, 0, True, , , , True, , , , False, , False)



            oExcel.Run wb2.Name & "!modForm"


            For Each oSheet In .Worksheets



                oSheet.SaveAs "C:\test\" & oFile.Name & "." & oSheet.Name & ".txt", 6


            Next
            .Close False, , False
        End With
    End If



Next
oExcel.Quit
oShell.Popup "Conversion complete", 10

So at the beginning of the loop it is opening personals.xlsb and running the macro from there for all the other workbooks. Just thought I should post in here just in case someone runs across this like I did but cant figure out why the macro is still not running.

Can a div have multiple classes (Twitter Bootstrap)

Absolutely, divs can have more than one class and with some Bootstrap components you'll often need to have multiple classes for them to function as you want them to. Applying multiple classes of course is possible outside of bootstrap as well. All you have to do is separate each class with a space.

Example below:

<label class="checkbox inline">
   <input type="checkbox" id="inlineCheckbox1" value="option1"> 1
</label>

How to access child's state in React?

Its 2020 and lots of you will come here looking for a similar solution but with Hooks ( They are great! ) and with latest approaches in terms of code cleanliness and syntax.

So as previous answers had stated, the best approach to this kind of problem is to hold the state outside of child component fieldEditor. You could do that in multiple ways.

The most "complex" is with global context (state) that both parent and children could access and modify. Its a great solution when components are very deep in the tree hierarchy and so its costly to send props in each level.

In this case I think its not worth it, and more simple approach will bring us the results we want, just using the powerful React.useState().

Approach with React.useState() hook, way simpler than with Class components

As said we will deal with changes and store the data of our child component fieldEditor in our parent fieldForm. To do that we will send a reference to the function that will deal and apply the changes to the fieldForm state, you could do that with:

function FieldForm({ fields }) {
  const [fieldsValues, setFieldsValues] = React.useState({});
  const handleChange = (event, fieldId) => {
    let newFields = { ...fieldsValues };
    newFields[fieldId] = event.target.value;

    setFieldsValues(newFields);
  };

  return (
    <div>
      {fields.map(field => (
        <FieldEditor
          key={field}
          id={field}
          handleChange={handleChange}
          value={fieldsValues[field]}
        />
      ))}
      <div>{JSON.stringify(fieldsValues)}</div>
    </div>
  );
}

Note that React.useState({}) will return an array with position 0 being the value specified on call (Empty object in this case), and position 1 being the reference to the function that modifies the value.

Now with the child component, FieldEditor, you don't even need to create a function with a return statement, a lean constant with an arrow function will do!

const FieldEditor = ({ id, value, handleChange }) => (
  <div className="field-editor">
    <input onChange={event => handleChange(event, id)} value={value} />
  </div>
);

Aaaaand we are done, nothing more, with just these two slime functional components we have our end goal "access" our child FieldEditor value and show it off in our parent.

You could check the accepted answer from 5 years ago and see how Hooks made React code leaner (By a lot!).

Hope my answer helps you learn and understand more about Hooks, and if you want to check a working example here it is.

Function to calculate distance between two coordinates

As said before, your function is calculating a straight line distance to the destination point. If you want the driving distance/route, you can use Google Maps Distance Matrix Service:

getDrivingDistanceBetweenTwoLatLong(origin, destination) {

 return new Observable(subscriber => {
  let service = new google.maps.DistanceMatrixService();
  service.getDistanceMatrix(
    {
      origins: [new google.maps.LatLng(origin.lat, origin.long)],
      destinations: [new google.maps.LatLng(destination.lat, destination.long)],
      travelMode: 'DRIVING'
    }, (response, status) => {
      if (status !== google.maps.DistanceMatrixStatus.OK) {
        console.log('Error:', status);
        subscriber.error({error: status, status: status});
      } else {
        console.log(response);
        try {
          let valueInMeters = response.rows[0].elements[0].distance.value;
          let valueInKms = valueInMeters / 1000;
          subscriber.next(valueInKms);
          subscriber.complete();
        }
       catch(error) {
        subscriber.error({error: error, status: status});
       }
      }
    });
});
}

Docker: adding a file from a parent directory

The solution for those who use composer is to use a volume pointing to the parent folder:

#docker-composer.yml

foo:
  build: foo
  volumes:
    - ./:/src/:ro

But I'm pretty sure the can be done playing with volumes in Dockerfile.

"Unmappable character for encoding UTF-8" error

For IntelliJ users, this is pretty easy once you find out what the original encoding was. You can select the encoding from the bottom right corner of your Window, you will be prompted with a dialog box saying:

The encoding you've chosen ('[encoding type]') may change the contents of '[Your file]'. Do you want to reload the file from disk or convert the text and save in the new encoding?

So if you happen to have a few characters saved in some odd encoding, what you should do is first select 'Reload' to load the file all in the encoding of the bad characters. For me this turned the ? characters into their proper value.

IntelliJ can tell if you most likely did not pick the right encoding and will warn you. Revert back and try again.

Once you can see the bad characters go away, change the encoding select box in the bottom right corner back to the format you originally intended (if you are Googling this error message, that will likely be UTF-8). This time select the 'Convert' button on the dialog.

For me, I needed to reload as 'windows-1252', then convert back to 'UTF-8'. The offending characters were single quotes (‘ and ’) likely pasted in from a Word doc (or e-mail) with the wrong encoding, and the above actions will convert them to UTF-8.

How do I view the list of functions a Linux shared library is exporting?

Among other already mentioned tools you can use also readelf (manual). It is similar to objdump but goes more into detail. See this for the difference explanation.

$ readelf -sW /lib/liblzma.so.5 |head -n10

Symbol table '.dynsym' contains 128 entries:
   Num:    Value  Size Type    Bind   Vis      Ndx Name
     0: 00000000     0 NOTYPE  LOCAL  DEFAULT  UND
     1: 00000000     0 FUNC    GLOBAL DEFAULT  UND pthread_mutex_unlock@GLIBC_2.0 (4)
     2: 00000000     0 FUNC    GLOBAL DEFAULT  UND pthread_mutex_destroy@GLIBC_2.0 (4)
     3: 00000000     0 NOTYPE  WEAK   DEFAULT  UND _ITM_deregisterTMCloneTable
     4: 00000000     0 FUNC    GLOBAL DEFAULT  UND memmove@GLIBC_2.0 (5)
     5: 00000000     0 FUNC    GLOBAL DEFAULT  UND free@GLIBC_2.0 (5)
     6: 00000000     0 FUNC    GLOBAL DEFAULT  UND memcpy@GLIBC_2.0 (5)

Bash or KornShell (ksh)?

For one thing, bash has tab completion. This alone is enough to make me prefer it over ksh.

Z shell has a good combination of ksh's unique features with the nice things that bash provides, plus a lot more stuff on top of that.

npm notice created a lockfile as package-lock.json. You should commit this file

Yes you should, As it locks the version of each and every package which you are using in your app and when you run npm install it install the exact same version in your node_modules folder. This is important becasue let say you are using bootstrap 3 in your application and if there is no package-lock.json file in your project then npm install will install bootstrap 4 which is the latest and you whole app ui will break due to version mismatch.

Altering a column: null to not null

For the inbuilt javaDB included in the JDK (Oracle's supported distribution of the Apache Derby) the below worked for me

alter table [table name] alter column [column name] not null;

How do I get a substring of a string in Python?

One example seems to be missing here: full (shallow) copy.

>>> x = "Hello World!"
>>> x
'Hello World!'
>>> x[:]
'Hello World!'
>>> x==x[:]
True
>>>

This is a common idiom for creating a copy of sequence types (not of interned strings), [:]. Shallow copies a list, see Python list slice syntax used for no obvious reason.

How to get PID of process I've just started within java program?

If portability is not a concern, and you just want to get the pid on Windows without a lot of hassle while using code that is tested and known to work on all modern versions of Windows, you can use kohsuke's winp library. It is also available on Maven Central for easy consumption.

Process process = //...;
WinProcess wp = new WinProcess(process);
int pid = wp.getPid();

Cassandra port usage - how are the ports used?

JMX now uses port 7199 instead of port 8080 (as of Cassandra 0.8.xx).

This is configurable in your cassandra-env.sh file, but the default is 7199.

JUnit Testing Exceptions

@Test(expected = Exception.class)  

Tells Junit that exception is the expected result so test will be passed (marked as green) when exception is thrown.

For

@Test

Junit will consider test as failed if exception is thrown, provided it's an unchecked exception. If the exception is checked it won't compile and you will need to use other methods. This link might help.

git still shows files as modified after adding to .gitignore

Using git rm --cached *file* is not working fine for me (I'm aware this question is 8 years old, but it still shows at the top of the search for this topic), it does remove the file from the index, but it also deletes the file from the remote.

I have no idea why that is. All I wanted was keeping my local config isolated (otherwise I had to comment the localhost base url before every commit), not delete the remote equivalent to config.

Reading some more I found what seems to be the proper way to do this, and the only way that did what I needed, although it does require more attention, especially during merges.

Anyway, all it requires is git update-index --assume-unchanged *path/to/file*.

As far as I understand, this is the most notable thing to keep in mind:

Git will fail (gracefully) in case it needs to modify this file in the index e.g. when merging in a commit; thus, in case the assumed-untracked file is changed upstream, you will need to handle the situation manually.

How to Deep clone in javascript

The JSON.parse(JSON.stringify()) combination to deep copy Javascript objects is an ineffective hack, as it was meant for JSON data. It does not support values of undefined or function () {}, and will simply ignore them (or null them) when "stringifying" (marshalling) the Javascript object into JSON.

A better solution is to use a deep copy function. The function below deep copies objects, and does not require a 3rd party library (jQuery, LoDash, etc).

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

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

  return bObject;
}

new Date() is working in Chrome but not Firefox

I was having a similar issue in both Firefox and Safari when working with AngularJS. For example, if a date returned from Angular looked like this:

2014-06-02 10:28:00

using this code:

new Date('2014-06-02 10:28:00').toISOString();

returns an invalid date error in Firefox and Safari. However in Chrome it works fine. As another answer stated, Chrome is most likely just more flexible with parsing date strings.

My eventual goal was to format the date a certain way. I found an excellent library that handled both the cross browser compatibility issue and the date formatting issue. The library is called moment.js.

Using this library the following code works correctly across all browsers I tested:

moment('2014-06-02 10:28:00').format('MMM d YY')

If you are willing to include this extra library into your app you can more easily build your date string while avoiding possible browser compatibility issues. As a bonus you will have a good way to easily format, add, subtract, etc dates if needed.

Why is Dictionary preferred over Hashtable in C#?

Collections & Generics are useful for handling group of objects. In .NET, all the collections objects comes under the interface IEnumerable, which in turn has ArrayList(Index-Value)) & HashTable(Key-Value). After .NET framework 2.0, ArrayList & HashTable were replaced with List & Dictionary. Now, the Arraylist & HashTable are no more used in nowadays projects.

Coming to the difference between HashTable & Dictionary, Dictionary is generic where as Hastable is not Generic. We can add any type of object to HashTable, but while retrieving we need to cast it to the required type. So, it is not type safe. But to dictionary, while declaring itself we can specify the type of key and value, so there is no need to cast while retrieving.

Let's look at an example:

HashTable

class HashTableProgram
{
    static void Main(string[] args)
    {
        Hashtable ht = new Hashtable();
        ht.Add(1, "One");
        ht.Add(2, "Two");
        ht.Add(3, "Three");
        foreach (DictionaryEntry de in ht)
        {
            int Key = (int)de.Key; //Casting
            string value = de.Value.ToString(); //Casting
            Console.WriteLine(Key + " " + value);
        }

    }
}

Dictionary,

class DictionaryProgram
{
    static void Main(string[] args)
    {
        Dictionary<int, string> dt = new Dictionary<int, string>();
        dt.Add(1, "One");
        dt.Add(2, "Two");
        dt.Add(3, "Three");
        foreach (KeyValuePair<int, String> kv in dt)
        {
            Console.WriteLine(kv.Key + " " + kv.Value);
        }
    }
}

ORA-01008: not all variables bound. They are bound

I found how to run the query without error, but I hesitate to call it a "solution" without really understanding the underlying cause.

This more closely resembles the beginning of my actual query:

-- Comment
-- More comment
SELECT rf.flowrow, rf.stage, rf.process,
rf.instr instnum, rf.procedure_id, rtd_history.runtime, rtd_history.waittime
FROM
(
    -- Comment at beginning of subquery
    -- These two comment lines are the problem
    SELECT sub2.flowrow, sub2.stage, sub2.process, sub2.instr, sub2.pid
    FROM ( ...

The second set of comments above, at the beginning of the subquery, were the problem. When removed, the query executes. Other comments are fine. This is not a matter of some rogue or missing newline causing the following line to be commented, because the following line is a SELECT. A missing select would yield a different error than "not all variables bound."

I asked around and found one co-worker who has run into this -- comments causing query failures -- several times. Does anyone know how this can be the cause? It is my understanding that the very first thing a DBMS would do with comments is see if they contain hints, and if not, remove them during parsing. How can an ordinary comment containing no unusual characters (just letters and a period) cause an error? Bizarre.

Convert A String (like testing123) To Binary In Java

       int no=44;
             String bNo=Integer.toString(no,2);//binary output 101100
             String oNo=Integer.toString(no,8);//Oct output 54
             String hNo=Integer.toString(no,16);//Hex output 2C

              String bNo1= Integer.toBinaryString(no);//binary output 101100
              String  oNo1=Integer.toOctalString(no);//Oct output 54
              String  hNo1=Integer.toHexString(no);//Hex output 2C

              String sBNo="101100";
              no=Integer.parseInt(sBNo,2);//binary to int output 44

              String sONo="54";
              no=Integer.parseInt(sONo,8);//oct to int  output 44

              String sHNo="2C";
              no=Integer.parseInt(sHNo,16);//hex to int output 44

Undefined reference to pow( ) in C, despite including math.h

You need to link with the math library:

gcc -o sphere sphere.c -lm

The error you are seeing: error: ld returned 1 exit status is from the linker ld (part of gcc that combines the object files) because it is unable to find where the function pow is defined.

Including math.h brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a. You need to link your program with this library so that the calls to functions like pow() are resolved.

What does void do in java?

You mean the tellItLikeItIs method? Yes, you have to specify void to specify that the method doesn't return anything. All methods have to have a return type specified, even if it's void.

It certainly doesn't return a string - look, there are no return statements anywhere. It's not really clear why you think it is returning a string. It's printing strings to the console, but that's not the same thing as returning one from the method.

org.hibernate.QueryException: could not resolve property: filename

Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity).

Make sure you refer to the property as fileName in the Criteria query, not filename.

Specifically, Hibernate will call the getter method of the filename property when executing that Criteria query, so it will look for a method called getFilename(). But the property is called FileName and the getter getFileName().

So, change the projection like so:

criteria.setProjection(Projections.property("fileName"));

Grant execute permission for a user on all stored procedures in database?

use below code , change proper database name and user name and then take that output and execute in SSMS. FOR SQL 2005 ABOVE

USE <database_name> 
select 'GRANT EXECUTE ON ['+name+'] TO [userName]  '  
from sys.objects  
where type ='P' 
and is_ms_shipped = 0  

How to solve "The specified service has been marked for deletion" error

Discovered one more thing to check - look in Task manager - if other users are connected to this box, even if they are 'disconnected' you have to actually sign them out to get the service to finally delete.

How do I Merge two Arrays in VBA?

It work if Lbound is different than 0 or 1. You Redim once at start

Function MergeArrays(ByRef arr1 As Variant, ByRef arr2 As Variant) As Variant

'Test if not isarray then exit
If Not IsArray(arr1) And Not IsArray(arr2) Then Exit Function

Dim arr As Variant
Dim a As Long, b As Long 'index Array
Dim len1 As Long, len2 As Long 'nb of item

'get len if array don't start to 0
len1 = UBound(arr1) - LBound(arr1) + 1
len2 = UBound(arr2) - LBound(arr2) + 1

b = 1 'position of start index
'dim new array
ReDim arr(b To len1 + len2)
'merge arr1
For a = LBound(arr1) To UBound(arr1)
    arr(b) = arr1(a)       
    b = b + 1 'move index
Next a
'merge arr2
For a = LBound(arr2) To UBound(arr2)
    arr(b) = arr2(a)
    b = b + 1 'move index
Next a

'final
MergeArrays = arr

End Function

Pandas groupby month and year

There are different ways to do that.

  • I created the data frame to showcase the different techniques to filter your data.
df = pd.DataFrame({'Date':['01-Jun-13','03-Jun-13', '15-Aug-13', '20-Jan-14', '21-Feb-14'],

'abc':[100,-20,40,25,60],'xyz':[200,50,-5,15,80] })

  • I separated months/year/day and seperated month-year as you explained.
def getMonth(s):
  return s.split("-")[1]

def getDay(s):
  return s.split("-")[0]

def getYear(s):
  return s.split("-")[2]

def getYearMonth(s):
  return s.split("-")[1]+"-"+s.split("-")[2]
  • I created new columns: year, month, day and 'yearMonth'. In your case, you need one of both. You can group using two columns 'year','month' or using one column yearMonth
df['year']= df['Date'].apply(lambda x: getYear(x))
df['month']= df['Date'].apply(lambda x: getMonth(x))
df['day']= df['Date'].apply(lambda x: getDay(x))
df['YearMonth']= df['Date'].apply(lambda x: getYearMonth(x))

Output:

        Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13
2  15-Aug-13   40   -5   13   Aug  15    Aug-13
3  20-Jan-14   25   15   14   Jan  20    Jan-14
4  21-Feb-14   60   80   14   Feb  21    Feb-14
  • You can go through the different groups in groupby(..) items.

In this case, we are grouping by two columns:

for key,g in df.groupby(['year','month']):
    print key,g

Output:

('13', 'Jun')         Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13
('13', 'Aug')         Date  abc  xyz year month day YearMonth
2  15-Aug-13   40   -5   13   Aug  15    Aug-13
('14', 'Jan')         Date  abc  xyz year month day YearMonth
3  20-Jan-14   25   15   14   Jan  20    Jan-14
('14', 'Feb')         Date  abc  xyz year month day YearMonth

In this case, we are grouping by one column:

for key,g in df.groupby(['YearMonth']):
    print key,g

Output:

Jun-13         Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13
Aug-13         Date  abc  xyz year month day YearMonth
2  15-Aug-13   40   -5   13   Aug  15    Aug-13
Jan-14         Date  abc  xyz year month day YearMonth
3  20-Jan-14   25   15   14   Jan  20    Jan-14
Feb-14         Date  abc  xyz year month day YearMonth
4  21-Feb-14   60   80   14   Feb  21    Feb-14
  • In case you wanna access to specific item, you can use get_group

print df.groupby(['YearMonth']).get_group('Jun-13')

Output:

        Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13
  • Similar to get_group. This hack would help to filter values and get the grouped values.

This also would give the same result.

print df[df['YearMonth']=='Jun-13'] 

Output:

        Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13

You can select list of abc or xyz values during Jun-13

print df[df['YearMonth']=='Jun-13'].abc.values
print df[df['YearMonth']=='Jun-13'].xyz.values

Output:

[100 -20]  #abc values
[200  50]  #xyz values

You can use this to go through the dates that you have classified as "year-month" and apply cretiria on it to get related data.

for x in set(df.YearMonth): 
    print df[df['YearMonth']==x].abc.values
    print df[df['YearMonth']==x].xyz.values

I recommend also to check this answer as well.

Remove characters from C# string

The simplest way would be to use String.Replace:

String s = string.Replace("StringToReplace", "NewString");

Simple line plots using seaborn

Yes, you can do the same in Seaborn directly. This is done with tsplot() which allows either a single array as input, or two arrays where the other is 'time' i.e. x-axis.

import seaborn as sns

data =  [1,5,3,2,6] * 20
time = range(100)

sns.tsplot(data, time)

enter image description here

Correct way to pause a Python program

For Windows only, use:

import os
os.system("pause")

Char array to hex string C++

The simplest:

int main()
{
    const char* str = "hello";
    for (const char* p = str; *p; ++p)
    {
        printf("%02x", *p);
    }
    printf("\n");
    return 0;
}

How can I print out C++ map values?

Since C++17 you can use range-based for loops together with structured bindings for iterating over your map. This improves readability, as you reduce the amount of needed first and second members in your code:

std::map<std::string, std::pair<std::string, std::string>> myMap;
myMap["x"] = { "a", "b" };
myMap["y"] = { "c", "d" };

for (const auto &[k, v] : myMap)
    std::cout << "m[" << k << "] = (" << v.first << ", " << v.second << ") " << std::endl;

Output:

m[x] = (a, b)
m[y] = (c, d)

Code on Coliru

Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java?

Another way to wait for maximum of certain amount say 10 seconds of time for the element to be displayed as below:

(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver d) {
                return d.findElement(By.id("<name>")).isDisplayed();

            }
        });

Remove attribute "checked" of checkbox

try something like this FIDDLE

    try
      {
        navigator.device.capture.captureImage(function(mediaFiles) {
        console.log("works");
         });
      }

    catch(err)
      {
        alert('hi');
        $("#captureImage").prop('checked', false);

      }

Turn Pandas Multi-Index into column

There may be situations when df.reset_index() cannot be used (e.g., when you need the index, too). In this case, use index.get_level_values() to access index values directly:

df['Trial'] = df.index.get_level_values(0)
df['measurement'] = df.index.get_level_values(1)

This will assign index values to individual columns and keep the index.

See the docs for further info.

Android Use Done button on Keyboard to click button

You can implement on key listener:

public class ProbabilityActivity extends Activity implements OnClickListener, View.OnKeyListener {

In onCreate:

max.setOnKeyListener(this);

...

@Override
public boolean onKey(View v, int keyCode, KeyEvent event){
    if(keyCode == event.KEYCODE_ENTER){
        //call your button method here
    }
    return true;
}

How to write unit testing for Angular / TypeScript for private methods with Jasmine

Do not write tests for private methods. This defeats the point of unit tests.

  • You should be testing the public API of your class
  • You should NOT be testing the implimentation details of your class

Example

class SomeClass {

  public addNumber(a: number, b: number) {
      return a + b;
  }
}

The test for this method should not need to change if later the implementation changes but the behaviour of the public API remains the same.

class SomeClass {

  public addNumber(a: number, b: number) {
      return this.add(a, b);
  }

  private add(a: number, b: number) {
       return a + b;
  }
}

Don't make methods and properties public just in order to test them. This usually means that either:

  1. You are trying to test implementation rather than API (public interface).
  2. You should move the logic in question into its own class to make testing easier.

SQLAlchemy: how to filter date field?

if you want to get the whole period:

    from sqlalchemy import and_, func

    query = DBSession.query(User).filter(and_(func.date(User.birthday) >= '1985-01-17'),\
                                              func.date(User.birthday) <= '1988-01-17'))

That means range: 1985-01-17 00:00 - 1988-01-17 23:59

MySQL: update a field only if condition is met

Another solution which, in my opinion, is easier to read would be:

UPDATE test 
    SET something = 1, field = IF(condition is true, 1, field) 
    WHERE id = 123

What this does is set 'field' to 1 (like OP used as example) if the condition is met and use the current value of 'field' if not met. Using the previous value is the same as not changing, so there you go.

How to insert a newline in front of a pattern?

In vi on Red Hat, I was able to insert carriage returns using just the \r character. I believe this internally executes 'ex' instead of 'sed', but it's similar, and vi can be another way to do bulk edits such as code patches. For example. I am surrounding a search term with an if statement that insists on carriage returns after the braces:

:.,$s/\(my_function(.*)\)/if(!skip_option){\r\t\1\r\t}/

Note that I also had it insert some tabs to make things align better.

How to link 2 cell of excel sheet?

I Found Solution Of You Question But In Stack Not Allow to Upload Video See the link below it show better explain

How to link two (multiple) workbooks and cells in Excel...

.htaccess redirect all pages to new domain

Simple just like this and this will not carry the trailing query from URL to new domain.

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteRule .* https://www.newdomain.com/? [R=301,L]

Http Servlet request lose params from POST body after read it once

First of all we should not read parameters within the filter. Usually the headers are read in the filter to do few authentication tasks. Having said that one can read the HttpRequest body completely in the Filter or Interceptor by using the CharStreams:

String body = com.google.common.io.CharStreams.toString(request.getReader());

This does not affect the subsequent reads at all.

How to save the contents of a div as a image?

There are several of this same question (1, 2). One way of doing it is using canvas. Here's a working solution. Here you can see some working examples of using this library.

Where's my invalid character (ORA-00911)

Of the top of my head, can you try to use the 'q' operator for the string literal

something like

insert all
  into domo_queries values (q'[select 
substr(to_char(max_data),1,4) as year,
substr(to_char(max_data),5,6) as month,
max_data
from dss_fin_user.acq_dashboard_src_load_success
where source = 'CHQ PeopleSoft FS']')
select * from dual;

Note that the single quotes of your predicate are not escaped, and the string sits between q'[...]'.

Why is lock(this) {...} bad?

I know this is an old thread, but because people can still look this up and rely on it, it seems important to point out that lock(typeof(SomeObject)) is significantly worse than lock(this). Having said that; sincere kudos to Alan for pointing out that lock(typeof(SomeObject)) is bad practice.

An instance of System.Type is one of the most generic, coarse-grained objects there is. At the very least, an instance of System.Type is global to an AppDomain, and .NET can run multiple programs in an AppDomain. This means that two entirely different programs could potentially cause interference in one another even to the extent of creating a deadlock if they both try to get a synchronization lock on the same type instance.

So lock(this) isn't particularly robust form, can cause problems and should always raise eyebrows for all the reasons cited. Yet there is widely used, relatively well-respected and apparently stable code like log4net that uses the lock(this) pattern extensively, even though I would personally prefer to see that pattern change.

But lock(typeof(SomeObject)) opens up a whole new and enhanced can of worms.

For what it's worth.

MVC 4 Razor adding input type date

 @Html.TextBoxFor(m => m.EntryDate, new{ type = "date" })

 or type = "time"

 it will display a calendar
 it will not work if you give @Html.EditorFor()

git rebase: "error: cannot stat 'file': Permission denied"

My encounter with this problem was caused by my editor, Intellij. As part of its internal version controls, it had gone through and locked all hidden git files. (For various reasons, I was not using the git plugin that comes with Intellij...)

So I opened a normal dos window as Administrator, changed to the directory, and executed

attrib -R /S

That removed the lock on the files and everything worked after that and I could sync my changes using the GitHub windows client.

Observable Finally on Subscribe

The only thing which worked for me is this

fetchData()
  .subscribe(
    (data) => {
       //Called when success
     },
    (error) => {
       //Called when error
    }
  ).add(() => {
       //Called when operation is complete (both success and error)
  });

Hibernate Error executing DDL via JDBC Statement

you have to be careful because reseved words are not only for table names, also you have to check column names, my mistake was that one of my columns was named "user". If you are using PostgreSQL the correct dialect is: org.hibernate.dialect.PostgreSQLDialect

cheers.

how to clear JTable

I think you meant that you want to clear all the cells in the jTable and make it just like a new blank jTable. For an example, if your table is myTable, you can do following.

DefaultTableModel model = new DefaultTableModel();
myTable.setModel(model);

How many threads can a Java VM support?

I know this question is pretty old but just want to share my findings.

My laptop is able to handle program which spawns 25,000 threads and all those threads write some data in MySql database at regular interval of 2 seconds.

I ran this program with 10,000 threads for 30 minutes continuously then also my system was stable and I was able to do other normal operations like browsing, opening, closing other programs, etc.

With 25,000 threads system slows down but it remains responsive.

With 50,000 threads system stopped responding instantly and I had to restart my system manually.

My system details are as follows :

Processor : Intel core 2 duo 2.13 GHz
RAM : 4GB
OS : Windows 7 Home Premium
JDK Version : 1.6

Before running I set jvm argument -Xmx2048m.

Hope it helps.

Conditional WHERE clause with CASE statement in Oracle

You can write the where clause as:

where (case when (:stateCode = '') then (1)
            when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
            else 0)
       end) = 1;

Alternatively, remove the case entirely:

where (:stateCode = '') or
      ((:stateCode != '') and vw.state_cd in (:stateCode));

Or, even better:

where (:stateCode = '') or vw.state_cd in (:stateCode)

How to enable support of CPU virtualization on Macbook Pro?

Here is a way to check is virtualization is enabled or disabled by the firmware as suggested by this link in parallels.com.

How to check that Intel VT-x is supported in CPU:

  1. Open Terminal application from Application/Utilities

  2. Copy/paste command bellow

sysctl -a | grep machdep.cpu.features

  1. You may see output similar to:

Mac:~ user$ sysctl -a | grep machdep.cpu.features kern.exec: unknown type returned machdep.cpu.features: FPU VME DE PSE TSC MSR PAE MCE CX8 APIC SEP MTRR PGE MCA CMOV PAT CLFSH DS ACPI MMX FXSR SSE SSE2 SS HTT TM SSE3 MON VMX EST TM2 TPR PDCM

If you see VMX entry then CPU supports Intel VT-x feature, but it still may be disabled.

Refer to this link on Apple.com to enable hardware support for virtualization:

How can I get the domain name of my site within a Django template?

from django.contrib.sites.models import Site
if Site._meta.installed:
    site = Site.objects.get_current()
else:
    site = RequestSite(request)

Char Comparison in C

In C the char type has a numeric value so the > operator will work just fine for example

#include <stdio.h>
main() {

    char a='z';

    char b='h';

    if ( a > b ) {
        printf("%c greater than %c\n",a,b);
    }
}

Change onclick action with a Javascript function

Your code is calling the function and assigning the return value to onClick, also it should be 'onclick'. This is how it should look.

document.getElementById("a").onclick = Bar;

Looking at your other code you probably want to do something like this:

document.getElementById(id+"Button").onclick = function() { HideError(id); }

"A lambda expression with a statement body cannot be converted to an expression tree"

The LINQ to SQL return object were implementing IQueryable interface. So for Select method predicate parameter you should only supply single lambda expression without body.

This is because LINQ for SQL code is not execute inside program rather than on remote side like SQL server or others. This lazy loading execution type were achieve by implementing IQueryable where its expect delegate is being wrapped in Expression type class like below.

Expression<Func<TParam,TResult>>

Expression tree do not support lambda expression with body and its only support single line lambda expression like var id = cols.Select( col => col.id );

So if you try the following code won't works.

Expression<Func<int,int>> function = x => {
    return x * 2;
}

The following will works as per expected.

Expression<Func<int,int>> function = x => x * 2;

How to use OAuth2RestTemplate?

In the answer from @mariubog (https://stackoverflow.com/a/27882337/1279002) I was using password grant types too as in the example but needed to set the client authentication scheme to form. Scopes were not supported by the endpoint for password and there was no need to set the grant type as the ResourceOwnerPasswordResourceDetails object sets this itself in the constructor.

...

public ResourceOwnerPasswordResourceDetails() {
    setGrantType("password");
}

...

The key thing for me was the client_id and client_secret were not being added to the form object to post in the body if resource.setClientAuthenticationScheme(AuthenticationScheme.form); was not set.

See the switch in: org.springframework.security.oauth2.client.token.auth.DefaultClientAuthenticationHandler.authenticateTokenRequest()

Finally, when connecting to Salesforce endpoint the password token needed to be appended to the password.

@EnableOAuth2Client
@Configuration
class MyConfig {

@Value("${security.oauth2.client.access-token-uri}")
private String tokenUrl;

@Value("${security.oauth2.client.client-id}")
private String clientId;

@Value("${security.oauth2.client.client-secret}")
private String clientSecret;

@Value("${security.oauth2.client.password-token}")
private String passwordToken;

@Value("${security.user.name}")
private String username;

@Value("${security.user.password}")
private String password;


@Bean
protected OAuth2ProtectedResourceDetails resource() {

    ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();

    resource.setAccessTokenUri(tokenUrl);
    resource.setClientId(clientId);
    resource.setClientSecret(clientSecret);
    resource.setClientAuthenticationScheme(AuthenticationScheme.form);
    resource.setUsername(username);
    resource.setPassword(password + passwordToken);

    return resource;
}

@Bean
 public OAuth2RestOperations restTemplate() {
    return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(new DefaultAccessTokenRequest()));
    }
}


@Service
@SuppressWarnings("unchecked")
class MyService {
    @Autowired
    private OAuth2RestOperations restTemplate;

    public MyService() {
        restTemplate.getAccessToken();
    }
}

Android: How to create a Dialog without a title?

Set the title to empty string using builder.

    Builder builder = new AlertDialog.Builder(context);
    builder.setTitle("");
...
    builder.show();

.NET Global exception handler in console application

I just inherited an old VB.NET console application and needed to set up a Global Exception Handler. Since this question mentions VB.NET a few times and is tagged with VB.NET, but all the other answers here are in C#, I thought I would add the exact syntax for a VB.NET application as well.

Public Sub Main()
    REM Set up Global Unhandled Exception Handler.
    AddHandler System.AppDomain.CurrentDomain.UnhandledException, AddressOf MyUnhandledExceptionEvent

    REM Do other stuff
End Sub

Public Sub MyUnhandledExceptionEvent(ByVal sender As Object, ByVal e As UnhandledExceptionEventArgs)
    REM Log Exception here and do whatever else is needed
End Sub

I used the REM comment marker instead of the single quote here because Stack Overflow seemed to handle the syntax highlighting a bit better with REM.

What are WSDL, SOAP and REST?

Example: In a simple terms if you have a web service of calculator.

WSDL: WSDL tells about the functions that you can implement or exposed to the client. For example: add, delete, subtract and so on.

SOAP: Where as using SOAP you actually perform actions like doDelete(), doSubtract(), doAdd(). So SOAP and WSDL are apples and oranges. We should not compare them. They both have their own different functionality.

Why we use SOAP and WSDL: For platform independent data exchange.

EDIT: In a normal day to day life example:

WSDL: When we go to a restaurant we see the Menu Items, those are the WSDL's.

Proxy Classes: Now after seeing the Menu Items we make up our Mind (Process our mind on what to order): So, basically we make Proxy classes based on WSDL Document.

SOAP: Then when we actually order the food based on the Menu's: Meaning we use proxy classes to call upon the service methods which is done using SOAP. :)

How to get duration, as int milli's and float seconds from <chrono>?

I don't know what "milliseconds and float seconds" means, but this should give you an idea:

#include <chrono>
#include <thread>
#include <iostream>

int main()
{
  auto then = std::chrono::system_clock::now();
  std::this_thread::sleep_for(std::chrono::seconds(1));
  auto now = std::chrono::system_clock::now();
  auto dur = now - then;
  typedef std::chrono::duration<float> float_seconds;
  auto secs = std::chrono::duration_cast<float_seconds>(dur);
  std::cout << secs.count() << '\n';
}

Using Mockito to stub and execute methods for testing

You are confusing a Mock with a Spy.

In a mock all methods are stubbed and return "smart return types". This means that calling any method on a mocked class will do nothing unless you specify behaviour.

In a spy the original functionality of the class is still there but you can validate method invocations in a spy and also override method behaviour.

What you want is

MyProcessingAgent mockMyAgent = Mockito.spy(MyProcessingAgent.class);

A quick example:

static class TestClass {

    public String getThing() {
        return "Thing";
    }

    public String getOtherThing() {
        return getThing();
    }
}

public static void main(String[] args) {
    final TestClass testClass = Mockito.spy(new TestClass());
    Mockito.when(testClass.getThing()).thenReturn("Some Other thing");
    System.out.println(testClass.getOtherThing());
}

Output is:

Some Other thing

NB: You should really try to mock the dependencies for the class being tested not the class itself.

Difference Between Select and SelectMany

Select is a simple one-to-one projection from source element to a result element. Select- Many is used when there are multiple from clauses in a query expression: each element in the original sequence is used to generate a new sequence.

The process cannot access the file because it is being used by another process (File is created but contains nothing)

Try This

string path = @"c:\mytext.txt";

if (File.Exists(path))
{
    File.Delete(path);
}

{ // Consider File Operation 1
    FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
    StreamWriter str = new StreamWriter(fs);
    str.BaseStream.Seek(0, SeekOrigin.End);
    str.Write("mytext.txt.........................");
    str.WriteLine(DateTime.Now.ToLongTimeString() + " " + 
                  DateTime.Now.ToLongDateString());
    string addtext = "this line is added" + Environment.NewLine;
    str.Flush();
    str.Close();
    fs.Close();
    // Close the Stream then Individually you can access the file.
}

File.AppendAllText(path, addtext);  // File Operation 2

string readtext = File.ReadAllText(path); // File Operation 3

Console.WriteLine(readtext);

In every File Operation, The File will be Opened and must be Closed prior Opened. Like wise in the Operation 1 you must Close the File Stream for the Further Operations.

How to dockerize maven project? and how many ways to accomplish it?

Create a Dockerfile
#
# Build stage
#

FROM maven:3.6.3-jdk-11-slim AS build

WORKDIR usr/src/app

COPY . ./

RUN mvn clean package

#
# Package stage
#

FROM openjdk:11-jre-slim

ARG JAR_NAME="project-name"

WORKDIR /usr/src/app

EXPOSE ${HTTP_PORT}

COPY --from=build /usr/src/app/target/${JAR_NAME}.jar ./app.jar

CMD ["java","-jar", "./app.jar"]

Javascript .querySelector find <div> by innerTEXT

Since there are no limits to the length of text in a data attribute, use data attributes! And then you can use regular css selectors to select your element(s) like the OP wants.

_x000D_
_x000D_
for (const element of document.querySelectorAll("*")) {_x000D_
  element.dataset.myInnerText = element.innerText;_x000D_
}_x000D_
_x000D_
document.querySelector("*[data-my-inner-text='Different text.']").style.color="blue";
_x000D_
<div>SomeText, text continues.</div>_x000D_
<div>Different text.</div>
_x000D_
_x000D_
_x000D_

Ideally you do the data attribute setting part on document load and narrow down the querySelectorAll selector a bit for performance.

Check if textbox has empty value

if (inp.val().length > 0) {
    // do something
}

if you want anything more complicated, consider regex or use the validation plugin which takes care of this for you

NameError: name 'python' is not defined

When you run the Windows Command Prompt, and type in python, it starts the Python interpreter.

Typing it again tries to interpret python as a variable, which doesn't exist and thus won't work:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\USER>python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> python
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
>>> print("interpreter has started")
interpreter has started
>>> quit() # leave the interpreter, and go back to the command line

C:\Users\USER>

If you're not doing this from the command line, and instead running the Python interpreter (python.exe or IDLE's shell) directly, you are not in the Windows Command Line, and python is interpreted as a variable, which you have not defined.

Get CPU Usage from Windows Command Prompt

The following works correctly on Windows 7 Ultimate from an elevated command prompt:

C:\Windows\system32>typeperf "\Processor(_Total)\% Processor Time"

"(PDH-CSV 4.0)","\\vm\Processor(_Total)\% Processor Time"
"02/01/2012 14:10:59.361","0.648721"
"02/01/2012 14:11:00.362","2.986384"
"02/01/2012 14:11:01.364","0.000000"
"02/01/2012 14:11:02.366","0.000000"
"02/01/2012 14:11:03.367","1.038332"

The command completed successfully.

C:\Windows\system32>

Or for a snapshot:

C:\Windows\system32>wmic cpu get loadpercentage
LoadPercentage
8

Can I use CASE statement in a JOIN condition?

Took DonkeyKong's example.

The issue is I needed to use a declared variable. This allows for stating your left and right-hand side of what you need to compare. This is for supporting an SSRS report where different fields must be linked based on the selection by the user.

The initial case sets the field choice based on the selection and then I can set the field I need to match on for the join.

A second case statement could be added for the right-hand side if the variable is needed to choose from different fields

LEFT OUTER JOIN Dashboard_Group_Level_Matching ON
       case
         when @Level  = 'lvl1' then  cw.Lvl1
         when @Level  = 'lvl2' then  cw.Lvl2
         when @Level  = 'lvl3' then  cw.Lvl3
       end
    = Dashboard_Group_Level_Matching.Dashboard_Level_Name

How to create the most compact mapping n ? isprime(n) up to a limit N?

I compared the efficiency of the most popular suggestions to determine if a number is prime. I used python 3.6 on ubuntu 17.10; I tested with numbers up to 100.000 (you can test with bigger numbers using my code below).

This first plot compares the functions (which are explained further down in my answer), showing that the last functions do not grow as fast as the first one when increasing the numbers.

plot1

And in the second plot we can see that in case of prime numbers the time grows steadily, but non-prime numbers do not grow so fast in time (because most of them can be eliminated early on).

plot2

Here are the functions I used:

  1. this answer and this answer suggested a construct using all():

    def is_prime_1(n):
        return n > 1 and all(n % i for i in range(2, int(math.sqrt(n)) + 1))
    
  2. This answer used some kind of while loop:

    def is_prime_2(n):
        if n <= 1:
            return False
        if n == 2:
            return True
        if n == 3:
            return True
        if n % 2 == 0:
            return False
        if n % 3 == 0:
            return False
    
        i = 5
        w = 2
        while i * i <= n:
            if n % i == 0:
                return False
            i += w
            w = 6 - w
    
        return True
    
  3. This answer included a version with a for loop:

    def is_prime_3(n):
        if n <= 1:
            return False
    
        if n % 2 == 0 and n > 2:
            return False
    
        for i in range(3, int(math.sqrt(n)) + 1, 2):
            if n % i == 0:
                return False
    
        return True
    
  4. And I mixed a few ideas from the other answers into a new one:

    def is_prime_4(n):
        if n <= 1:          # negative numbers, 0 or 1
            return False
        if n <= 3:          # 2 and 3
            return True
        if n % 2 == 0 or n % 3 == 0:
            return False
    
        for i in range(5, int(math.sqrt(n)) + 1, 2):
            if n % i == 0:
                return False
    
        return True
    

Here is my script to compare the variants:

import math
import pandas as pd
import seaborn as sns
import time
from matplotlib import pyplot as plt


def is_prime_1(n):
    ...
def is_prime_2(n):
    ...
def is_prime_3(n):
    ...
def is_prime_4(n):
    ...

default_func_list = (is_prime_1, is_prime_2, is_prime_3, is_prime_4)

def assert_equal_results(func_list=default_func_list, n):
    for i in range(-2, n):
        r_list = [f(i) for f in func_list]
        if not all(r == r_list[0] for r in r_list):
            print(i, r_list)
            raise ValueError
    print('all functions return the same results for integers up to {}'.format(n))

def compare_functions(func_list=default_func_list, n):
    result_list = []
    n_measurements = 3

    for f in func_list:
        for i in range(1, n + 1):
            ret_list = []
            t_sum = 0
            for _ in range(n_measurements):
                t_start = time.perf_counter()
                is_prime = f(i)
                t_end = time.perf_counter()

                ret_list.append(is_prime)
                t_sum += (t_end - t_start)

            is_prime = ret_list[0]
            assert all(ret == is_prime for ret in ret_list)
            result_list.append((f.__name__, i, is_prime, t_sum / n_measurements))

    df = pd.DataFrame(
        data=result_list,
        columns=['f', 'number', 'is_prime', 't_seconds'])
    df['t_micro_seconds'] = df['t_seconds'].map(lambda x: round(x * 10**6, 2))
    print('df.shape:', df.shape)

    print()
    print('', '-' * 41)
    print('| {:11s} | {:11s} | {:11s} |'.format(
        'is_prime', 'count', 'percent'))
    df_sub1 = df[df['f'] == 'is_prime_1']
    print('| {:11s} | {:11,d} | {:9.1f} % |'.format(
        'all', df_sub1.shape[0], 100))
    for (is_prime, count) in df_sub1['is_prime'].value_counts().iteritems():
        print('| {:11s} | {:11,d} | {:9.1f} % |'.format(
            str(is_prime), count, count * 100 / df_sub1.shape[0]))
    print('', '-' * 41)

    print()
    print('', '-' * 69)
    print('| {:11s} | {:11s} | {:11s} | {:11s} | {:11s} |'.format(
        'f', 'is_prime', 't min (us)', 't mean (us)', 't max (us)'))
    for f, df_sub1 in df.groupby(['f', ]):
        col = df_sub1['t_micro_seconds']
        print('|{0}|{0}|{0}|{0}|{0}|'.format('-' * 13))
        print('| {:11s} | {:11s} | {:11.2f} | {:11.2f} | {:11.2f} |'.format(
            f, 'all', col.min(), col.mean(), col.max()))
        for is_prime, df_sub2 in df_sub1.groupby(['is_prime', ]):
            col = df_sub2['t_micro_seconds']
            print('| {:11s} | {:11s} | {:11.2f} | {:11.2f} | {:11.2f} |'.format(
                f, str(is_prime), col.min(), col.mean(), col.max()))
    print('', '-' * 69)

    return df

Running the function compare_functions(n=10**5) (numbers up to 100.000) I get this output:

df.shape: (400000, 5)

 -----------------------------------------
| is_prime    | count       | percent     |
| all         |     100,000 |     100.0 % |
| False       |      90,408 |      90.4 % |
| True        |       9,592 |       9.6 % |
 -----------------------------------------

 ---------------------------------------------------------------------
| f           | is_prime    | t min (us)  | t mean (us) | t max (us)  |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_1  | all         |        0.57 |        2.50 |      154.35 |
| is_prime_1  | False       |        0.57 |        1.52 |      154.35 |
| is_prime_1  | True        |        0.89 |       11.66 |       55.54 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_2  | all         |        0.24 |        1.14 |      304.82 |
| is_prime_2  | False       |        0.24 |        0.56 |      304.82 |
| is_prime_2  | True        |        0.25 |        6.67 |       48.49 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_3  | all         |        0.20 |        0.95 |       50.99 |
| is_prime_3  | False       |        0.20 |        0.60 |       40.62 |
| is_prime_3  | True        |        0.58 |        4.22 |       50.99 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_4  | all         |        0.20 |        0.89 |       20.09 |
| is_prime_4  | False       |        0.21 |        0.53 |       14.63 |
| is_prime_4  | True        |        0.20 |        4.27 |       20.09 |
 ---------------------------------------------------------------------

Then, running the function compare_functions(n=10**6) (numbers up to 1.000.000) I get this output:

df.shape: (4000000, 5)

 -----------------------------------------
| is_prime    | count       | percent     |
| all         |   1,000,000 |     100.0 % |
| False       |     921,502 |      92.2 % |
| True        |      78,498 |       7.8 % |
 -----------------------------------------

 ---------------------------------------------------------------------
| f           | is_prime    | t min (us)  | t mean (us) | t max (us)  |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_1  | all         |        0.51 |        5.39 |     1414.87 |
| is_prime_1  | False       |        0.51 |        2.19 |      413.42 |
| is_prime_1  | True        |        0.87 |       42.98 |     1414.87 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_2  | all         |        0.24 |        2.65 |      612.69 |
| is_prime_2  | False       |        0.24 |        0.89 |      322.81 |
| is_prime_2  | True        |        0.24 |       23.27 |      612.69 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_3  | all         |        0.20 |        1.93 |       67.40 |
| is_prime_3  | False       |        0.20 |        0.82 |       61.39 |
| is_prime_3  | True        |        0.59 |       14.97 |       67.40 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_4  | all         |        0.18 |        1.88 |      332.13 |
| is_prime_4  | False       |        0.20 |        0.74 |      311.94 |
| is_prime_4  | True        |        0.18 |       15.23 |      332.13 |
 ---------------------------------------------------------------------

I used the following script to plot the results:

def plot_1(func_list=default_func_list, n):
    df_orig = compare_functions(func_list=func_list, n=n)
    df_filtered = df_orig[df_orig['t_micro_seconds'] <= 20]
    sns.lmplot(
        data=df_filtered, x='number', y='t_micro_seconds',
        col='f',
        # row='is_prime',
        markers='.',
        ci=None)

    plt.ticklabel_format(style='sci', axis='x', scilimits=(3, 3))
    plt.show()

Flask at first run: Do not use the development server in a production environment

If for some people (like me earlier) the above answers don't work, I think the following answer would work (for Mac users I think) Enter the following commands to do flask run

$ export FLASK_APP = hello.py
$ export FLASK_ENV = development
$ flask run

Alternatively you can do the following (I haven't tried this but one resource online talks about it)

$ export FLASK_APP = hello.py
$ python -m flask run

source: For more

Rails: Get Client IP address

I found request.env['HTTP_X_FORWARDED_FOR'] very useful too in cases when request.remote_ip returns 127.0.0.1

SVN check out linux

There should be svn utility on you box, if installed:

$ svn checkout http://example.com/svn/somerepo somerepo

This will check out a working copy from a specified repository to a directory somerepo on our file system.

You may want to print commands, supported by this utility:

$ svn help

uname -a output in your question is identical to one, used by Parallels Virtuozzo Containers for Linux 4.0 kernel, which is based on Red Hat 5 kernel, thus your friends are rpm or the following command:

$ sudo yum install subversion

catching stdout in realtime from subprocess

To avoid caching of output you might wanna try pexpect,

child = pexpect.spawn(launchcmd,args,timeout=None)
while True:
    try:
        child.expect('\n')
        print(child.before)
    except pexpect.EOF:
        break

PS : I know this question is pretty old, still providing the solution which worked for me.

PPS: got this answer from another question

How can I set Image source with base64

Try using setAttribute instead:

document.getElementById('img')
    .setAttribute(
        'src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
    );

Real answer: (And make sure you remove the line-breaks in the base64.)

Java 8 - Difference between Optional.flatMap and Optional.map

What helped me was a look at the source code of the two functions.

Map - wraps the result in an Optional.

public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
    Objects.requireNonNull(mapper);
    if (!isPresent())
        return empty();
    else {
        return Optional.ofNullable(mapper.apply(value)); //<--- wraps in an optional
    }
}

flatMap - returns the 'raw' object

public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
    Objects.requireNonNull(mapper);
    if (!isPresent())
        return empty();
    else {
        return Objects.requireNonNull(mapper.apply(value)); //<---  returns 'raw' object
    }
}

How to change sa password in SQL Server 2008 express?

This is what worked for me:

  • Close all Sql Server referencing apps.
  • Open Services in Control Panel.
  • Find the "SQL Server (SQLEXPRESS)" entry and select properties.
  • Stop the service (all Sql Server services).
  • Enter "-m" at the Start parameters" fields.
  • Start the service (click on Start button on General Tab).
  • Open a Command Prompt (right click, Run as administrator if needed).
  • Enter the command:

    osql -S localhost\SQLEXPRESS -E

    (or change localhost to whatever your PC is called).

  • At the prompt type the following commands:

    CREATE LOGIN my_Login_here WITH PASSWORD = 'my_Password_here'

    go

    sp_addsrvrolemember 'my_Login_here', 'sysadmin'

    go

    quit

  • Stop the "SQL Server (SQLEXPRESS)" service.

  • Remove the "-m" from the Start parameters field (if still there).

  • Start the service.

  • In Management Studio, use the login and password you just created. This should give it admin permission.

Taking pictures with camera on Android programmatically

For those who came here looking for a way to take pictures/photos programmatically using both Android's Camera and Camera2 API, take a look at the open source sample provided by Google itself here.

Is it safe to use Project Lombok?

My take on Lombok is that it merely provides shortcuts for writing bolilerplate Java code.
When it comes to using shortcuts for writing bolilerplate Java code, I would rely on such features provided by IDE -- like in Eclipse, we can go to menu Source > Generate Getters and Setters for generating getters and setters.
I would not rely on a library like Lombok for this:

  1. It pollutes your code with an indirection layer of alternative syntax (read @Getter, @Setter, etc. annotations). Rather than learning an alternative syntax for Java, I would switch to any other language that natively provides Lombok like syntax.
  2. Lombok requires the use of a Lombok supported IDE to work with your code. This dependency introduces a considerable risk for any non-trivial project. Does the open source Lombok project have enough resources to keep providing support for different versions of a wide range of Java IDE's available?
  3. Does the open source Lombok project have enough resources to keep providing support for newer versions of Java that will be coming in future?
  4. I also feel nervous that Lombok may introduce compatibility issues with widely used frameworks/libraries (like Spring, Hibernate, Jackson, JUnit, Mockito) that work with your byte code at runtime.

All in all I would not prefer to "spice up" my Java with Lombok.

OWIN Security - How to Implement OAuth2 Refresh Tokens

I don't think that you should be using an array to maintain tokens. Neither you need a guid as a token.

You can easily use context.SerializeTicket().

See my below code.

public class RefreshTokenProvider : IAuthenticationTokenProvider
{
    public async Task CreateAsync(AuthenticationTokenCreateContext context)
    {
        Create(context);
    }

    public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
    {
        Receive(context);
    }

    public void Create(AuthenticationTokenCreateContext context)
    {
        object inputs;
        context.OwinContext.Environment.TryGetValue("Microsoft.Owin.Form#collection", out inputs);

        var grantType = ((FormCollection)inputs)?.GetValues("grant_type");

        var grant = grantType.FirstOrDefault();

        if (grant == null || grant.Equals("refresh_token")) return;

        context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(Constants.RefreshTokenExpiryInDays);

        context.SetToken(context.SerializeTicket());
    }

    public void Receive(AuthenticationTokenReceiveContext context)
    {
        context.DeserializeTicket(context.Token);

        if (context.Ticket == null)
        {
            context.Response.StatusCode = 400;
            context.Response.ContentType = "application/json";
            context.Response.ReasonPhrase = "invalid token";
            return;
        }

        if (context.Ticket.Properties.ExpiresUtc <= DateTime.UtcNow)
        {
            context.Response.StatusCode = 401;
            context.Response.ContentType = "application/json";
            context.Response.ReasonPhrase = "unauthorized";
            return;
        }

        context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(Constants.RefreshTokenExpiryInDays);
        context.SetTicket(context.Ticket);
    }
}

How to get the children of the $(this) selector?

If your img is exactly first element inside div then try

$(this.firstChild);

_x000D_
_x000D_
$( "#box" ).click( function() {_x000D_
  let img = $(this.firstChild);_x000D_
  console.log({img});_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="box"><img src="https://picsum.photos/seed/picsum/300/150"></div>
_x000D_
_x000D_
_x000D_

Angular 4 setting selected option in Dropdown

Lets see an example with Select control
binded to: $scope.cboPais,
source: $scope.geoPaises

HTML

<select 
  ng-model="cboPais"  
  ng-options="item.strPais for item in geoPaises"
  ></select>

JavaScript

$http.get(strUrl2).success(function (response) {
  if (response.length > 0) {
    $scope.geoPaises = response; //Data source
    nIndex = indexOfUnsortedArray(response, 'iPais', default_values.iPais); //array index of default value, using a custom function to search
    if (nIndex >= 0) {
      $scope.cboPais = response[nIndex]; //if index of array was found
    } else {
      $scope.cboPais = response[0]; //select the first element of array
    }
    $scope.geo_getDepartamentos();
  }
}

How to get the hours difference between two date objects?

Try using getTime (mdn doc) :

var diff = Math.abs(date1.getTime() - date2.getTime()) / 3600000;
if (diff < 18) { /* do something */ }

Using Math.abs() we don't know which date is the smallest. This code is probably more relevant :

var diff = (date1 - date2) / 3600000;
if (diff < 18) { array.push(date1); }

Why is my CSS style not being applied?

Clear the cache and cookies and restart the browser .As the style is not suppose to change frequently for a website browser kinda store it .

Working with select using AngularJS's ng-options

In CoffeeScript:

#directive
app.directive('select2', ->
    templateUrl: 'partials/select.html'
    restrict: 'E'
    transclude: 1
    replace: 1
    scope:
        options: '='
        model: '='
    link: (scope, el, atr)->
        el.bind 'change', ->
            console.log this.value
            scope.model = parseInt(this.value)
            console.log scope
            scope.$apply()
)
<!-- HTML partial -->
<select>
  <option ng-repeat='o in options'
          value='{{$index}}' ng-bind='o'></option>
</select>

<!-- HTML usage -->
<select2 options='mnuOffline' model='offlinePage.toggle' ></select2>

<!-- Conclusion -->
<p>Sometimes it's much easier to create your own directive...</p>

Portable way to check if directory exists [Windows/Linux, C]

You can use the GTK glib to abstract from OS stuff.

glib provides a g_dir_open() function which should do the trick.

How to make an HTTP POST web request

When using Windows.Web.Http namespace, for POST instead of FormUrlEncodedContent we write HttpFormUrlEncodedContent. Also the response is type of HttpResponseMessage. The rest is as Evan Mulawski wrote down.

Sheet.getRange(1,1,1,12) what does the numbers in bracket specify?

Found these docu on the google docu pages:

  • row --- int --- top row of the range
  • column --- int--- leftmost column of the range
  • optNumRows --- int --- number of rows in the range.
  • optNumColumns --- int --- number of columns in the range

In your example, you would get (if you picked the 3rd row) "C3:O3", cause C --> O is 12 columns

edit

Using the example on the docu:

// The code below will get the number of columns for the range C2:G8
// in the active spreadsheet, which happens to be "4"
var count = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getNumColumns(); Browser.msgBox(count);

The values between brackets:
2: the starting row = 2
3: the starting col = C
6: the number of rows = 6 so from 2 to 8
4: the number of cols = 4 so from C to G

So you come to the range: C2:G8

How to convert date into this 'yyyy-MM-dd' format in angular 2

_x000D_
_x000D_
const formatDate=(dateObj)=>{
const days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
const months = ["January","February","March","April","May","June","July","August","September","October","November","December"];

const dateOrdinal=(dom)=> {
    if (dom == 31 || dom == 21 || dom == 1) return dom + "st";
    else if (dom == 22 || dom == 2) return dom + "nd";
    else if (dom == 23 || dom == 3) return dom + "rd";
    else return dom + "th";
};
return dateOrdinal(dateObj.getDate())+', '+days[dateObj.getDay()]+' '+ months[dateObj.getMonth()]+', '+dateObj.getFullYear();
}
const ddate = new Date();
const result=formatDate(ddate)
document.getElementById("demo").innerHTML = result
_x000D_
<!DOCTYPE html>
<html>
<body>
<h2>Example:20th, Wednesday September, 2020 <h2>
<p id="demo"></p>
</body>
</html>
_x000D_
_x000D_
_x000D_

jQuery Multiple ID selectors

Make sure upload plugin implements this.each in it so that it will execute the logic for all the matching elements. It should ideally work

$("#upload_link,#upload_link2,#upload_link3").upload(function(){ });

Android WSDL/SOAP service client

private static  final  String NAMESPACE = "http://tempuri.org/";
private static  final String URL = "http://example.com/CRM/Service.svc";
private static  final  String SOAP_ACTION = "http://tempuri.org/Login";
private static  final String METHOD_NAME = "Login";


//calling web services method

String loginresult=callService(username,password,usertype);


//calling webservices
String callService(String a1,String b1,Integer c1) throws Exception {

            Boolean flag=true;
            do
            {
                try{
                    System.out.println(flag);

                SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

                PropertyInfo pa1 = new PropertyInfo();
                pa1.setName("Username");
                pa1.setValue(a1.toString());

                PropertyInfo pb1 = new PropertyInfo();
                pb1.setName("Password");
                pb1.setValue(b1.toString());

                PropertyInfo pc1 = new PropertyInfo();
                pc1.setName("UserType");
                pc1.setValue(c1);
                System.out.println(c1+"this is integer****s");




                System.out.println("new");
                request.addProperty(pa1);
                request.addProperty(pb1);
                request.addProperty(pc1);



                System.out.println("new2");
                SoapSerializationEnvelope envelope = new    SoapSerializationEnvelope(SoapEnvelope.VER11);
                envelope.dotNet = true;
                System.out.println("new3");
                envelope.setOutputSoapObject(request);
                HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
                androidHttpTransport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                System.out.println("new4");
                try{
                androidHttpTransport.call(SOAP_ACTION, envelope);
                }
                catch(Exception e)
                {

                    System.out.println(e+"   this is exception");
                }
                System.out.println("new5");
                SoapObject response = (SoapObject)envelope.bodyIn;

                result = response.getProperty(0).toString(); 

                flag=false;
                System.out.println(flag);
                }catch (Exception e) {
                // TODO: handle exception
                    flag=false;
            }
            }
            while(flag);
            return result;

        }  
///

Should I use window.navigate or document.location in JavaScript?

window.navigate is NOT supported in some browsers, so that one should be avoided. Any of the other methods using the location property are the most reliable and consistent approach

Curl not recognized as an internal or external command, operable program or batch file

Method 1:\

add "C:\Program Files\cURL\bin" path into system variables Path right-click My Computer and click Properties >advanced > Environment Variables enter image description here

Method 2: (if method 1 not work then)

simple open command prompt with "run as administrator"

How to apply filters to *ngFor?

This is your array

products: any = [
        {
            "name": "John-Cena",
                    },
        {
            "name": "Brock-Lensar",

        }
    ];

This is your ngFor loop Filter By :

<input type="text" [(ngModel)]='filterText' />
    <ul *ngFor='let product of filterProduct'>
      <li>{{product.name }}</li>
    </ul>

There I'm using filterProduct instant of products, because i want to preserve my original data. Here model _filterText is used as a input box.When ever there is any change setter function will call. In setFilterText performProduct is called it will return the result only those who match with the input. I'm using lower case for case insensitive.

filterProduct = this.products;
_filterText : string;
    get filterText() : string {
        return this._filterText;
    }

    set filterText(value : string) {
        this._filterText = value;
        this.filterProduct = this._filterText ? this.performProduct(this._filterText) : this.products;

    } 

    performProduct(value : string ) : any {
            value = value.toLocaleLowerCase();
            return this.products.filter(( products : any ) => 
                products.name.toLocaleLowerCase().indexOf(value) !== -1);
        }

How to combine multiple inline style objects?

If you're using React Native, you can use the array notation:

<View style={[styles.base, styles.background]} />

Check out my detailed blog post about this.

How do you change the width and height of Twitter Bootstrap's tooltips?

Set the class to the main tooltip div and for the inner tooltip

div.tooltip {
    width: 270px;
}

div.tooltip-inner {
    max-width: 280px;
}

How to connect to Oracle 11g database remotely

You will need to run the lsnrctl utility on server A to start the listener. You would then connect from computer B using the following syntax:

sqlplus username/password@hostA:1521 /XE

The port information is optional if the default of 1521 is used.

Listener configuration documentation here. Remote connection documentation here.

How can I combine hashes in Perl?

Check out perlfaq4: How do I merge two hashes. There is a lot of good information already in the Perl documentation and you can have it right away rather than waiting for someone else to answer it. :)


Before you decide to merge two hashes, you have to decide what to do if both hashes contain keys that are the same and if you want to leave the original hashes as they were.

If you want to preserve the original hashes, copy one hash (%hash1) to a new hash (%new_hash), then add the keys from the other hash (%hash2 to the new hash. Checking that the key already exists in %new_hash gives you a chance to decide what to do with the duplicates:

my %new_hash = %hash1; # make a copy; leave %hash1 alone

foreach my $key2 ( keys %hash2 )
    {
    if( exists $new_hash{$key2} )
        {
        warn "Key [$key2] is in both hashes!";
        # handle the duplicate (perhaps only warning)
        ...
        next;
        }
    else
        {
        $new_hash{$key2} = $hash2{$key2};
        }
    }

If you don't want to create a new hash, you can still use this looping technique; just change the %new_hash to %hash1.

foreach my $key2 ( keys %hash2 )
    {
    if( exists $hash1{$key2} )
        {
        warn "Key [$key2] is in both hashes!";
        # handle the duplicate (perhaps only warning)
        ...
        next;
        }
    else
        {
        $hash1{$key2} = $hash2{$key2};
        }
    }

If you don't care that one hash overwrites keys and values from the other, you could just use a hash slice to add one hash to another. In this case, values from %hash2 replace values from %hash1 when they have keys in common:

@hash1{ keys %hash2 } = values %hash2;

don't fail jenkins build if execute shell fails

Jenkins is executing shell build steps using /bin/sh -xe by default. -x means to print every command executed. -e means to exit with failure if any of the commands in the script failed.

So I think what happened in your case is your git command exit with 1, and because of the default -e param, the shell picks up the non-0 exit code, ignores the rest of the script and marks the step as a failure. We can confirm this if you can post your build step script here.

If that's the case, you can try to put #!/bin/sh so that the script will be executed without option; or do a set +e or anything similar on top of the build step to override this behavior.


Edited: Another thing to note is that, if the last command in your shell script returns non-0 code, the whole build step will still be marked as fail even with this setup. In this case, you can simply put a true command at the end to avoid that.

Another related question

How to check for null in a single statement in scala?

Option(getObject) foreach (QueueManager add)

Data binding for TextBox

We can use following code

textBox1.DataBindings.Add("Text", model, "Name", false, DataSourceUpdateMode.OnPropertyChanged);

Where

  • "Text" – the property of textbox
  • model – the model object enter code here
  • "Name" – the value of model which to bind the textbox.

How to define multiple CSS attributes in jQuery?

Better to just use .addClass() and .removeClass() even if you have 1 or more styles to change. It's more maintainable and readable.

If you really have the urge to do multiple CSS properties, then use the following:

.css({
   'font-size' : '10px',
   'width' : '30px',
   'height' : '10px'
});

NB!
Any CSS properties with a hyphen need to be quoted.
I've placed the quotes so no one will need to clarify that, and the code will be 100% functional.

Loading cross-domain endpoint with AJAX

To get the data form external site by passing using a local proxy as suggested by jherax you can create a php page that fetches the content for you from respective external url and than send a get request to that php page.

var req = new XMLHttpRequest();
req.open('GET', 'http://localhost/get_url_content.php',false);
if(req.status == 200) {
   alert(req.responseText);
}

as a php proxy you can use https://github.com/cowboy/php-simple-proxy

How do you programmatically update query params in react-router?

Within the push method of hashHistory, you can specify your query parameters. For instance,

history.push({
  pathname: '/dresses',
  search: '?color=blue'
})

or

history.push('/dresses?color=blue')

You can check out this repository for additional examples on using history

How to convert ZonedDateTime to Date?

If you are using the ThreeTen backport for Android and can't use the newer Date.from(Instant instant) (which requires minimum of API 26) you can use:

ZonedDateTime zdt = ZonedDateTime.now();
Date date = new Date(zdt.toInstant().toEpochMilli());

or:

Date date = DateTimeUtils.toDate(zdt.toInstant());

Please also read the advice in Basil Bourque's answer

how to set the default value to the drop down list control?

if you know the index of the item of default value,just

lstDepartment.SelectedIndex = 1;//the second item

or if you know the value you want to set, just

lstDepartment.SelectedValue = "the value you want to set";

How to set the locale inside a Debian/Ubuntu Docker container?

@Mixel's answer worked great for the Ubuntu-based docker image we have.

However, we also have a centos-based docker image for testing recipes via chef (using the kitchen-docker driver). One of the packages we pre-install was failing to install due to no locale being set. In order to get a locale installed, I had to run the following:

localedef -c -f UTF-8 -i en_US en_US.UTF-8
export LC_ALL=en_US.UTF-8

I got this information from this answer on ServerFault.

After running the above commands as part of the docker provisioning the package installed without any errors. From .kitchen.yml:

platforms:
  - name: centos7
    driver_config:
      image: #(private image)
      platform: centos
      provision_command:
      - localedef -c -f UTF-8 -i en_US en_US.UTF-8
      - export LC_ALL=en_US.UTF-8

Python: Finding differences between elements of a list

If you don't want to use numpy nor zip, you can use the following solution:

>>> t = [1, 3, 6]
>>> v = [t[i+1]-t[i] for i in range(len(t)-1)]
>>> v
[2, 3]

How to use workbook.saveas with automatic Overwrite

I recommend that before executing SaveAs, delete the file it exists.

If Dir("f:ull\path\with\filename.xls") <> "" Then
    Kill "f:ull\path\with\filename.xls"
End If

It's easier than setting DisplayAlerts off and on, plus if DisplayAlerts remains off due to code crash, it can cause problems if you work with Excel in the same session.

Why is using the JavaScript eval function a bad idea?

eval isn't always evil. There are times where it's perfectly appropriate.

However, eval is currently and historically massively over-used by people who don't know what they're doing. That includes people writing JavaScript tutorials, unfortunately, and in some cases this can indeed have security consequences - or, more often, simple bugs. So the more we can do to throw a question mark over eval, the better. Any time you use eval you need to sanity-check what you're doing, because chances are you could be doing it a better, safer, cleaner way.

To give an all-too-typical example, to set the colour of an element with an id stored in the variable 'potato':

eval('document.' + potato + '.style.color = "red"');

If the authors of the kind of code above had a clue about the basics of how JavaScript objects work, they'd have realised that square brackets can be used instead of literal dot-names, obviating the need for eval:

document[potato].style.color = 'red';

...which is much easier to read as well as less potentially buggy.

(But then, someone who /really/ knew what they were doing would say:

document.getElementById(potato).style.color = 'red';

which is more reliable than the dodgy old trick of accessing DOM elements straight out of the document object.)

How to dynamically add a style for text-align using jQuery

function add_question(){ var count=document.getElementById("nofquest").value; var container = document.getElementById("container"); // Clear previous contents of the container while (container.hasChildNodes()) { container.removeChild(container.lastChild); } for (i=1;i

how to set center of the textboxes

Find all files in a folder

First off; best practice would be to get the users Desktop folder with

string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

Then you can find all the files with something like

string[] files = Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories);

Note that with the above line you will find all files with a .txt extension in the Desktop folder of the logged in user AND all subfolders.

Then you could copy or move the files by enumerating the above collection like

// For copying...
foreach (string s in files)
{
   File.Copy(s, "C:\newFolder\newFilename.txt");
}

// ... Or for moving
foreach (string s in files)
{
   File.Move(s, "C:\newFolder\newFilename.txt");
}

Please note that you will have to include the filename in your Copy() (or Move()) operation. So you would have to find a way to determine the filename of at least the extension you are dealing with and not name all the files the same like what would happen in the above example.

With that in mind you could also check out the DirectoryInfo and FileInfo classes. These work in similair ways, but you can get information about your path-/filenames, extensions, etc. more easily

Check out these for more info:

http://msdn.microsoft.com/en-us/library/system.io.directory.aspx

http://msdn.microsoft.com/en-us/library/ms143316.aspx

http://msdn.microsoft.com/en-us/library/system.io.file.aspx

how to use List<WebElement> webdriver

List<WebElement> myElements = driver.findElements(By.xpath("some/path//a"));
        System.out.println("Size of List: "+myElements.size());
        for(WebElement e : myElements) 
        {        
            System.out.print("Text within the Anchor tab"+e.getText()+"\t");
            System.out.println("Anchor: "+e.getAttribute("href"));
        }

//NOTE: "//a" will give you all the anchors there on after the point your XPATH has reached.

How to overload __init__ method based on argument type?

Excellent question. I've tackled this problem as well, and while I agree that "factories" (class-method constructors) are a good method, I would like to suggest another, which I've also found very useful:

Here's a sample (this is a read method and not a constructor, but the idea is the same):

def read(self, str=None, filename=None, addr=0):
    """ Read binary data and return a store object. The data
        store is also saved in the interal 'data' attribute.

        The data can either be taken from a string (str 
        argument) or a file (provide a filename, which will 
        be read in binary mode). If both are provided, the str 
        will be used. If neither is provided, an ArgumentError 
        is raised.
    """
    if str is None:
        if filename is None:
            raise ArgumentError('Please supply a string or a filename')

        file = open(filename, 'rb')
        str = file.read()
        file.close()
    ...
    ... # rest of code

The key idea is here is using Python's excellent support for named arguments to implement this. Now, if I want to read the data from a file, I say:

obj.read(filename="blob.txt")

And to read it from a string, I say:

obj.read(str="\x34\x55")

This way the user has just a single method to call. Handling it inside, as you saw, is not overly complex

How to place Text and an Image next to each other in HTML?

img {
    float:left;
}
h3 {
    float:right;
}

jsFiddle example

Note that you will probably want to use the style clear:both on whatever elements comes after the code you provided so that it doesn't slide up directly beneath the floated elements.

How to call multiple functions with @click in vue?

Separate into pieces.

Inline:

<div @click="f1() + f2()"></div> 

OR: Through a composite function:

<div @click="f3()"></div> 

<script>
var app = new Vue({
  // ...
  methods: {
    f3: function() { f1() + f2(); }
    f1: function() {},
    f2: function() {}
  }
})
</script>

How to fix the "508 Resource Limit is reached" error in WordPress?

Actually it happens when the number of processes exceeds the limits set by the hosting provider.

To avoid either we need to enhance the capacity by hosting providers or we need to check in the code whether any process takes longer time (like background tasks).

Way to get all alphabetic chars in an array in PHP?

$alphabet = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');

Python: 'ModuleNotFoundError' when trying to import module from imported package

FIRST, if you want to be able to access man1.py from man1test.py AND manModules.py from man1.py, you need to properly setup your files as packages and modules.

Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A.

...

When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

You need to set it up to something like this:

man
|- __init__.py
|- Mans
   |- __init__.py
   |- man1.py
|- MansTest
   |- __init.__.py
   |- SoftLib
      |- Soft
         |- __init__.py
         |- SoftWork
            |- __init__.py
            |- manModules.py
      |- Unittests
         |- __init__.py
         |- man1test.py

SECOND, for the "ModuleNotFoundError: No module named 'Soft'" error caused by from ...Mans import man1 in man1test.py, the documented solution to that is to add man1.py to sys.path since Mans is outside the MansTest package. See The Module Search Path from the Python documentation. But if you don't want to modify sys.path directly, you can also modify PYTHONPATH:

sys.path is initialized from these locations:

  • The directory containing the input script (or the current directory when no file is specified).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • The installation-dependent default.

THIRD, for from ...MansTest.SoftLib import Soft which you said "was to facilitate the aforementioned import statement in man1.py", that's now how imports work. If you want to import Soft.SoftLib in man1.py, you have to setup man1.py to find Soft.SoftLib and import it there directly.

With that said, here's how I got it to work.

man1.py:

from Soft.SoftWork.manModules import *
# no change to import statement but need to add Soft to PYTHONPATH

def foo():
    print("called foo in man1.py")
    print("foo call module1 from manModules: " + module1())

man1test.py

# no need for "from ...MansTest.SoftLib import Soft" to facilitate importing..
from ...Mans import man1

man1.foo()

manModules.py

def module1():
    return "module1 in manModules"

Terminal output:

$ python3 -m man.MansTest.Unittests.man1test
Traceback (most recent call last):
  ...
    from ...Mans import man1
  File "/temp/man/Mans/man1.py", line 2, in <module>
    from Soft.SoftWork.manModules import *
ModuleNotFoundError: No module named 'Soft'

$ PYTHONPATH=$PYTHONPATH:/temp/man/MansTest/SoftLib
$ export PYTHONPATH
$ echo $PYTHONPATH
:/temp/man/MansTest/SoftLib
$ python3 -m man.MansTest.Unittests.man1test
called foo in man1.py
foo called module1 from manModules: module1 in manModules 

As a suggestion, maybe re-think the purpose of those SoftLib files. Is it some sort of "bridge" between man1.py and man1test.py? The way your files are setup right now, I don't think it's going to work as you expect it to be. Also, it's a bit confusing for the code-under-test (man1.py) to be importing stuff from under the test folder (MansTest).

Simple export and import of a SQLite database on Android

This is a simple method to export the database to a folder named backup folder you can name it as you want and a simple method to import the database from the same folder a

    public class ExportImportDB extends Activity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
//creating a new folder for the database to be backuped to
            File direct = new File(Environment.getExternalStorageDirectory() + "/Exam Creator");

               if(!direct.exists())
                {
                    if(direct.mkdir()) 
                      {
                       //directory is created;
                      }

                }
            exportDB();
            importDB();

        }
    //importing database
        private void importDB() {
            // TODO Auto-generated method stub

            try {
                File sd = Environment.getExternalStorageDirectory();
                File data  = Environment.getDataDirectory();

                if (sd.canWrite()) {
                    String  currentDBPath= "//data//" + "PackageName"
                            + "//databases//" + "DatabaseName";
                    String backupDBPath  = "/BackupFolder/DatabaseName";
                    File  backupDB= new File(data, currentDBPath);
                    File currentDB  = new File(sd, backupDBPath);

                    FileChannel src = new FileInputStream(currentDB).getChannel();
                    FileChannel dst = new FileOutputStream(backupDB).getChannel();
                    dst.transferFrom(src, 0, src.size());
                    src.close();
                    dst.close();
                    Toast.makeText(getBaseContext(), backupDB.toString(),
                            Toast.LENGTH_LONG).show();

                }
            } catch (Exception e) {

                Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
                        .show();

            }
        }
    //exporting database 
        private void exportDB() {
            // TODO Auto-generated method stub

            try {
                File sd = Environment.getExternalStorageDirectory();
                File data = Environment.getDataDirectory();

                if (sd.canWrite()) {
                    String  currentDBPath= "//data//" + "PackageName"
                            + "//databases//" + "DatabaseName";
                    String backupDBPath  = "/BackupFolder/DatabaseName";
                    File currentDB = new File(data, currentDBPath);
                    File backupDB = new File(sd, backupDBPath);

                    FileChannel src = new FileInputStream(currentDB).getChannel();
                    FileChannel dst = new FileOutputStream(backupDB).getChannel();
                    dst.transferFrom(src, 0, src.size());
                    src.close();
                    dst.close();
                    Toast.makeText(getBaseContext(), backupDB.toString(),
                            Toast.LENGTH_LONG).show();

                }
            } catch (Exception e) {

                Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
                        .show();

            }
        }

    }

Dont forget to add this permission to proceed it

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

Enjoy

CSS3 selector :first-of-type with class name?

Not sure how to explain this but I ran into something similar today. Not being able to set .user:first-of-type{} while .user:last-of-type{} worked fine. This was fixed after I wrapped them inside a div without any class or styling:

https://codepen.io/adrianTNT/pen/WgEpbE

<style>
.user{
  display:block;
  background-color:#FFCC00;
}

.user:first-of-type{
  background-color:#FF0000;
}
</style>

<p>Not working while this P additional tag exists</p>

<p class="user">A</p>
<p class="user">B</p>
<p class="user">C</p>

<p>Working while inside a div:</p>

<div>
<p class="user">A</p>
<p class="user">B</p>
<p class="user">C</p>
</div>

How do I get a string format of the current date time, in python?

You can use the datetime module for working with dates and times in Python. The strftime method allows you to produce string representation of dates and times with a format you specify.

>>> import datetime
>>> datetime.date.today().strftime("%B %d, %Y")
'July 23, 2010'
>>> datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")
'10:36AM on July 23, 2010'

How to solve error: "Clock skew detected"?

please try to do

make clean

(instead of make), then

make

again.

Graph implementation C++

There can be an even simpler representation assuming that one has to only test graph algorithms not use them(graph) else where. This can be as a map from vertices to their adjacency lists as shown below :-

#include<bits/stdc++.h>
using namespace std;

/* implement the graph as a map from the integer index as a key to the   adjacency list
 * of the graph implemented as a vector being the value of each individual key. The
 * program will be given a matrix of numbers, the first element of each row will
 * represent the head of the adjacency list and the rest of the elements will be the
 * list of that element in the graph.
*/

typedef map<int, vector<int> > graphType;

int main(){

graphType graph;
int vertices = 0;

cout << "Please enter the number of vertices in the graph :- " << endl;
cin >> vertices;
if(vertices <= 0){
    cout << "The number of vertices in the graph can't be less than or equal to 0." << endl;
    exit(0);
}

cout << "Please enter the elements of the graph, as an adjacency list, one row after another. " << endl;
for(int i = 0; i <= vertices; i++){

    vector<int> adjList;                    //the vector corresponding to the adjacency list of each vertex

    int key = -1, listValue = -1;
    string listString;
    getline(cin, listString);
    if(i != 0){
        istringstream iss(listString);
        iss >> key;
        iss >> listValue;
        if(listValue != -1){
            adjList.push_back(listValue);
            for(; iss >> listValue; ){
                adjList.push_back(listValue);
            }
            graph.insert(graphType::value_type(key, adjList));
        }
        else
            graph.insert(graphType::value_type(key, adjList));
    }
}

//print the elements of the graph
cout << "The graph that you entered :- " << endl;
for(graphType::const_iterator iterator = graph.begin(); iterator != graph.end(); ++iterator){
    cout << "Key : " << iterator->first << ", values : ";

    vector<int>::const_iterator vectBegIter = iterator->second.begin();
    vector<int>::const_iterator vectEndIter = iterator->second.end();
    for(; vectBegIter != vectEndIter; ++vectBegIter){
        cout << *(vectBegIter) << ", ";
    }
    cout << endl;
}
}

How to make java delay for a few seconds?

Use Thread.sleep(2000); //2000 for 2 seconds

Python/Django: log to console under runserver, log to file under Apache

Text printed to stderr will show up in httpd's error log when running under mod_wsgi. You can either use print directly, or use logging instead.

print >>sys.stderr, 'Goodbye, cruel world!'

Reset identity seed after deleting records in SQL Server

Reset identity column with new id...

DECLARE @MAX INT
SELECT @MAX=ISNULL(MAX(Id),0) FROM [TestTable]

DBCC CHECKIDENT ('[TestTable]', RESEED,@MAX)

How can I prevent the backspace key from navigating back?

A more elegant/concise solution:

$(document).on('keydown',function(e){
  var $target = $(e.target||e.srcElement);
  if(e.keyCode == 8 && !$target.is('input,[contenteditable="true"],textarea'))
  {
    e.preventDefault();
  }
})

Adding an onclick function to go to url in JavaScript?

try

location = url;

_x000D_
_x000D_
function url() {_x000D_
    location = 'https://example.com';_x000D_
}
_x000D_
<input type="button" value="Inline" _x000D_
onclick="location='https://example.com'" />_x000D_
_x000D_
<input type="button" value="URL()" _x000D_
onclick="url()" />
_x000D_
_x000D_
_x000D_

Logout button php

Instead of a button, put a link and navigate it to another page

<a href="logout.php">Logout</a>

Then in logout.php page, use

session_start();
session_destroy();
header('Location: login.php');
exit;

Define the selected option with the old input in Laravel / Blade

Laravel 6 or above: just use the old() function for instance @if (old('cat')==$cat->id), it will do the rest of the work for you.

How its works: select tag store the selected option value into its name attribute in bellow case if you select any option it will store into cat. At the first time when page loaded there is nothing inside cat, when user chose a option the value of that selected option is stored into cat so when user were redirected old() function pull the previous value from cat.

 {!!Form::open(['action'=>'CategoryController@storecat', 'method'=>'POST']) !!}
        <div class="form-group">
            <select name="cat" id="cat" class="form-control input-lg">
                <option value="">Select App</option>
                @foreach ($cats as $cat)
                    @if (old('cat')==$cat->id)
                        <option value={{$cat->id}} selected>{{ $cat->title }}</option>
                    @else
                        <option value={{$cat->id}} >{{ $cat->title }}</option>
                    @endif
                @endforeach
            </select>
        </div>

        <div class="from-group">
            {{Form::label('name','Category name:')}}
            {{Form::text('name','',['class'=>'form-control', 'placeholder'=>'Category name'])}}
        </div>
    <br>
    {!!Form::submit('Submit', ['class'=>'btn btn-primary'])!!}
    {!!Form::close()!!}

How to disable clicking inside div

If you want it in pure CSS:

pointer-events:none;

How to get a microtime in Node.js?

A rewrite to help quick understanding:

const hrtime = process.hrtime();     // [0] is seconds, [1] is nanoseconds

let nanoSeconds = (hrtime[0] * 1e9) + hrtime[1];    // 1 second is 1e9 nano seconds
console.log('nanoSeconds:  ' + nanoSeconds);
//nanoSeconds:  97760957504895

let microSeconds = parseInt(((hrtime[0] * 1e6) + (hrtime[1]) * 1e-3));
console.log('microSeconds: ' + microSeconds);
//microSeconds: 97760957504

let milliSeconds = parseInt(((hrtime[0] * 1e3) + (hrtime[1]) * 1e-6));
console.log('milliSeconds: ' + milliSeconds);
//milliSeconds: 97760957

Source: https://nodejs.org/api/process.html#process_process_hrtime_time

Replace words in the body text

I was trying to replace a really large string and for some reason regular expressions were throwing some errors/exceptions.

So I found this alternative to regular expressions which also runs pretty fast. At least it was fast enough for me:

var search = "search string";
var replacement = "replacement string";

document.body.innerHTML = document.body.innerHTML.split(search).join(replacement)

src: How to replace all occurrences of a string in JavaScript?

How to set image to fit width of the page using jsPDF?

The API changed since this commit, using version 1.4.1 it's now

var width = pdf.internal.pageSize.getWidth();
var height = pdf.internal.pageSize.getHeight();

querySelectorAll with multiple conditions

According to the documentation, just like with any css selector, you can specify as many conditions as you want, and they are treated as logical 'OR'.

This example returns a list of all div elements within the document with a class of either "note" or "alert":

var matches = document.querySelectorAll("div.note, div.alert");

source: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

Meanwhile to get the 'AND' functionality you can for example simply use a multiattribute selector, as jquery says:

https://api.jquery.com/multiple-attribute-selector/

ex. "input[id][name$='man']" specifies both id and name of the element and both conditions must be met. For classes it's as obvious as ".class1.class2" to require object of 2 classes.

All possible combinations of both are valid, so you can easily get equivalent of more sophisticated 'OR' and 'AND' expressions.

How to send a POST request in Go?

You have mostly the right idea, it's just the sending of the form that is wrong. The form belongs in the body of the request.

req, err := http.NewRequest("POST", url, strings.NewReader(form.Encode()))

How to remove numbers from string using Regex.Replace?

the best design is:

public static string RemoveIntegers(this string input)
    {
        return Regex.Replace(input, @"[\d-]", string.Empty);
    }

Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ' '

For the OP's command:

select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0,  Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from  #tmp_CTF** 

I get this error:

Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.

when debugging something like this split the long line up so you'll get a better row number:

select compid
,2
, convert(datetime
, '01/01/' 
+ CONVERT(char(4)
,cal_yr) 
,101) 
,0
,  Update_dt
, th1
, th2
, th3_pc 
, Update_id
, Update_dt
,1
from  #tmp_CTF** 

this now results in:

Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.

which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:

from [#tmp_CTF**]

if that is the table name.

Untrack files from git temporarily

An alternative to assume-unchanged is skip-worktree. The latter has a different meaning, something like "Git should not track this file. Developers can, and are encouraged, to make local changes."

In your situation where you do not wish to track changes to (typically large) build files, assume-unchanged is a good choice.

In the situation where the file should have default contents and the developer is free to modify the file locally, but should not check their local changes back to the remote repo, skip-worktree is a better choice.

Another elegant option is to have a default file in the repo. Say the filename is BuildConfig.Default.cfg. The developer is expected to rename this locally to BuildConfig.cfg and they can make whatever local changes they need. Now add BuildConfig.cfg to .gitignore so the file is untracked.

See this question which has some nice background information in the accepted answer.

How to install MySQLi on MacOS

Since many of these answers are old here is how to install mysqli for Easyapache 4.

If you try and search for mysqli under your PHP extensions in WHM you are not going to find it. The way to know which extension you need to install mysqli you will need to run this command in terminal

repoquery -q --whatprovides 'ea-php70-php-mysqli' | sort -V | tail -1

Should return something like

ea-php70-php-mysqlnd-0:7.0.33-1.1.4.cpanel.x86_64

All you really need from this is mysqlnd copy it

To install mysqli using EachApache4:

  • Login to WHM.
  • Search for "EasyApache4"
  • At the top look for "Currently Installed Packages" and click on the button "Customize"
  • On the left panel click "PHP Extensions"
  • Search for mysqlnd
  • You should see something like "php70-php-mysqlnd"
  • Toggle the switch to enable it
  • On the left panel click on review
  • At the bottom click "Provision"
  • You're Done

Lombok annotations do not compile under Intellij idea

I followed this procedure to get ride of a similar/same error.

mvn idea:clean

mvn idea:idea

After that I could build both from the IDE intellij and from command line.

get name of a variable or parameter

Pre C# 6.0 solution

You can use this to get a name of any provided member:

public static class MemberInfoGetting
{
    public static string GetMemberName<T>(Expression<Func<T>> memberExpression)
    {
        MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
        return expressionBody.Member.Name;
    }
}

To get name of a variable:

string testVariable = "value";
string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => testVariable);

To get name of a parameter:

public class TestClass
{
    public void TestMethod(string param1, string param2)
    {
        string nameOfParam1 = MemberInfoGetting.GetMemberName(() => param1);
    }
}

C# 6.0 and higher solution

You can use the nameof operator for parameters, variables and properties alike:

string testVariable = "value";
string nameOfTestVariable = nameof(testVariable);

Getting and removing the first character of a string

removing first characters:

x <- 'hello stackoverflow'
substring(x, 2, nchar(x))

Idea is select all characters starting from 2 to number of characters in x. This is important when you have unequal number of characters in word or phrase.

Selecting the first letter is trivial as previous answers:

substring(x,1,1)

extract column value based on another column pandas dataframe

You could use loc to get series which satisfying your condition and then iloc to get first element:

In [2]: df
Out[2]:
    A  B
0  p1  1
1  p1  2
2  p3  3
3  p2  4

In [3]: df.loc[df['B'] == 3, 'A']
Out[3]:
2    p3
Name: A, dtype: object

In [4]: df.loc[df['B'] == 3, 'A'].iloc[0]
Out[4]: 'p3'

Blur or dim background when Android PopupWindow active

Since PopupWindow just adds a View to WindowManager you can use updateViewLayout (View view, ViewGroup.LayoutParams params) to update the LayoutParams of your PopupWindow's contentView after calling show..().

Setting the window flag FLAG_DIM_BEHIND will dimm everything behind the window. Use dimAmount to control the amount of dim (1.0 for completely opaque to 0.0 for no dim).

Keep in mind that if you set a background to your PopupWindow it will put your contentView into a container, which means you need to update it's parent.

With background:

PopupWindow popup = new PopupWindow(contentView, width, height);
popup.setBackgroundDrawable(background);
popup.showAsDropDown(anchor);

View container = (View) popup.getContentView().getParent();
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams p = (WindowManager.LayoutParams) container.getLayoutParams();
// add flag
p.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
p.dimAmount = 0.3f;
wm.updateViewLayout(container, p);

Without background:

PopupWindow popup = new PopupWindow(contentView, width, height);
popup.setBackgroundDrawable(null);
popup.showAsDropDown(anchor);

WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams p = (WindowManager.LayoutParams) contentView.getLayoutParams();
// add flag
p.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
p.dimAmount = 0.3f;
wm.updateViewLayout(contentView, p);

Marshmallow Update:

On M PopupWindow wraps the contentView inside a FrameLayout called mDecorView. If you dig into the PopupWindow source you will find something like createDecorView(View contentView).The main purpose of mDecorView is to handle event dispatch and content transitions, which are new to M. This means we need to add one more .getParent() to access the container.

With background that would require a change to something like:

View container = (View) popup.getContentView().getParent().getParent();

Better alternative for API 18+

A less hacky solution using ViewGroupOverlay:

1) Get a hold of the desired root layout

ViewGroup root = (ViewGroup) getWindow().getDecorView().getRootView();

2) Call applyDim(root, 0.5f); or clearDim()

public static void applyDim(@NonNull ViewGroup parent, float dimAmount){
    Drawable dim = new ColorDrawable(Color.BLACK);
    dim.setBounds(0, 0, parent.getWidth(), parent.getHeight());
    dim.setAlpha((int) (255 * dimAmount));

    ViewGroupOverlay overlay = parent.getOverlay();
    overlay.add(dim);
}

public static void clearDim(@NonNull ViewGroup parent) {
    ViewGroupOverlay overlay = parent.getOverlay();
    overlay.clear();
}

How do I get the entity that represents the current user in Symfony2?

Well, first you need to request the username of the user from the session in your controller action like this:

$username=$this->get('security.context')->getToken()->getUser()->getUserName();

then do a query to the db and get your object with regular dql like

$em = $this->get('doctrine.orm.entity_manager');    
"SELECT u FROM Acme\AuctionBundle\Entity\User u where u.username=".$username;
$q=$em->createQuery($query);
$user=$q->getResult();

the $user should now hold the user with this username ( you could also use other fields of course)

...but you will have to first configure your /app/config/security.yml configuration to use the appropriate field for your security provider like so:

security:
 provider:
  example:
   entity: {class Acme\AuctionBundle\Entity\User, property: username}

hope this helps!

How to get first two characters of a string in oracle query?

Try select substr(orderno, 1,2) from shipment;

Jquery, checking if a value exists in array or not

http://api.jquery.com/jQuery.inArray/

if ($.inArray('example', myArray) != -1)
{
  // found it
}

Fill remaining vertical space - only CSS

You can just add the overflow:auto option:

#second
{
   width:300px;
   height:100%;
   overflow: auto;
   background-color:#9ACD32;
}

How do I fit an image (img) inside a div and keep the aspect ratio?

HTML

<div>
    <img src="something.jpg" alt="" />
</div>

CSS

div {
   width: 48px;
   height: 48px;
}

div img {
   display: block;
   width: 100%;
}

This will make the image expand to fill its parent, of which its size is set in the div CSS.