Programs & Examples On #Xts

xts is an R package that contains an eXtensible Time Series class and methods. xts extends and behaves like zoo.

Longer object length is not a multiple of shorter object length?

Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.

In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.

Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.

matplotlib set yaxis label size

If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40).

If you use pyplot programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40) or afterwards with ax.yaxis.label.set_size(40).

shell-script headers (#!/bin/sh vs #!/bin/csh)

This defines what shell (command interpreter) you are using for interpreting/running your script. Each shell is slightly different in the way it interacts with the user and executes scripts (programs).

When you type in a command at the Unix prompt, you are interacting with the shell.

E.g., #!/bin/csh refers to the C-shell, /bin/tcsh the t-shell, /bin/bash the bash shell, etc.

You can tell which interactive shell you are using the

 echo $SHELL

command, or alternatively

 env | grep -i shell

You can change your command shell with the chsh command.

Each has a slightly different command set and way of assigning variables and its own set of programming constructs. For instance the if-else statement with bash looks different that the one in the C-shell.

This page might be of interest as it "translates" between bash and tcsh commands/syntax.

Using the directive in the shell script allows you to run programs using a different shell. For instance I use the tcsh shell interactively, but often run bash scripts using /bin/bash in the script file.

Aside:

This concept extends to other scripts too. For instance if you program in Python you'd put

 #!/usr/bin/python

at the top of your Python program

AngularJS: ng-repeat list is not updated when a model element is spliced from the model array

There's an easy way to do that. Very easy. Since I noticed that

$scope.yourModel = [];

removes all $scope.yourModel array list you can do like this

function deleteAnObjectByKey(objects, key) {
    var clonedObjects = Object.assign({}, objects);

     for (var x in clonedObjects)
        if (clonedObjects.hasOwnProperty(x))
             if (clonedObjects[x].id == key)
                 delete clonedObjects[x];

    $scope.yourModel = clonedObjects;
}

The $scope.yourModel will be updated with the clonedObjects.

Hope that helps.

Autoreload of modules in IPython

You can use:

  import ipy_autoreload
  %autoreload 2 
  %aimport your_mod

Cross-Origin Request Blocked

You need other headers, not only access-control-allow-origin. If your request have the "Access-Control-Allow-Origin" header, you must copy it into the response headers, If doesn't, you must check the "Origin" header and copy it into the response. If your request doesn't have Access-Control-Allow-Origin not Origin headers, you must return "*".

You can read the complete explanation here: http://www.html5rocks.com/en/tutorials/cors/#toc-adding-cors-support-to-the-server

and this is the function I'm using to write cross domain headers:

func writeCrossDomainHeaders(w http.ResponseWriter, req *http.Request) {
    // Cross domain headers
    if acrh, ok := req.Header["Access-Control-Request-Headers"]; ok {
        w.Header().Set("Access-Control-Allow-Headers", acrh[0])
    }
    w.Header().Set("Access-Control-Allow-Credentials", "True")
    if acao, ok := req.Header["Access-Control-Allow-Origin"]; ok {
        w.Header().Set("Access-Control-Allow-Origin", acao[0])
    } else {
        if _, oko := req.Header["Origin"]; oko {
            w.Header().Set("Access-Control-Allow-Origin", req.Header["Origin"][0])
        } else {
            w.Header().Set("Access-Control-Allow-Origin", "*")
        }
    }
    w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
    w.Header().Set("Connection", "Close")

}

SQL Insert Multiple Rows

1--> {Simple Insertion when table column sequence is known}
    Insert into Table1
    values(1,2,...)

2--> {Simple insertion mention column}  
    Insert into Table1(col2,col4)
    values(1,2)

3--> {bulk insertion when num of selected collumns of a table(#table2) are equal to Insertion table(Table1) }   
    Insert into Table1 {Column sequence}
    Select * -- column sequence should be same.
       from #table2

4--> {bulk insertion when you want to insert only into desired column of a table(table1)}
    Insert into Table1 (Column1,Column2 ....Desired Column from Table1)  
    Select Column1,Column2..desired column from #table2

Close dialog on click (anywhere)

If you have several dialogs that could be opened on a page, this will allow any of them to be closed by clicking on the background:

$('body').on('click','.ui-widget-overlay', function() {
    $('.ui-dialog').filter(function () {
    return $(this).css("display") === "block";
    }).find('.ui-dialog-content').dialog('close');
});

(Only works for modal dialogs, as it relies on '.ui-widget-overlay'. And it does close all open dialogs any time the background of one of them is clicked.)

http post - how to send Authorization header?

I had the same issue. This is my solution using angular documentation and firebase Token:

getService()  {

const accessToken=this.afAuth.auth.currentUser.getToken().then(res=>{
  const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      'Authorization': res
    })
  };
  return this.http.get('Url',httpOptions)
    .subscribe(res => console.log(res));
}); }}

Java - ignore exception and continue

You could catch the NullPointerException explicitly and ignore it - though its generally not recommended. You should not, however, ignore all exceptions as you're currently doing.

UserInfo ui = new UserInfo();
try {
    DirectoryUser du = LDAPService.findUser(username);
    if (du!=null) {
       ui.setUserInfo(du.getUserInfo());
    }
} catch (NullPointerException npe) {
    // Lulz @ your NPE
    Logger.log("No user info for " +username+ ", will find some way to cope");
}

Implementing two interfaces in a class with same method. Which interface method is overridden?

As in interface,we are just declaring methods,concrete class which implements these both interfaces understands is that there is only one method(as you described both have same name in return type). so there should not be an issue with it.You will be able to define that method in concrete class.

But when two interface have a method with the same name but different return type and you implement two methods in concrete class:

Please look at below code:

public interface InterfaceA {
  public void print();
}


public interface InterfaceB {
  public int print();
}

public class ClassAB implements InterfaceA, InterfaceB {
  public void print()
  {
    System.out.println("Inside InterfaceA");
  }
  public int print()
  {
    System.out.println("Inside InterfaceB");
    return 5;
  }
}

when compiler gets method "public void print()" it first looks in InterfaceA and it gets it.But still it gives compile time error that return type is not compatible with method of InterfaceB.

So it goes haywire for compiler.

In this way, you will not be able to implement two interface having a method of same name but different return type.

Hibernate: failed to lazily initialize a collection of role, no session or session was closed

Your trying to load the lazy loaded collection, but the hibernate session is closed or unavailable. the best solution for this problem, change the lazy loaded object to eager fetch = FetchType.EAGER loading. this problem will solve.

Combine Date and Time columns using python pandas

The accepted answer works for columns that are of datatype string. For completeness: I come across this question when searching how to do this when the columns are of datatypes: date and time.

df.apply(lambda r : pd.datetime.combine(r['date_column_name'],r['time_column_name']),1)

Merging dictionaries in C#

Try the following

static Dictionary<TKey, TValue>
    Merge<TKey, TValue>(this IEnumerable<Dictionary<TKey, TValue>> enumerable)
{
    return enumerable.SelectMany(x => x).ToDictionary(x => x.Key, y => y.Value);
}

Get current directory name (without full path) in a Bash script

Just use:

pwd | xargs basename

or

basename "`pwd`"

How can I detect whether an iframe is loaded?

You may try this (using jQuery)

_x000D_
_x000D_
$(function(){_x000D_
    $('#MainPopupIframe').load(function(){_x000D_
        $(this).show();_x000D_
        console.log('iframe loaded successfully')_x000D_
    });_x000D_
        _x000D_
    $('#click').on('click', function(){_x000D_
        $('#MainPopupIframe').attr('src', 'https://heera.it');    _x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id='click'>click me</button>_x000D_
_x000D_
<iframe style="display:none" id='MainPopupIframe' src='' /></iframe>
_x000D_
_x000D_
_x000D_

jsfiddle DEMO.

Update: Using plain javascript

_x000D_
_x000D_
window.onload=function(){_x000D_
    var ifr=document.getElementById('MainPopupIframe');_x000D_
    ifr.onload=function(){_x000D_
        this.style.display='block';_x000D_
        console.log('laod the iframe')_x000D_
    };_x000D_
    var btn=document.getElementById('click');    _x000D_
    btn.onclick=function(){_x000D_
        ifr.src='https://heera.it';    _x000D_
    };_x000D_
};
_x000D_
<button id='click'>click me</button>_x000D_
_x000D_
<iframe style="display:none" id='MainPopupIframe' src='' /></iframe>
_x000D_
_x000D_
_x000D_

jsfiddle DEMO.

Update: Also you can try this (dynamic iframe)

_x000D_
_x000D_
$(function(){_x000D_
    $('#click').on('click', function(){_x000D_
        var ifr=$('<iframe/>', {_x000D_
            id:'MainPopupIframe',_x000D_
            src:'https://heera.it',_x000D_
            style:'display:none;width:320px;height:400px',_x000D_
            load:function(){_x000D_
                $(this).show();_x000D_
                alert('iframe loaded !');_x000D_
            }_x000D_
        });_x000D_
        $('body').append(ifr);    _x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id='click'>click me</button><br />
_x000D_
_x000D_
_x000D_

jsfiddle DEMO.

Run Batch File On Start-up

There are a few ways to run a batch file on start up. The one I usually use is through task scheduler. If you press the windows key then type task scheduler it will come up as an option (or find through administerative tools).

When you create a new task you can chose from trigger options such as 'At log on' for a specific user, on workstation unlock etc. Then in actions you select start a program and put the full path to your batch script (there is also an option to put any command line args required).

Here is a an example script to launch Stack Overflow in Firefox:

@echo off

title Auto launch Stack Overflow


start firefox http://stackoverflow.com/questions/tagged/python+or+sql+or+sqlite+or+plsql+or+oracle+or+windows-7+or+cmd+or+excel+or+access+or+vba+or+excel-vba+or+access-vba?sort=newest

REM Optional - I tend to log these sorts of events so that you can see what has happened afterwards
echo %date% %time%, %computername% >> %logs%\StackOverflowAuto.csv

exit

How can I style the border and title bar of a window in WPF?

Those are "non-client" areas and are controlled by Windows. Here is the MSDN docs on the subject (the pertinent info is at the top).

Basically, you set your Window's WindowStyle="None", then build your own window interface. (similar question on SO)

Can not run Java Applets in Internet Explorer 11 using JRE 7u51

Finally resolved my java install issue on Win 7 64-bit running IE11.

Even though I installed the latest Java (65) via a java auto-update prompt, tried a verify java version and java failed to run, shut down all IE instances, failed to run verify again, shut down all running programs, failed to run verify again, rebooted, failed to run verify again, re-installed 65 again (shutting down the browser manually as it downloaded), and finally verify ran. What a pain.

The message I kept receiving was "The page you are viewing uses Java ..."; e.g. https://www.java.com/en/download/help/ie_tips.xml. I do use sleep mode on my desktop and I believe that this is probably the major issue with install and IE with its "clever" integration into the OS and explorer/desktop. I thought the government told them to not do that. I've had issues with CD-ROM drive disappearing and other unexplained periodic issues; all cured after a full reboot. They are infrequent, so I live with them for the convenience of faster startup times.

Hope this helps someone!

proper hibernate annotation for byte[]

I have finally got this working. It expands on the solution from A. Garcia, however, since the problem lies in the hibernate type MaterializedBlob type just mapping Blob > bytea is not sufficient, we need a replacement for MaterializedBlobType which works with hibernates broken blob support. This implementation only works with bytea, but maybe the guy from the JIRA issue who wanted OID could contribute an OID implementation.

Sadly replacing these types at runtime is a pain, since they should be part of the Dialect. If only this JIRA enhanement gets into 3.6 it would be possible.

public class PostgresqlMateralizedBlobType extends AbstractSingleColumnStandardBasicType<byte[]> {
 public static final PostgresqlMateralizedBlobType INSTANCE = new PostgresqlMateralizedBlobType();

 public PostgresqlMateralizedBlobType() {
  super( PostgresqlBlobTypeDescriptor.INSTANCE, PrimitiveByteArrayTypeDescriptor.INSTANCE );
 }

  public String getName() {
   return "materialized_blob";
  }
}

Much of this could probably be static (does getBinder() really need a new instance?), but I don't really understand the hibernate internal so this is mostly copy + paste + modify.

public class PostgresqlBlobTypeDescriptor extends BlobTypeDescriptor implements SqlTypeDescriptor {
  public static final BlobTypeDescriptor INSTANCE = new PostgresqlBlobTypeDescriptor();

  public <X> ValueBinder<X> getBinder(final JavaTypeDescriptor<X> javaTypeDescriptor) {
   return new PostgresqlBlobBinder<X>(javaTypeDescriptor, this);
  }
  public <X> ValueExtractor<X> getExtractor(final JavaTypeDescriptor<X> javaTypeDescriptor) {
   return new BasicExtractor<X>( javaTypeDescriptor, this ) {
    protected X doExtract(ResultSet rs, String name, WrapperOptions options) throws SQLException { 
      return (X)rs.getBytes(name);
    }
   };
  }
}

public class PostgresqlBlobBinder<J> implements ValueBinder<J> {
 private final JavaTypeDescriptor<J> javaDescriptor;
 private final SqlTypeDescriptor sqlDescriptor;

 public PostgresqlBlobBinder(JavaTypeDescriptor<J> javaDescriptor, SqlTypeDescriptor sqlDescriptor) { 
  this.javaDescriptor = javaDescriptor; this.sqlDescriptor = sqlDescriptor;
 }  
 ...
 public final void bind(PreparedStatement st, J value, int index, WrapperOptions options) 
 throws SQLException {
  st.setBytes(index, (byte[])value);
 }
}

Big-O summary for Java Collections Framework implementations?

The book Java Generics and Collections has this information (pages: 188, 211, 222, 240).

List implementations:

                      get  add  contains next remove(0) iterator.remove
ArrayList             O(1) O(1) O(n)     O(1) O(n)      O(n)
LinkedList            O(n) O(1) O(n)     O(1) O(1)      O(1)
CopyOnWrite-ArrayList O(1) O(n) O(n)     O(1) O(n)      O(n)

Set implementations:

                      add      contains next     notes
HashSet               O(1)     O(1)     O(h/n)   h is the table capacity
LinkedHashSet         O(1)     O(1)     O(1) 
CopyOnWriteArraySet   O(n)     O(n)     O(1) 
EnumSet               O(1)     O(1)     O(1) 
TreeSet               O(log n) O(log n) O(log n)
ConcurrentSkipListSet O(log n) O(log n) O(1)

Map implementations:

                      get      containsKey next     Notes
HashMap               O(1)     O(1)        O(h/n)   h is the table capacity
LinkedHashMap         O(1)     O(1)        O(1) 
IdentityHashMap       O(1)     O(1)        O(h/n)   h is the table capacity 
EnumMap               O(1)     O(1)        O(1) 
TreeMap               O(log n) O(log n)    O(log n) 
ConcurrentHashMap     O(1)     O(1)        O(h/n)   h is the table capacity 
ConcurrentSkipListMap O(log n) O(log n)    O(1)

Queue implementations:

                      offer    peek poll     size
PriorityQueue         O(log n) O(1) O(log n) O(1)
ConcurrentLinkedQueue O(1)     O(1) O(1)     O(n)
ArrayBlockingQueue    O(1)     O(1) O(1)     O(1)
LinkedBlockingQueue   O(1)     O(1) O(1)     O(1)
PriorityBlockingQueue O(log n) O(1) O(log n) O(1)
DelayQueue            O(log n) O(1) O(log n) O(1)
LinkedList            O(1)     O(1) O(1)     O(1)
ArrayDeque            O(1)     O(1) O(1)     O(1)
LinkedBlockingDeque   O(1)     O(1) O(1)     O(1)

The bottom of the javadoc for the java.util package contains some good links:

How do you stylize a font in Swift?

You can set custom font in two ways : design time and run-time.

  1. First you need to download required font (.ttf file format). Then, double click on the file to install it.

  2. This will show a pop-up. Click on 'install font' button.

Screenshot 1

  1. This will install the font and will appear in 'Fonts' window.

Screenshot 2

  1. Now, the font is installed successfully. Drag and drop the custom font in your project. While doing this make sure that 'Add to targets' is checked.

Screenshot 3

  1. You need to make sure that this file is also added into 'Copy Bundle Resources' present in Build Phases of Targets of your project.

Screenshot 4

  1. After this you need to add this font in Info.plist of your project. Create a new key with 'Font Provided by application' with type as Array. Add a the font as an element with type String in Array.

Screenshot 5

A. Design mode :

  1. Select the label from Storyboard file. Goto Font attribute present in Attribute inspector of Utilities.

Screenshot 6

  1. Click on Font and select 'Custom font'

Screenshot 7

  1. From Family section select the custom font you have installed.

Screenshot 8

  1. Now you can see that font of label is set to custom font.

Screenshot 9

B. Run-time mode :

 self.lblWelcome.font = UIFont(name: "BananaYeti-Extrabold Trial", size: 16)

It seems that run-time mode doesn't work for dynamically formed string like

self.lblWelcome.text = "Welcome, " + fullname + "!"

Note that in above case only design-time approach worked correctly for me.

How to capture the browser window close event?

For a solution that worked well with third party controls like Telerik (ex.: RadComboBox) and DevExpress that use the Anchor tags for various reasons, consider using the following code, which is a slightly tweaked version of desm's code with a better selector for self targeting anchor tags:

var inFormOrLink;
$('a[href]:not([target]), a[href][target=_self]').live('click', function() { inFormOrLink = true; });
$('form').bind('submit', function() { inFormOrLink = true; });

$(window).bind('beforeunload', function(eventObject) {
    var returnValue = undefined;
    if (! inFormOrLink) {
        returnValue = "Do you really want to close?";
    }
    eventObject.returnValue = returnValue;
    return returnValue;
});

How can I set the current working directory to the directory of the script in Bash?

Get the real path to your script

if [ -L $0 ] ; then
    ME=$(readlink $0)
else
    ME=$0
fi
DIR=$(dirname $ME)

(This is answer to the same my question here: Get the name of the directory where a script is executed)

Spring,Request method 'POST' not supported

Try this

@RequestMapping(value = "proffessional", method = RequestMethod.POST)
    public @ResponseBody
    String forgotPassword(@ModelAttribute("PROFESSIONAL") UserProfessionalForm professionalForm,
            BindingResult result, Model model) {

        UserProfileVO userProfileVO = new UserProfileVO();
        userProfileVO.setUser(sessionData.getUser());
        userService.saveUserProfile(userProfileVO);
        model.addAttribute("professional", professionalForm);
        return "Your Professional Details Updated";
    }

How to download file in swift?

You can also use a third party library that makes life easy, like Just

Just.get("http://www.mywebsite.com/myfile.pdf")

More awesome Swift stuff here https://github.com/matteocrippa/awesome-swift

CSS opacity only to background color, not the text on it?

It sounds like you want to use a transparent background, in which case you could try using the rgba() function:

rgba(R, G, B, A)

R (red), G (green), and B (blue) can be either <integer>s or <percentage>s, where the number 255 corresponds to 100%. A (alpha) can be a <number> between 0 and 1, or a <percentage>, where the number 1 corresponds to 100% (full opacity).

RGBa example

rgba(51, 170, 51, .1)    /*  10% opaque green */ 
rgba(51, 170, 51, .4)    /*  40% opaque green */ 
rgba(51, 170, 51, .7)    /*  70% opaque green */ 
rgba(51, 170, 51,  1)    /* full opaque green */ 

A small example showing how rgba can be used.

As of 2018, practically every browser supports the rgba syntax.

Catch error if iframe src fails to load . Error :-"Refused to display 'http://www.google.co.in/' in a frame.."

As explained in the accepted answer, https://stackoverflow.com/a/18665488/4038790, you need to check via a server.

Because there's no reliable way to check this in the browser, I suggest you build yourself a quick server endpoint that you can use to check if any url is loadable via iframe. Once your server is up and running, just send a AJAX request to it to check any url by providing the url in the query string as url (or whatever your server desires). Here's the server code in NodeJs:

_x000D_
_x000D_
const express = require('express')_x000D_
const app = express()_x000D_
_x000D_
app.get('/checkCanLoadIframeUrl', (req, res) => {_x000D_
  const request = require('request')_x000D_
  const Q = require('q')_x000D_
_x000D_
  return Q.Promise((resolve) => {_x000D_
    const url = decodeURIComponent(req.query.url)_x000D_
_x000D_
    const deafultTimeout = setTimeout(() => {_x000D_
      // Default to false if no response after 10 seconds_x000D_
      resolve(false)_x000D_
    }, 10000)_x000D_
_x000D_
    request({_x000D_
        url,_x000D_
        jar: true /** Maintain cookies through redirects */_x000D_
      })_x000D_
      .on('response', (remoteRes) => {_x000D_
        const opts = (remoteRes.headers['x-frame-options'] || '').toLowerCase()_x000D_
        resolve(!opts || (opts !== 'deny' && opts !== 'sameorigin'))_x000D_
        clearTimeout(deafultTimeout)_x000D_
      })_x000D_
      .on('error', function() {_x000D_
        resolve(false)_x000D_
        clearTimeout(deafultTimeout)_x000D_
      })_x000D_
  }).then((result) => {_x000D_
    return res.status(200).json(!!result)_x000D_
  })_x000D_
})_x000D_
_x000D_
app.listen(process.env.PORT || 3100)
_x000D_
_x000D_
_x000D_

I lose my data when the container exits

None of the answers address the point of this design choice. I think docker works this way to prevent these 2 errors:

  • Repeated restart
  • Partial error

How to check if a word is an English word with Python?

For All Linux/Unix Users

If your OS uses the Linux kernel, there is a simple way to get all the words from the English/American dictionary. In the directory /usr/share/dict you have a words file. There is also a more specific american-english and british-english files. These contain all of the words in that specific language. You can access this throughout every programming language which is why I thought you might want to know about this.

Now, for python specific users, the python code below should assign the list words to have the value of every single word:

import re
file = open("/usr/share/dict/words", "r")
words = re.sub("[^\w]", " ",  file.read()).split()

def is_word(word):
    return word.lower() in words

is_word("tarts") ## Returns true
is_word("jwiefjiojrfiorj") ## Returns False

Hope this helps!!!

What's the difference between a web site and a web application?

Websites are primarily informational. In this sense, http://cnn.com and http://php.net are websites, not web applications.

Web applications primarily allow the user to perform actions. Google Analytics, gmail, and jslint are web applications.

They are not entirely exclusive. A university website likely gives information such as location, tuition rates, programs available, etc; it will likely have web applications that allow teachers to manage grades and course materials, applications for students to register for and withdraw from courses, etc.

How do you create optional arguments in php?

The date function would be defined something like this:

function date($format, $timestamp = null)
{
    if ($timestamp === null) {
        $timestamp = time();
    }

    // Format the timestamp according to $format
}

Usually, you would put the default value like this:

function foo($required, $optional = 42)
{
    // This function can be passed one or more arguments
}

However, only literals are valid default arguments, which is why I used null as default argument in the first example, not $timestamp = time(), and combined it with a null check. Literals include arrays (array() or []), booleans, numbers, strings, and null.

Overriding interface property type defined in Typescript d.ts file

If someone else needs a generic utility type to do this, I came up with the following solution:

/**
 * Returns object T, but with T[K] overridden to type U.
 * @example
 * type MyObject = { a: number, b: string }
 * OverrideProperty<MyObject, "a", string> // returns { a: string, b: string }
 */
export type OverrideProperty<T, K extends keyof T, U> = Omit<T, K> & { [P in keyof Pick<T, K>]: U };

I needed this because in my case, the key to override was a generic itself.

If you don't have Omit ready, see Exclude property from type.

"Retrieving the COM class factory for component.... error: 80070005 Access is denied." (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

try to do the following:

  1. Make sure Office interop assemblies are installed.
  2. Check the version of the assemblies on development and production.
  3. Create Desktop folder under systemprofile.
  4. set the DCOM security explicitly for the service user.

you can find more details here

Nested iframes, AKA Iframe Inception

If browser supports iframe, then DOM inside iframe come from src attribute of respective tag. Contents that are inside iframe tag are used as a fall back mechanism where browser does not supports iframe tag.

Ref: http://www.w3schools.com/tags/tag_iframe.asp

R: invalid multibyte string

I realize this is pretty late, but I had a similar problem and I figured I'd post what worked for me. I used the iconv utility (e.g., "iconv file.pcl -f UTF-8 -t ISO-8859-1 -c"). The "-c" option skips characters that can't be translated.

How to pass a JSON array as a parameter in URL

& is a keyword for the next parameter like this ur?param1=1&param2=2

so effectively you send a second param named R". You should urlencode your string. Isn't POST an option?

Create Setup/MSI installer in Visual Studio 2017

Other answers posted here for this question did not work for me using the latest Visual Studio 2017 Enterprise edition (as of 2018-09-18).

Instead, I used this method:

  1. Close all but one instance of Visual Studio.
  2. In the running instance, access the menu Tools->Extensions and Updates.
  3. In that dialog, choose Online->Visual Studio Marketplace->Tools->Setup & Deployment.
  4. From the list that appears, select Microsoft Visual Studio 2017 Installer Projects.

Once installed, close and restart Visual Studio. Go to File->New Project and search for the word Installer. You'll know you have the correct templates installed if you see a list that looks something like this:

enter image description here

display:inline vs display:block

Block

Takes up the full width available, with a new line before and after (display:block;)

Inline

Takes up only as much width as it needs, and does not force new lines (display:inline;)

The tilde operator in Python

It is a unary operator (taking a single argument) that is borrowed from C, where all data types are just different ways of interpreting bytes. It is the "invert" or "complement" operation, in which all the bits of the input data are reversed.

In Python, for integers, the bits of the twos-complement representation of the integer are reversed (as in b <- b XOR 1 for each individual bit), and the result interpreted again as a twos-complement integer. So for integers, ~x is equivalent to (-x) - 1.

The reified form of the ~ operator is provided as operator.invert. To support this operator in your own class, give it an __invert__(self) method.

>>> import operator
>>> class Foo:
...   def __invert__(self):
...     print 'invert'
...
>>> x = Foo()
>>> operator.invert(x)
invert
>>> ~x
invert

Any class in which it is meaningful to have a "complement" or "inverse" of an instance that is also an instance of the same class is a possible candidate for the invert operator. However, operator overloading can lead to confusion if misused, so be sure that it really makes sense to do so before supplying an __invert__ method to your class. (Note that byte-strings [ex: '\xff'] do not support this operator, even though it is meaningful to invert all the bits of a byte-string.)

background-image: url("images/plaid.jpg") no-repeat; wont show up

If that really is all that's in your CSS file, then yes, nothing will happen. You need a selector, even if it's as simple as body:

body {
    background-image: url(...);
}

How do I install jmeter on a Mac?

Once you got the ZIP from the download, extract it locally, and with your finder, go in bin directory.

Then double-click on ApacheJMeter.jar to launch the User Interface of JMeter.

This and the next steps are described in a blog entry.

How to give spacing between buttons using bootstrap

The original code is mostly there, but you need btn-groups around each button. In Bootstrap 3 you can use a btn-toolbar and a btn-group to get the job done; I haven't done BS4 but it has similar constructs.

<div class="btn-toolbar" role="toolbar">
  <div class="btn-group" role="group">
    <button class="btn btn-default">Button 1</button>
  </div>
  <div class="btn-group" role="group">
    <button class="btn btn-default">Button 2</button>
  </div>
</div>

Clear the cache in JavaScript

You can also disable browser caching with meta HTML tags just put html tags in the head section to avoid the web page to be cached while you are coding/testing and when you are done you can remove the meta tags.

(in the head section)

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0"/>

Refresh your page after pasting this in the head and should refresh the new javascript code too.

This link will give you other options if you need them http://cristian.sulea.net/blog/disable-browser-caching-with-meta-html-tags/

or you can just create a button like so

<button type="button" onclick="location.reload(true)">Refresh</button>

it refreshes and avoid caching but it will be there on your page till you finish testing, then you can take it off. Fist option is best I thing.

How do I evenly add space between a label and the input field regardless of length of text?

You can always use the 'pre' tag inside the label, and just enter the blank spaces in it, So you can always add the same or different number of spaces you require

<form>
<label>First Name :<pre>Here just enter number of spaces you want to use(I mean using spacebar to enter blank spaces)</pre>
<input type="text"></label>
<label>Last Name :<pre>Now Enter enter number of spaces to match above number of 
spaces</pre>
<input type="text"></label>
</form>

Hope you like my answer, It's a simple and efficient hack

Export and import table dump (.sql) using pgAdmin

  1. In pgAdmin, select the required target schema in object tree (databases->your_db_name->schemas->your_target_schema)
  2. Click on Plugins/PSQL Console (in top-bar)
  3. Write \i /path/to/yourfile.sql
  4. Press enter

How can I compare two lists in python and return matches

another a bit more functional way to check list equality for list 1 (lst1) and list 2 (lst2) where objects have depth one and which keeps the order is:

all(i == j for i, j in zip(lst1, lst2))   

android get real path by Uri.getPath()

@Rene Juuse - above in comments... Thanks for this link !

. the code to get the real path is a bit different from one SDK to another so below we have three methods that deals with different SDKs.

getRealPathFromURI_API19(): returns real path for API 19 (or above but not tested) getRealPathFromURI_API11to18(): returns real path for API 11 to API 18 getRealPathFromURI_below11(): returns real path for API below 11

public class RealPathUtil {

@SuppressLint("NewApi")
public static String getRealPathFromURI_API19(Context context, Uri uri){
    String filePath = "";
    String wholeID = DocumentsContract.getDocumentId(uri);

     // Split at colon, use second item in the array
     String id = wholeID.split(":")[1];

     String[] column = { MediaStore.Images.Media.DATA };     

     // where id is equal to             
     String sel = MediaStore.Images.Media._ID + "=?";

     Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
                               column, sel, new String[]{ id }, null);

     int columnIndex = cursor.getColumnIndex(column[0]);

     if (cursor.moveToFirst()) {
         filePath = cursor.getString(columnIndex);
     }   
     cursor.close();
     return filePath;
}


@SuppressLint("NewApi")
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
      String[] proj = { MediaStore.Images.Media.DATA };
      String result = null;

      CursorLoader cursorLoader = new CursorLoader(
              context, 
        contentUri, proj, null, null, null);        
      Cursor cursor = cursorLoader.loadInBackground();

      if(cursor != null){
       int column_index = 
         cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
       cursor.moveToFirst();
       result = cursor.getString(column_index);
      }
      return result;  
}

public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){
           String[] proj = { MediaStore.Images.Media.DATA };
           Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
           int column_index
      = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
           cursor.moveToFirst();
           return cursor.getString(column_index);
}

font: http://hmkcode.com/android-display-selected-image-and-its-real-path/


UPDATE 2016 March

To fix all problems with path of images i try create a custom gallery as facebook and other apps. This is because you can use just local files ( real files, not virtual or temporary) , i solve all problems with this library.

https://github.com/nohana/Laevatein (this library is to take photo from camera or choose from galery , if you choose from gallery he have a drawer with albums and just show local files)

jQuery - Disable Form Fields

$('input, select').attr('disabled', 'disabled');

How to select a single child element using jQuery?

<html>
<title>

    </title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="assets/css/bootstrap.css">
<body>




<!-- <asp:LinkButton ID="MoreInfoButton" runat="server" Text="<%#MoreInfo%>" > -->
 <!-- </asp:LinkButton> -->
<!-- </asp:LinkButton> -->

<br />
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
    <!-- repeater1 starts -->
        <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
            <ul  >
                <li ><h6><strong>lorem</strong></h6></li>
                <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                <li ><h6><strong>Full Service Contracts</strong></h6></li>
                <li ><h6><strong>Maintenance Contracts</strong></h6></li>
            </ul>
    <!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
    <!-- repeater1 starts -->
        <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
            <ul  >
                <li ><h6><strong>lorem</strong></h6></li>
                <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                <li ><h6><strong>Full Service Contracts</strong></h6></li>
                <li ><h6><strong>Maintenance Contracts</strong></h6></li>
            </ul>
    <!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
    <!-- repeater1 starts -->
        <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
            <ul  >
                <li ><h6><strong>lorem</strong></h6></li>
                <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                <li ><h6><strong>Full Service Contracts</strong></h6></li>
                <li ><h6><strong>Maintenance Contracts</strong></h6></li>
            </ul>
    <!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
    <!-- repeater1 starts -->
        <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
            <ul  >
                <li ><h6><strong>lorem</strong></h6></li>
                <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                <li ><h6><strong>Full Service Contracts</strong></h6></li>
                <li ><h6><strong>Maintenance Contracts</strong></h6></li>
            </ul>
    <!-- repeater1 ends -->
</div>
</div>




</asp:Repeater>


</body>
<!-- Predefined JavaScript -->
<script src="jquery.js"></script>
<script src="bootstrap.js"></script>

<script>

 $(function () {
        $('a').click(function() {
            $(this).parent().children('.dataContentSectionMessages').slideToggle();
        });
    });

    </script>


</html>

Calling a javascript function in another js file

// module.js
export function hello() {
  return "Hello";
}

// main.js
import {hello} from 'module'; // or './module'
let val = hello(); // val is "Hello";

reference from https://hype.codes/how-include-js-file-another-js-file

Add/delete row from a table

I suggest using jQuery. What you are doing right now is easy to achieve without jQuery, but as you will want new features and more functionality, jQuery will save you a lot of time. I would also like to mention that you shouldn't have multiple DOM elements with the same ID in one document. In such case use class attribute.

html:

<table id="dsTable">
  <tr>
     <td> Relationship Type </td>
     <td> Date of Birth </td>
     <td> Gender </td>
  </tr>
  <tr>
     <td> Spouse </td>
     <td> 1980-22-03 </td>
     <td> female </td>
     <td> <input type="button" class="addDep" value="Add"/></td>
     <td> <input type="button" class="deleteDep" value="Delete"/></td>
  </tr>
   <tr>
     <td> Child </td>
     <td> 2008-23-06 </td>
     <td> female </td>
     <td> <input type="button" class="addDep" value="Add"/></td>
     <td> <input type="button" class="deleteDep" value="Delete"/></td>
  </tr>
</table>

javascript:

$('body').on('click', 'input.deleteDep', function() {
   $(this).parents('tr').remove();  
});

Remember that you need to reference jQuery:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>

Here a working jsfiddle example: http://jsfiddle.net/p9dey/1/

Check if an object belongs to a class in Java

The usual way would be:

if (a instanceof A)

However, there are cases when you can't do this, such as when A in a generic argument.

Due to Java's type erasure, the following won't compile:

<A> boolean someMethod(Object a) {
    if (a instanceof A)
    ...
}

and the following won't work (and will produce an unchecked cast warning):

<A> void someMethod(Object a) {
    try {
        A casted = (A)a;    
    } catch (ClassCastException e) {
         ...
    }
}

You can't cast to A at runtime, because at runtime, A is essentially Object.

The solutions to such cases is to use a Class instead of the generic argument:

void someMethod(Object a, Class<A> aClass) {
    if (aClass.isInstance(a)) {
       A casted = aClass.cast(a);
       ...
    }
}

You can then call the method as:

someMethod(myInstance, MyClass.class);
someMethod(myInstance, OtherClass.class);

Shortcut to comment out a block of code with sublime text

You're looking for the toggle_comment command. (Edit > Comment > Toggle Comment)

By default, this command is mapped to:

  • Ctrl+/ (On Windows and Linux)
  • Command ?+/ (On Mac)

This command also takes a block argument, which allows you to use block comments instead of single lines (e.g. /* ... */ as opposed to // ... in JavaScript). By default, the following key combinations are mapped to toggle block comments:

  • Ctrl+Shift+/ (On Windows and Linux)
  • Command ?+Alt+/ (On Mac)

Return Result from Select Query in stored procedure to a List

May be this will help:

Getting rows from DB:

public static DataRowCollection getAllUsers(string tableName) 
{
     DataSet set = new DataSet();
     SqlCommand comm = new SqlCommand();
     comm.Connection = DAL.DAL.conn;
     comm.CommandType = CommandType.StoredProcedure;
     comm.CommandText = "getAllUsers";
     SqlDataAdapter da = new SqlDataAdapter();
     da.SelectCommand = comm;
     da.Fill(set,tableName);

     DataRowCollection usersCollection = set.Tables[tableName].Rows;
     return usersCollection;
}

Populating DataGridView from DataRowCollection :

public static void ShowAllUsers(DataGridView grdView,string table, params string[] fields) 
{
    DataRowCollection userSet = getAllUsers(table);
    foreach (DataRow user in userSet)
    {
         grdView.Rows.Add(user[fields[0]],
         user[fields[1]],
         user[fields[2]],
         user[fields[3]]);
    }
}

Implementation :

BLL.BLL.ShowAllUsers(grdUsers,"eusers","eid","euname","eupassword","eposition");

'\r': command not found - .bashrc / .bash_profile

I had the same problem. Solution: I edit the file with pspad editor, and give it a unix format (Menu - Format -> UNIX)

I believe you can set this format to your file with many other editors

Compiler error "archive for required library could not be read" - Spring Tool Suite

I was using Eclipse as IDE and I was getting very same error. I had to do Project->Maven->Update Project. Select all the checkboxes below except "offline" esp. the one "Force update of snapshots/releases" and click OK. Did the Clean Build for the Project again.

Using floats with sprintf() in embedded C

use the %f modifier:

sprintf (str, "adc_read = %f\n", adc_read);

For instance:

#include <stdio.h>

int main (void) 
{
    float x = 2.5;
    char y[200];

    sprintf(y, "x = %f\n", x);
    printf(y);
    return 0;
}

Yields this:

x = 2.500000

iOS: Convert UTC NSDate to local Timezone

I write this Method to convert date time to our LocalTimeZone

-Here (NSString *)TimeZone parameter is a server timezone

-(NSString *)convertTimeIntoLocal:(NSString *)defaultTime :(NSString *)TimeZone
{
    NSDateFormatter *serverFormatter = [[NSDateFormatter alloc] init];
    [serverFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:TimeZone]];
    [serverFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *theDate = [serverFormatter dateFromString:defaultTime];
    NSDateFormatter *userFormatter = [[NSDateFormatter alloc] init];
    [userFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [userFormatter setTimeZone:[NSTimeZone localTimeZone]];
    NSString *dateConverted = [userFormatter stringFromDate:theDate];
    return dateConverted;
}

How do I copy the contents of a String to the clipboard in C#?

WPF: System.Windows.Clipboard (PresentationCore.dll)

Winforms: System.Windows.Forms.Clipboard

Both have a static SetText method.

Is there a way to get colored text in GitHubflavored Markdown?

You can not color plain text in a GitHub README.md file. You can however add color to code samples in your GitHub README.md file with the tags below.

To do this, just add tags, such as these samples, to your README.md file:

```json
   // Code for coloring
```
```html
   // Code for coloring
```
```js
   // Code for coloring
```
```css
   // Code for coloring
```
// etc.

**Colored Code Example, JavaScript:** place this code below, in your GitHub README.md file and see how it colors the code for you.
  import { Component } from '@angular/core';
  import { MovieService } from './services/movie.service';

  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    providers: [ MovieService ]
  })
  export class AppComponent {
    title = 'app works!';
  }

No "pre" or "code" tags are needed.

This is now covered in the GitHub Markdown documentation (about half way down the page, there's an example using Ruby). GitHub uses Linguist to identify and highlight syntax - you can find a full list of supported languages (as well as their markdown keywords) over in the Linguist's YAML file.

DEMO

Check if element at position [x] exists in the list

if(list.ElementAtOrDefault(2) != null)
{
   // logic
}

ElementAtOrDefault() is part of the System.Linq namespace.

Although you have a List, so you can use list.Count > 2.

Undefined Symbols for architecture x86_64: Compiling problems

There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.

Similarity::Similarity() or Similarity::~Similarity() are just missing and you have defined the others incorrectly,

void Similarity::readData(Scanner& inStream){
}

not

void readData(Scanner& inStream){
}

etc. etc.

The second one is a function called readData, only the first is the readData method of the Similarity class.

To be clear about this, in Similarity.h

void readData(Scanner& inStream);

but in Similarity.cpp

void Similarity::readData(Scanner& inStream){
}

How do I generate random number for each row in a TSQL Select?

Use newid()

select newid()

or possibly this

select binary_checksum(newid())

What's the difference between size_t and int in C++?

The size_t type is defined as the unsigned integral type of the sizeof operator. In the real world, you will often see int defined as 32 bits (for backward compatibility) but size_t defined as 64 bits (so you can declare arrays and structures more than 4 GiB in size) on 64-bit platforms. If a long int is also 64-bits, this is called the LP64 convention; if long int is 32 bits but long long int and pointers are 64 bits, that’s LLP64. You also might get the reverse, a program that uses 64-bit instructions for speed, but 32-bit pointers to save memory. Also, int is signed and size_t is unsigned.

There were historically a number of other platforms where addresses were wider or shorter than the native size of int. In fact, in the ’70s and early ’80s, this was more common than not: all the popular 8-bit microcomputers had 8-bit registers and 16-bit addresses, and the transition between 16 and 32 bits also produced many machines that had addresses wider than their registers. I occasionally still see questions here about Borland Turbo C for MS-DOS, whose Huge memory mode had 20-bit addresses stored in 32 bits on a 16-bit CPU (but which could support the 32-bit instruction set of the 80386); the Motorola 68000 had a 16-bit ALU with 32-bit registers and addresses; there were IBM mainframes with 15-bit, 24-bit or 31-bit addresses. You also still see different ALU and address-bus sizes in embedded systems.

Any time int is smaller than size_t, and you try to store the size or offset of a very large file or object in an unsigned int, there is the possibility that it could overflow and cause a bug. With an int, there is also the possibility of getting a negative number. If an int or unsigned int is wider, the program will run correctly but waste memory.

You should generally use the correct type for the purpose if you want portability. A lot of people will recommend that you use signed math instead of unsigned (to avoid nasty, subtle bugs like 1U < -3). For that purpose, the standard library defines ptrdiff_t in <stddef.h> as the signed type of the result of subtracting a pointer from another.

That said, a workaround might be to bounds-check all addresses and offsets against INT_MAX and either 0 or INT_MIN as appropriate, and turn on the compiler warnings about comparing signed and unsigned quantities in case you miss any. You should always, always, always be checking your array accesses for overflow in C anyway.

Use Conditional formatting to turn a cell Red, yellow or green depending on 3 values in another sheet

  1. Highlight the range in question.
  2. On the Home tab, in the Styles Group, Click "Conditional Formatting".
  3. Click "Highlight cell rules"

For the first rule,

Click "greater than", then in the value option box, click on the cell criteria you want it to be less than, than use the format drop-down to select your color.

For the second,

Click "less than", then in the value option box, type "=.9*" and then click the cell criteria, then use the formatting just like step 1.

For the third,

Same as the second, except your formula is =".8*" rather than .9.

Reverse Contents in Array

I would try to using pointers to solve this problem:

#include <iostream>

void displayArray(int table[], int size);

void rev(int table[], int size);


int main(int argc, char** argv) {

    int a[10] = { 1,2,3,4,5,6,7,8,9,10 };

    rev(a, 10);
    displayArray(a, 10);

    return 0;
}

void displayArray(int table[], int size) {
    for (int i = 0; i < size; i++) {
        std::cout << table[i] << " ";
    }
    std::cout << std::endl;
}

void rev(int table[], int size) {

    int *start = table;
    int *end = table + (size - 1);

    for (int i = 0; i < size; i++) {

        if (start < end) {
            int temp = *end;
            *end = *start;
            *start = temp;
        }

        start++;
        end--;
    }
}

PHP: How to get current time in hour:minute:second?

You can combine both in the same date function call

date("d-m-Y H:i:s");  

How to subtract one month using moment.js?

For substracting in moment.js:

moment().subtract(1, 'months').format('MMM YYYY');

Documentation:

http://momentjs.com/docs/#/manipulating/subtract/

Before version 2.8.0, the moment#subtract(String, Number) syntax was also supported. It has been deprecated in favor of moment#subtract(Number, String).

  moment().subtract('seconds', 1); // Deprecated in 2.8.0
  moment().subtract(1, 'seconds');

As of 2.12.0 when decimal values are passed for days and months, they are rounded to the nearest integer. Weeks, quarters, and years are converted to days or months, and then rounded to the nearest integer.

  moment().subtract(1.5, 'months') == moment().subtract(2, 'months')
  moment().subtract(.7, 'years') == moment().subtract(8, 'months') //.7*12 = 8.4, rounded to 8

What does it mean by command cd /d %~dp0 in Windows

Let's dissect it. There are three parts:

  1. cd -- This is change directory command.
  2. /d -- This switch makes cd change both drive and directory at once. Without it you would have to do cd %~d0 & cd %~p0. (%~d0 Changs active drive, cd %~p0 change the directory).
  3. %~dp0 -- This can be dissected further into three parts:
    1. %0 -- This represents zeroth parameter of your batch script. It expands into the name of the batch file itself.
    2. %~0 -- The ~ there strips double quotes (") around the expanded argument.
    3. %dp0 -- The d and p there are modifiers of the expansion. The d forces addition of a drive letter and the p adds full path.

Node.js: Python not found exception due to node-sass and node-gyp

This is 2 years old, but none of them helped me.

I uninstalled my NodeJS v12.8.1 (Current) and installed a brand new v10.16.3 (LTS) and my ng build --prod worked.

Setting the JVM via the command line on Windows

Yes - just explicitly provide the path to java.exe. For instance:

c:\Users\Jon\Test>"c:\Program Files\java\jdk1.6.0_03\bin\java.exe" -version
java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing)

c:\Users\Jon\Test>"c:\Program Files\java\jdk1.6.0_12\bin\java.exe" -version
java version "1.6.0_12"
Java(TM) SE Runtime Environment (build 1.6.0_12-b04)
Java HotSpot(TM) Client VM (build 11.2-b01, mixed mode, sharing)

The easiest way to do this for a running command shell is something like:

set PATH=c:\Program Files\Java\jdk1.6.0_03\bin;%PATH%

For example, here's a complete session showing my default JVM, then the change to the path, then the new one:

c:\Users\Jon\Test>java -version
java version "1.6.0_12"
Java(TM) SE Runtime Environment (build 1.6.0_12-b04)
Java HotSpot(TM) Client VM (build 11.2-b01, mixed mode, sharing)

c:\Users\Jon\Test>set PATH=c:\Program Files\Java\jdk1.6.0_03\bin;%PATH%

c:\Users\Jon\Test>java -version
java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing)

This won't change programs which explicitly use JAVA_HOME though.

Note that if you get the wrong directory in the path - including one that doesn't exist - you won't get any errors, it will effectively just be ignored.

Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile

I was getting similar errors and eventually found just that cleaning the build folder resolved my issue.

mvn clean install

How do I prevent a Gateway Timeout with FastCGI on Nginx

In server proxy set like that

location / {

                proxy_pass http://ip:80;                

                proxy_connect_timeout   90;
                proxy_send_timeout      90;
                proxy_read_timeout      90;

            }

In server php set like that

server {
        client_body_timeout 120;
        location = /index.php {

                #include fastcgi.conf; //example
                #fastcgi_pass unix:/run/php/php7.3-fpm.sock;//example veriosn

                fastcgi_read_timeout 120s;
       }
}

Java JDBC - How to connect to Oracle using Service Name instead of SID

Try this: jdbc:oracle:thin:@oracle.hostserver2.mydomain.ca:1522/ABCD

Edit: per comment below this is actualy correct: jdbc:oracle:thin:@//oracle.hostserver2.mydomain.ca:1522/ABCD (note the //)

Here is a link to a helpful article

What is the difference between a process and a thread?

Consider process like a unit of ownership or what resources are needed by a task. A Process can have resources like memory space, specific input/output, specific files, and priority etc.

A thread is a dispatchable unit of execution or in simple words the progress through a sequence of instructions

INSERT and UPDATE a record using cursors in oracle

This is a highly inefficient way of doing it. You can use the merge statement and then there's no need for cursors, looping or (if you can do without) PL/SQL.

MERGE INTO studLoad l
USING ( SELECT studId, studName FROM student ) s
ON (l.studId = s.studId)
WHEN MATCHED THEN
  UPDATE SET l.studName = s.studName
   WHERE l.studName != s.studName
WHEN NOT MATCHED THEN 
INSERT (l.studID, l.studName)
VALUES (s.studId, s.studName)

Make sure you commit, once completed, in order to be able to see this in the database.


To actually answer your question I would do it something like as follows. This has the benefit of doing most of the work in SQL and only updating based on the rowid, a unique address in the table.

It declares a type, which you place the data within in bulk, 10,000 rows at a time. Then processes these rows individually.

However, as I say this will not be as efficient as merge.

declare

   cursor c_data is
    select b.rowid as rid, a.studId, a.studName
      from student a
      left outer join studLoad b
        on a.studId = b.studId
       and a.studName <> b.studName
           ;

   type t__data is table of c_data%rowtype index by binary_integer;
   t_data t__data;

begin

   open c_data;
   loop
      fetch c_data bulk collect into t_data limit 10000;

      exit when t_data.count = 0;

      for idx in t_data.first .. t_data.last loop
         if t_data(idx).rid is null then
            insert into studLoad (studId, studName)
            values (t_data(idx).studId, t_data(idx).studName);
         else
            update studLoad
               set studName = t_data(idx).studName
             where rowid = t_data(idx).rid
                   ;
         end if;
      end loop;

   end loop;
   close c_data;

end;
/

Switch to another Git tag

Clone the repository as normal:

git clone git://github.com/rspec/rspec-tmbundle.git RSpec.tmbundle

Then checkout the tag you want like so:

git checkout tags/1.1.4

This will checkout out the tag in a 'detached HEAD' state. In this state, "you can look around, make experimental changes and commit them, and [discard those commits] without impacting any branches by performing another checkout".

To retain any changes made, move them to a new branch:

git checkout -b 1.1.4-jspooner

You can get back to the master branch by using:

git checkout master

Note, as was mentioned in the first revision of this answer, there is another way to checkout a tag:

git checkout 1.1.4

But as was mentioned in a comment, if you have a branch by that same name, this will result in git warning you that the refname is ambiguous and checking out the branch by default:

warning: refname 'test' is ambiguous.
Switched to branch '1.1.4'

The shorthand can be safely used if the repository does not share names between branches and tags.

Convert UTF-8 encoded NSData to NSString

If the data is not null-terminated, you should use -initWithData:encoding:

NSString* newStr = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];

If the data is null-terminated, you should instead use -stringWithUTF8String: to avoid the extra \0 at the end.

NSString* newStr = [NSString stringWithUTF8String:[theData bytes]];

(Note that if the input is not properly UTF-8-encoded, you will get nil.)


Swift variant:

let newStr = String(data: data, encoding: .utf8)
// note that `newStr` is a `String?`, not a `String`.

If the data is null-terminated, you could go though the safe way which is remove the that null character, or the unsafe way similar to the Objective-C version above.

// safe way, provided data is \0-terminated
let newStr1 = String(data: data.subdata(in: 0 ..< data.count - 1), encoding: .utf8)
// unsafe way, provided data is \0-terminated
let newStr2 = data.withUnsafeBytes(String.init(utf8String:))

How do I revert an SVN commit?

If you're using the TortoiseSVN client, it's easily done via the Show Log dialog.

Can you test google analytics on a localhost address?

After spending about two hours trying to come up with a solution I realized that I had adblockers blocking the call to GA. Once I turned them off I was good to go.

dlib installation on Windows 10

Just a quick update on what has worked for me (two years later). Davis King has provided two ways to add the latest python dlib (19.17.0) to any python environment in Windows 10 for me. Note, I run several Linux configs in Oracle VirtualBox but Windows 10 is my native OS which has access to the Nvidia GPU so i need an install on Windows 10. (Cannot access the GPU - easily - through VirtualBox).

First - the easiest:

pip install dlib

and the website link: https://pypi.org/project/dlib/

And then it can be easily be build from sources. Download from https://pypi.org/simple/dlib/ and follow instructions on http://dlib.net/compile.html.

Also, just found another way to access with Visual Studio 2019 (or 2017). Use vcpkg - see link https://vcpkg.readthedocs.io/en/latest/

I built dlib 19.17 on Windows 10 with CMake and it worked fine but then I found vcpkg and now the dlib libraries are integral to the Visual Studio. I no longer need to add all the external links to C++ and the linker.The version in vcpkg is currently 19.16-1 and it is built with full CUDA support.

Hope this helps others..

Correct way of using log4net (logger naming)

Instead of naming my invoking class, I started using the following:

private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

In this way, I can use the same line of code in every class that uses log4net without having to remember to change code when I copy and paste. Alternatively, i could create a logging class, and have every other class inherit from my logging class.

How to simulate a click with JavaScript?

This isn't very well documented, but we can trigger any kinds of events very simply.

This example will trigger 50 double click on the button:

_x000D_
_x000D_
let theclick = new Event("dblclick")

for (let i = 0;i < 50;i++){
  action.dispatchEvent(theclick) 
}
_x000D_
<button id="action" ondblclick="out.innerHTML+='Wtf '">TEST</button>
<div id="out"></div>
_x000D_
_x000D_
_x000D_

The Event interface represents an event which takes place in the DOM.

An event can be triggered by the user action e.g. clicking the mouse button or tapping keyboard, or generated by APIs to represent the progress of an asynchronous task. It can also be triggered programmatically, such as by calling the HTMLElement.click() method of an element, or by defining the event, then sending it to a specified target using EventTarget.dispatchEvent().

https://developer.mozilla.org/en-US/docs/Web/API/Event

https://developer.mozilla.org/en-US/docs/Web/API/Event/Event

Cannot find control with name: formControlName in angular reactive form

you're missing group nested controls with formGroupName directive

<div class="panel-body" formGroupName="address">
  <div class="form-group">
    <label for="address" class="col-sm-3 control-label">Business Address</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="street" placeholder="Business Address">
    </div>
  </div>
  <div class="form-group">
    <label for="website" class="col-sm-3 control-label">Website</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="website" placeholder="website">
    </div>
  </div>
  <div class="form-group">
    <label for="telephone" class="col-sm-3 control-label">Telephone</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="mobile" placeholder="telephone">
    </div>
  </div>
  <div class="form-group">
    <label for="email" class="col-sm-3 control-label">Email</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="email" placeholder="email">
    </div>
  </div>
  <div class="form-group">
    <label for="page id" class="col-sm-3 control-label">Facebook Page ID</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="pageId" placeholder="facebook page id">
    </div>
  </div>
  <div class="form-group">
    <label for="about" class="col-sm-3  control-label"></label>
    <div class="col-sm-3">
      <!--span class="btn btn-success form-control" (click)="openGeneralPanel()">Back</span-->
    </div>
    <label for="about" class="col-sm-2  control-label"></label>
    <div class="col-sm-3">
      <button class="btn btn-success form-control" [disabled]="companyCreatForm.invalid" (click)="openContactInfo()">Continue</button>
    </div>
  </div>
</div>

Rotating a Div Element in jQuery

yeah you're not going to have much luck i think. Typically across the 3 drawing methods the major browsers use (Canvas, SVG, VML), text support is poor, I believe. If you want to rotate an image, then it's all good, but if you've got mixed content with formatting and styles, probably not.

Check out RaphaelJS for a cross-browser drawing API.

Android SeekBar setOnSeekBarChangeListener

Override all methods

    @Override
    public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {


    }

    @Override
    public void onStartTrackingTouch(SeekBar arg0) {


    }

    @Override
    public void onStopTrackingTouch(SeekBar arg0) {


    }

Android ListView Selector Color

TO ADD: @Christopher's answer does not work on API 7/8 (as per @Jonny's correct comment) IF you are using colours, instead of drawables. (In my testing, using drawables as per Christopher works fine)

Here is the FIX for 2.3 and below when using colours:

As per @Charles Harley, there is a bug in 2.3 and below where filling the list item with a colour causes the colour to flow out over the whole list. His fix is to define a shape drawable containing the colour you want, and to use that instead of the colour.

I suggest looking at this link if you want to just use a colour as selector, and are targeting Android 2 (or at least allow for Android 2).

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

if you want to disable the values of the dropdown

$('select option:not(selected)').prop('disabled', true);

$('select').prop('disabled', true);

How to parse my json string in C#(4.0)using Newtonsoft.Json package?

foreach (var data in dynObj.quizlist)
{
    foreach (var data1 in data.QUIZ.QPROP)
    {
        Response.Write("Name" + ":" + data1.name + "<br>");
        Response.Write("Intro" + ":" + data1.intro + "<br>");
        Response.Write("Timeopen" + ":" + data1.timeopen + "<br>");
        Response.Write("Timeclose" + ":" + data1.timeclose + "<br>");
        Response.Write("Timelimit" + ":" + data1.timelimit + "<br>");
        Response.Write("Noofques" + ":" + data1.noofques + "<br>");

        foreach (var queprop in data1.QUESTION.QUEPROP)
        {
            Response.Write("Questiontext" + ":" + queprop.questiontext  + "<br>");
            Response.Write("Mark" + ":" + queprop.mark  + "<br>");
        }
    }
}

Remove CSS from a Div using JQuery

I used the second solution of user147767

However, there is a typo here. It should be

curCssName.toUpperCase().indexOf(cssName.toUpperCase() + ':') < 0

not <= 0

I also changed this condition for:

!curCssName.match(new RegExp(cssName + "(-.+)?:"), "mi")

as sometimes we add a css property over jQuery, and it's added in a different way for different browsers (i.e. the border property will be added as "border" for Firefox, and "border-top", "border-bottom" etc for IE).

Equivalent of Super Keyword in C#

C# equivalent of your code is

  class Imagedata : PDFStreamEngine
  {
     // C# uses "base" keyword whenever Java uses "super" 
     // so instead of super(...) in Java we should call its C# equivalent (base):
     public Imagedata()
       : base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true)) 
     { }

     // Java methods are virtual by default, when C# methods aren't.
     // So we should be sure that processOperator method in base class 
     // (that is PDFStreamEngine)
     // declared as "virtual"
     protected override void processOperator(PDFOperator operations, List arguments)
     {
        base.processOperator(operations, arguments);
     }
  }

What is the point of WORKDIR on Dockerfile?

According to the documentation:

The WORKDIR instruction sets the working directory for any RUN, CMD, ENTRYPOINT, COPY and ADD instructions that follow it in the Dockerfile. If the WORKDIR doesn’t exist, it will be created even if it’s not used in any subsequent Dockerfile instruction.

Also, in the Docker best practices it recommends you to use it:

... you should use WORKDIR instead of proliferating instructions like RUN cd … && do-something, which are hard to read, troubleshoot, and maintain.

I would suggest to keep it.

I think you can refactor your Dockerfile to something like:

FROM node:latest
WORKDIR /usr/src/app
COPY package.json .
RUN npm install
COPY . ./
EXPOSE 3000
CMD [ “npm”, “start” ] 

What is the yield keyword used for in C#?

Recently Raymond Chen also ran an interesting series of articles on the yield keyword.

While it's nominally used for easily implementing an iterator pattern, but can be generalized into a state machine. No point in quoting Raymond, the last part also links to other uses (but the example in Entin's blog is esp good, showing how to write async safe code).

Can I convert a C# string value to an escaped string literal

Interesting question.

If you can't find a better method, you can always replace.
In case you're opting for it, you could use this C# Escape Sequence List:

  • \' - single quote, needed for character literals
  • \" - double quote, needed for string literals
  • \ - backslash
  • \0 - Unicode character 0
  • \a - Alert (character 7)
  • \b - Backspace (character 8)
  • \f - Form feed (character 12)
  • \n - New line (character 10)
  • \r - Carriage return (character 13)
  • \t - Horizontal tab (character 9)
  • \v - Vertical quote (character 11)
  • \uxxxx - Unicode escape sequence for character with hex value xxxx
  • \xn[n][n][n] - Unicode escape sequence for character with hex value nnnn (variable length version of \uxxxx)
  • \Uxxxxxxxx - Unicode escape sequence for character with hex value xxxxxxxx (for generating surrogates)

This list can be found in the C# Frequently Asked Questions What character escape sequences are available?

Where is virtualenvwrapper.sh after pip install?

For RPM-based distributions(like Fedora 19), after running the sudo pip install virtualenvwrapper command, you may find the file at:

/usr/bin/virtualenvwrapper.sh

How to insert Records in Database using C# language?

sql = "insert into Main (Firt Name, Last Name) values(textbox2.Text,textbox3.Text)";

(Firt Name) is not a valid field. It should be FirstName or First_Name. It may be your problem.

standard size for html newsletter template

Bdizzle,

I would recommend that you read this link

You will see that Newsletters can have different widths, There seems to be no major standard, What is recommended is that the width will be about 95% of the page width, as different browsers use the extra margins differently. You will also find that email readers have problems when reading css so applying the guide lines in this tutorial might help you save some time and trouble-shooting down the road.

Be happy, Julian

How to get the Power of some Integer in Swift language?

Or just :

var a:Int = 3
var b:Int = 3
println(pow(Double(a),Double(b)))

How to count check-boxes using jQuery?

You can do it by using name attibute, class, id or just universal checkbox; If you want to count only checked number of checkbox.

By the class name :

var countChk = $('checkbox.myclassboxName:checked').length;

By name attribute :

var countByName= $('checkbox[name=myAllcheckBoxName]:checked').length;

Complete code

$('checkbox.className').blur(function() {
    //count only checked checkbox 
    $('checkbox[name=myAllcheckBoxName]:checked').length;
});

Resize an Array while keeping current elements in Java?

It is not possible to resize an array. However, it is possible change the size of an array through copying the original array to the newly sized one and keep the current elements. The array can also be reduced in size by removing an element and resizing.

import java.util.Arrays 
public class ResizingArray {

    public static void main(String[] args) {

        String[] stringArray = new String[2] //A string array with 2 strings 
        stringArray[0] = "string1";
        stringArray[1] = "string2";

        // increase size and add string to array by copying to a temporary array
        String[] tempStringArray = Arrays.copyOf(stringArray, stringArray.length + 1);
        // Add in the new string 
        tempStringArray[2] = "string3";
        // Copy temp array to original array
        stringArray = tempStringArray;

       // decrease size by removing certain string from array (string1 for example)
       for(int i = 0; i < stringArray.length; i++) {
           if(stringArray[i] == string1) {
               stringArray[i] = stringArray[stringArray.length - 1];
               // This replaces the string to be removed with the last string in the array
               // When the array is resized by -1, The last string is removed 
               // Which is why we copied the last string to the position of the string we wanted to remove
               String[] tempStringArray2 = Arrays.copyOf(arrayString, arrayString.length - 1);
                // Set the original array to the new array
               stringArray = tempStringArray2;
           }
       }
    }    
}

How to reference static assets within vue javascript

It works for me by using require syntax like this:

$('.eventSlick').slick({
    dots: true,
    slidesToShow: 3,
    slidesToScroll: 1,
    autoplay: false,
    autoplaySpeed: 2000,
    arrows: true,
    draggable: false,
    prevArrow: '<button type="button" data-role="none" class="slick-prev"><img src="' + require("@/assets/img/icon/Arrow_Left.svg")+'"></button>',

case statement in SQL, how to return multiple variables?

In a SQL CASE clause, the first successfully matched condition is applied and any subsequent matching conditions are ignored.

How to remove illegal characters from path and filenames?

Or you can just do

[YOUR STRING].Replace('\\', ' ').Replace('/', ' ').Replace('"', ' ').Replace('*', ' ').Replace(':', ' ').Replace('?', ' ').Replace('<', ' ').Replace('>', ' ').Replace('|', ' ').Trim();

Base table or view not found: 1146 Table Laravel 5

Check your migration file, maybe you are using Schema::table, like this:

Schema::table('table_name', function ($table)  {
    // ...
});

If you want to create a new table you must use Schema::create:

Schema::create('table_name', function ($table)  {
    // ...
});

Recommended way to insert elements into map

Use insert if you want to insert a new element. insert will not overwrite an existing element, and you can verify that there was no previously exising element:

if ( !myMap.insert( std::make_pair( key, value ) ).second ) {
    //  Element already present...
}

Use [] if you want to overwrite a possibly existing element:

myMap[ key ] = value;
assert( myMap.find( key )->second == value ); // post-condition

This form will overwrite any existing entry.

Calculate the center point of multiple latitude/longitude coordinate pairs

Very useful post! I've implemented this in JavaScript, hereby my code. I've used this successfully.

function rad2degr(rad) { return rad * 180 / Math.PI; }
function degr2rad(degr) { return degr * Math.PI / 180; }

/**
 * @param latLngInDeg array of arrays with latitude and longtitude
 *   pairs in degrees. e.g. [[latitude1, longtitude1], [latitude2
 *   [longtitude2] ...]
 *
 * @return array with the center latitude longtitude pairs in 
 *   degrees.
 */
function getLatLngCenter(latLngInDegr) {
    var LATIDX = 0;
    var LNGIDX = 1;
    var sumX = 0;
    var sumY = 0;
    var sumZ = 0;

    for (var i=0; i<latLngInDegr.length; i++) {
        var lat = degr2rad(latLngInDegr[i][LATIDX]);
        var lng = degr2rad(latLngInDegr[i][LNGIDX]);
        // sum of cartesian coordinates
        sumX += Math.cos(lat) * Math.cos(lng);
        sumY += Math.cos(lat) * Math.sin(lng);
        sumZ += Math.sin(lat);
    }

    var avgX = sumX / latLngInDegr.length;
    var avgY = sumY / latLngInDegr.length;
    var avgZ = sumZ / latLngInDegr.length;

    // convert average x, y, z coordinate to latitude and longtitude
    var lng = Math.atan2(avgY, avgX);
    var hyp = Math.sqrt(avgX * avgX + avgY * avgY);
    var lat = Math.atan2(avgZ, hyp);

    return ([rad2degr(lat), rad2degr(lng)]);
}

Declaring and using MySQL varchar variables

If you are using phpmyadmin to add new routine then don't forget to wrap your code between BEGIN and ENDenter image description here

How to determine when Fragment becomes visible in ViewPager

New

ViewPager2 + FragmentStateAdapter + onResume() (in Fragment) solve the problem

Old Answer (deprecated)

To detect Fragment in ViewPager visible, I'm quite sure that only using setUserVisibleHint is not enough.
Here is my solution to check if a fragment is visible or invisible. First when launching viewpager, switch between page, go to another activity/fragment/ background/foreground`

public class BaseFragmentHelpLoadDataWhenVisible extends Fragment {
    protected boolean mIsVisibleToUser; // you can see this variable may absolutely <=> getUserVisibleHint() but it not. Currently, after many test I find that

    /**
     * This method will be called when viewpager creates fragment and when we go to this fragment background or another activity or fragment
     * NOT called when we switch between each page in ViewPager
     */
    @Override
    public void onStart() {
        super.onStart();
        if (mIsVisibleToUser) {
            onVisible();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mIsVisibleToUser) {
            onInVisible();
        }
    }

    /**
     * This method will called at first time viewpager created and when we switch between each page
     * NOT called when we go to background or another activity (fragment) when we go back
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        mIsVisibleToUser = isVisibleToUser;
        if (isResumed()) { // fragment have created
            if (mIsVisibleToUser) {
                onVisible();
            } else {
                onInVisible();
            }
        }
    }

    public void onVisible() {
        Toast.makeText(getActivity(), TAG + "visible", Toast.LENGTH_SHORT).show();
    }

    public void onInVisible() {
        Toast.makeText(getActivity(), TAG + "invisible", Toast.LENGTH_SHORT).show();
    }
}

EXPLANATION You can check the logcat below carefully then I think you may know why this solution will work

First launch

Fragment1: setUserVisibleHint: isVisibleToUser=false isResumed=false
Fragment2: setUserVisibleHint: isVisibleToUser=false isResumed=false
Fragment3: setUserVisibleHint: isVisibleToUser=false isResumed=false
Fragment1: setUserVisibleHint: isVisibleToUser=true isResumed=false // AT THIS TIME isVisibleToUser=true but fragment still not created. If you do something with View here, you will receive exception
Fragment1: onCreateView
Fragment1: onStart mIsVisibleToUser=true
Fragment2: onCreateView
Fragment3: onCreateView
Fragment2: onStart mIsVisibleToUser=false
Fragment3: onStart mIsVisibleToUser=false

Go to page2

Fragment1: setUserVisibleHint: isVisibleToUser=false isResumed=true
Fragment2: setUserVisibleHint: isVisibleToUser=true isResumed=true

Go to page3

Fragment2: setUserVisibleHint: isVisibleToUser=false isResumed=true
Fragment3: setUserVisibleHint: isVisibleToUser=true isResumed=true

Go to background:

Fragment1: onStop mIsVisibleToUser=false
Fragment2: onStop mIsVisibleToUser=false
Fragment3: onStop mIsVisibleToUser=true

Go to foreground

Fragment1: onStart mIsVisibleToUser=false
Fragment2: onStart mIsVisibleToUser=false
Fragment3: onStart mIsVisibleToUser=true

DEMO project here

Hope it help

Using Jquery Ajax to retrieve data from Mysql

This answer was for @
Neha Gandhi but I modified it for  people who use pdo and mysqli sing mysql functions are not supported. Here is the new answer 

    <html>
<!--Save this as index.php-->
      <script src="//code.jquery.com/jquery-1.9.1.js"></script>
        <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
    
     <script type="text/javascript">
    
     $(document).ready(function() {
    
        $("#display").click(function() {                
    
          $.ajax({    //create an ajax request to display.php
            type: "GET",
            url: "display.php",             
            dataType: "html",   //expect html to be returned                
            success: function(response){                    
                $("#responsecontainer").html(response); 
                //alert(response);
            }
    
        });
    });
    });
    
    </script>
    
    <body>
    <h3 align="center">Manage Student Details</h3>
    <table border="1" align="center">
       <tr>
           <td> <input type="button" id="display" value="Display All Data" /> </td>
       </tr>
    </table>
    <div id="responsecontainer" align="center">
    
    </div>
    </body>
    </html>

<?php
// save this as display.php


    // show errors 
error_reporting(E_ALL);
ini_set('display_errors', 1);
    //errors ends here 
// call the page for connecting to the db
require_once('dbconnector.php');
?>
<?php
$get_member =" SELECT 
empid, lastName, firstName, email, usercode, companyid, userid, jobTitle, cell, employeetype, address ,initials   FROM employees";
$user_coder1 = $con->prepare($get_member);
$user_coder1 ->execute();

echo "<table border='1' >
<tr>
<td align=center> <b>Roll No</b></td>
<td align=center><b>Name</b></td>
<td align=center><b>Address</b></td>
<td align=center><b>Stream</b></td></td>
<td align=center><b>Status</b></td>";

while($row =$user_coder1->fetch(PDO::FETCH_ASSOC)){
$firstName = $row['firstName'];
$empid = $row['empid'];
$lastName =    $row['lastName'];
$cell =    $row['cell'];

    echo "<tr>";
    echo "<td align=center>$firstName</td>";
    echo "<td align=center>$empid</td>";
    echo "<td align=center>$lastName </td>";
    echo "<td align=center>$cell</td>";
    echo "<td align=center>$cell</td>";
    echo "</tr>";
}
echo "</table>";
?>

<?php
// save this as dbconnector.php
function connected_Db(){

    $dsn  = 'mysql:host=localhost;dbname=mydb;charset=utf8';
    $opt  = array(
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    );
    #echo "Yes we are connected";
    return new PDO($dsn,'username','password', $opt);
    
}
$con = connected_Db();
if($con){
//echo "me  is connected ";
}
else {
//echo "Connection faid ";
exit();
}
?>

Can a constructor in Java be private?

According to me we can declare constructor as a private and also we can get the instance of that class in the subclass by using static method in class in which we declare constructor and then return class object. we class this method from to the sub class by using classname.method name bcz it is static method and the we will get the instance of class in which we declare const.

Get latitude and longitude automatically using php, API

...and don't forget "$region" for the code to work:

$address = "Salzburg";
$address = str_replace(" ", "+", $address);
$region = "Austria";

$json = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=$region");
$json = json_decode($json);

$lat = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lat'};
$long = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lng'};
echo $lat."</br>".$long;

How to split a String by space

Here is a method to trim a String that has a "," or white space

private String shorterName(String s){
        String[] sArr = s.split("\\,|\\s+");
        String output = sArr[0];

        return output;
    }

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its dependencies could not be resolved

Mainly this occurs during Eclipse upgrade.
I Solved using:

-> Right Click Project-> Maven->Update Project-> Select all (checkbox)

Old or out-dated, projects got refreshed with the updated jar files, and the required plugins. No more errors were visible.

jQuery UI DatePicker to show year only

check this out jquery calendar to show only year and month

or something like this

$("#datepicker").datepicker( "option", "dateFormat", "yy" );?

Bulk insert with SQLAlchemy ORM

I usually do it using add_all.

from app import session
from models import User

objects = [User(name="u1"), User(name="u2"), User(name="u3")]
session.add_all(objects)
session.commit()

How do I detect if a user is already logged in Firebase?

use Firebase.getAuth(). It returns the current state of the Firebase client. Otherwise the return value is nullHere are the docs: https://www.firebase.com/docs/web/api/firebase/getauth.html

SQL Server : How to test if a string has only digit characters

There is a system function called ISNUMERIC for SQL 2008 and up. An example:

SELECT myCol
FROM mTable
WHERE ISNUMERIC(myCol)<> 1;

I did a couple of quick tests and also looked further into the docs:

ISNUMERIC returns 1 when the input expression evaluates to a valid numeric data type; otherwise it returns 0.

Which means it is fairly predictable for example

-9879210433 would pass but 987921-0433 does not. $9879210433 would pass but 9879210$433 does not.

So using this information you can weed out based on the list of valid currency symbols and + & - characters.

What is the best open-source java charting library? (other than jfreechart)

I found this framework: jensoft sw2d, free for non commercial use (dual licensing)

http://www.jensoft.org

regards.

Python string.replace regular expression

As a summary

import sys
import re

f = sys.argv[1]
find = sys.argv[2]
replace = sys.argv[3]
with open (f, "r") as myfile:
     s=myfile.read()
ret = re.sub(find,replace, s)   # <<< This is where the magic happens
print ret

Matplotlib tight_layout() doesn't take into account figure suptitle

This website has a simple solution to this with an example that worked for me. The line of code that does the actual leaving of space for the title is the following:

plt.tight_layout(rect=[0, 0, 1, 0.95]) 

Here is an image of proof that it worked for me: Image Link

What CSS selector can be used to select the first div within another div

The MOST CORRECT answer to your question is...

#content > div:first-of-type { /* css */ }

This will apply the CSS to the first div that is a direct child of #content (which may or may not be the first child element of #content)

Another option:

#content > div:nth-of-type(1) { /* css */ }

Check whether a cell contains a substring

Here is the formula I'm using

=IF( ISNUMBER(FIND(".",A1)), LEN(A1) - FIND(".",A1), 0 )

Installing specific package versions with pip

Since this appeared to be a breaking change introduced in version 10 of pip, I downgraded to a compatible version:

pip install 'pip<10' 

This command tells pip to install a version of the module lower than version 10. Do this in a virutalenv so you don't screw up your site installation of Python.

file_get_contents() how to fix error "Failed to open stream", "No such file"

You may try using this

<?php
$json = json_decode(file_get_contents('./prod.api.pvp.net/api/lol/euw/v1.1/game/by-summoner/20986461/recent?api_key=*key*'));
print_r($json);
?>

The "./" allows to search url from current directory. You may use

chdir($_SERVER["DOCUMENT_ROOT"]);

to change current working directory to root of your website if path is relative from root directory.

How to read a file line-by-line into a list?

Here is a Python(3) helper library class that I use to simplify file I/O:

import os

# handle files using a callback method, prevents repetition
def _FileIO__file_handler(file_path, mode, callback = lambda f: None):
  f = open(file_path, mode)
  try:
    return callback(f)
  except Exception as e:
    raise IOError("Failed to %s file" % ["write to", "read from"][mode.lower() in "r rb r+".split(" ")])
  finally:
    f.close()


class FileIO:
  # return the contents of a file
  def read(file_path, mode = "r"):
    return __file_handler(file_path, mode, lambda rf: rf.read())

  # get the lines of a file
  def lines(file_path, mode = "r", filter_fn = lambda line: len(line) > 0):
    return [line for line in FileIO.read(file_path, mode).strip().split("\n") if filter_fn(line)]

  # create or update a file (NOTE: can also be used to replace a file's original content)
  def write(file_path, new_content, mode = "w"):
    return __file_handler(file_path, mode, lambda wf: wf.write(new_content))

  # delete a file (if it exists)
  def delete(file_path):
    return os.remove() if os.path.isfile(file_path) else None

You would then use the FileIO.lines function, like this:

file_ext_lines = FileIO.lines("./path/to/file.ext"):
for i, line in enumerate(file_ext_lines):
  print("Line {}: {}".format(i + 1, line))

Remember that the mode ("r" by default) and filter_fn (checks for empty lines by default) parameters are optional.

You could even remove the read, write and delete methods and just leave the FileIO.lines, or even turn it into a separate method called read_lines.

How do I request and process JSON with python?

Python's standard library has json and urllib2 modules.

import json
import urllib2

data = json.load(urllib2.urlopen('http://someurl/path/to/json'))

Read a local text file using Javascript

You can use a FileReader object to read text file here is example code:

  <div id="page-wrapper">

        <h1>Text File Reader</h1>
        <div>
            Select a text file: 
            <input type="file" id="fileInput">
        </div>
        <pre id="fileDisplayArea"><pre>

    </div>
<script>
window.onload = function() {
        var fileInput = document.getElementById('fileInput');
        var fileDisplayArea = document.getElementById('fileDisplayArea');

        fileInput.addEventListener('change', function(e) {
            var file = fileInput.files[0];
            var textType = /text.*/;

            if (file.type.match(textType)) {
                var reader = new FileReader();

                reader.onload = function(e) {
                    fileDisplayArea.innerText = reader.result;
                }

                reader.readAsText(file);    
            } else {
                fileDisplayArea.innerText = "File not supported!"
            }
        });
}

</script>

Here is the codepen demo

If you have a fixed file to read every time your application load then you can use this code :

<script>
var fileDisplayArea = document.getElementById('fileDisplayArea');
function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                fileDisplayArea.innerText = allText 
            }
        }
    }
    rawFile.send(null);
}

readTextFile("file:///C:/your/path/to/file.txt");
</script>

How to correctly save instance state of Fragments in back stack?

I just want to give the solution that I came up with that handles all cases presented in this post that I derived from Vasek and devconsole. This solution also handles the special case when the phone is rotated more than once while fragments aren't visible.

Here is were I store the bundle for later use since onCreate and onSaveInstanceState are the only calls that are made when the fragment isn't visible

MyObject myObject;
private Bundle savedState = null;
private boolean createdStateInDestroyView;
private static final String SAVED_BUNDLE_TAG = "saved_bundle";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        savedState = savedInstanceState.getBundle(SAVED_BUNDLE_TAG);
    }
}

Since destroyView isn't called in the special rotation situation we can be certain that if it creates the state we should use it.

@Override
public void onDestroyView() {
    super.onDestroyView();
    savedState = saveState();
    createdStateInDestroyView = true;
    myObject = null;
}

This part would be the same.

private Bundle saveState() { 
    Bundle state = new Bundle();
    state.putSerializable(SAVED_BUNDLE_TAG, myObject);
    return state;
}

Now here is the tricky part. In my onActivityCreated method I instantiate the "myObject" variable but the rotation happens onActivity and onCreateView don't get called. Therefor, myObject will be null in this situation when the orientation rotates more than once. I get around this by reusing the same bundle that was saved in onCreate as the out going bundle.

    @Override
public void onSaveInstanceState(Bundle outState) {

    if (myObject == null) {
        outState.putBundle(SAVED_BUNDLE_TAG, savedState);
    } else {
        outState.putBundle(SAVED_BUNDLE_TAG, createdStateInDestroyView ? savedState : saveState());
    }
    createdStateInDestroyView = false;
    super.onSaveInstanceState(outState);
}

Now wherever you want to restore the state just use the savedState bundle

  @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    ...
    if(savedState != null) {
        myObject = (MyObject) savedState.getSerializable(SAVED_BUNDLE_TAG);
    }
    ...
}

How to find a value in an excel column by vba code Cells.Find

Dim strFirstAddress As String
Dim searchlast As Range
Dim search As Range

Set search = ActiveSheet.Range("A1:A100")
Set searchlast = search.Cells(search.Cells.Count)

Set rngFindValue = ActiveSheet.Range("A1:A100").Find(Text, searchlast, xlValues)
If Not rngFindValue Is Nothing Then
  strFirstAddress = rngFindValue.Address
  Do
    Set rngFindValue = search.FindNext(rngFindValue)
  Loop Until rngFindValue.Address = strFirstAddress

List of lists into numpy array

It's as simple as:

>>> lists = [[1, 2], [3, 4]]
>>> np.array(lists)
array([[1, 2],
       [3, 4]])

How to get random value out of an array?

Another approach through flipping array to get direct value.

Snippet

$array = [ 'Name1' => 'John', 'Name2' => 'Jane', 'Name3' => 'Jonny' ];
$val = array_rand(array_flip($array));

array_rand return key not value. So, we're flipping value as key.

Note: PHP key alway be an unique key, so when array is flipped, duplicate value as a key will be overwritten.

iPhone: How to get current milliseconds?

If you're looking at using this for relative timing (for example for games or animation) I'd rather use CACurrentMediaTime()

double CurrentTime = CACurrentMediaTime();

Which is the recommended way; NSDate draws from the networked synch-clock and will occasionally hiccup when re-synching it against the network.

It returns the current absolute time, in seconds.


If you want only the decimal part (often used when syncing animations),

let ct = CACurrentMediaTime().truncatingRemainder(dividingBy: 1)

Create a table without a header in Markdown

Most Markdown parsers don't support tables without headers. That means the separation line for headers is mandatory.

Parsers that do not support tables without headers

Parsers that do support tables without headers.

CSS solution

If you're able to change the CSS of the HTML output you can however leverage the :empty pseudo class to hide an empty header and make it look like there is no header at all.

SQL Server : login success but "The database [dbName] is not accessible. (ObjectExplorer)"

I had twoo users: one that had the sysadmin role, the other one (the problematic one) didn't.

So I logged in with the other user(you can create a new one) and checked the ckeck box 'sysadmin' from: Security --> Logins --> Right ckick on your SQL user name --> Properties --> Server Roles --> make sure that the 'sysadmin' checkbox has the check mark. Press OK and try connecting with the newly checked user.

How to properly set Column Width upon creating Excel file? (Column properties)

Excel ColumnWidth from dataGridView:

           foreach (DataGridViewColumn co in dataGridView1.Columns)
           { worksheet.Columns[co.Index + 1].ColumnWidth = co.Width/8; }

If input field is empty, disable submit button

Please try this

<!DOCTYPE html>
<html>
  <head>
    <title>Jquery</title>
    <meta charset="utf-8">       
    <script src='http://code.jquery.com/jquery-1.7.1.min.js'></script>
  </head>

  <body>

    <input type="text" id="message" value="" />
    <input type="button" id="sendButton" value="Send">

    <script>
    $(document).ready(function(){  

      var checkField;

      //checking the length of the value of message and assigning to a variable(checkField) on load
      checkField = $("input#message").val().length;  

      var enableDisableButton = function(){         
        if(checkField > 0){
          $('#sendButton').removeAttr("disabled");
        } 
        else {
          $('#sendButton').attr("disabled","disabled");
        }
      }        

      //calling enableDisableButton() function on load
      enableDisableButton();            

      $('input#message').keyup(function(){ 
        //checking the length of the value of message and assigning to the variable(checkField) on keyup
        checkField = $("input#message").val().length;
        //calling enableDisableButton() function on keyup
        enableDisableButton();
      });
    });
    </script>
  </body>
</html>

How to create text file and insert data to that file on Android

First create a Project With PdfCreation in Android Studio

Then Follow below steps:

1.Download itextpdf-5.3.2.jar library from this link [https://sourceforge.net/projects/itext/files/iText/iText5.3.2/][1] and then
2.Add to app>libs>itextpdf-5.3.2.jar
3.Right click on jar file then click on add to library
4. Document document = new Document(PageSize.A4); // Create Directory in External Storage
        String root = Environment.getExternalStorageDirectory().toString();
        File myDir = new File(root + "/PDF");
        System.out.print(myDir.toString());
        myDir.mkdirs(); // Create Pdf Writer for Writting into New Created Document
        try {
            PdfWriter.getInstance(document, new FileOutputStream(FILE));
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } // Open Document for Writting into document
        document.open(); // User Define Method
        addMetaData(document);
        try {
            addTitlePage(document);
        } catch (DocumentException e) {
            e.printStackTrace();
        } // Close Document after writting all content
        document.close();

5.   public void addMetaData(Document document)
    {
        document.addTitle("RESUME");
        document.addSubject("Person Info");
        document.addKeywords("Personal, Education, Skills");
                document.addAuthor("TAG");
        document.addCreator("TAG");
    }
    public void addTitlePage(Document document) throws DocumentException
    { // Font Style for Document
        Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
        Font titleFont = new Font(Font.FontFamily.TIMES_ROMAN, 22, Font.BOLD
                | Font.UNDERLINE, BaseColor.GRAY);
        Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
        Font normal = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL); // Start New Paragraph
        Paragraph prHead = new Paragraph(); // Set Font in this Paragraph
        prHead.setFont(titleFont); // Add item into Paragraph
        prHead.add("RESUME – Name\n"); // Create Table into Document with 1 Row
        PdfPTable myTable = new PdfPTable(1); // 100.0f mean width of table is same as Document size
        myTable.setWidthPercentage(100.0f); // Create New Cell into Table
        PdfPCell myCell = new PdfPCell(new Paragraph(""));
        myCell.setBorder(Rectangle.BOTTOM); // Add Cell into Table
        myTable.addCell(myCell);
        prHead.setFont(catFont);
        prHead.add("\nName1 Name2\n");
        prHead.setAlignment(Element.ALIGN_CENTER); // Add all above details into Document
        document.add(prHead);
        document.add(myTable);
        document.add(myTable); // Now Start another New Paragraph
        Paragraph prPersinalInfo = new Paragraph();
        prPersinalInfo.setFont(smallBold);
        prPersinalInfo.add("Address 1\n");
        prPersinalInfo.add("Address 2\n");
        prPersinalInfo.add("City: SanFran. State: CA\n");
        prPersinalInfo.add("Country: USA Zip Code: 000001\n");
        prPersinalInfo.add("Mobile: 9999999999 Fax: 1111111 Email: [email protected] \n");
        prPersinalInfo.setAlignment(Element.ALIGN_CENTER);
        document.add(prPersinalInfo);
        document.add(myTable);
        document.add(myTable);
        Paragraph prProfile = new Paragraph();
        prProfile.setFont(smallBold);
        prProfile.add("\n \n Profile : \n ");
        prProfile.setFont(normal);
        prProfile.add("\nI am Mr. XYZ. I am Android Application Developer at TAG.");
        prProfile.setFont(smallBold);
        document.add(prProfile); // Create new Page in PDF
        document.newPage();
    }

Difference between break and continue statement

The break statement exists the current looping control structure and jumps behind it while the continue exits too but jumping back to the looping condition.

Can I set background image and opacity in the same property?

You can use CSS psuedo selector ::after to achieve this. Here is a working demo.

enter image description here

_x000D_
_x000D_
.bg-container{_x000D_
  width: 100%;_x000D_
  height: 300px;_x000D_
  border: 1px solid #000;_x000D_
  position: relative;_x000D_
}_x000D_
.bg-container .content{_x000D_
  position: absolute;_x000D_
  z-index:999;_x000D_
  text-align: center;_x000D_
  width: 100%;_x000D_
}_x000D_
.bg-container::after{_x000D_
  content: "";_x000D_
  position: absolute;_x000D_
  top: 0px;_x000D_
  left: 0px;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  z-index:-99;_x000D_
  background-image: url(https://i.stack.imgur.com/Hp53k.jpg);_x000D_
  background-size: cover;_x000D_
  opacity: 0.4;_x000D_
}
_x000D_
<div class="bg-container">_x000D_
   <div class="content">_x000D_
     <h1>Background Opacity 0.4</h1>_x000D_
   </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use

Execute dump query in terminal then it will work

mysql -u root -p  <Database_Name> > <path of the input file>

String comparison: InvariantCultureIgnoreCase vs OrdinalIgnoreCase?

You seem to be doing file name comparisons, so I would just add that OrdinalIgnoreCase is closest to what NTFS does (it's not exactly the same, but it's closer than InvariantCultureIgnoreCase)

T-SQL CASE Clause: How to specify WHEN NULL

When you get frustrated trying this:

CASE WHEN last_name IS NULL THEN '' ELSE ' '+last_name END

Try this one instead:

CASE LEN(ISNULL(last_Name,''))
WHEN 0 THEN '' 
ELSE ' ' + last_name
END AS newlastName

LEN(ISNULL(last_Name,'')) measures the number of characters in that column, which will be zero whether it's empty, or NULL, therefore WHEN 0 THEN will evaluate to true and return the '' as expected.

I hope this is a helpful alternative.

I have included this test case for sql server 2008 and above:

DECLARE @last_Name varchar(50) = NULL

SELECT 
CASE LEN(ISNULL(@last_Name,''))
WHEN 0 THEN '' 
ELSE 'A ' + @last_name
END AS newlastName

SET @last_Name = 'LastName'

SELECT 
CASE LEN(ISNULL(@last_Name,''))
WHEN 0 THEN '' 
ELSE 'A ' + @last_name
END AS newlastName

Using BeautifulSoup to extract text without tags

Just loop through all the <strong> tags and use next_sibling to get what you want. Like this:

for strong_tag in soup.find_all('strong'):
    print(strong_tag.text, strong_tag.next_sibling)

Demo:

from bs4 import BeautifulSoup

html = '''
<p>
  <strong class="offender">YOB:</strong> 1987<br />
  <strong class="offender">RACE:</strong> WHITE<br />
  <strong class="offender">GENDER:</strong> FEMALE<br />
  <strong class="offender">HEIGHT:</strong> 5'05''<br />
  <strong class="offender">WEIGHT:</strong> 118<br />
  <strong class="offender">EYE COLOR:</strong> GREEN<br />
  <strong class="offender">HAIR COLOR:</strong> BROWN<br />
</p>
'''

soup = BeautifulSoup(html)

for strong_tag in soup.find_all('strong'):
    print(strong_tag.text, strong_tag.next_sibling)

This gives you:

YOB:  1987
RACE:  WHITE
GENDER:  FEMALE
HEIGHT:  5'05''
WEIGHT:  118
EYE COLOR:  GREEN
HAIR COLOR:  BROWN

Add hover text without javascript like we hover on a user's reputation

The title attribute also works well with other html elements, for example a link...

<a title="hover text" ng-href="{{getUrl()}}"> download link
</a>

Can Console.Clear be used to only clear a line instead of whole console?

Description

You can use the Console.SetCursorPosition function to go to a specific line number. Than you can use this function to clear the line

public static void ClearCurrentConsoleLine()
{
    int currentLineCursor = Console.CursorTop;
    Console.SetCursorPosition(0, Console.CursorTop);
    Console.Write(new string(' ', Console.WindowWidth)); 
    Console.SetCursorPosition(0, currentLineCursor);
}

Sample

Console.WriteLine("Test");
Console.SetCursorPosition(0, Console.CursorTop - 1);
ClearCurrentConsoleLine();

More Information

How To Get The Current Year Using Vba

Try =Year(Now()) and format the cell as General.

How can I generate a unique ID in Python?

here you can find an implementation :

def __uniqueid__():
    """
      generate unique id with length 17 to 21.
      ensure uniqueness even with daylight savings events (clocks adjusted one-hour backward).

      if you generate 1 million ids per second during 100 years, you will generate 
      2*25 (approx sec per year) * 10**6 (1 million id per sec) * 100 (years) = 5 * 10**9 unique ids.

      with 17 digits (radix 16) id, you can represent 16**17 = 295147905179352825856 ids (around 2.9 * 10**20).
      In fact, as we need far less than that, we agree that the format used to represent id (seed + timestamp reversed)
      do not cover all numbers that could be represented with 35 digits (radix 16).

      if you generate 1 million id per second with this algorithm, it will increase the seed by less than 2**12 per hour
      so if a DST occurs and backward one hour, we need to ensure to generate unique id for twice times for the same period.
      the seed must be at least 1 to 2**13 range. if we want to ensure uniqueness for two hours (100% contingency), we need 
      a seed for 1 to 2**14 range. that's what we have with this algorithm. You have to increment seed_range_bits if you
      move your machine by airplane to another time zone or if you have a glucky wallet and use a computer that can generate
      more than 1 million ids per second.

      one word about predictability : This algorithm is absolutely NOT designed to generate unpredictable unique id.
      you can add a sha-1 or sha-256 digest step at the end of this algorithm but you will loose uniqueness and enter to collision probability world.
      hash algorithms ensure that for same id generated here, you will have the same hash but for two differents id (a pair of ids), it is
      possible to have the same hash with a very little probability. You would certainly take an option on a bijective function that maps
      35 digits (or more) number to 35 digits (or more) number based on cipher block and secret key. read paper on breaking PRNG algorithms 
      in order to be convinced that problems could occur as soon as you use random library :)

      1 million id per second ?... on a Intel(R) Core(TM)2 CPU 6400 @ 2.13GHz, you get :

      >>> timeit.timeit(uniqueid,number=40000)
      1.0114529132843018

      an average of 40000 id/second
    """
    mynow=datetime.now
    sft=datetime.strftime
    # store old datetime each time in order to check if we generate during same microsecond (glucky wallet !)
    # or if daylight savings event occurs (when clocks are adjusted backward) [rarely detected at this level]
    old_time=mynow() # fake init - on very speed machine it could increase your seed to seed + 1... but we have our contingency :)
    # manage seed
    seed_range_bits=14 # max range for seed
    seed_max_value=2**seed_range_bits - 1 # seed could not exceed 2**nbbits - 1
    # get random seed
    seed=random.getrandbits(seed_range_bits)
    current_seed=str(seed)
    # producing new ids
    while True:
        # get current time 
        current_time=mynow()
        if current_time <= old_time:
            # previous id generated in the same microsecond or Daylight saving time event occurs (when clocks are adjusted backward)
            seed = max(1,(seed + 1) % seed_max_value)
            current_seed=str(seed)
        # generate new id (concatenate seed and timestamp as numbers)
        #newid=hex(int(''.join([sft(current_time,'%f%S%M%H%d%m%Y'),current_seed])))[2:-1]
        newid=int(''.join([sft(current_time,'%f%S%M%H%d%m%Y'),current_seed]))
        # save current time
        old_time=current_time
        # return a new id
        yield newid

""" you get a new id for each call of uniqueid() """
uniqueid=__uniqueid__().next

import unittest
class UniqueIdTest(unittest.TestCase):
    def testGen(self):
        for _ in range(3):
            m=[uniqueid() for _ in range(10)]
            self.assertEqual(len(m),len(set(m)),"duplicates found !")

hope it helps !

Where could I buy a valid SSL certificate?

You are really asking a couple of questions here:

1) Why does the price of SSL certificates vary so much

2) Where can I get good, cheap SSL certificates?

The first question is a good one. For example, the type of SSL certificate you buy is important. Many SSL certificates are domain verified only - that is, the company issuing the certificate only validate that you own the domain. They don't validate your identity, so people visiting your site might know that the domain has a SSL certificate, but that doesn't mean the person behing the website isn't a scammer or phisher, for example. This is why the Verisign solution is much more expensive - you are getting a cert that not only secures your site, but validates the identity of the owner of the site (well, that's the claim).

You can read more on this subject here

For your second question, I can personally recommend RapidSSL. I've bought several certificates from them in the past and they are, well, rapid. However, you should always do your research first. A company based in France might be better for you to deal with as you can get support in your local hours, etc.

Sorting list based on values from another list

Another alternative, combining several of the answers.

zip(*sorted(zip(Y,X)))[1]

In order to work for python3:

list(zip(*sorted(zip(B,A))))[1]

How do I ignore an error on 'git pull' about my local changes would be overwritten by merge?

In the recent Git, you can add -r/--rebase on pull command to rebase your current branch on top of the upstream branch after fetching. The warning should disappear, but there is a risk that you'll get some conflicts which you'll need to solve.


Alternatively you can checkout different branch with force, then go back to master again, e.g.:

git checkout origin/master -f
git checkout master -f

Then pull it again as usual:

git pull origin master

Using this method can save you time from stashing (git stash) and potential permission issues, reseting files (git reset HEAD --hard), removing files (git clean -fd), etc. Also the above it's easier to remember.

Circle-Rectangle collision detection (intersection)

Actually, this is much more simple. You need only two things.

First, you need to find four orthogonal distances from the circle centre to each line of the rectangle. Then your circle will not intersect the rectangle if any three of them are larger than the circle radius.

Second, you need to find the distance between the circle centre and the rectangle centre, then you circle will not be inside of the rectangle if the distance is larger than a half of the rectangle diagonal length.

Good luck!

Oracle Partition - Error ORA14400 - inserted partition key does not map to any partition

For this issue need to add the partition for date column values, If last partition 20201231245959, then inserting the 20210110245959 values, this issue will occurs.

For that need to add the 2021 partition into that table

ALTER TABLE TABLE_NAME ADD PARTITION PARTITION_NAME VALUES LESS THAN (TO_DATE('2021-12-31 24:59:59', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')) NOCOMPRESS

RestClientException: Could not extract response. no suitable HttpMessageConverter found

Please add the shared dependency having jackson databind package . Hope this will clear the issue.

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

Parse rfc3339 date strings in Python?

You can use dateutil.parser.parse (install with python -m pip install python-dateutil) to parse strings into datetime objects.

dateutil.parser.parse will attempt to guess the format of your string, if you know the exact format in advance then you can use datetime.strptime which you supply a format string to (see Brent Washburne's answer).

from dateutil.parser import parse

a = "2012-10-09T19:00:55Z"

b = parse(a)

print(b.weekday())
# 1 (equal to a Tuesday)

How to close current tab in a browser window?

This is one way of solving the same, declare a JavaScript function like this

<script>
  function Exit() {
     var x=confirm('Are You sure want to exit:');
     if(x) window.close();
   }
</script>

Add the following line to the HTML to call the function using a <button>

<button name='closeIt' onClick="Exit()" >Click to exit </Button>

org.postgresql.util.PSQLException: FATAL: sorry, too many clients already

No need to increase the MaxConnections & InitialConnections. Just close your connections after after doing your work. For example if you are creating connection:

try {
     connection = DriverManager.getConnection(
                    "jdbc:postgresql://127.0.0.1/"+dbname,user,pass);

   } catch (SQLException e) {
    e.printStackTrace();
    return;
}

After doing your work close connection:

try {
    connection.commit();
    connection.close();
} catch (SQLException e) {
    e.printStackTrace();
}

How to make a countdown timer in Android?

Here's the solution I used in Kotlin

private fun startTimer()
{
    Log.d(TAG, ":startTimer: timeString = '$timeString'")

    object : CountDownTimer(TASK_SWITCH_TIMER, 250)
    {
        override fun onTick(millisUntilFinished: Long)
        {
            val secondsUntilFinished : Long = 
            Math.ceil(millisUntilFinished.toDouble()/1000).toLong()
            val timeString = "${TimeUnit.SECONDS.toMinutes(secondsUntilFinished)}:" +
                    "%02d".format(TimeUnit.SECONDS.toSeconds(secondsUntilFinished))
            Log.d(TAG, ":startTimer::CountDownTimer:millisUntilFinished = $ttlseconds")
            Log.d(TAG, ":startTimer::CountDownTimer:millisUntilFinished = $millisUntilFinished")
        }

        @SuppressLint("SetTextI18n")
        override fun onFinish()
        {
            timerTxtVw.text = "0:00"
            gameStartEndVisibility(true)
        }
    }.start()
}

POST Multipart Form Data using Retrofit 2.0 including image

There is a correct way of uploading a file with its name with Retrofit 2, without any hack:

Define API interface:

@Multipart
@POST("uploadAttachment")
Call<MyResponse> uploadAttachment(@Part MultipartBody.Part filePart); 
                                   // You can add other parameters too

Upload file like this:

File file = // initialize file here

MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));

Call<MyResponse> call = api.uploadAttachment(filePart);

This demonstrates only file uploading, you can also add other parameters in the same method with @Part annotation.

How to call a PHP file from HTML or Javascript

You just need to post the form data to the insert php file function, see below :)

class DbConnect
{
// Database login vars
private $dbHostname = '';
private $dbDatabase = '';
private $dbUsername = '';
private $dbPassword = '';
public $db = null;

public function connect()
{

    try
    {
        $this->db = new PDO("mysql:host=".$this->dbHostname.";dbname=".$this->dbDatabase, $this->dbUsername, $this->dbPassword);
        $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch(PDOException $e)
    {
        echo "It seems there was an error.  Please refresh your browser and try again. ".$e->getMessage();
    }
}

public function store($email)
{
    $stm = $this->db->prepare('INSERT INTO subscribers (email) VALUES ?');
    $stm->bindValue(1, $email);

    return $stm->execute();
}
}

Log4j, configuring a Web App to use a relative path

My suggestion is the log file should always be logged above the root context of the webApp, so in case we redeploy the webApp, we don't want to override the existing log files.

Validating with an XML schema in Python

There are two ways(actually there are more) that you could do this.
1. using lxml
pip install lxml

from lxml import etree, objectify
from lxml.etree import XMLSyntaxError

def xml_validator(some_xml_string, xsd_file='/path/to/my_schema_file.xsd'):
    try:
        schema = etree.XMLSchema(file=xsd_file)
        parser = objectify.makeparser(schema=schema)
        objectify.fromstring(some_xml_string, parser)
        print "YEAH!, my xml file has validated"
    except XMLSyntaxError:
        #handle exception here
        print "Oh NO!, my xml file does not validate"
        pass

xml_file = open('my_xml_file.xml', 'r')
xml_string = xml_file.read()
xml_file.close()

xml_validator(xml_string, '/path/to/my_schema_file.xsd')
  1. Use xmllint from the commandline. xmllint comes installed in many linux distributions.

>> xmllint --format --pretty 1 --load-trace --debug --schema /path/to/my_schema_file.xsd /path/to/my_xml_file.xml

Apache Maven install "'mvn' not recognized as an internal or external command" after setting OS environmental variables?

A temporary work around would be to set the path from the terminal itself. Worked for me after that. Running as administrator also works. Both M2 and M2_HOME are already set as system variables in my case.

DateTime.Compare how to check if a date is less than 30 days old?

No, the Compare function will return either 1, 0, or -1. 0 when the two values are equal, -1 and 1 mean less than and greater than, I believe in that order, but I often mix them up.

Using Python's list index() method on a list of tuples or objects?

z = list(zip(*tuple_list))
z[1][z[0].index('persimon')]

How many parameters are too many?

If you start having to mentally count off the parameters in the signature and match them to the call, then it is time to refactor!

Python match a string with regex

r stands for a raw string, so things like \ will be automatically escaped by Python.

Normally, if you wanted your pattern to include something like a backslash you'd need to escape it with another backslash. raw strings eliminate this problem.

short explanation

In your case, it does not matter much but it's a good habit to get into early otherwise something like \b will bite you in the behind if you are not careful (will be interpreted as backspace character instead of word boundary)

As per re.match vs re.search here's an example that will clarify it for you:

>>> import re
>>> testString = 'hello world'
>>> re.match('hello', testString)
<_sre.SRE_Match object at 0x015920C8>
>>> re.search('hello', testString)
<_sre.SRE_Match object at 0x02405560>
>>> re.match('world', testString)
>>> re.search('world', testString)
<_sre.SRE_Match object at 0x015920C8>

So search will find a match anywhere, match will only start at the beginning

List of Stored Procedures/Functions Mysql Command Line

My favorite rendering of the procedures list of the current database: name, parameters list, comment

SELECT specific_name AS name, param_list AS params, `comment`
FROM mysql.proc
WHERE db = DATABASE()
AND type = 'PROCEDURE';

Add returns for functions:

SELECT specific_name AS name, param_list AS params, `returns`, `comment`
FROM mysql.proc
WHERE db = DATABASE()
AND type = 'FUNCTION';

How do I tell matplotlib that I am done with a plot?

Just enter plt.hold(False) before the first plt.plot, and you can stick to your original code.

PHP new line break in emails

When we insert any line break with a programming language the char code for this is "\n". php does output that but html can't display that due to htmls line break is
. so easy way to do this job is replacing all the "\n" with "
". so the code should be

str_replace("\n","<br/>",$str);

after adding this code you wont have to use pre tag for all the output oparation.

copyed this ans from this website :

Could not load file or assembly "Oracle.DataAccess" or one of its dependencies

I found the solution with following steps:

  • remove the Oracle.DataAcces.dll reference,
    and add a fresh reference to:
    C:\windows\assembly\GAC\Oracle.DataAccess\X.XXX.X.XX__89b483f429c47342/oracle.dataaccess.dll
  • Make local copy= false.

Hope it helps

Can I use an image from my local file system as background in HTML?

You forgot the C: after the file:///
This works for me

<!DOCTYPE html>
<html>
    <head>
        <title>Experiment</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <style>
            html,body { width: 100%; height: 100%; }
        </style>
    </head>
    <body style="background: url('file:///C:/Users/Roby/Pictures/battlefield-3.jpg')">
    </body>
</html>

Windows equivalent to UNIX pwd

You can simply put "." the dot sign. I've had a cmd application that was requiring the path and I was already in the needed directory and I used the dot symbol.

Hope it helps.

SMTP server response: 530 5.7.0 Must issue a STARTTLS command first

Problem Solved,

I edited the file /etc/postfix/master.cf

and commented

-o smtpd_relay_restrictions=permit_sasl_authenticated,reject

and changed the line from

-o smtpd_tls_security_level=encrypt 

to

-o smtpd_tls_security_level=may

And worked on fine

How to convert hashmap to JSON object in Java

You can convert Map to JSON using Jackson as follows:

Map<String,Object> map = new HashMap<>();
//You can convert any Object.
String[] value1 = new String[] { "value11", "value12", "value13" };
String[] value2 = new String[] { "value21", "value22", "value23" };
map.put("key1", value1);
map.put("key2", value2);
map.put("key3","string1");
map.put("key4","string2");

String json = new ObjectMapper().writeValueAsString(map);
System.out.println(json);

Maven Dependencies for Jackson :

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.5.3</version>
    <scope>compile</scope>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.3</version>
    <scope>compile</scope>
</dependency>

If you are using JSONObject library, you can convert map to JSON as follows:

Map<String, Object> map = new HashMap<>();
// Convert a map having list of values.
String[] value1 = new String[] { "value11", "value12", "value13" };
String[] value2 = new String[] { "value21", "value22", "value23" };
map.put("key1", value1);
map.put("key2", value2);

JSONObject json = new JSONObject(map);
System.out.println(json);

Maven Dependencies for JSONObject :

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20140107</version>
</dependency>

Hope this will help. Happy coding.

How to connect from windows command prompt to mysql command line

To make it easier to invoke MySQL programs, you can add the path name of the MySQL bin directory to your Windows system PATH environment variable:

On the Windows desktop, right-click the My Computer icon, and select Properties.

Next select the Advanced tab from the System Properties menu that appears, and click the Environment Variables button.

Under System Variables, select Path, and then click the Edit button. The Edit System Variable dialogue should appear.

Place your cursor at the end of the text appearing in the space marked Variable Value. (Use the End key to ensure that your cursor is positioned at the very end of the text in this space.) Then enter the complete path name of your MySQL bin directory (for example, C:\Program Files\MySQL\MySQL Server 8.0\bin).

Open a different terminal and if you are using root as user run mysql -u root -p else use the a different username you created.

Vertical line using XML drawable

To make a vertical line, just use a rectangle with width of 1dp:

<shape>
    <size
        android:width="1dp"
        android:height="16dp" />
    <solid
        android:color="#c8cdd2" />
</shape>

Don't use stroke, use solid (which is the "fill" color) to specify the color of the line.

How to make the division of 2 ints produce a float instead of another int?

Cast one of the integers/both of the integer to float to force the operation to be done with floating point Math. Otherwise integer Math is always preferred. So:

1. v = (float)s / t;
2. v = (float)s / (float)t;

regex match any single character (one character only)

Match any single character

  • Use the dot . character as a wildcard to match any single character.

Example regex: a.c

abc   // match
a c   // match
azc   // match
ac    // no match
abbc  // no match

Match any specific character in a set

  • Use square brackets [] to match any characters in a set.
  • Use \w to match any single alphanumeric character: 0-9, a-z, A-Z, and _ (underscore).
  • Use \d to match any single digit.
  • Use \s to match any single whitespace character.

Example 1 regex: a[bcd]c

abc   // match
acc   // match
adc   // match
ac    // no match
abbc  // no match

Example 2 regex: a[0-7]c

a0c   // match
a3c   // match
a7c   // match
a8c   // no match
ac    // no match
a55c  // no match

Match any character except ...

Use the hat in square brackets [^] to match any single character except for any of the characters that come after the hat ^.

Example regex: a[^abc]c

aac   // no match
abc   // no match
acc   // no match
a c   // match
azc   // match
ac    // no match
azzc  // no match

(Don't confuse the ^ here in [^] with its other usage as the start of line character: ^ = line start, $ = line end.)

Match any character optionally

Use the optional character ? after any character to specify zero or one occurrence of that character. Thus, you would use .? to match any single character optionally.

Example regex: a.?c

abc   // match
a c   // match
azc   // match
ac    // match
abbc  // no match

See also

How to make graphics with transparent background in R using ggplot2?

As for someone don't like gray background like academic editor, try this:

p <- p + theme_bw()
p

How to build x86 and/or x64 on Windows from command line with CMAKE?

Besides CMAKE_GENERATOR_PLATFORM variable, there is also the -A switch

cmake -G "Visual Studio 16 2019" -A Win32
cmake -G "Visual Studio 16 2019" -A x64

https://cmake.org/cmake/help/v3.16/generator/Visual%20Studio%2016%202019.html#platform-selection

  -A <platform-name>           = Specify platform name if supported by
                                 generator.

How to kill all processes matching a name?

The safe way to do this is:

pkill -f amarok

How do I create a simple Qt console application in C++?

I managed to create a simple console "hello world" with QT Creator

used creator 2.4.1 and QT 4.8.0 on windows 7

two ways to do this

Plain C++

do the following

  1. File- new file project
  2. under projects select : other Project
  3. select "Plain C++ Project"
  4. enter project name 5.Targets select Desktop 'tick it'
  5. project managment just click next
  6. you can use c++ commands as normal c++

or

QT Console

  1. File- new file project
  2. under projects select : other Project
  3. select QT Console Application
  4. Targets select Desktop 'tick it'
  5. project managment just click next
  6. add the following lines (all the C++ includes you need)
  7. add "#include 'iostream' "
  8. add "using namespace std; "
  9. after QCoreApplication a(int argc, cghar *argv[]) 10 add variables, and your program code..

example: for QT console "hello world"

file - new file project 'project name '

other projects - QT Console Application

Targets select 'Desktop'

project management - next

code:

    #include <QtCore/QCoreApplication>
    #include <iostream>
    using namespace std;
    int main(int argc, char *argv[])
    {
     QCoreApplication a(argc, argv);
     cout<<" hello world";
     return a.exec();
     }

ctrl -R to run

compilers used for above MSVC 2010 (QT SDK) , and minGW(QT SDK)

hope this helps someone

As I have just started to use QT recently and also searched the Www for info and examples to get started with simple examples still searching...

Replace forward slash "/ " character in JavaScript string?

First of all, that's a forward slash. And no, you can't have any in regexes unless you escape them. To escape them, put a backslash (\) in front of it.

someString.replace(/\//g, "-");

Live example

Read XLSX file in Java

Try this:

  1. Unzip XLSX file
  2. Read XML files
  3. Compose and use data

Example code:

    public Workbook getTemplateData(String xlsxFile) {
    Workbook workbook = new Workbook();
    parseSharedStrings(xlsxFile);
    parseWorkesheet(xlsxFile, workbook);
    parseComments(xlsxFile, workbook);
    for (Worksheet worksheet : workbook.sheets) {
        worksheet.dimension = manager.getDimension(worksheet);
    }

    return workbook;
}

private void parseComments(String tmpFile, Workbook workbook) {
    try {
        FileInputStream fin = new FileInputStream(tmpFile);
        final ZipInputStream zin = new ZipInputStream(fin);
        InputStream in = getInputStream(zin);
        while (true) {
            ZipEntry entry = zin.getNextEntry();
            if (entry == null)
                break;

            String name = entry.getName();
            if (name.endsWith(".xml")) { //$NON-NLS-1$
                if (name.contains(COMMENTS)) {
                    parseComments(in, workbook);
                }
            }
            zin.closeEntry();
        }
        in.close();
        zin.close();
        fin.close();
    } catch (FileNotFoundException e) {
        System.out.println(e);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private void parseComments(InputStream in, Workbook workbook) {
    try {
        DefaultHandler handler = getCommentHandler(workbook);
        SAXParser saxParser = getSAXParser();
        saxParser.parse(in, handler);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private DefaultHandler getCommentHandler(Workbook workbook) {
    final Worksheet ws = workbook.sheets.get(0);
    return new DefaultHandler() {
        String lastTag = "";
        private Cell ccell;

        @Override
        public void startElement(String uri, String localName,
                String qName, Attributes attributes) throws SAXException {
            lastTag = qName;
            if (lastTag.equals("comment")) {
                String cellName = attributes.getValue("ref");
                int r = manager.getRowIndex(cellName);
                int c = manager.getColumnIndex(cellName);
                Row row = ws.rows.get(r);
                if (row == null) {
                    row = new Row();
                    row.index = r;
                    ws.rows.put(r, row);
                }
                ccell = row.cells.get(c);
                if (ccell == null) {
                    ccell = new Cell();
                    ccell.cellName = cellName;
                    row.cells.put(c, ccell);
                }
            }
        }

        @Override
        public void characters(char[] ch, int start, int length)
                throws SAXException {
            String val = "";
            if (ccell != null && lastTag.equals("t")) {
                for (int i = start; i < start + length; i++) {
                    val += ch[i];
                }
                if (ccell.comment == null)
                    ccell.comment = val;
                else {
                    ccell.comment += val;
                }
            }
        }
    };
}

private void parseSharedStrings(String tmpFile) {
    try {
        FileInputStream fin = new FileInputStream(tmpFile);
        final ZipInputStream zin = new ZipInputStream(fin);
        InputStream in = getInputStream(zin);
        while (true) {
            ZipEntry entry = zin.getNextEntry();
            if (entry == null)
                break;
            String name = entry.getName();
            if (name.endsWith(".xml")) { //$NON-NLS-1$
                if (name.startsWith(SHARED_STRINGS)) {
                    parseStrings(in);
                }
            }
            zin.closeEntry();
        }
        in.close();
        zin.close();
        fin.close();
    } catch (FileNotFoundException e) {
        System.out.println(e);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void parseWorkesheet(String tmpFile, Workbook workbook) {
    try {
        FileInputStream fin = new FileInputStream(tmpFile);
        final ZipInputStream zin = new ZipInputStream(fin);
        InputStream in = getInputStream(zin);
        while (true) {
            ZipEntry entry = zin.getNextEntry();
            if (entry == null)
                break;

            String name = entry.getName();
            if (name.endsWith(".xml")) { //$NON-NLS-1$
                if (name.contains("worksheets")) {
                    Worksheet worksheet = new Worksheet();
                    worksheet.name = name;
                    parseWorksheet(in, worksheet);
                    workbook.sheets.add(worksheet);
                }
            }
            zin.closeEntry();
        }
        in.close();
        zin.close();
        fin.close();
    } catch (FileNotFoundException e) {
        System.out.println(e);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void parseWorksheet(InputStream in, Worksheet worksheet)
        throws IOException {
    // read sheet1 sharedStrings
    // styles, strings, formulas ...
    try {
        DefaultHandler handler = getDefaultHandler(worksheet);
        SAXParser saxParser = getSAXParser();
        saxParser.parse(in, handler);
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
}

where Workbook class:

public class Workbook {
Integer id = null;
public List<Worksheet> sheets = new ArrayList<Worksheet>();}

and Worksheet class:

public class Worksheet {
public Integer id = null;
public String name = null;
public String dimension = null;
public Map<Integer, Row> rows = new TreeMap<Integer, Row>();
public Map<Integer, Column> columns = new TreeMap<Integer, Column>();
public List<Span> spans = new ArrayList<Span>();}

and Row class:

public class Row {
public Integer id = null;
public Integer index = null;
public Row tmpRow = null;
public Style style = null;
public Double height = null;
public Map<Integer,Cell> cells = new TreeMap<Integer, Cell>();
public String spans = null;
public Integer customHeight = null;}

and Cell class:

public class Cell {
public Integer id = null;
public Integer rowIndex = null;
public Integer colIndex = null;
public String cellName = null;
public String text = null;
public String formula = null;
public String comment = null;
public Style style = null;
public Object value = null;
public Cell tmpCell = null;}

and Column class:

public class Column {
    public Integer index = null;
    public Style style = null;
    public String width = null;
    public Column tmpColumn = null;
}

and Span class:

public class Span {
    Integer id = null;
    String topLeft = null;
    String bottomRight = null;
}

How to extract week number in sql

Use 'dd-mon-yyyy' if you are using the 2nd date format specified in your answer. Ex:

to_date(<column name>,'dd-mon-yyyy')

How do I create a new column from the output of pandas groupby().sum()?

How do I create a new column with Groupby().Sum()?

There are two ways - one straightforward and the other slightly more interesting.


Everybody's Favorite: GroupBy.transform() with 'sum'

@Ed Chum's answer can be simplified, a bit. Call DataFrame.groupby rather than Series.groupby. This results in simpler syntax.

# The setup.
df[['Date', 'Data3']]

         Date  Data3
0  2015-05-08      5
1  2015-05-07      8
2  2015-05-06      6
3  2015-05-05      1
4  2015-05-08     50
5  2015-05-07    100
6  2015-05-06     60
7  2015-05-05    120

df.groupby('Date')['Data3'].transform('sum')

0     55
1    108
2     66
3    121
4     55
5    108
6     66
7    121
Name: Data3, dtype: int64 

It's a tad faster,

df2 = pd.concat([df] * 12345)

%timeit df2['Data3'].groupby(df['Date']).transform('sum')
%timeit df2.groupby('Date')['Data3'].transform('sum')

10.4 ms ± 367 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
8.58 ms ± 559 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Unconventional, but Worth your Consideration: GroupBy.sum() + Series.map()

I stumbled upon an interesting idiosyncrasy in the API. From what I tell, you can reproduce this on any major version over 0.20 (I tested this on 0.23 and 0.24). It seems like you consistently can shave off a few milliseconds of the time taken by transform if you instead use a direct function of GroupBy and broadcast it using map:

df.Date.map(df.groupby('Date')['Data3'].sum())

0     55
1    108
2     66
3    121
4     55
5    108
6     66
7    121
Name: Date, dtype: int64

Compare with

df.groupby('Date')['Data3'].transform('sum')

0     55
1    108
2     66
3    121
4     55
5    108
6     66
7    121
Name: Data3, dtype: int64

My tests show that map is a bit faster if you can afford to use the direct GroupBy function (such as mean, min, max, first, etc). It is more or less faster for most general situations upto around ~200 thousand records. After that, the performance really depends on the data.

(Left: v0.23, Right: v0.24)

Nice alternative to know, and better if you have smaller frames with smaller numbers of groups. . . but I would recommend transform as a first choice. Thought this was worth sharing anyway.

Benchmarking code, for reference:

import perfplot

perfplot.show(
    setup=lambda n: pd.DataFrame({'A': np.random.choice(n//10, n), 'B': np.ones(n)}),
    kernels=[
        lambda df: df.groupby('A')['B'].transform('sum'),
        lambda df:  df.A.map(df.groupby('A')['B'].sum()),
    ],
    labels=['GroupBy.transform', 'GroupBy.sum + map'],
    n_range=[2**k for k in range(5, 20)],
    xlabel='N',
    logy=True,
    logx=True
)

Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'

Try to add ReactiveFormsModule in your component as well.

import { FormGroup, FormArray, FormBuilder,
          Validators,ReactiveFormsModule  } from '@angular/forms';

How to compile a 32-bit binary on a 64-bit linux machine with gcc/cmake

$ gcc test.c -o testc
$ file testc
testc: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.9, not stripped
$ ldd testc 
    linux-vdso.so.1 =>  (0x00007fff227ff000)
    libc.so.6 => /lib64/libc.so.6 (0x000000391f000000)
    /lib64/ld-linux-x86-64.so.2 (0x000000391ec00000)
$ gcc -m32 test.c -o testc
$ file testc
testc: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.9, not stripped
$ ldd testc
    linux-gate.so.1 =>  (0x009aa000)
    libc.so.6 => /lib/libc.so.6 (0x00780000)
    /lib/ld-linux.so.2 (0x0075b000)

In short: use the -m32 flag to compile a 32-bit binary.

Also, make sure that you have the 32-bit versions of all required libraries installed (in my case all I needed on Fedora was glibc-devel.i386)

How to change onClick handler dynamically?

Try:

document.getElementById("foo").onclick = function (){alert('foo');};

@Html.DropDownListFor how to set default value

try this

 @Html.DropDownListFor(model => model.UserName, new List<SelectListItem> 
   { new SelectListItem{Text="Active", Value="True",Selected =true },
     new SelectListItem{Text="Deactive", Value="False"}})

Programmatically set left drawable in a TextView

A Kotlin extension + some padding around the drawable

fun TextView.addDrawable(drawable: Int) {
val imgDrawable = ContextCompat.getDrawable(context, drawable)
compoundDrawablePadding = 32
setCompoundDrawablesWithIntrinsicBounds(imgDrawable, null, null, null)
}

What primitive data type is time_t?

It's platform-specific. But you can cast it to a known type.

printf("%lld\n", (long long) time(NULL));

install / uninstall APKs programmatically (PackageManager vs Intents)

Prerequisite:

Your APK needs to be signed by system as correctly pointed out earlier. One way to achieve that is building the AOSP image yourself and adding the source code into the build.

Code:

Once installed as a system app, you can use the package manager methods to install and uninstall an APK as following:

Install:

public boolean install(final String apkPath, final Context context) {
    Log.d(TAG, "Installing apk at " + apkPath);
    try {
        final Uri apkUri = Uri.fromFile(new File(apkPath));
        final String installerPackageName = "MyInstaller";
        context.getPackageManager().installPackage(apkUri, installObserver, PackageManager.INSTALL_REPLACE_EXISTING, installerPackageName);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

Uninstall:

public boolean uninstall(final String packageName, final Context context) {
    Log.d(TAG, "Uninstalling package " + packageName);
    try {
        context.getPackageManager().deletePackage(packageName, deleteObserver, PackageManager.DELETE_ALL_USERS);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

To have a callback once your APK is installed/uninstalled you can use this:

/**
 * Callback after a package was installed be it success or failure.
 */
private class InstallObserver implements IPackageInstallObserver {

    @Override
    public void packageInstalled(String packageName, int returnCode) throws RemoteException {

        if (packageName != null) {
            Log.d(TAG, "Successfully installed package " + packageName);
            callback.onAppInstalled(true, packageName);
        } else {
            Log.e(TAG, "Failed to install package.");
            callback.onAppInstalled(false, null);
        }
    }

    @Override
    public IBinder asBinder() {
        return null;
    }
}

/**
 * Callback after a package was deleted be it success or failure.
 */
private class DeleteObserver implements IPackageDeleteObserver {

    @Override
    public void packageDeleted(String packageName, int returnCode) throws RemoteException {
        if (packageName != null) {
            Log.d(TAG, "Successfully uninstalled package " + packageName);
            callback.onAppUninstalled(true, packageName);
        } else {
            Log.e(TAG, "Failed to uninstall package.");
            callback.onAppUninstalled(false, null);
        }
    }

    @Override
    public IBinder asBinder() {
        return null;
    }
}

/**
 * Callback to give the flow back to the calling class.
 */
public interface InstallerCallback {
    void onAppInstalled(final boolean success, final String packageName);
    void onAppUninstalled(final boolean success, final String packageName);
}

What is REST call and how to send a REST call?

REST is just a software architecture style for exposing resources.

  • Use HTTP methods explicitly.
  • Be stateless.
  • Expose directory structure-like URIs.
  • Transfer XML, JavaScript Object Notation (JSON), or both.

A typical REST call to return information about customer 34456 could look like:

http://example.com/customer/34456

Have a look at the IBM tutorial for REST web services

Printing the value of a variable in SQL Developer

select View-->DBMS Output in menu and

Remove Item from ArrayList

Try it this way,

ArrayList<String> List_Of_Array = new ArrayList<String>();
List_Of_Array.add("A");
List_Of_Array.add("B");
List_Of_Array.add("C");
List_Of_Array.add("D");
List_Of_Array.add("E");
List_Of_Array.add("F");
List_Of_Array.add("G");
List_Of_Array.add("H");

int i[] = {5,3,1};

for (int j = 0; j < i.length; j++) {
    List_Of_Array.remove(i[j]);
}

alert() not working in Chrome

I had the same issue recently on my test server. After searching for reasons this might be happening and testing the solutions I found here, I recalled that I had clicked the "Stop this page from creating pop-ups" option a few hours before when the script I was working on was wildly popping up alerts.

The solution was as simple as closing the tab and opening a fresh one!