Programs & Examples On #Multi database

How to make a hyperlink in telegram without using bots?

You can make a hyperlink in Telegram by writing an URL and send the message. Using Telegram Bot APIs you can send a clickable URL in two ways:

Markdown:

[This is an example](https://example.com)

HTML:

<a href="https://example.com">This is an example</a>

In both cases you will have:

This is an example

EDIT: In new version of Telegram clients you can do that, see above answers.

How to restart kubernetes nodes?

I had this problem too but it looks like it depends on the Kubernetes offering and how everything was installed. In Azure, if you are using acs-engine install, you can find the shell script that is actually being run to provision it at:

/opt/azure/containers/provision.sh

To get a more fine-grained understanding, just read through it and run the commands that it specifies. For me, I had to run as root:

systemctl enable kubectl
systemctl restart kubectl

I don't know if the enable is necessary and I can't say if these will work with your particular installation, but it definitely worked for me.

How to find out if a Python object is a string?

isinstance(your_object, basestring)

will be True if your object is indeed a string-type. 'str' is reserved word.

my apologies, the correct answer is using 'basestring' instead of 'str' in order of it to include unicode strings as well - as been noted above by one of the other responders.

How do I download and save a file locally on iOS using objective C?

NSURLSession introduced in iOS 7, is the recommended SDK way of downloading a file. No need to import 3rd party libraries.

NSURL *url = [NSURL URLWithString:@"http://www.something.com/file"];
NSURLRequest *downloadRequest = [NSURLRequest requestWithURL:url];
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
self.downloadTask = [self.urlSession downloadTaskWithRequest:downloadRequest];
[self.downloadTask resume];

You can then use the NSURLSessionDownloadDelegate delegate methods to monitor errors, download completion, download progress etc... There are inline block completion handler callback methods too if you prefer. Apples docs explain when you need to use one over the other.

Have a read of these articles:

objc.io NSURLConnection to NSURLSession

URL Loading System Programming Guide

Spring MVC: difference between <context:component-scan> and <annotation-driven /> tags?

<mvc:annotation-driven /> means that you can define spring beans dependencies without actually having to specify a bunch of elements in XML or implement an interface or extend a base class. For example @Repository to tell spring that a class is a Dao without having to extend JpaDaoSupport or some other subclass of DaoSupport. Similarly @Controller tells spring that the class specified contains methods that will handle Http requests without you having to implement the Controller interface or extend a subclass that implements the controller.

When spring starts up it reads its XML configuration file and looks for <bean elements within it if it sees something like <bean class="com.example.Foo" /> and Foo was marked up with @Controller it knows that the class is a controller and treats it as such. By default, Spring assumes that all the classes it should manage are explicitly defined in the beans.XML file.

Component scanning with <context:component-scan base-package="com.mycompany.maventestwebapp" /> is telling spring that it should search the classpath for all the classes under com.mycompany.maventestweapp and look at each class to see if it has a @Controller, or @Repository, or @Service, or @Component and if it does then Spring will register the class with the bean factory as if you had typed <bean class="..." /> in the XML configuration files.

In a typical spring MVC app you will find that there are two spring configuration files, a file that configures the application context usually started with the Spring context listener.

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

And a Spring MVC configuration file usually started with the Spring dispatcher servlet. For example.

<servlet>
        <servlet-name>main</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>main</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

Spring has support for hierarchical bean factories, so in the case of the Spring MVC, the dispatcher servlet context is a child of the main application context. If the servlet context was asked for a bean called "abc" it will look in the servlet context first, if it does not find it there it will look in the parent context, which is the application context.

Common beans such as data sources, JPA configuration, business services are defined in the application context while MVC specific configuration goes not the configuration file associated with the servlet.

Hope this helps.

Emulate Samsung Galaxy Tab

Go to this link ... https://github.com/bsodmike/android-avd-profiles-2016/blob/master/Samsung%20Galaxy%20Tab%20A%2010.1%20(2016).xml

Save as xml file in your computer. Go on Android Studio => Tools => AVD Manager => + Create Virtual Device => Import Hardware Profiles ... choose the saved file and the device will be available on the tablet's section.

Happy Android developments guys!!!

How can I be notified when an element is added to the page?

Between the deprecation of mutation events and the emergence of MutationObserver, an efficent way to be notified when a specific element was added to the DOM was to exploit CSS3 animation events.

To quote the blog post:

Setup a CSS keyframe sequence that targets (via your choice of CSS selector) whatever DOM elements you want to receive a DOM node insertion event for. I used a relatively benign and little used css property, clip I used outline-color in an attempt to avoid messing with intended page styles – the code once targeted the clip property, but it is no longer animatable in IE as of version 11. That said, any property that can be animated will work, choose whichever one you like.

Next I added a document-wide animationstart listener that I use as a delegate to process the node insertions. The animation event has a property called animationName on it that tells you which keyframe sequence kicked off the animation. Just make sure the animationName property is the same as the keyframe sequence name you added for node insertions and you’re good to go.

CSV file written with Python has blank lines between each row

Borrowing from this answer, it seems like the cleanest solution is to use io.TextIOWrapper. I managed to solve this problem for myself as follows:

from io import TextIOWrapper

...

with open(filename, 'wb') as csvfile, TextIOWrapper(csvfile, encoding='utf-8', newline='') as wrapper:
    csvwriter = csv.writer(wrapper)
    for data_row in data:
        csvwriter.writerow(data_row)

The above answer is not compatible with Python 2. To have compatibility, I suppose one would simply need to wrap all the writing logic in an if block:

if sys.version_info < (3,):
    # Python 2 way of handling CSVs
else:
    # The above logic

Are static methods inherited in Java?

B.display() works because static declaration makes the method/member to belong to the class, and not any particular class instance (aka Object). You can read more about it here.

Another thing to note is that you cannot override a static method, you can have your sub class declare a static method with the same signature, but its behavior may be different than what you'd expect. This is probably the reason why it is not considered inherited. You can check out the problematic scenario and the explanation here.

How do I upgrade PHP in Mac OS X?

Check your current php version in terminal with the following command,

$ php -v

You see current php version in terminal, and next command run in terminal if you want to upgrade your php version with php concat with version liked as,

$ brew install homebrew/php/php71

Please restart terminal if you finished php version upgrade installed and run the command.

$ php -v

Now you see the current php version in terminal....thank

Easy way to use variables of enum types as string in C?

If you are using gcc, it's possible to use:

const char * enum_to_string_map[]={ [enum1]='string1', [enum2]='string2'};

Then just call for instance

enum_to_string_map[enum1]

Is it possible to do a sparse checkout without checking out the whole repository first?

Yes, Possible to download a folder instead of downloading the whole repository. Even any/last commit

Nice way to do this

D:\Lab>git svn clone https://github.com/Qamar4P/LolAdapter.git/trunk/lol-adapter -r HEAD
  1. -r HEAD will only download last revision, ignore all history.

  2. Note trunk and /specific-folder

Copy and change URL before and after /trunk/. I hope this will help someone. Enjoy :)

Updated on 26 Sep 2019

How to get a path to the desktop for current user in C#?

// Environment.GetFolderPath
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); // Current User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); // All User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles); // Program Files
Environment.GetFolderPath(Environment.SpecialFolder.Cookies); // Internet Cookie
Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // Logical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); // Physical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.Favorites); // Favorites
Environment.GetFolderPath(Environment.SpecialFolder.History); // Internet History
Environment.GetFolderPath(Environment.SpecialFolder.InternetCache); // Internet Cache
Environment.GetFolderPath(Environment.SpecialFolder.MyComputer); // "My Computer" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // "My Documents" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyMusic); // "My Music" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); // "My Pictures" Folder
Environment.GetFolderPath(Environment.SpecialFolder.Personal); // "My Document" Folder
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); // Program files Folder
Environment.GetFolderPath(Environment.SpecialFolder.Programs); // Programs Folder
Environment.GetFolderPath(Environment.SpecialFolder.Recent); // Recent Folder
Environment.GetFolderPath(Environment.SpecialFolder.SendTo); // "Sent to" Folder
Environment.GetFolderPath(Environment.SpecialFolder.StartMenu); // Start Menu
Environment.GetFolderPath(Environment.SpecialFolder.Startup); // Startup
Environment.GetFolderPath(Environment.SpecialFolder.System); // System Folder
Environment.GetFolderPath(Environment.SpecialFolder.Templates); // Document Templates

Slide div left/right using jQuery

$('#hello').hide('slide', {direction: 'left'}, 1000); requires the jQuery-ui library. See http://www.jqueryui.com

Peak signal detection in realtime timeseries data

We’ve attempted to use the smoothed z-score algorithm on our dataset, which results in either oversensitivity or undersensitivity (depending on how the parameters are tuned), with little middle ground. In our site’s traffic signal, we’ve observed a low frequency baseline which represents the daily cycle and even with the best possible parameters (shown below), it still trailed off especially on the 4th day because most of the data points are recognized as anomaly.

Building on top of the original z-score algorithm, we came up a way to solve this problem by reverse filtering. The details of the modified algorithm and its application on TV commercial trafic attribution are posted on our team blog.

enter image description here

CSS to keep element at "fixed" position on screen

Try this one:

p.pos_fixed {
    position:fixed;
    top:30px;
    right:5px;
}

Sorting objects by property values

Here's a short example, that creates and array of objects, and sorts numerically or alphabetically:

// Create Objects Array

var arrayCarObjects = [
{brand: "Honda",        topSpeed: 45},
{brand: "Ford",         topSpeed: 6},
{brand: "Toyota",       topSpeed: 240},
{brand: "Chevrolet",    topSpeed: 120},
{brand: "Ferrari",      topSpeed: 1000}
];

// Sort Objects Numerically

arrayCarObjects.sort((a, b) => (a.topSpeed - b.topSpeed));

// Sort Objects Alphabetically

arrayCarObjects.sort((a, b) => (a.brand > b.brand) ? 1 : -1);

Using mysql concat() in WHERE clause?

What you have should work but can be reduced to:

select * from table where concat_ws(' ',first_name,last_name) 
like '%$search_term%';

Can you provide an example name and search term where this doesn't work?

File tree view in Notepad++

step-1) On Notepad++ Toolbar:

Plugins -> Plugin Manager -> Show Plugin Manager -> Available . Then select the Explorer. And click Install.

(Note: As in above comments some people like SherloXplorer. Pls, note that this requires .Net v2 )

step-2) Again on Notepad++ Toolbar:

Explorer->Explorer

Now you can view files with tree view.

Update: After adding Explorer, right click to edit a file in Notepad++ may stop working. To make it work again, restart Notepad++ afresh.

Create a user with all privileges in Oracle

My issue was, i am unable to create a view with my "scott" user in oracle 11g edition. So here is my solution for this

Error in my case

SQL>create view v1 as select * from books where id=10;

insufficient privileges.

Solution

1)open your cmd and change your directory to where you install your oracle database. in my case i was downloaded in E drive so my location is E:\app\B_Amar\product\11.2.0\dbhome_1\BIN> after reaching in the position you have to type sqlplus sys as sysdba

E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba

2) Enter password: here you have to type that password that you give at the time of installation of oracle software.

3) Here in this step if you want create a new user then you can create otherwise give all the privileges to existing user.

for creating new user

SQL> create user abc identified by xyz;

here abc is user and xyz is password.

giving all the privileges to abc user

SQL> grant all privileges to abc;

 grant succeeded. 

if you are seen this message then all the privileges are giving to the abc user.

4) Now exit from cmd, go to your SQL PLUS and connect to the user i.e enter your username & password.Now you can happily create view.

In My case

in cmd E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba

SQL> grant all privileges to SCOTT;

grant succeeded.

Now I can create views.

Convert all strings in a list to int

Here is a simple solution with explanation for your query.

 a=['1','2','3','4','5'] #The integer represented as a string in this list
 b=[] #Fresh list
 for i in a: #Declaring variable (i) as an item in the list (a).
     b.append(int(i)) #Look below for explanation
 print(b)

Here, append() is used to add items ( i.e integer version of string (i) in this program ) to the end of the list (b).

Note: int() is a function that helps to convert an integer in the form of string, back to its integer form.

Output console:

[1, 2, 3, 4, 5]

So, we can convert the string items in the list to an integer only if the given string is entirely composed of numbers or else an error will be generated.

Change navbar color in Twitter Bootstrap

Just add an id to the HTML navbar, such as:

<nav id="navbar-yellow" class="navbar navbar-default navbar-fixed-top" role="navigation">

With this id you can style the navbar color, but also the links and dropdowns

Examples applied to different types of navbars

Black

Yellow

Darkblue

Red (Cherry)

Darkgreen

Here is the CSS

/*
 * Black navbar style
 */
#navbar-black.navbar-default { /* #3C3C3C - #222222 */
    font-size: 14px;
    background-color: rgba(34, 34, 34, 1);
    background: -webkit-linear-gradient(top, rgba(60, 60, 60, 1) 0%, rgba(34, 34, 34, 1) 100%);
    background: linear-gradient(to bottom, rgba(60, 60, 60, 1) 0%, rgba(34, 34, 34, 1) 100%);
    border: 0px;
    border-radius: 0;
}
#navbar-black.navbar-default .navbar-nav>li>a:hover,
#navbar-black.navbar-default .navbar-nav>li>a:focus,
#navbar-black.navbar-default .navbar-nav>li>ul>li>a:hover,
#navbar-black.navbar-default .navbar-nav>li>ul>li>a:focus,
#navbar-black.navbar-default .navbar-nav>.active>a,
#navbar-black.navbar-default .navbar-nav>.active>a:hover,
#navbar-black.navbar-default .navbar-nav>.active>a:focus {
    color: rgba(255, 255, 255, 1);
    background-color: rgba(0, 0, 0, 1);
    background: -webkit-linear-gradient(top, rgba(0, 0, 0, 1) 0%, rgba(0, 0, 0, 1) 100%);
    background: linear-gradient(to bottom, rgba(0, 0, 0, 1) 0%, rgba(0, 0, 0, 1) 100%);
}
#sidebar-black, #column-black {
      background-color: #222222;
}
#navbar-black.navbar-default .navbar-toggle {
    border-color: #222222;
}
#navbar-black.navbar-default .navbar-toggle:hover,
#navbar-black.navbar-default .navbar-toggle:focus {
    background-color: #3C3C3C;
}
#navbar-black.navbar-default .navbar-nav>li>a,
#navbar-black.navbar-default .navbar-nav>li>ul>li>a,
#navbar-black.navbar-default .navbar-brand {
    color: #999999;
}
#navbar-black.navbar-default .navbar-toggle .icon-bar,
#navbar-black.navbar-default .navbar-toggle:hover .icon-bar,
#navbar-black.navbar-default .navbar-toggle:focus .icon-bar {
    background-color: #ffffff;
}

/*
 * Red navbar style
 */
#navbar-red.navbar-default { /* #990033 - #cc0033 */
    font-size: 14px;
    background-color: rgba(153, 0, 51, 1);
    background: -webkit-linear-gradient(top, rgba(204, 0, 51, 1) 0%, rgba(153, 0, 51, 1) 100%);
    background: linear-gradient(to bottom, rgba(204, 0, 51, 1) 0%, rgba(153, 0, 51, 1) 100%);
    border: 0px;
    border-radius: 0;
}
#navbar-red.navbar-default .navbar-nav>li>a:hover,
#navbar-red.navbar-default .navbar-nav>li>a:focus,
#navbar-red.navbar-default .navbar-nav>li>ul>li>a:hover,
#navbar-red.navbar-default .navbar-nav>li>ul>li>a:focus,
#navbar-red.navbar-default .navbar-nav>.active>a,
#navbar-red.navbar-default .navbar-nav>.active>a:hover,
#navbar-red.navbar-default .navbar-nav>.active>a:focus {
    color: rgba(51, 51, 51, 1);
    background-color: rgba(255, 255, 255, 1);
    background: -webkit-linear-gradient(top, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 1) 100%);
    background: linear-gradient(to bottom, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 1) 100%);
}
#sidebar-red, #column-red {
      background-color: #990033;
}
#navbar-red.navbar-default .navbar-toggle {
    border-color: #990033;
}
#navbar-red.navbar-default .navbar-toggle:hover,
#navbar-red.navbar-default .navbar-toggle:focus {
    background-color: #cc0033;
}
#navbar-red.navbar-default .navbar-nav>li>a,
#navbar-red.navbar-default .navbar-nav>li>ul>li>a,
#navbar-red.navbar-default .navbar-brand {
    color: #999999;
}
#navbar-red.navbar-default .navbar-toggle .icon-bar,
#navbar-red.navbar-default .navbar-toggle:hover .icon-bar,
#navbar-red.navbar-default .navbar-toggle:focus .icon-bar {
    background-color: #ffffff;
}

/*
 * Darkblue navbar style
 */
#navbar-darkblue.navbar-default { /* #003399 - #0033cc */
    font-size: 14px;
    background-color: rgba(51, 51, 153, 1);
    background: -webkit-linear-gradient(top, rgba(51, 51, 204, 1) 0%, rgba(51, 51, 153, 1) 100%);
    background: linear-gradient(to bottom, rgba(51, 51, 204, 1) 0%, rgba(51, 51, 153, 1) 100%);
    border: 0px;
    border-radius: 0;
}
#navbar-darkblue.navbar-default .navbar-nav>li>a:hover,
#navbar-darkblue.navbar-default .navbar-nav>li>a:focus,
#navbar-darkblue.navbar-default .navbar-nav>li>ul>li>a:hover,
#navbar-darkblue.navbar-default .navbar-nav>li>ul>li>a:focus,
#navbar-darkblue.navbar-default .navbar-nav>.active>a,
#navbar-darkblue.navbar-default .navbar-nav>.active>a:hover,
#navbar-darkblue.navbar-default .navbar-nav>.active>a:focus {
    color: rgba(51, 51, 51, 1);
    background-color: rgba(255, 255, 255, 1);
    background: -webkit-linear-gradient(top, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 1) 100%);
    background: linear-gradient(to bottom, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 1) 100%);
}
#sidebar-darkblue, #column-darkblue {
    background-color: #333399;
}
#navbar-darkblue.navbar-default .navbar-toggle {
    border-color: #333399;
}
#navbar-darkblue.navbar-default .navbar-toggle:hover,
#navbar-darkblue.navbar-default .navbar-toggle:focus {
    background-color: #3333cc;
}
#navbar-darkblue.navbar-default .navbar-nav>li>a,
#navbar-darkblue.navbar-default .navbar-nav>li>ul>li>a,
#navbar-darkblue.navbar-default .navbar-brand {
    color: #999999;
}
#navbar-darkblue.navbar-default .navbar-toggle .icon-bar,
#navbar-darkblue.navbar-default .navbar-toggle:hover .icon-bar,
#navbar-darkblue.navbar-default .navbar-toggle:focus .icon-bar {
    background-color: #ffffff;
}

/*
 * Darkgreen navbar style
 */
#navbar-darkgreen.navbar-default { /* #006633 - #009933 */
    font-size: 14px;
    background-color: rgba(0, 102, 51, 1);
    background: -webkit-linear-gradient(top, rgba(0, 153, 51, 1) 0%, rgba(0, 102, 51, 1) 100%);
    background: linear-gradient(to bottom, rgba(0, 153, 51, 1) 0%, rgba(0, 102, 51, 1) 100%);
    border: 0px;
    border-radius: 0;
}
#navbar-darkgreen.navbar-default .navbar-nav>li>a:hover,
#navbar-darkgreen.navbar-default .navbar-nav>li>a:focus,
#navbar-darkgreen.navbar-default .navbar-nav>li>ul>li>a:hover,
#navbar-darkgreen.navbar-default .navbar-nav>li>ul>li>a:focus,
#navbar-darkgreen.navbar-default .navbar-nav>.active>a,
#navbar-darkgreen.navbar-default .navbar-nav>.active>a:hover,
#navbar-darkgreen.navbar-default .navbar-nav>.active>a:focus {
    color: rgba(51, 51, 51, 1);
    background-color: rgba(255, 255, 255, 1);
    background: -webkit-linear-gradient(top, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 1) 100%);
    background: linear-gradient(to bottom, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 1) 100%);
}
#sidebar-darkgreen, #column-darkgreen {
    background-color: #006633;
}
#navbar-darkgreen.navbar-default .navbar-toggle {
    border-color: #006633;
}
#navbar-darkgreen.navbar-default .navbar-toggle:hover,
#navbar-darkgreen.navbar-default .navbar-toggle:focus {
    background-color: #009933;
}
#navbar-darkgreen.navbar-default .navbar-nav>li>a,
#navbar-darkgreen.navbar-default .navbar-nav>li>ul>li>a,
#navbar-darkgreen.navbar-default .navbar-brand {
    color: #999999;
}
#navbar-darkgreen.navbar-default .navbar-toggle .icon-bar,
#navbar-darkgreen.navbar-default .navbar-toggle:hover .icon-bar,
#navbar-darkgreen.navbar-default .navbar-toggle:focus .icon-bar {
    background-color: #ffffff;
}

/*
 * Yellow navbar style
 */
#navbar-yellow.navbar-default { /* #99ff00 - #ccff00 */
    font-size: 14px;
    background-color: rgba(153, 255, 0, 1);
    background: -webkit-linear-gradient(top, rgba(204, 255, 0, 1) 0%, rgba(153, 255, 0, 1) 100%);
    background: linear-gradient(to bottom, rgba(204, 255, 0, 1) 0%, rgba(153, 255, 0, 1) 100%);
    border: 0px;
    border-radius: 0;
}
#navbar-yellow.navbar-default .navbar-nav>li>a:hover,
#navbar-yellow.navbar-default .navbar-nav>li>a:focus,
#navbar-yellow.navbar-default .navbar-nav>li>ul>li>a:hover,
#navbar-yellow.navbar-default .navbar-nav>li>ul>li>a:focus,
#navbar-yellow.navbar-default .navbar-nav>.active>a,
#navbar-yellow.navbar-default .navbar-nav>.active>a:hover,
#navbar-yellow.navbar-default .navbar-nav>.active>a:focus {
    color: rgba(51, 51, 51, 1);
    background-color: rgba(255, 255, 255, 1);
    background: -webkit-linear-gradient(top, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 1) 100%);
    background: linear-gradient(to bottom, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 1) 100%);
}
#sidebar-yellow, #column-yellow {
    background-color: #99ff00;
}
#navbar-yellow.navbar-default .navbar-toggle {
    border-color: #99ff00;
}
#navbar-yellow.navbar-default .navbar-toggle:hover,
#navbar-yellow.navbar-default .navbar-toggle:focus {
    background-color: #ccff00;
}
#navbar-yellow.navbar-default .navbar-nav>li>a,
#navbar-yellow.navbar-default .navbar-nav>li>ul>li>a,
#navbar-yellow.navbar-default .navbar-brand {
    color: #999999;
}
#navbar-yellow.navbar-default .navbar-toggle .icon-bar,
#navbar-yellow.navbar-default .navbar-toggle:hover .icon-bar,
#navbar-yellow.navbar-default .navbar-toggle:focus .icon-bar {
    background-color: #ffffff;
}

How can I control Chromedriver open window size?

Use this for your custom size:

driver.manage().window().setSize(new Dimension(1024,768));

you can change your dimensions as per your requirements.

Shell script current directory?

To print the current working Directory i.e. pwd just type command like:

echo "the PWD is : ${pwd}"

React.js: onChange event for contentEditable

I suggest using a mutationObserver to do this. It gives you a lot more control over what is going on. It also gives you more details on how the browse interprets all the keystrokes

Here in TypeScript

import * as React from 'react';

export default class Editor extends React.Component {
    private _root: HTMLDivElement; // Ref to the editable div
    private _mutationObserver: MutationObserver; // Modifications observer
    private _innerTextBuffer: string; // Stores the last printed value

    public componentDidMount() {
        this._root.contentEditable = "true";
        this._mutationObserver = new MutationObserver(this.onContentChange);
        this._mutationObserver.observe(this._root, {
            childList: true, // To check for new lines
            subtree: true, // To check for nested elements
            characterData: true // To check for text modifications
        });
    }

    public render() {
        return (
            <div ref={this.onRootRef}>
                Modify the text here ...
            </div>
        );
    }

    private onContentChange: MutationCallback = (mutations: MutationRecord[]) => {
        mutations.forEach(() => {
            // Get the text from the editable div
            // (Use innerHTML to get the HTML)
            const {innerText} = this._root; 

            // Content changed will be triggered several times for one key stroke
            if (!this._innerTextBuffer || this._innerTextBuffer !== innerText) {
                console.log(innerText); // Call this.setState or this.props.onChange here
                this._innerTextBuffer = innerText;
            }
        });
    }

    private onRootRef = (elt: HTMLDivElement) => {
        this._root = elt;
    }
}

Jquery split function

Javascript String objects have a split function, doesn't really need to be jQuery specific

 var str = "nice.test"
 var strs = str.split(".")

strs would be

 ["nice", "test"]

I'd be tempted to use JSON in your example though. The php could return the JSON which could easily be parsed

 success: function(data) {
   var items = JSON.parse(data)
 }

How do I find the stack trace in Visual Studio?

Do you mean finding a stack trace of the thrown exception location? That's either Debug/Exceptions, or better - Ctrl-Alt-E. Set filters for the exceptions you want to break on.

There's even a way to reconstruct the thrower stack after the exception was caught, but it's really unpleasant. Much, much easier to set a break on the throw.

Way to go from recursion to iteration

There is a general way of converting recursive traversal to iterator by using a lazy iterator which concatenates multiple iterator suppliers (lambda expression which returns an iterator). See my Converting Recursive Traversal to Iterator.

Save bitmap to file function

implementation save bitmap and load bitmap directly. fast and ease on mfc class

void CMRSMATH1Dlg::Loadit(TCHAR *destination, CDC &memdc)
{
CImage img;
PBITMAPINFO bmi;
BITMAPINFOHEADER Info;
BITMAPFILEHEADER bFileHeader;
CBitmap bm;     
CFile file2;
file2.Open(destination, CFile::modeRead | CFile::typeBinary);
file2.Read(&bFileHeader, sizeof(BITMAPFILEHEADER));
file2.Read(&Info, sizeof(BITMAPINFOHEADER));    
BYTE ch;
int width = Info.biWidth;
int height = Info.biHeight;
if (height < 0)height = -height;
int size1 = width*height * 3;
int size2 = ((width * 24 + 31) / 32) * 4 * height;
int widthnew = (size2 - size1) / height;
BYTE * buffer = (BYTE *)GlobalAlloc(GPTR, size2);
//////////////////////////
HGDIOBJ old;
unsigned char alpha = 0;    
int z = 0;  
z = 0;
int gap = (size2 - size1) / height;
for (int y = 0;y < height;y++)
{
    for (int x = 0;x < width*3;x++)
    {
        file2.Read(&ch, 1);
        buffer[z] = ch;
        z++;
    }
    for (int z1 = 0;z1 <gap;z1++)
    {
        file2.Read(&ch,1);
    }
}
bm.CreateCompatibleBitmap(&memdc, width, height);
bm.SetBitmapBits(size1,buffer);
old = memdc.SelectObject(&bm);   
///////////////////////////  
 //bm.SetBitmapBits(size1, buffer);     
 GetDC()->BitBlt(1, 95, width, height, &memdc, 0, 0, SRCCOPY);
 memdc.SelectObject(&old);
 bm.DeleteObject();
 GlobalFree(buffer);     
 file2.Close();
 }
 void CMRSMATH1Dlg::saveit(CBitmap &bit1, CDC &memdc, TCHAR *destination)
  {     
BITMAP bm;
PBITMAPINFO bmi;
BITMAPINFOHEADER Info;
BITMAPFILEHEADER bFileHeader;
CFile file1;
            CSize size = bit1.GetBitmap(&bm);
 int z = 0;  
 BYTE ch = 0;
 size.cx = bm.bmWidth;
 size.cy = bm.bmHeight;
 int width = size.cx;    
 int size1 = (size.cx)*(size.cy);
 int size2 = size1 * 3;  
 size1 = ((size.cx * 24 + 31) / 32) *4* size.cy;     
 BYTE * buffer = (BYTE *)GlobalAlloc(GPTR, size2);               
 bFileHeader.bfType = 'B' + ('M' << 8); 
 bFileHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
 bFileHeader.bfSize = bFileHeader.bfOffBits + size1;
 bFileHeader.bfReserved1 = 0;
 bFileHeader.bfReserved2 = 0;   
 Info.biSize = sizeof(BITMAPINFOHEADER);
 Info.biPlanes = 1;
 Info.biBitCount = 24;//bm.bmBitsPixel;//bitsperpixel///////////////////32
 Info.biCompression = BI_RGB;
 Info.biWidth =bm.bmWidth;
 Info.biHeight =-bm.bmHeight;///reverse pic if negative height
 Info.biSizeImage =size1;
 Info.biClrImportant = 0;
 if (bm.bmBitsPixel <= 8)
 {
     Info.biClrUsed = 1 << bm.bmBitsPixel;
 }else
 Info.biClrUsed = 0;
 Info.biXPelsPerMeter = 0;
 Info.biYPelsPerMeter = 0;
 bit1.GetBitmapBits(size2, buffer);      
 file1.Open(destination, CFile::modeCreate | CFile::modeWrite |CFile::typeBinary,0);
 file1.Write(&bFileHeader, sizeof(BITMAPFILEHEADER));
 file1.Write(&Info, sizeof(BITMAPINFOHEADER));
 unsigned char alpha = 0;    
 for (int y = 0;y<size.cy;y++)
 {
     for (int x = 0;x<size.cx;x++)
     {
         //for reverse picture below
         //z = (((size.cy - 1 - y)*size.cx) + (x)) * 3;          
     z = (((y)*size.cx) + (x)) * 3;
     file1.Write(&buffer[z], 1);
     file1.Write(&buffer[z + 1], 1);
     file1.Write(&buffer[z + 2], 1);
     }               
     for (int z = 0;z < (size1 - size2) / size.cy;z++)
     {
         file1.Write(&alpha, 1);
     }
 }   
 GlobalFree(buffer);     
 file1.Close();  
 file1.m_hFile = NULL;
        }

How to parse JSON in Kotlin?

This uses kotlinx.serialization like Elisha's answer. Meanwhile the API is being stabilized for the upcoming 1.0 release. Note that e.g. JSON.parse was renamed to Json.parse and is now Json.decodeFromString. Also it is imported in gradle differently starting in Kotlin 1.4.0:

dependencies {
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-core:1.0.0-RC"
}
apply plugin: 'kotlinx-serialization'

Example usage:

@Serializable
data class Properties(val nid: Int, val tid: Int)
@Serializable
data class Feature(val pos: List<Double>, val properties: Properties? = null, 
    val count: Int? = null)
@Serializable
data class Root(val features: List<Feature>)


val root = Json.decodeFromString<Root>(jsonStr)
val rootAlt = Json.decodeFromString(Root.serializer(), jsonStr)  // equivalent

val str = Json.encodeToString(root)  // type 'Root' can be inferred!

// For a *top-level* list (does not apply in my case) you would use 
val fList = Json.decodeFromString<List<Feature>>(jsonStr)
val fListAlt = Json.decodeFromString(ListSerializer(Feature.serializer()), jsonStr)

Kotlin's data class defines a class that mainly holds data and has .toString() and other methods (e.g. destructuring declarations) automatically defined. I'm using nullable (?) types here for optional fields.

Can't access 127.0.0.1

In windows first check under services if world wide web publishing services is running. If not start it.

If you cannot find it switch on IIS features of windows: In 7,8,10 it is under control panel , "turn windows features on or off". Internet Information Services World Wide web services and Internet information Services Hostable Core are required. Not sure if there is another way to get it going on windows, but this worked for me for all browsers. You might need to add localhost or http:/127.0.0.1 to the trusted websites also under IE settings.

Windows error 2 occured while loading the Java VM

I had same mistake, it was produced because i had disabled the creation of "_jvm" in the InstallAnywhere (project - JVM settings - Installer Settings - Bundled/Downloaded Virtual Machine), then into file "Uninstall $PRODUCT_NAME$.lax" into uninstall folder, the variable "lax.nl.current.vm" is empty.

If you don't need jvm is disabled check "Install Bundled / Downloaded Virtual Machine" option in the checkbox (project - JVM settings - Installer Settings - Bundled/Downloaded Virtual Machine).

If you need jvm is disabled because you create it manually, then you can do the following: create an action "Modify Text File" to append variable with the value of the _jvm folder.

(Existing File)
$USER_INSTALL_DIR$\Uninstall_$PRODUCT_NAME$ \Uninstall $PRODUCT_NAME$.lax

(Append)

lax.nl.current.vm=..\_jvm\bin\java.exe

Check string length in PHP

$message is propably not a string at all, but an array. Use $message[0] to access the first element.

Difference between "and" and && in Ruby?

The Ruby Style Guide says it better than I could:

Use &&/|| for boolean expressions, and/or for control flow. (Rule of thumb: If you have to use outer parentheses, you are using the wrong operators.)

# boolean expression
if some_condition && some_other_condition
  do_something
end

# control flow
document.saved? or document.save!

Interactive shell using Docker Compose

You need to include the following lines in your docker-compose.yml:

version: "3"
services:
  app:
    image: app:1.2.3
    stdin_open: true # docker run -i
    tty: true        # docker run -t

The first corresponds to -i in docker run and the second to -t.

Quick Sort Vs Merge Sort

The answer would slightly tilt towards quicksort w.r.t to changes brought with DualPivotQuickSort for primitive values . It is used in JAVA 7 to sort in java.util.Arrays

It is proved that for the Dual-Pivot Quicksort the average number of
comparisons is 2*n*ln(n), the average number of swaps is 0.8*n*ln(n),
whereas classical Quicksort algorithm has 2*n*ln(n) and 1*n*ln(n)
respectively. Full mathematical proof see in attached proof.txt
and proof_add.txt files. Theoretical results are also confirmed
by experimental counting of the operations.

You can find the JAVA7 implmentation here - http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/util/Arrays.java

Further Awesome Reading on DualPivotQuickSort - http://permalink.gmane.org/gmane.comp.java.openjdk.core-libs.devel/2628

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

You can use compileall in the terminal. The following command will go recursively into sub directories and make pyc files for all the python files it finds. The compileall module is part of the python standard library, so you don't need to install anything extra to use it. This works exactly the same way for python2 and python3.

python -m compileall .

Delete all lines beginning with a # from a file

I'm a little surprised nobody has suggested the most obvious solution:

grep -v '^#' filename

This solves the problem as stated.

But note that a common convention is for everything from a # to the end of a line to be treated as a comment:

sed 's/#.*$//' filename

though that treats, for example, a # character within a string literal as the beginning of a comment (which may or may not be relevant for your case) (and it leaves empty lines).

A line starting with arbitrary whitespace followed by # might also be treated as a comment:

grep -v '^ *#' filename

if whitespace is only spaces, or

grep -v '^[  ]#' filename

where the two spaces are actually a space followed by a literal tab character (type "control-v tab").

For all these commands, omit the filename argument to read from standard input (e.g., as part of a pipe).

How to copy a file along with directory structure/path using python?

To create all intermediate-level destination directories you could use os.makedirs() before copying:

import os
import shutil

srcfile = 'a/long/long/path/to/file.py'
dstroot = '/home/myhome/new_folder'


assert not os.path.isabs(srcfile)
dstdir =  os.path.join(dstroot, os.path.dirname(srcfile))

os.makedirs(dstdir) # create all directories, raise an error if it already exists
shutil.copy(srcfile, dstdir)

ReDim Preserve to a Multi-Dimensional Array in Visual Basic 6

You can use a user defined type containing an array of strings which will be the inner array. Then you can use an array of this user defined type as your outer array.

Have a look at the following test project:

'1 form with:
'  command button: name=Command1
'  command button: name=Command2
Option Explicit

Private Type MyArray
  strInner() As String
End Type

Private mudtOuter() As MyArray

Private Sub Command1_Click()
  'change the dimensens of the outer array, and fill the extra elements with "1"
  Dim intOuter As Integer
  Dim intInner As Integer
  Dim intOldOuter As Integer
  intOldOuter = UBound(mudtOuter)
  ReDim Preserve mudtOuter(intOldOuter + 2) As MyArray
  For intOuter = intOldOuter + 1 To UBound(mudtOuter)
    ReDim mudtOuter(intOuter).strInner(intOuter) As String
    For intInner = 0 To UBound(mudtOuter(intOuter).strInner)
      mudtOuter(intOuter).strInner(intInner) = "1"
    Next intInner
  Next intOuter
End Sub

Private Sub Command2_Click()
  'change the dimensions of the middle inner array, and fill the extra elements with "2"
  Dim intOuter As Integer
  Dim intInner As Integer
  Dim intOldInner As Integer
  intOuter = UBound(mudtOuter) / 2
  intOldInner = UBound(mudtOuter(intOuter).strInner)
  ReDim Preserve mudtOuter(intOuter).strInner(intOldInner + 5) As String
  For intInner = intOldInner + 1 To UBound(mudtOuter(intOuter).strInner)
    mudtOuter(intOuter).strInner(intInner) = "2"
  Next intInner
End Sub

Private Sub Form_Click()
  'clear the form and print the outer,inner arrays
  Dim intOuter As Integer
  Dim intInner As Integer
  Cls
  For intOuter = 0 To UBound(mudtOuter)
    For intInner = 0 To UBound(mudtOuter(intOuter).strInner)
      Print CStr(intOuter) & "," & CStr(intInner) & " = " & mudtOuter(intOuter).strInner(intInner)
    Next intInner
    Print "" 'add an empty line between the outer array elements
  Next intOuter
End Sub

Private Sub Form_Load()
  'init the arrays
  Dim intOuter As Integer
  Dim intInner As Integer
  ReDim mudtOuter(5) As MyArray
  For intOuter = 0 To UBound(mudtOuter)
    ReDim mudtOuter(intOuter).strInner(intOuter) As String
    For intInner = 0 To UBound(mudtOuter(intOuter).strInner)
      mudtOuter(intOuter).strInner(intInner) = CStr((intOuter + 1) * (intInner + 1))
    Next intInner
  Next intOuter
  WindowState = vbMaximized
End Sub

Run the project, and click on the form to display the contents of the arrays.

Click on Command1 to enlarge the outer array, and click on the form again to show the results.

Click on Command2 to enlarge an inner array, and click on the form again to show the results.

Be careful though: when you redim the outer array, you also have to redim the inner arrays for all the new elements of the outer array

How to get length of a string using strlen function

Function strlen shows the number of character before \0 and using it for std::string may report wrong length.

strlen(str.c_str()); // It may return wrong length.

In C++, a string can contain \0 within the characters but C-style-zero-terminated strings can not but at the end. If the std::string has a \0 before the last character then strlen reports a length less than the actual length.

Try to use .length() or .size(), I prefer second one since another standard containers have it.

str.size()

html5 localStorage error with Safari: "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota."

Here's a solution for AngularJS using an IIFE and leveraging the fact that services are singletons.

This results in isLocalStorageAvailable being set immediately when the service is first injected and avoids needlessly running the check every time local storage needs to be accessed.

angular.module('app.auth.services', []).service('Session', ['$log', '$window',
  function Session($log, $window) {
    var isLocalStorageAvailable = (function() {
      try {
        $window.localStorage.world = 'hello';
        delete $window.localStorage.world;
        return true;
      } catch (ex) {
        return false;
      }
    })();

    this.store = function(key, value) {
      if (isLocalStorageAvailable) {
        $window.localStorage[key] = value;
      } else {
        $log.warn('Local Storage is not available');
      }
    };
  }
]);

Java - Writing strings to a CSV file

Basically it's because MS Excel can't decide how to open the file with such content.

When you put ID as the first character in a Spreadsheet type file, it matches the specification of a SYLK file and MS Excel (and potentially other Spreadsheet Apps) try to open it as a SYLK file. But at the same time, it does not meet the complete specification of a SYLK file since rest of the values in the file are comma separated. Hence, the error is shown.

To solve the issue, change "ID" to "id" and it should work as expected.

enter image description here

This is weird. But, yeah!

Also trying to minimize file access by using file object less.

I tested and the code below works perfect.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class CsvWriter {
  public static void main(String[] args) {

    try (PrintWriter writer = new PrintWriter(new File("test.csv"))) {

      StringBuilder sb = new StringBuilder();
      sb.append("id,");
      sb.append(',');
      sb.append("Name");
      sb.append('\n');

      sb.append("1");
      sb.append(',');
      sb.append("Prashant Ghimire");
      sb.append('\n');

      writer.write(sb.toString());

      System.out.println("done!");

    } catch (FileNotFoundException e) {
      System.out.println(e.getMessage());
    }

  }
}

How to use __DATE__ and __TIME__ predefined macros in as two integers, then stringify?

You could always write a simple program in Python or something to create an include file that has simple #define statements with a build number, time, and date. You would then need to run this program before doing a build.

If you like I'll write one and post source here.

If you are lucky, your build tool (IDE or whatever) might have the ability to run an external command, and then you could have the external tool rewrite the include file automatically with each build.

EDIT: Here's a Python program. This writes a file called build_num.h and has an integer build number that starts at 1 and increments each time this program is run; it also writes #define values for the year, month, date, hours, minutes and seconds of the time this program is run. It also has a #define for major and minor parts of the version number, plus the full VERSION and COMPLETE_VERSION that you wanted. (I wasn't sure what you wanted for the date and time numbers, so I went for just concatenated digits from the date and time. You can change this easily.)

Each time you run it, it reads in the build_num.h file, and parses it for the build number; if the build_num.h file does not exist, it starts the build number at 1. Likewise it parses out major and minor version numbers, and if the file does not exist defaults those to version 0.1.

import time

FNAME = "build_num.h"

build_num = None
version_major = None
version_minor = None

DEF_BUILD_NUM = "#define BUILD_NUM "
DEF_VERSION_MAJOR = "#define VERSION_MAJOR "
DEF_VERSION_MINOR = "#define VERSION_MINOR "

def get_int(s_marker, line):
    _, _, s = line.partition(s_marker) # we want the part after the marker
    return int(s)

try:
    with open(FNAME) as f:
        for line in f:
            if DEF_BUILD_NUM in line:
                build_num = get_int(DEF_BUILD_NUM, line)
                build_num += 1
            elif DEF_VERSION_MAJOR in line:
                version_major = get_int(DEF_VERSION_MAJOR, line)
            elif DEF_VERSION_MINOR in line:
                version_minor = get_int(DEF_VERSION_MINOR, line)
except IOError:
    build_num = 1
    version_major = 0
    version_minor = 1

assert None not in (build_num, version_major, version_minor)


with open(FNAME, 'w') as f:
    f.write("#ifndef BUILD_NUM_H\n")
    f.write("#define BUILD_NUM_H\n")
    f.write("\n")
    f.write(DEF_BUILD_NUM + "%d\n" % build_num)
    f.write("\n")
    t = time.localtime()
    f.write("#define BUILD_YEAR %d\n" % t.tm_year)
    f.write("#define BUILD_MONTH %d\n" % t.tm_mon)
    f.write("#define BUILD_DATE %d\n" % t.tm_mday)
    f.write("#define BUILD_HOUR %d\n" % t.tm_hour)
    f.write("#define BUILD_MIN %d\n" % t.tm_min)
    f.write("#define BUILD_SEC %d\n" % t.tm_sec)
    f.write("\n")
    f.write("#define VERSION_MAJOR %d\n" % version_major)
    f.write("#define VERSION_MINOR %d\n" % version_minor)
    f.write("\n")
    f.write("#define VERSION \"%d.%d\"\n" % (version_major, version_minor))
    s = "%d.%d.%04d%02d%02d.%02d%02d%02d" % (version_major, version_minor,
            t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec)
    f.write("#define COMPLETE_VERSION \"%s\"\n" % s)
    f.write("\n")
    f.write("#endif // BUILD_NUM_H\n")

I made all the defines just be integers, but since they are simple integers you can use the standard stringizing tricks to build a string out of them if you like. Also you can trivially extend it to build additional pre-defined strings.

This program should run fine under Python 2.6 or later, including any Python 3.x version. You could run it under an old Python with a few changes, like not using .partition() to parse the string.

How to install popper.js with Bootstrap 4?

Try doing this:

npm install bootstrap jquery popper.js --save

See this page for more information: how-to-include-bootstrap-in-your-project-with-webpack

Find string between two substrings

This is essentially cji's answer - Jul 30 '10 at 5:58. I changed the try except structure for a little more clarity on what was causing the exception.

def find_between( inputStr, firstSubstr, lastSubstr ):
'''
find between firstSubstr and lastSubstr in inputStr  STARTING FROM THE LEFT
    http://stackoverflow.com/questions/3368969/find-string-between-two-substrings
        above also has a func that does this FROM THE RIGHT   
'''
start, end = (-1,-1)
try:
    start = inputStr.index( firstSubstr ) + len( firstSubstr )
except ValueError:
    print '    ValueError: ',
    print "firstSubstr=%s  -  "%( firstSubstr ), 
    print sys.exc_info()[1]

try:
    end = inputStr.index( lastSubstr, start )       
except ValueError:
    print '    ValueError: ',
    print "lastSubstr=%s  -  "%( lastSubstr ), 
    print sys.exc_info()[1]

return inputStr[start:end]    

How to use subprocess popen Python

Use sh, it'll make things a lot easier:

import sh
print sh.swfdump("/tmp/filename.swf", "-d")

Difference between SelectedItem, SelectedValue and SelectedValuePath

To answer a little more conceptually:

SelectedValuePath defines which property (by its name) of the objects bound to the ListBox's ItemsSource will be used as the item's SelectedValue.

For example, if your ListBox is bound to a collection of Person objects, each of which has Name, Age, and Gender properties, SelectedValuePath=Name will cause the value of the selected Person's Name property to be returned in SelectedValue.

Note that if you override the ListBox's ControlTemplate (or apply a Style) that specifies what property should display, SelectedValuePath cannot be used.

SelectedItem, meanwhile, returns the entire Person object currently selected.

(Here's a further example from MSDN, using TreeView)

Update: As @Joe pointed out, the DisplayMemberPath property is unrelated to the Selected* properties. Its proper description follows:

Note that these values are distinct from DisplayMemberPath (which is defined on ItemsControl, not Selector), but that property has similar behavior to SelectedValuePath: in the absence of a style/template, it identifies which property of the object bound to item should be used as its string representation.

Do HttpClient and HttpClientHandler have to be disposed between requests?

In my understanding, calling Dispose() is necessary only when it's locking resources you need later (like a particular connection). It's always recommended to free resources you're no longer using, even if you don't need them again, simply because you shouldn't generally be holding onto resources you're not using (pun intended).

The Microsoft example is not incorrect, necessarily. All resources used will be released when the application exits. And in the case of that example, that happens almost immediately after the HttpClient is done being used. In like cases, explicitly calling Dispose() is somewhat superfluous.

But, in general, when a class implements IDisposable, the understanding is that you should Dispose() of its instances as soon as you're fully ready and able. I'd posit this is particularly true in cases like HttpClient wherein it's not explicitly documented as to whether resources or connections are being held onto/open. In the case wherein the connection will be reused again [soon], you'll want to forgo Dipose()ing of it -- you're not "fully ready" in that case.

See also: IDisposable.Dispose Method and When to call Dispose

Interface type check with Typescript

TypeGuards

interface MyInterfaced {
    x: number
}

function isMyInterfaced(arg: any): arg is MyInterfaced {
    return arg.x !== undefined;
}

if (isMyInterfaced(obj)) {
    (obj as MyInterfaced ).x;
}

Could not find the main class, program will exit

if you build the source files with lower version of Java (example Java1.5) and trying to run that program/application with higher version of Java (example java 1.6) you will get this problem. for better explanation see this link. click here

Use IntelliJ to generate class diagram

Use Diagrams | Show Diagram... from the context menu of a package. Invoking it on the project root will show module dependencies diagram.

If you need multiple packages, you can drag & drop them to the already opened diagram for the first package and press e to expand it.

Note: This feature is available in the Ultimate Edition, not the free Community Edition.

Error: " 'dict' object has no attribute 'iteritems' "

As you are in python3 , use dict.items() instead of dict.iteritems()

iteritems() was removed in python3, so you can't use this method anymore.

Take a look at Python 3.0 Wiki Built-in Changes section, where it is stated:

Removed dict.iteritems(), dict.iterkeys(), and dict.itervalues().

Instead: use dict.items(), dict.keys(), and dict.values() respectively.

Using if-else in JSP

You may try this example:

_x000D_
_x000D_
<form>_x000D_
  <h1>Hello! I'm duke! What's you name?</h1>_x000D_
  <input type="text" name="user">_x000D_
  <br>_x000D_
  <br>_x000D_
  <input type="submit" value="submit">&nbsp;&nbsp;&nbsp;&nbsp;_x000D_
  <input type="reset">_x000D_
</form>_x000D_
<h1>Hello ${param.user}</h1> _x000D_
<!-- its Expression Language -->
_x000D_
_x000D_
_x000D_

Mount current directory as a volume in Docker on Windows 10

Here is mine which is compatible for both Win10 docker-ce & Win7 docker-toolbox. At las at the time I'm writing this :).

You can notice I prefer use /host_mnt/c instead of c:/ because I sometimes encountered trouble on docker-ce Win 10 with c:/

$WIN_PATH=Convert-Path .

#Convert for docker mount to be OK on Windows10 and Windows 7 Powershell
#Exact conversion is : remove the ":" symbol, replace all "\" by "/", remove last "/" and minor case only the disk letter
#Then for Windows10, add a /host_mnt/" at the begin of string => this way : c:\Users is translated to /host_mnt/c/Users
#For Windows7, add "//" => c:\Users is translated to //c/Users
$MOUNT_PATH=(($WIN_PATH -replace "\\","/") -replace ":","").Trim("/")

[regex]$regex='^[a-zA-Z]/'
$MOUNT_PATH=$regex.Replace($MOUNT_PATH, {$args[0].Value.ToLower()})

#Win 10
if ([Environment]::OSVersion.Version -ge (new-object 'Version' 10,0)) {
$MOUNT_PATH="/host_mnt/$MOUNT_PATH"
}
elseif ([Environment]::OSVersion.Version -ge (new-object 'Version' 6,1)) {
$MOUNT_PATH="//$MOUNT_PATH"
}

docker run -it -v "${MOUNT_PATH}:/tmp/test" busybox ls /tmp/test

How can I display my windows user name in excel spread sheet using macros?

Range("A1").value = Environ("Username")

This is better than Application.Username, which doesn't always supply the Windows username. Thanks to Kyle for pointing this out.

  • Application Username is the name of the User set in Excel > Tools > Options
  • Environ("Username") is the name you registered for Windows; see Control Panel >System

What’s the best way to check if a file exists in C++? (cross platform)

I would reconsider trying to find out if a file exists. Instead, you should try to open it (in Standard C or C++) in the same mode you intend to use it. What use is knowing that the file exists if, say, it isn't writable when you need to use it?

How to list only files and not directories of a directory Bash?

Using find:

find . -maxdepth 1 -type f

Using the -maxdepth 1 option ensures that you only look in the current directory (or, if you replace the . with some path, that directory). If you want a full recursive listing of all files in that and subdirectories, just remove that option.

What is the purpose of the "final" keyword in C++11 for functions?

Supplement to Mario Knezovic 's answer:

class IA
{
public:
  virtual int getNum() const = 0;
};

class BaseA : public IA
{
public:
 inline virtual int getNum() const final {return ...};
};

class ImplA : public BaseA {...};

IA* pa = ...;
...
ImplA* impla = static_cast<ImplA*>(pa);

//the following line should cause compiler to use the inlined function BaseA::getNum(), 
//instead of dynamic binding (via vtable or something).
//any class/subclass of BaseA will benefit from it

int n = impla->getNum();

The above code shows the theory, but not actually tested on real compilers. Much appreciated if anyone paste a disassembled output.

Regex to extract URLs from href attribute in HTML with Python

The best answer is...

Don't use a regex

The expression in the accepted answer misses many cases. Among other things, URLs can have unicode characters in them. The regex you want is here, and after looking at it, you may conclude that you don't really want it after all. The most correct version is ten-thousand characters long.

Admittedly, if you were starting with plain, unstructured text with a bunch of URLs in it, then you might need that ten-thousand-character-long regex. But if your input is structured, use the structure. Your stated aim is to "extract the url, inside the anchor tag's href." Why use a ten-thousand-character-long regex when you can do something much simpler?

Parse the HTML instead

For many tasks, using Beautiful Soup will be far faster and easier to use:

>>> from bs4 import BeautifulSoup as Soup
>>> html = Soup(s, 'html.parser')           # Soup(s, 'lxml') if lxml is installed
>>> [a['href'] for a in html.find_all('a')]
['http://example.com', 'http://example2.com']

If you prefer not to use external tools, you can also directly use Python's own built-in HTML parsing library. Here's a really simple subclass of HTMLParser that does exactly what you want:

from html.parser import HTMLParser

class MyParser(HTMLParser):
    def __init__(self, output_list=None):
        HTMLParser.__init__(self)
        if output_list is None:
            self.output_list = []
        else:
            self.output_list = output_list
    def handle_starttag(self, tag, attrs):
        if tag == 'a':
            self.output_list.append(dict(attrs).get('href'))

Test:

>>> p = MyParser()
>>> p.feed(s)
>>> p.output_list
['http://example.com', 'http://example2.com']

You could even create a new method that accepts a string, calls feed, and returns output_list. This is a vastly more powerful and extensible way than regular expressions to extract information from html.

How can getContentResolver() be called in Android?

Access contentResolver in Kotlin , inside activities, Object classes &... :

Application().contentResolver

How to generate an openSSL key using a passphrase from the command line?

genrsa has been replaced by genpkey & when run manually in a terminal it will prompt for a password:

openssl genpkey -aes-256-cbc -algorithm RSA -out /etc/ssl/private/key.pem -pkeyopt rsa_keygen_bits:4096

However when run from a script the command will not ask for a password so to avoid the password being viewable as a process use a function in a shell script:

get_passwd() {
    local passwd=
    echo -ne "Enter passwd for private key: ? "; read -s passwd
    openssl genpkey -aes-256-cbc -pass pass:$passwd -algorithm RSA -out $PRIV_KEY -pkeyopt rsa_keygen_bits:$PRIV_KEYSIZE
}

Automating the InvokeRequired code pattern

Usage:

control.InvokeIfRequired(c => c.Visible = false);

return control.InvokeIfRequired(c => {
    c.Visible = value

    return c.Visible;
});

Code:

using System;
using System.ComponentModel;

namespace Extensions
{
    public static class SynchronizeInvokeExtensions
    {
        public static void InvokeIfRequired<T>(this T obj, Action<T> action)
            where T : ISynchronizeInvoke
        {
            if (obj.InvokeRequired)
            {
                obj.Invoke(action, new object[] { obj });
            }
            else
            {
                action(obj);
            }
        }

        public static TOut InvokeIfRequired<TIn, TOut>(this TIn obj, Func<TIn, TOut> func) 
            where TIn : ISynchronizeInvoke
        {
            return obj.InvokeRequired
                ? (TOut)obj.Invoke(func, new object[] { obj })
                : func(obj);
        }
    }
}

Comment out HTML and PHP together

PHP parser will search your entire code for <?php (or <? if short_open_tag = On), so HTML comment tags have no effect on PHP parser behavior & if you don't want to parse your PHP code, you have to use PHP commenting directives(/* */ or //).

How to check if the user can go back in browser history or not

Here is how i did it.

I used the 'beforeunload' event to set a boolean. Then I set a timeout to watch if the 'beforeunload' fired.

var $window = $(window),
    $trigger = $('.select_your_link'),
    fallback = 'your_fallback_url';
    hasHistory = false;

$window.on('beforeunload', function(){
    hasHistory = true;
});

$trigger.on('click', function(){

    window.history.go(-1);

    setTimeout(function(){
        if (!hasHistory){
            window.location.href = fallback;
        }
    }, 200);

    return false;
});

Seems to work in major browsers (tested FF, Chrome, IE11 so far).

Errno 10061 : No connection could be made because the target machine actively refused it ( client - server )

The solution is to use the same IP and Port number in both client and server. Try, in client to use TCP_IP = 'write the ip number here' TCP_PORT = writ the port number here s.connect((TCP_IP, TCP_PORT))

Redirect in Spring MVC

i know this is late , but you should try redirecting to a path and not to a file ha ha

Python: pandas merge multiple dataframes

There are 2 solutions for this, but it return all columns separately:

import functools

dfs = [df1, df2, df3]

df_final = functools.reduce(lambda left,right: pd.merge(left,right,on='date'), dfs)
print (df_final)
          date     a_x   b_x       a_y      b_y   c_x         a        b   c_y
0  May 15,2017  900.00  0.2%  1,900.00  1000000  0.2%  2,900.00  2000000  0.2%

k = np.arange(len(dfs)).astype(str)
df = pd.concat([x.set_index('date') for x in dfs], axis=1, join='inner', keys=k)
df.columns = df.columns.map('_'.join)
print (df)
                0_a   0_b       1_a      1_b   1_c       2_a      2_b   2_c
date                                                                       
May 15,2017  900.00  0.2%  1,900.00  1000000  0.2%  2,900.00  2000000  0.2%

How to debug Angular JavaScript Code

For Visual Studio Code (Not Visual Studio) do Ctrl+Shift+P

Type Debugger for Chrome in the search bar, install it and enable it.

In your launch.json file add this config :

{
    "version": "0.1.0",
    "configurations": [
        {
            "name": "Launch localhost with sourcemaps",
            "type": "chrome",
            "request": "launch",
            "url": "http://localhost/mypage.html",
            "webRoot": "${workspaceRoot}/app/files",
            "sourceMaps": true
        },
        {
            "name": "Launch index.html (without sourcemaps)",
            "type": "chrome",
            "request": "launch",
            "file": "${workspaceRoot}/index.html"
        },
    ]
}

You must launch Chrome with remote debugging enabled in order for the extension to attach to it.

  • Windows

Right click the Chrome shortcut, and select properties In the "target" field, append --remote-debugging-port=9222 Or in a command prompt, execute /chrome.exe --remote-debugging-port=9222

  • OS X

In a terminal, execute /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222

  • Linux

In a terminal, launch google-chrome --remote-debugging-port=9222

Find More ===>

SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed

Recently Google has lauched something called App Password. By creating an app-password for my mailer instance solved the issue for me.

https://support.google.com/accounts/answer/185833?p=InvalidSecondFactor&visit_id=1-636228492770322608-2743677043&rd=1

What are the differences between ArrayList and Vector?

ArrayList is newer and 20-30% faster.

If you don't need something explitly apparent in Vector, use ArrayList

SQL/mysql - Select distinct/UNIQUE but return all columns?

You're looking for a group by:

select *
from table
group by field1

Which can occasionally be written with a distinct on statement:

select distinct on field1 *
from table

On most platforms, however, neither of the above will work because the behavior on the other columns is unspecified. (The first works in MySQL, if that's what you're using.)

You could fetch the distinct fields and stick to picking a single arbitrary row each time.

On some platforms (e.g. PostgreSQL, Oracle, T-SQL) this can be done directly using window functions:

select *
from (
   select *,
          row_number() over (partition by field1 order by field2) as row_number
   from table
   ) as rows
where row_number = 1

On others (MySQL, SQLite), you'll need to write subqueries that will make you join the entire table with itself (example), so not recommended.

What's the difference between utf8_general_ci and utf8_unicode_ci?

For those people still arriving at this question in 2020 or later, there are newer options that may be better than both of these. For example, utf8mb4_0900_ai_ci.

All these collations are for the UTF-8 character encoding. The differences are in how text is sorted and compared.

_unicode_ci and _general_ci are two different sets of rules for sorting and comparing text according to the way we expect. Newer versions of MySQL introduce new sets of rules, too, such as _0900_ai_ci for equivalent rules based on Unicode 9.0 - and with no equivalent _general_ci variant. People reading this now should probably use one of these newer collations instead of either _unicode_ci or _general_ci. The description of those older collations below is provided for interest only.

MySQL is currently transitioning away from an older, flawed UTF-8 implementation. For now, you need to use utf8mb4 instead of utf8 for the character encoding part, to ensure you are getting the fixed version. The flawed version remains for backward compatibility, though it is being deprecated.

Key differences

  • utf8mb4_unicode_ci is based on the official Unicode rules for universal sorting and comparison, which sorts accurately in a wide range of languages.

  • utf8mb4_general_ci is a simplified set of sorting rules which aims to do as well as it can while taking many short-cuts designed to improve speed. It does not follow the Unicode rules and will result in undesirable sorting or comparison in some situations, such as when using particular languages or characters.

    On modern servers, this performance boost will be all but negligible. It was devised in a time when servers had a tiny fraction of the CPU performance of today's computers.

Benefits of utf8mb4_unicode_ci over utf8mb4_general_ci

utf8mb4_unicode_ci, which uses the Unicode rules for sorting and comparison, employs a fairly complex algorithm for correct sorting in a wide range of languages and when using a wide range of special characters. These rules need to take into account language-specific conventions; not everybody sorts their characters in what we would call 'alphabetical order'.

As far as Latin (ie "European") languages go, there is not much difference between the Unicode sorting and the simplified utf8mb4_general_ci sorting in MySQL, but there are still a few differences:

  • For examples, the Unicode collation sorts "ß" like "ss", and "Œ" like "OE" as people using those characters would normally want, whereas utf8mb4_general_ci sorts them as single characters (presumably like "s" and "e" respectively).

  • Some Unicode characters are defined as ignorable, which means they shouldn't count toward the sort order and the comparison should move on to the next character instead. utf8mb4_unicode_ci handles these properly.

In non-latin languages, such as Asian languages or languages with different alphabets, there may be a lot more differences between Unicode sorting and the simplified utf8mb4_general_ci sorting. The suitability of utf8mb4_general_ci will depend heavily on the language used. For some languages, it'll be quite inadequate.

What should you use?

There is almost certainly no reason to use utf8mb4_general_ci anymore, as we have left behind the point where CPU speed is low enough that the performance difference would be important. Your database will almost certainly be limited by other bottlenecks than this.

In the past, some people recommended to use utf8mb4_general_ci except when accurate sorting was going to be important enough to justify the performance cost. Today, that performance cost has all but disappeared, and developers are treating internationalization more seriously.

There's an argument to be made that if speed is more important to you than accuracy, you may as well not do any sorting at all. It's trivial to make an algorithm faster if you do not need it to be accurate. So, utf8mb4_general_ci is a compromise that's probably not needed for speed reasons and probably also not suitable for accuracy reasons.

One other thing I'll add is that even if you know your application only supports the English language, it may still need to deal with people's names, which can often contain characters used in other languages in which it is just as important to sort correctly. Using the Unicode rules for everything helps add peace of mind that the very smart Unicode people have worked very hard to make sorting work properly.

What the parts mean

Firstly, ci is for case-insensitive sorting and comparison. This means it's suitable for textual data, and case is not important. The other types of collation are cs (case-sensitive) for textual data where case is important, and bin, for where the encoding needs to match, bit for bit, which is suitable for fields which are really encoded binary data (including, for example, Base64). Case-sensitive sorting leads to some weird results and case-sensitive comparison can result in duplicate values differing only in letter case, so case-sensitive collations are falling out of favor for textual data - if case is significant to you, then otherwise ignorable punctuation and so on is probably also significant, and a binary collation might be more appropriate.

Next, unicode or general refers to the specific sorting and comparison rules - in particular, the way text is normalized or compared. There are many different sets of rules for the utf8mb4 character encoding, with unicode and general being two that attempt to work well in all possible languages rather than one specific one. The differences between these two sets of rules are the subject of this answer. Note that unicode uses rules from Unicode 4.0. Recent versions of MySQL add the rulesets unicode_520 using rules from Unicode 5.2, and 0900 (dropping the "unicode_" part) using rules from Unicode 9.0.

And lastly, utf8mb4 is of course the character encoding used internally. In this answer I'm talking only about Unicode based encodings.

Ajax success event not working

in my case the error was this was in the server side and for that reason it was returning a html

wp_nonce_field(basename(__FILE__), "mu-meta-box-nonce");

How to download folder from putty using ssh client

You need to use some kind of file-transfer protocol (ftp, scp, etc), putty can't send remote files back to your computer. I use Win-SCP, which has a straightforward gui. Select SCP and you should be able to log in with the same ssh credentials and on the same port (probably 22) that you use with putty.

How to run a script file remotely using SSH

Backticks will run the command on the local shell and put the results on the command line. What you're saying is 'execute ./test/foo.sh and then pass the output as if I'd typed it on the commandline here'.

Try the following command, and make sure that thats the path from your home directory on the remote computer to your script.

ssh kev@server1 './test/foo.sh'

Also, the script has to be on the remote computer. What this does is essentially log you into the remote computer with the listed command as your shell. You can't run a local script on a remote computer like this (unless theres some fun trick I don't know).

Merge (with squash) all changes from another branch as a single commit

Another option is git merge --squash <feature branch> then finally do a git commit.

From Git merge

--squash

--no-squash

Produce the working tree and index state as if a real merge happened (except for the merge information), but do not actually make a commit or move the HEAD, nor record $GIT_DIR/MERGE_HEAD to cause the next git commit command to create a merge commit. This allows you to create a single commit on top of the current branch whose effect is the same as merging another branch (or more in case of an octopus).

Remove carriage return from string

How about:

string s = orig.Replace("\n","").Replace("\r","");

which should handle the common line-endings.

Alternatively, if you have that string hard-coded or are assembling it at runtime - just don't add the newlines in the first place.

What is com.sun.proxy.$Proxy

What are they?

Nothing special. Just as same as common Java Class Instance.

But those class are Synthetic proxy classes created by java.lang.reflect.Proxy#newProxyInstance

What is there relationship to the JVM? Are they JVM implementation specific?

Introduced in 1.3

http://docs.oracle.com/javase/1.3/docs/relnotes/features.html#reflection

It is a part of Java. so each JVM should support it.

How are they created (Openjdk7 source)?

In short : they are created using JVM ASM tech ( defining javabyte code at runtime )

something using same tech:

What happens after calling java.lang.reflect.Proxy#newProxyInstance

  1. reading the source you can see newProxyInstance call getProxyClass0 to obtain a `Class

    `

  2. after lots of cache or sth it calls the magic ProxyGenerator.generateProxyClass which return a byte[]
  3. call ClassLoader define class to load the generated $Proxy Class (the classname you have seen)
  4. just instance it and ready for use

What happens in magic sun.misc.ProxyGenerator

  1. draw a class(bytecode) combining all methods in the interfaces into one
  2. each method is build with same bytecode like

    1. get calling Method meth info (stored while generating)
    2. pass info into invocation handler's invoke()
    3. get return value from invocation handler's invoke()
    4. just return it
  3. the class(bytecode) represent in form of byte[]

How to draw a class

Thinking your java codes are compiled into bytecodes, just do this at runtime

Talk is cheap show you the code

core method in sun/misc/ProxyGenerator.java

generateClassFile

/**
 * Generate a class file for the proxy class.  This method drives the
 * class file generation process.
 */
private byte[] generateClassFile() {

    /* ============================================================
     * Step 1: Assemble ProxyMethod objects for all methods to
     * generate proxy dispatching code for.
     */

    /*
     * Record that proxy methods are needed for the hashCode, equals,
     * and toString methods of java.lang.Object.  This is done before
     * the methods from the proxy interfaces so that the methods from
     * java.lang.Object take precedence over duplicate methods in the
     * proxy interfaces.
     */
    addProxyMethod(hashCodeMethod, Object.class);
    addProxyMethod(equalsMethod, Object.class);
    addProxyMethod(toStringMethod, Object.class);

    /*
     * Now record all of the methods from the proxy interfaces, giving
     * earlier interfaces precedence over later ones with duplicate
     * methods.
     */
    for (int i = 0; i < interfaces.length; i++) {
        Method[] methods = interfaces[i].getMethods();
        for (int j = 0; j < methods.length; j++) {
            addProxyMethod(methods[j], interfaces[i]);
        }
    }

    /*
     * For each set of proxy methods with the same signature,
     * verify that the methods' return types are compatible.
     */
    for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
        checkReturnTypes(sigmethods);
    }

    /* ============================================================
     * Step 2: Assemble FieldInfo and MethodInfo structs for all of
     * fields and methods in the class we are generating.
     */
    try {
        methods.add(generateConstructor());

        for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
            for (ProxyMethod pm : sigmethods) {

                // add static field for method's Method object
                fields.add(new FieldInfo(pm.methodFieldName,
                    "Ljava/lang/reflect/Method;",
                     ACC_PRIVATE | ACC_STATIC));

                // generate code for proxy method and add it
                methods.add(pm.generateMethod());
            }
        }

        methods.add(generateStaticInitializer());

    } catch (IOException e) {
        throw new InternalError("unexpected I/O Exception");
    }

    if (methods.size() > 65535) {
        throw new IllegalArgumentException("method limit exceeded");
    }
    if (fields.size() > 65535) {
        throw new IllegalArgumentException("field limit exceeded");
    }

    /* ============================================================
     * Step 3: Write the final class file.
     */

    /*
     * Make sure that constant pool indexes are reserved for the
     * following items before starting to write the final class file.
     */
    cp.getClass(dotToSlash(className));
    cp.getClass(superclassName);
    for (int i = 0; i < interfaces.length; i++) {
        cp.getClass(dotToSlash(interfaces[i].getName()));
    }

    /*
     * Disallow new constant pool additions beyond this point, since
     * we are about to write the final constant pool table.
     */
    cp.setReadOnly();

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    DataOutputStream dout = new DataOutputStream(bout);

    try {
        /*
         * Write all the items of the "ClassFile" structure.
         * See JVMS section 4.1.
         */
                                    // u4 magic;
        dout.writeInt(0xCAFEBABE);
                                    // u2 minor_version;
        dout.writeShort(CLASSFILE_MINOR_VERSION);
                                    // u2 major_version;
        dout.writeShort(CLASSFILE_MAJOR_VERSION);

        cp.write(dout);             // (write constant pool)

                                    // u2 access_flags;
        dout.writeShort(ACC_PUBLIC | ACC_FINAL | ACC_SUPER);
                                    // u2 this_class;
        dout.writeShort(cp.getClass(dotToSlash(className)));
                                    // u2 super_class;
        dout.writeShort(cp.getClass(superclassName));

                                    // u2 interfaces_count;
        dout.writeShort(interfaces.length);
                                    // u2 interfaces[interfaces_count];
        for (int i = 0; i < interfaces.length; i++) {
            dout.writeShort(cp.getClass(
                dotToSlash(interfaces[i].getName())));
        }

                                    // u2 fields_count;
        dout.writeShort(fields.size());
                                    // field_info fields[fields_count];
        for (FieldInfo f : fields) {
            f.write(dout);
        }

                                    // u2 methods_count;
        dout.writeShort(methods.size());
                                    // method_info methods[methods_count];
        for (MethodInfo m : methods) {
            m.write(dout);
        }

                                     // u2 attributes_count;
        dout.writeShort(0); // (no ClassFile attributes for proxy classes)

    } catch (IOException e) {
        throw new InternalError("unexpected I/O Exception");
    }

    return bout.toByteArray();
}

addProxyMethod

/**
 * Add another method to be proxied, either by creating a new
 * ProxyMethod object or augmenting an old one for a duplicate
 * method.
 *
 * "fromClass" indicates the proxy interface that the method was
 * found through, which may be different from (a subinterface of)
 * the method's "declaring class".  Note that the first Method
 * object passed for a given name and descriptor identifies the
 * Method object (and thus the declaring class) that will be
 * passed to the invocation handler's "invoke" method for a given
 * set of duplicate methods.
 */
private void addProxyMethod(Method m, Class fromClass) {
    String name = m.getName();
    Class[] parameterTypes = m.getParameterTypes();
    Class returnType = m.getReturnType();
    Class[] exceptionTypes = m.getExceptionTypes();

    String sig = name + getParameterDescriptors(parameterTypes);
    List<ProxyMethod> sigmethods = proxyMethods.get(sig);
    if (sigmethods != null) {
        for (ProxyMethod pm : sigmethods) {
            if (returnType == pm.returnType) {
                /*
                 * Found a match: reduce exception types to the
                 * greatest set of exceptions that can thrown
                 * compatibly with the throws clauses of both
                 * overridden methods.
                 */
                List<Class<?>> legalExceptions = new ArrayList<Class<?>>();
                collectCompatibleTypes(
                    exceptionTypes, pm.exceptionTypes, legalExceptions);
                collectCompatibleTypes(
                    pm.exceptionTypes, exceptionTypes, legalExceptions);
                pm.exceptionTypes = new Class[legalExceptions.size()];
                pm.exceptionTypes =
                    legalExceptions.toArray(pm.exceptionTypes);
                return;
            }
        }
    } else {
        sigmethods = new ArrayList<ProxyMethod>(3);
        proxyMethods.put(sig, sigmethods);
    }
    sigmethods.add(new ProxyMethod(name, parameterTypes, returnType,
                                   exceptionTypes, fromClass));
}

Full code about gen the proxy method

    private MethodInfo generateMethod() throws IOException {
        String desc = getMethodDescriptor(parameterTypes, returnType);
        MethodInfo minfo = new MethodInfo(methodName, desc,
            ACC_PUBLIC | ACC_FINAL);

        int[] parameterSlot = new int[parameterTypes.length];
        int nextSlot = 1;
        for (int i = 0; i < parameterSlot.length; i++) {
            parameterSlot[i] = nextSlot;
            nextSlot += getWordsPerType(parameterTypes[i]);
        }
        int localSlot0 = nextSlot;
        short pc, tryBegin = 0, tryEnd;

        DataOutputStream out = new DataOutputStream(minfo.code);

        code_aload(0, out);

        out.writeByte(opc_getfield);
        out.writeShort(cp.getFieldRef(
            superclassName,
            handlerFieldName, "Ljava/lang/reflect/InvocationHandler;"));

        code_aload(0, out);

        out.writeByte(opc_getstatic);
        out.writeShort(cp.getFieldRef(
            dotToSlash(className),
            methodFieldName, "Ljava/lang/reflect/Method;"));

        if (parameterTypes.length > 0) {

            code_ipush(parameterTypes.length, out);

            out.writeByte(opc_anewarray);
            out.writeShort(cp.getClass("java/lang/Object"));

            for (int i = 0; i < parameterTypes.length; i++) {

                out.writeByte(opc_dup);

                code_ipush(i, out);

                codeWrapArgument(parameterTypes[i], parameterSlot[i], out);

                out.writeByte(opc_aastore);
            }
        } else {

            out.writeByte(opc_aconst_null);
        }

        out.writeByte(opc_invokeinterface);
        out.writeShort(cp.getInterfaceMethodRef(
            "java/lang/reflect/InvocationHandler",
            "invoke",
            "(Ljava/lang/Object;Ljava/lang/reflect/Method;" +
                "[Ljava/lang/Object;)Ljava/lang/Object;"));
        out.writeByte(4);
        out.writeByte(0);

        if (returnType == void.class) {

            out.writeByte(opc_pop);

            out.writeByte(opc_return);

        } else {

            codeUnwrapReturnValue(returnType, out);
        }

        tryEnd = pc = (short) minfo.code.size();

        List<Class<?>> catchList = computeUniqueCatchList(exceptionTypes);
        if (catchList.size() > 0) {

            for (Class<?> ex : catchList) {
                minfo.exceptionTable.add(new ExceptionTableEntry(
                    tryBegin, tryEnd, pc,
                    cp.getClass(dotToSlash(ex.getName()))));
            }

            out.writeByte(opc_athrow);

            pc = (short) minfo.code.size();

            minfo.exceptionTable.add(new ExceptionTableEntry(
                tryBegin, tryEnd, pc, cp.getClass("java/lang/Throwable")));

            code_astore(localSlot0, out);

            out.writeByte(opc_new);
            out.writeShort(cp.getClass(
                "java/lang/reflect/UndeclaredThrowableException"));

            out.writeByte(opc_dup);

            code_aload(localSlot0, out);

            out.writeByte(opc_invokespecial);

            out.writeShort(cp.getMethodRef(
                "java/lang/reflect/UndeclaredThrowableException",
                "<init>", "(Ljava/lang/Throwable;)V"));

            out.writeByte(opc_athrow);
        }

RegEx for valid international mobile phone number

Even though it is about international numbers I would want the code to be like :

/^(\+|\d)[0-9]{7,16}$/;

As you can have international numbers starting with '00' as well.

Why I prefer 15 digits : http://en.wikipedia.org/wiki/E.164

Get current value when change select option - Angular2

For me, passing ($event.target.value) as suggested by @microniks did not work. What worked was ($event.value) instead. I am using Angular 4.2.x and Angular Material 2

<select (change)="onItemChange($event.value)">
    <option *ngFor="#value of values" [value]="value.key">
       {{value.value}}
    </option>
</select>

Difference between a Seq and a List in Scala

In Scala, a List inherits from Seq, but implements Product; here is the proper definition of List :

sealed abstract class List[+A] extends AbstractSeq[A] with Product with ...

[Note: the actual definition is a tad bit more complex, in order to fit in with and make use of Scala's very powerful collection framework.]

Difference between jQuery .hide() and .css("display", "none")

Yes there is a difference.

jQuery('#id').css("display","block") will always set the element you want to show as block.

jQuery('#id').show() will et is to what display type it initially was, display: inline for example.

See Jquery Doc

Why is a "GRANT USAGE" created the first time I grant a user privileges?

As you said, in MySQL USAGE is synonymous with "no privileges". From the MySQL Reference Manual:

The USAGE privilege specifier stands for "no privileges." It is used at the global level with GRANT to modify account attributes such as resource limits or SSL characteristics without affecting existing account privileges.

USAGE is a way to tell MySQL that an account exists without conferring any real privileges to that account. They merely have permission to use the MySQL server, hence USAGE. It corresponds to a row in the `mysql`.`user` table with no privileges set.

The IDENTIFIED BY clause indicates that a password is set for that user. How do we know a user is who they say they are? They identify themselves by sending the correct password for their account.

A user's password is one of those global level account attributes that isn't tied to a specific database or table. It also lives in the `mysql`.`user` table. If the user does not have any other privileges ON *.*, they are granted USAGE ON *.* and their password hash is displayed there. This is often a side effect of a CREATE USER statement. When a user is created in that way, they initially have no privileges so they are merely granted USAGE.

SVN: Is there a way to mark a file as "do not commit"?

You can configure the "ignore-on-commit" changelist directly with TortoiseSVN. No need to configure any other changelist including all the others files

1) Click "SVN Commit..." (we will not commit, just a way to find a graphical menu for the changelist) 2) On the list Right click on the file you want to exclude. 3) Menu: move to changelist > ignore-on-commit

The next time you do a SVN Commit... The files will appear unchecked at the end of the list, under the category ignore-on-commit.

Tested with : TortoiseSVN 1.8.7, Build 25475 - 64 Bit , 2014/05/05 20:52:12, Subversion 1.8.9, -release

How to comment in Vim's config files: ".vimrc"?

"This is a comment in vimrc. It does not have a closing quote 

Source: http://vim.wikia.com/wiki/Backing_up_and_commenting_vimrc

How to reload current page?

I believe Angular 6 has the BehaviorSubject object. My sample below is done using Angular 8 and will hopefully work for Angular 6 as well.

This method is a more "reactive" approach to the problem, and assumes you are using and are well versed in rxjs.

Assuming you are using an Observable in your parent component, the component that is used in your routing definition, then you should be able to just pulse the data stream pretty easily.

My example also assumes you are using a view model in your component like so...

vm$: Observable<IViewModel>;

And in the HTML like so...

<div *ngIf="(vm$ | async) as vm">

In your component file, add a BehaviorSubject instance...

private refreshBs: BehaviorSubject<number> = new BehaviorSubject<number>(0);

Then also add an action that can be invoked by a UI element...

  refresh() {
    this.refreshBs.next(1);
  }

Here's the UI snippet, a Material Bootstrap button...

<button mdbBtn color="primary" class="ml-1 waves-dark" type="button" outline="true"
                    (click)="refresh()" mdbWavesEffect>Refresh</button>

Then, in your ngOnIt function do something like this, keep in mind that my example is simplified a bit so that I don't have to provide a lot of code...

  ngOnInit() {

    this.vm$ = this.refreshBs.asObservable().pipe(
      switchMap(v => this.route.queryParamMap),
      map(qpm => qpm.get("value")),
      tap(v => console.log(`query param value: "${v}"`)),

      // simulate data load
      switchMap(v => of(v).pipe(
        delay(500),
        map(v => ({ items: [] }))
      )),
      
      catchError(e => of({ items: [], error: e }))
    );
    
  }

Convert a file path to Uri in Android

Please try the following code

Uri.fromFile(new File("/sdcard/sample.jpg"))

force Maven to copy dependencies into target/lib

It's a heavy solution for embedding heavy dependencies, but Maven's Assembly Plugin does the trick for me.

@Rich Seller's answer should work, although for simpler cases you should only need this excerpt from the usage guide:

<project>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.2.2</version>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

How to add color to Github's README.md file

As of writing, Github Markdown renders color codes like `#ffffff` (note the backticks!) with a color preview. Just use a color code and surround it with backticks.

For example:

GitHub markdown with color codes

becomes

rendered GitHub markdown with color codes

Operator overloading ==, !=, Equals

public class BOX
{
    double height, length, breadth;

    public static bool operator == (BOX b1, BOX b2)
    {
        if (b1 is null)
            return b2 is null;

        return b1.Equals(b2);
    }

    public static bool operator != (BOX b1, BOX b2)
    {
        return !(b1 == b2);
    }

    public override bool Equals(object obj)
    {
        if (obj == null)
            return false;

        return obj is BOX b2? (length == b2.length && 
                               breadth == b2.breadth && 
                               height == b2.height): false;

    }

    public override int GetHashCode()
    {
        return (height,length,breadth).GetHashCode();
    }
}

Jquery to get SelectedText from dropdown

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="jquery-3.1.0.js"></script>
    <script>
        $(function () {
            $('#selectnumber').change(function(){
                alert('.val() = ' + $('#selectnumber').val() + '  AND  html() = ' + $('#selectnumber option:selected').html() + '  AND .text() = ' + $('#selectnumber option:selected').text());
            })
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <select id="selectnumber">
            <option value="1">one</option>
            <option value="2">two</option>
            <option value="3">three</option>
            <option value="4">four</option>
        </select>

    </div>
    </form>
</body>
</html>

Click to see Output Screen

Thanks...:)

How to read strings from a Scanner in a Java console application?

Scanner scanner = new Scanner(System.in);
int employeeId, supervisorId;
String name;
System.out.println("Enter employee ID:");
employeeId = scanner.nextInt();
scanner.nextLine(); //This is needed to pick up the new line
System.out.println("Enter employee name:");
name = scanner.nextLine();
System.out.println("Enter supervisor ID:");
supervisorId = scanner.nextInt();

Calling nextInt() was a problem as it didn't pick up the new line (when you hit enter). So, calling scanner.nextLine() after that does the work.

jQuery position DIV fixed at top on scroll

instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0; once your window has scrolled pass a certain height:

jQuery

  $(window).scroll(function(){
      if ($(this).scrollTop() > 135) {
          $('#task_flyout').addClass('fixed');
      } else {
          $('#task_flyout').removeClass('fixed');
      }
  });

css

.fixed {position:fixed; top:0; left:0;}

Example

Javascript Regex: How to put a variable inside a regular expression?

You can use the RegExp object:

var regexstring = "whatever";
var regexp = new RegExp(regexstring, "gi");
var str = "whateverTest";
var str2 = str.replace(regexp, "other");
document.write(str2);

Then you can construct regexstring in any way you want.

You can read more about it here.

assignment operator overloading in c++

There are no problems with the second version of the assignment operator. In fact, that is the standard way for an assignment operator.

Edit: Note that I am referring to the return type of the assignment operator, not to the implementation itself. As has been pointed out in comments, the implementation itself is another issue. See here.

How do I perform HTML decoding/encoding using Python/Django?

This is the easiest solution for this problem -

{% autoescape on %}
   {{ body }}
{% endautoescape %}

From this page.

WebSockets vs. Server-Sent events/EventSource

Here is a talk about the differences between web sockets and server sent events. Since Java EE 7 a WebSocket API is already part of the specification and it seems that server sent events will be released in the next version of the enterprise edition.

Instagram API to fetch pictures with specific hashtags

Take a look here in order to get started: http://instagram.com/developer/

and then in order to retrieve pictures by tag, look here: http://instagram.com/developer/endpoints/tags/

Getting tags from Instagram doesn't require OAuth, so you can make the calls via these URLs:

GET IMAGES https://api.instagram.com/v1/tags/{tag-name}/media/recent?access_token={TOKEN}

SEARCH https://api.instagram.com/v1/tags/search?q={tag-query}&access_token={TOKEN}

TAG INFO https://api.instagram.com/v1/tags/{tag-name}?access_token={TOKEN}

How to execute a file within the python interpreter?

python -c "exec(open('main.py').read())"

Compare cell contents against string in Excel

If a case-insensitive comparison is acceptable, just use =:

=IF(A1="ENG",1,0)

How to request a random row in SQL?

A simple and efficient way from http://akinas.com/pages/en/blog/mysql_random_row/

SET @i = (SELECT FLOOR(RAND() * COUNT(*)) FROM table); PREPARE get_stmt FROM 'SELECT * FROM table LIMIT ?, 1'; EXECUTE get_stmt USING @i;

Free Online Team Foundation Server

Readify used to run their TFSNow hosted TFS service, but I don't think it's going any longer. The only others I've heard of, apart from CodePlex, aren't free:

Include another HTML file in a HTML file

The Athari´s answer (the first!) was too much conclusive! Very Good!

But if you would like to pass the name of the page to be included as URL parameter, this post has a very nice solution to be used combined with:

http://www.jquerybyexample.net/2012/06/get-url-parameters-using-jquery.html

So it becomes something like this:

Your URL:

www.yoursite.com/a.html?p=b.html

The a.html code now becomes:

<html> 
  <head> 
    <script src="jquery.js"></script> 
    <script> 
    function GetURLParameter(sParam)
    {
      var sPageURL = window.location.search.substring(1);
      var sURLVariables = sPageURL.split('&');
      for (var i = 0; i < sURLVariables.length; i++) 
      {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) 
        {
            return sParameterName[1];
        }
      }
    }?
    $(function(){
      var pinc = GetURLParameter('p');
      $("#includedContent").load(pinc); 
    });
    </script> 
  </head> 

  <body> 
     <div id="includedContent"></div>
  </body> 
</html>

It worked very well for me! I hope have helped :)

Set the location in iPhone Simulator

As of Xcode 11.6 and Swift 5.3, facility to simulate custom location has been moved from "Debug" to "Features" in iOS Simulator menu.

How to convert a GUID to a string in C#?

According to MSDN the method Guid.ToString(string format) returns a string representation of the value of this Guid instance, according to the provided format specifier.

Examples:

  • guidVal.ToString() or guidVal.ToString("D") returns 32 hex digits separated by hyphens: 00000000-0000-0000-0000-000000000000
  • guidVal.ToString("N") returns 32 hex digits:00000000000000000000000000000000
  • guidVal.ToString("B") returns 32 hex digits separated by hyphens, enclosed in braces:{00000000-0000-0000-0000-000000000000}
  • guidVal.ToString("P") returns 32 hex digits separated by hyphens, enclosed in parentheses: (00000000-0000-0000-0000-000000000000)

How to increase executionTimeout for a long-running query?

RE. "Can we set this value for individual page" – MonsterMMORPG.

Yes, you can (& normally should) enclose the previous answer using the location-tag.

e.g.

  ...
  <location path="YourWebpage.aspx">
    <system.web>
      <httpRuntime executionTimeout="300" maxRequestLength="29296" />
    </system.web>
  </location>
</configuration>

The above snippet is taken from the end of my own working web.config, which I tested yesterday - it works for me.

XMLHttpRequest blocked by CORS Policy

I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer

Get protocol, domain, and port from URL

Simple answer that works for all browsers:

let origin;

if (!window.location.origin) {
  origin = window.location.protocol + "//" + window.location.hostname + 
     (window.location.port ? ':' + window.location.port: '');
}

origin = window.location.origin;

how to set start page in webconfig file in asp.net c#

If your project contains a RouteConfig.cs file, then you probably need to ignore the route to the root by adding routes.IgnoreRoute(""); in this file.

If it doen't solve your problem, try this :

void Application_BeginRequest(object sender, EventArgs e)
{
    if (Request.AppRelativeCurrentExecutionFilePath == "~/")
        Response.Redirect("~/index.aspx");
}

Django: Model Form "object has no attribute 'cleaned_data'"

I would write the code like this:

def search_book(request):
    form = SearchForm(request.POST or None)
    if request.method == "POST" and form.is_valid():
        stitle = form.cleaned_data['title']
        sauthor = form.cleaned_data['author']
        scategory = form.cleaned_data['category']
        return HttpResponseRedirect('/thanks/')
    return render_to_response("books/create.html", {
        "form": form,
    }, context_instance=RequestContext(request))

Pretty much like the documentation.

click command in selenium webdriver does not work

If you know for sure that the element is present, you could try this to simulate the click - if .Click() isn't working

driver.findElement(By.name("submit")).sendKeys(Keys.RETURN);

or

driver.findElement(By.name("submit")).sendKeys(Keys.ENTER);

How to add an extra column to a NumPy array

Assuming M is a (100,3) ndarray and y is a (100,) ndarray append can be used as follows:

M=numpy.append(M,y[:,None],1)

The trick is to use

y[:, None]

This converts y to a (100, 1) 2D array.

M.shape

now gives

(100, 4)

What in layman's terms is a Recursive Function using PHP

Its a function that calls itself. Its useful for walking certain data structures that repeat themselves, such as trees. An HTML DOM is a classic example.

An example of a tree structure in javascript and a recursive function to 'walk' the tree.

    1
   / \
  2   3
     / \
    4   5

--

var tree = {
  id: 1,
  left: {
    id: 2,
    left: null,
    right: null
  },
  right: {
    id: 3,
    left: {
      id: 4,
      left: null,
      right: null
    },
    right: {
      id: 5,
      left: null,
      right: null
    }
  }
};

To walk the tree, we call the same function repeatedly, passing the child nodes of the current node to the same function. We then call the function again, first on the left node, and then on the right.

In this example, we'll get the maximum depth of the tree

var depth = 0;

function walkTree(node, i) {

  //Increment our depth counter and check
  i++;
  if (i > depth) depth = i;

  //call this function again for each of the branch nodes (recursion!)
  if (node.left != null) walkTree(node.left, i);
  if (node.right != null) walkTree(node.right, i);

  //Decrement our depth counter before going back up the call stack
  i--;
}

Finally we call the function

alert('Tree depth:' + walkTree(tree, 0));

A great way of understanding recursion is to step through the code at runtime.

How to remove duplicates from Python list and keep order?

If you want to keep order of the original list, just use OrderedDict with None as values.

In Python2:

    from collections import OrderedDict
    from itertools import izip, repeat

    unique_list = list(OrderedDict(izip(my_list, repeat(None))))

In Python3 it's even simpler:

    from collections import OrderedDict
    from itertools import repeat

    unique_list = list(OrderedDict(zip(my_list, repeat(None))))

If you don't like iterators (zip and repeat) you can use a generator (works both in 2 & 3):

    from collections import OrderedDict
    unique_list = list(OrderedDict((element, None) for element in my_list))

How to remove close button on the jQuery UI dialog?

I catch the close event of the dialog box. This code then removes the <div> (#dhx_combo_list):

open: function(event, ui) { 
  //hide close button.
  $(this).parent().children().children('.ui-dialog-titlebar-close').click(function(){
    $("#dhx_combo_list").remove();
  });
},

Constructor in an Interface?

A work around you can try is defining a getInstance() method in your interface so the implementer is aware of what parameters need to be handled. It isn't as solid as an abstract class, but it allows more flexibility as being an interface.

However this workaround does require you to use the getInstance() to instantiate all objects of this interface.

E.g.

public interface Module {
    Module getInstance(Receiver receiver);
}

SaveFileDialog setting default path and file type?

Here's an example that actually filters for BIN files. Also Windows now want you to save files to user locations, not system locations, so here's an example (you can use intellisense to browse the other options):

            var saveFileDialog = new Microsoft.Win32.SaveFileDialog()
            {
                DefaultExt = "*.xml",
                Filter = "BIN Files (*.bin)|*.bin",
                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
            };

            var result = saveFileDialog.ShowDialog();
            if (result != null && result == true)
            {
                // Save the file here
            }

How to develop or migrate apps for iPhone 5 screen resolution?

I would suggest to use Autoresizing Mask in your applications according to your UI interface, it saves a lot of trouble and is better than making different UI for iPhone 4 and 5 screens.

Style child element when hover on parent

you can use this too

_x000D_
_x000D_
.parent:hover * {
   /* ... */
}
_x000D_
_x000D_
_x000D_

Finding and removing non ascii characters from an Oracle Varchar2

I'm a bit late in answering this question, but had the same problem recently (people cut and paste all sorts of stuff into a string and we don't always know what it is). The following is a simple character whitelist approach:

SELECT est.clients_ref
  ,TRANSLATE (
              est.clients_ref
             ,   'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890#$%^&*()_+-={}|[]:";<>?,./'
              || REPLACE (
                          TRANSLATE (
                                     est.clients_ref
                                    ,'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890#$%^&*()_+-={}|[]:";<>?,./'
                                    ,'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
                                    )
                         ,'~'
                         )
             ,'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890#$%^&*()_+-={}|[]:";<>?,./'
             )
      clean_ref

FROM edms_staging_table est

How to view unallocated free space on a hard disk through terminal

when you cut you disk in partitions by fdisk you may be careful so as not to left gaps with free space. So command automatically align partitions and you'll get some gaps between parts. There are many articles in net why need to do so. The reason is that it gives solution with less errors. That was many years ago. Now I don't know is there errors occurs if you do all without any gaps. But first. You may do so if you don't allow alignment you sen begin of the next part=end previous+1. But is first part begins always with 2048 sector. So call expert part you may shift it to 0. But strongly recomended to do so if you plan to boot from this disk. If only for data you'll gain 1 Mb additional disk space. This is an MBR space. If you plan to install OS on this disk you don't use GPT partition type. Also it's more suitable not all OS see GPT parts of disks. But some see them. If you don't sure it use msdos. While format the block size is 4096 bytes(logical) physical one is 512 bytes. I don't do so but you may set block size=512 too. There was many discussion about that. It's lead to disk errors. But you'll give some free disk space too especially when you have many small size files. You disk will fill more compactly. And if you give already partitioned disk with filled them with data and maybe installed OS you maybe want to do so, it was very problems to do. But is possible for Linux. For Windows no... You must save backup and mbr too, write UUID every part then use fdisk and format as setting right UUID and LABEL for every part restore mbr with dd command and if you don't do any wrong all will be work as before but without any gaps.

How to force Sequential Javascript Execution?

I had the same problem, this is my solution:

_x000D_
_x000D_
var functionsToCall = new Array();_x000D_
_x000D_
function f1() {_x000D_
    $.ajax({_x000D_
        type:"POST",_x000D_
        url: "/some/url",_x000D_
        success: function(data) {_x000D_
            doSomethingWith(data);_x000D_
            //When done, call the next function.._x000D_
            callAFunction("parameter");_x000D_
        }_x000D_
    });_x000D_
}_x000D_
_x000D_
function f2() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter2");_x000D_
}_x000D_
function f3() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter3");_x000D_
}_x000D_
function f4() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter4");_x000D_
}_x000D_
function f5() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter5");_x000D_
}_x000D_
function f6() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter6");_x000D_
}_x000D_
function f7() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter7");_x000D_
}_x000D_
function f8() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter8");_x000D_
}_x000D_
function f9() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter9");_x000D_
}_x000D_
    _x000D_
function callAllFunctionsSy(params) {_x000D_
 functionsToCall.push(f1);_x000D_
 functionsToCall.push(f2);_x000D_
 functionsToCall.push(f3);_x000D_
 functionsToCall.push(f4);_x000D_
 functionsToCall.push(f5);_x000D_
 functionsToCall.push(f6);_x000D_
 functionsToCall.push(f7);_x000D_
 functionsToCall.push(f8);_x000D_
 functionsToCall.push(f9);_x000D_
 functionsToCall.reverse();_x000D_
 callAFunction(params);_x000D_
}_x000D_
_x000D_
function callAFunction(params) {_x000D_
 if (functionsToCall.length > 0) {_x000D_
  var f=functionsToCall.pop();_x000D_
  f(params);_x000D_
 }_x000D_
}
_x000D_
_x000D_
_x000D_

How to use refs in React with Typescript

class SelfFocusingInput extends React.Component<{ value: string, onChange: (value: string) => any }, {}>{
    ctrls: {
        input?: HTMLInputElement;
    } = {};
    render() {
        return (
            <input
                ref={(input) => this.ctrls.input = input}
                value={this.props.value}
                onChange={(e) => { this.props.onChange(this.ctrls.input.value) } }
                />
        );
    }
    componentDidMount() {
        this.ctrls.input.focus();
    }
}

put them in an object

Convert ndarray from float64 to integer

Use .astype.

>>> a = numpy.array([1, 2, 3, 4], dtype=numpy.float64)
>>> a
array([ 1.,  2.,  3.,  4.])
>>> a.astype(numpy.int64)
array([1, 2, 3, 4])

See the documentation for more options.

Fastest way to remove non-numeric characters from a VARCHAR in SQL Server

I would recommend enforcing a strict format for phone numbers in the database. I use the following format. (Assuming US phone numbers)

Database: 5555555555x555

Display: (555) 555-5555 ext 555

Input: 10 digits or more digits embedded in any string. (Regex replacing removes all non-numeric characters)

How to add Web API to an existing ASP.NET MVC 4 Web Application project?

NOTE : this is just an abbreviation of this answer above

  1. Open NuGet Package manager console and run

    PM> Install-Package Microsoft.AspNet.WebApi
    
  2. Add references to System.Web.Routing, System.Web.Net and System.Net.Http dlls if not there already

  3. Add the following class

    public static class WebApiConfig
    {
         public static void Register(HttpConfiguration config)
         {
             // Web API routes
             config.MapHttpAttributeRoutes();
    
             config.Routes.MapHttpRoute(
                 name: "DefaultApi",
                 routeTemplate: "api/{controller}/{id}",
                 defaults: new { id = RouteParameter.Optional }
             );
         }
     }
    
  4. Add Application_Start method if not there already (in global.asax.cs file)

    protected void Application_Start()
    {
        //this should be line #1 in this method
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
    
  5. Right click controllers folder > add new item > web > Add Web API controller

    namespace <Your.NameSpace.Here>
    {
        public class VSController : ApiController
        {
            // GET api/<controller>   : url to use => api/vs
            public string Get()
            {
                return "Hi from web api controller";
            }  
        }
    }
    

Download image from the site in .NET/C#

The best practice to download an image from Server or from Website and store it locally.

WebClient client=new Webclient();
client.DownloadFile("WebSite URL","C:\\....image.jpg");
client.Dispose();

Create 3D array using Python

You should use a list comprehension:

>>> import pprint
>>> n = 3
>>> distance = [[[0 for k in xrange(n)] for j in xrange(n)] for i in xrange(n)]
>>> pprint.pprint(distance)
[[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
 [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
 [[0, 0, 0], [0, 0, 0], [0, 0, 0]]]
>>> distance[0][1]
[0, 0, 0]
>>> distance[0][1][2]
0

You could have produced a data structure with a statement that looked like the one you tried, but it would have had side effects since the inner lists are copy-by-reference:

>>> distance=[[[0]*n]*n]*n
>>> pprint.pprint(distance)
[[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
 [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
 [[0, 0, 0], [0, 0, 0], [0, 0, 0]]]
>>> distance[0][0][0] = 1
>>> pprint.pprint(distance)
[[[1, 0, 0], [1, 0, 0], [1, 0, 0]],
 [[1, 0, 0], [1, 0, 0], [1, 0, 0]],
 [[1, 0, 0], [1, 0, 0], [1, 0, 0]]]

SQL Server stored procedure Nullable parameter

You can/should set your parameter to value to DBNull.Value;

if (variable == "")
{
     cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = DBNull.Value;
}
else
{
     cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = variable;
}

Or you can leave your server side set to null and not pass the param at all.

datetime dtypes in pandas read_csv

I tried using the dtypes=[datetime, ...] option, but

import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4'] 
dtypes = [datetime, datetime, str, float] 
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)

I encountered the following error:

TypeError: data type not understood

The only change I had to make is to replace datetime with datetime.datetime

import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4'] 
dtypes = [datetime.datetime, datetime.datetime, str, float] 
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)

How do I remove an item from a stl vector with a certain value?

std::remove does not actually erase the element from the container, but it does return the new end iterator which can be passed to container_type::erase to do the REAL removal of the extra elements that are now at the end of the container:

std::vector<int> vec;
// .. put in some values ..
int int_to_remove = n;
vec.erase(std::remove(vec.begin(), vec.end(), int_to_remove), vec.end());

C# removing items from listbox

The problem here is that you're changing your enumerator as you remove items from the list. This isn't valid with a 'foreach' loop. But just about any other type of loop will be OK.

So you could try something like this:

for(int i=0; i < listBox1.Items.Count; )
{
    string removelistitem = "OBJECT";
    if(listBox1.Items[i].Contains(removelistitem))
         listBox1.Items.Remove(item);
    else
        ++i;
}

How to fix the error "Windows SDK version 8.1" was not found?

Another way (worked for 2015) is open "Install/remove programs" (Apps & features), find Visual Studio, select Modify. In opened window, press Modify, check

  • Languages -> Visual C++ -> Common tools for Visual C++
  • Windows and web development -> Tools for universal windows apps -> Tools (1.4.1) and Windows 10 SDK ([version])
  • Windows and web development -> Tools for universal windows apps -> Windows 10 SDK ([version])

and install. Then right click on solution -> Re-target and it will compile

Setting environment variables in Linux using Bash

The reason people often suggest writing

VAR=value
export VAR

instead of the shorter

export VAR=value

is that the longer form works in more different shells than the short form. If you know you're dealing with bash, either works fine, of course.

Write HTML string in JSON

You should escape the characters like double quotes in the html string by adding "\"

eg: <h2 class=\"fg-white\">

How to get file name from file path in android

Other Way is:

String[] parts = selectedFilePath.split("/");
    final String fileName = parts[parts.length-1];

change figure size and figure format in matplotlib

The first part (setting the output size explictly) isn't too hard:

import matplotlib.pyplot as plt
list1 = [3,4,5,6,9,12]
list2 = [8,12,14,15,17,20]
fig = plt.figure(figsize=(4,3))
ax = fig.add_subplot(111)
ax.plot(list1, list2)
fig.savefig('fig1.png', dpi = 300)
fig.close()

But after a quick google search on matplotlib + tiff, I'm not convinced that matplotlib can make tiff plots. There is some mention of the GDK backend being able to do it.

One option would be to convert the output with a tool like imagemagick's convert.

(Another option is to wait around here until a real matplotlib expert shows up and proves me wrong ;-)

how to show only even or odd rows in sql server 2008?

odd number query:

SELECT *
  FROM   ( SELECT rownum rn, empno, ename
           FROM emp
         ) temp
  WHERE  MOD(temp.rn,2) = 1

even number query:

SELECT *
  FROM   ( SELECT rownum rn, empno, ename
           FROM emp
         ) temp
  WHERE  MOD(temp.rn,3) = 0

what is the multicast doing on 224.0.0.251?

If you don't have avahi installed then it's probably cups.

Sending GET request with Authentication headers using restTemplate

These days something like the following will suffice:

HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(accessToken);
restTemplate.exchange(RequestEntity.get(new URI(url)).headers(headers).build(), returnType);

Hide Button After Click (With Existing Form on Page)

This is my solution. I Hide and then confirm check

onclick="return ConfirmSubmit(this);" />

function ConfirmSubmit(sender)
    {
        sender.disabled = true;
        var displayValue = sender.style.
        sender.style.display = 'none'

        if (confirm('Seguro que desea entregar los paquetes?')) {
            sender.disabled = false
            return true;
        }

        sender.disabled = false;
        sender.style.display = displayValue;
        return false;
    }

Can I loop through a table variable in T-SQL?

You can loop through the table variable or you can cursor through it. This is what we usually call a RBAR - pronounced Reebar and means Row-By-Agonizing-Row.

I would suggest finding a SET-BASED answer to your question (we can help with that) and move away from rbars as much as possible.

Changing fonts in ggplot2

Late to the party, but this might be of interest for people looking to add custom fonts to their ggplots inside a shiny app on shinyapps.io.

You can:

  1. Place custom font in www directory: e.g. IndieFlower.ttf from here
  2. Follow the steps from here

This leads to the following upper section inside the app.R file:

dir.create('~/.fonts')
file.copy("www/IndieFlower.ttf", "~/.fonts")
system('fc-cache -f ~/.fonts')

A full example app can be found here.

Import SQL file into mysql

From the mysql console:

mysql> use DATABASE_NAME;

mysql> source path/to/file.sql;


make sure there is no slash before path if you are referring to a relative path... it took me a while to realize that! lol

How to install the Sun Java JDK on Ubuntu 10.10 (Maverick Meerkat)?

You might have to use the version in the Lucid partner repository. I did this in Lucid (I used the version from Karmic multiverse, before I realized it had been moved to the partner repo), and it worked fine. Not sure where it went in Maverick though.

Where does pip install its packages?

By default, on Linux, Pip installs packages to /usr/local/lib/python2.7/dist-packages.

Using virtualenv or --user during install will change this default location. If you use pip show make sure you are using the right user or else pip may not see the packages you are referencing.

Android - Back button in the title bar

First you need to write this codes

@Override
    protected void onCreate(Bundle savedInstanceState) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

Then add this line in manifest

 <activity android:name=".MainActivity"
            android:parentActivityName=".PreviousActivity"></activity>

I think it will work

Unknown version of Tomcat was specified in Eclipse

I am on MacOS and installed tomcat using homebrew, Following path fixed my problem

/usr/local/Cellar/tomcat/9.0.14/libexec

Insert content into iFrame

You really don't need jQuery for that:

var doc = document.getElementById('iframe').contentWindow.document;
doc.open();
doc.write('Test');
doc.close();

jsFiddle Demo

If you absolutely have to use jQuery, you should use contents():

var $iframe = $('#iframe');
$iframe.ready(function() {
    $iframe.contents().find("body").append('Test');
});

jsFiddle Demo

Please don't forget that if you're using jQuery, you'll need to hook into the DOMReady function as follows:

$(function() {  
    var $iframe = $('#iframe');
    $iframe.ready(function() {
        $iframe.contents().find("body").append('Test');
    });
});

How do I specify the platform for MSBuild?

Hopefully this helps someone out there.

For platform I was specifying "Any CPU", changed it to "AnyCPU" and that fixed the problem.

msbuild C:\Users\Project\Project.publishproj /p:Platform="AnyCPU"  /p:DeployOnBuild=true /p:PublishProfile=local /p:Configuration=Debug

If you look at your .csproj file you'll see the correct platform name to use.

JavaScript isset() equivalent

javascript isset

let test = {
  a: {
    b: [0, 1]
  }
};

console.log(test.isset('a.b'))   // true
console.log(test.isset('a.b.1')) // true
console.log(test.isset('a.b.5')) // false
console.log(test.isset('a.c'))   // false
console.log('abv'.isset('0'))    // true

Check if MySQL table exists or not

You can try this

$query = mysql_query("SELECT * FROM $this_table") or die (mysql_error());

or this

$query = mysql_query("SELECT * FROM $this_table") or die ("Table does not exists!");

or this

$query = mysql_query("SELECT * FROM $this_table");

if(!$query)
   echo "The ".$this_table." does not exists";

Hope it helps!

Python NameError: name is not defined

Define the class before you use it:

class Something:
    def out(self):
        print("it works")

s = Something()
s.out()

You need to pass self as the first argument to all instance methods.

adb server version doesn't match this client

Did you try using the SDK version 8. Since the device is in 2.2, and your SDK is at 10, there might be conflict.

Best of luck with ur downgrading efforts!! Hope this solves.

How to use org.apache.commons package?

Download commons-net binary from here. Extract the files and reference the commons-net-x.x.jar file.

Why are my PHP files showing as plain text?

Are you using the userdir mod?

In that case the thing is that PHP5 seems to be disabling running scripts from that location by default and you have to comment out the following lines:

<IfModule mod_userdir.c>
    <Directory /home/*/public_html>
        php_admin_flag engine Off
    </Directory>
</IfModule>

in /etc/apache2/mods-enabled/php5.conf (on a ubuntu system)

How to install Python MySQLdb module using pip?

If you have Windows installed on your system then type the following command on cmd :

pip install mysql-connector

if the above command does not work try using:

pip install mysql-connector-python

Now,if the above commands do not get the work done, try using:

pip install mysql-connector-python-rf

That's it you are good to go now.

Trim characters in Java

You could use removeStart and removeEnd from Apache Commons Lang StringUtils

Python Tkinter clearing a frame

For clear frame, first need to destroy all widgets inside the frame,. it will clear frame.

import tkinter as tk
from tkinter import *
root = tk.Tk()

frame = Frame(root)
frame.pack(side="top", expand=True, fill="both")

lab = Label(frame, text="hiiii")
lab.grid(row=0, column=0, padx=10, pady=5)

def clearFrame():
    # destroy all widgets from frame
    for widget in frame.winfo_children():
       widget.destroy()
    
    # this will clear frame and frame will be empty
    # if you want to hide the empty panel then
    frame.pack_forget()

frame.but = Button(frame, text="clear frame", command=clearFrame)
frame.but.grid(row=0, column=1, padx=10, pady=5)

# then whenever you add data in frame then you can show that frame
lab2 = Label(frame, text="hiiii")
lab2.grid(row=1, column=0, padx=10, pady=5)
frame.pack()
root.mainloop()

Why is my JavaScript function sometimes "not defined"?

A syntax error in the function -- or in the code above it -- may cause it to be undefined.

Get today date in google appScript

Utilities.formatDate(new Date(), "GMT+1", "dd/MM/yyyy")

You can change the format by doing swapping the values.

  • dd = day(31)
  • MM = Month(12) - Case sensitive
  • yyyy = Year(2017)
function changeDate() {
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GA_CONFIG);
    // You could use now Date(); on its own but it will not look nice.
    var date = Utilities.formatDate(new Date(), "GMT+1", "dd/MM/yyyy")
    var endDate = date
}

Java Error opening registry key

I had the same:

Error opening registry key 'Software\JavaSoft\Java Runtime Environment

Clearing Windows\SysWOW64 doesn't help for Win7

In my case it installing JDK8 offline helped (from link)

How to make CREATE OR REPLACE VIEW work in SQL Server?

Here is another method, where you don't have to duplicate the contents of the view:

IF (NOT EXISTS (SELECT 1 FROM sys.views WHERE name = 'data_VVV'))
BEGIN
    EXECUTE('CREATE VIEW data_VVVV as SELECT 1 as t');
END;

GO

ALTER VIEW data_VVVV AS 
    SELECT VCV.xxxx, VCV.yyyy AS yyyy, VCV.zzzz AS zzzz FROM TABLE_A ;

The first checks for the existence of the view (there are other ways to do this). If it doesn't exist, then create it with something simple and dumb. If it does, then just move on to the alter view statement.

Matplotlib connect scatterplot points with line - Python

In addition to what provided in the other answers, the keyword "zorder" allows one to decide the order in which different objects are plotted vertically. E.g.:

plt.plot(x,y,zorder=1) 
plt.scatter(x,y,zorder=2)

plots the scatter symbols on top of the line, while

plt.plot(x,y,zorder=2)
plt.scatter(x,y,zorder=1)

plots the line over the scatter symbols.

See, e.g., the zorder demo

.NET Format a string with fixed spaces

As of Visual Studio 2015 you can also do this with Interpolated Strings (its a compiler trick, so it doesn't matter which version of the .net framework you target).

string value = "String goes here";
string txt1 = $"{value,20}";
string txt2 = $"{value,-20}";

The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly

In your example, the compiler has no way of knowing what type should TModel be. You could do something close to what you are probably trying to do with an extension method.

static class ModelExtensions
{
   public static IDictionary<string, object> GetHtmlAttributes<TModel, TProperty>
      (this TModel model, Expression<Func<TModel, TProperty>> propertyExpression)
   {
       return new Dictionary<string, object>();
   }
}

But you wouldn't be able to have anything similar to virtual, I think.

EDIT:

Actually, you can do virtual, using self-referential generics:

class ModelBase<TModel>
{
    public virtual IDictionary<string, object> GetHtmlAttributes<TProperty>
        (Expression<Func<TModel, TProperty>> propertyExpression)
    {
        return new Dictionary<string, object>();
    }
}

class FooModel : ModelBase<FooModel>
{
    public override IDictionary<string, object> GetHtmlAttributes<TProperty>
        (Expression<Func<FooModel, TProperty>> propertyExpression)
    {
        return new Dictionary<string, object> { { "foo", "bar" } };
    }
}

How to make correct date format when writing data to Excel

This worked for me:

hoja_trabajo.Cells[i + 2, j + 1] = fecha.ToString("dd-MMM-yyyy").Replace(".", "");

What is a constant reference? (not a reference to a constant)

As it mentioned in another answers, a reference is inherently const.

int &ref = obj;

Once you initialized a reference with an object, you can't unbound this reference with its object it refers to. A reference works just like an alias.

When you declare a const reference, it is nothing but a reference which refers to a const object.

const int &ref = obj;

The declarative sentences above like const and int is determining the available features of the object which will be referenced by the reference. To be more clear, I want to show you the pointer equivalent of a const reference;

const int *const ptr = &obj;

So the above line of code is equivalent to a const reference in its working way. Additionally, there is a one last point which I want to mention;

A reference must be initialized only with an object

So when you do this, you are going to get an error;

int  &r = 0; // Error: a nonconst reference cannot be initialized to a literal

This rule has one exception. If the reference is declared as const, then you can initialize it with literals as well;

const int  &r = 0; // a valid approach

How can I dynamically add items to a Java array?

keep a count of where you are in the primitive array

class recordStuff extends Thread
{
    double[] aListOfDoubles;
    int i = 0;

    void run()
    {
        double newData;
        newData = getNewData(); // gets data from somewhere

        aListofDoubles[i] = newData; // adds it to the primitive array of doubles
        i++ // increments the counter for the next pass

        System.out.println("mode: " + doStuff());
    }

    void doStuff()
    {
        // Calculate the mode of the double[] array

        for (int i = 0; i < aListOfDoubles.length; i++) 
        {
            int count = 0;
            for (int j = 0; j < aListOfDoubles.length; j++)
            {
                if (a[j] == a[i]) count++;
            }
            if (count > maxCount) 
            {
                maxCount = count;
                maxValue = aListOfDoubles[i];
            }
        }
        return maxValue;
    }
}

IndentationError expected an indented block

You've mixed tabs and spaces. This can lead to some confusing errors.

I'd suggest using only tabs or only spaces for indentation.

Using only spaces is generally the easier choice. Most editors have an option for automatically converting tabs to spaces. If your editor has this option, turn it on.


As an aside, your code is more verbose than it needs to be. Instead of this:

if str_p == str_q:
    result = True
else:
    result = False
return result

Just do this:

return str_p == str_q

You also appear to have a bug on this line:

str_q = p[b+1:]

I'll leave you to figure out what the error is.

Creating a byte array from a stream

You can simply use ToArray() method of MemoryStream class, for ex-

MemoryStream ms = (MemoryStream)dataInStream;
byte[] imageBytes = ms.ToArray();

JPA OneToMany and ManyToOne throw: Repeated column in mapping for entity column (should be mapped with insert="false" update="false")

You should never use the unidirectional @OneToMany annotation because:

  1. It generates inefficient SQL statements
  2. It creates an extra table which increases the memory footprint of your DB indexes

Now, in your first example, both sides are owning the association, and this is bad.

While the @JoinColumn would let the @OneToMany side in charge of the association, it's definitely not the best choice. Therefore, always use the mappedBy attribute on the @OneToMany side.

public class User{
    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    public List<APost> aPosts;

    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    public List<BPost> bPosts;
}

public class BPost extends Post {

    @ManyToOne(fetch=FetchType.LAZY)    
    public User user;
}

public class APost extends Post {

     @ManyToOne(fetch=FetchType.LAZY) 
     public User user;
}

Can iterators be reset in Python?

While there is no iterator reset, the "itertools" module from python 2.6 (and later) has some utilities that can help there. One of then is the "tee" which can make multiple copies of an iterator, and cache the results of the one running ahead, so that these results are used on the copies. I will seve your purposes:

>>> def printiter(n):
...   for i in xrange(n):
...     print "iterating value %d" % i
...     yield i

>>> from itertools import tee
>>> a, b = tee(printiter(5), 2)
>>> list(a)
iterating value 0
iterating value 1
iterating value 2
iterating value 3
iterating value 4
[0, 1, 2, 3, 4]
>>> list(b)
[0, 1, 2, 3, 4]

How to get a substring of text?

If you want a string, then the other answers are fine, but if what you're looking for is the first few letters as characters you can access them as a list:

your_text.chars.take(30)

Where is the Java SDK folder in my computer? Ubuntu 12.04

WAY-1 : Updated for the shortest and easy way

Below command will give you the path, But it will only work if java command is working in other words if java path is configured.

readlink -f $(which java) 

Read more at Where can I find the Java SDK in Linux?


WAY-2 (Better than WAY-1) : Below answer is still working and try it if above command is not working for you.

You need to dig into symbolic links. Below is steps to get Java directory

Step 1:

$ whereis java
java: /usr/bin/java /etc/java /usr/share/java

That tells the command java resides in /usr/bin/java.

Dig again:

Step 2:

$ ls -l /usr/bin/java
lrwxrwxrwx 1 root root 22 2009-01-15 18:34 /usr/bin/java -> /etc/alternatives/java

So, now we know that /usr/bin/java is actually a symbolic link to /etc/alternatives/java.

Dig deeper using the same method above:

Step 3:

$ ls -l /etc/alternatives/java
lrwxrwxrwx 1 root root 31 2009-01-15 18:34 /etc/alternatives/java -> /usr/local/jre1.6.0_07/bin/java

So, thats the actual location of java: /usr/local/jre.....

You could still dig deeper to find other symbolic links.


Reference : where is java's home dir?

Search and replace in bash using regular expressions

Use sed:

MYVAR=ho02123ware38384you443d34o3434ingtod38384day
echo "$MYVAR" | sed -e 's/[a-zA-Z]/X/g' -e 's/[0-9]/N/g'
# prints XXNNNNNXXXXNNNNNXXXNNNXNNXNNNNXXXXXXNNNNNXXX

Note that the subsequent -e's are processed in order. Also, the g flag for the expression will match all occurrences in the input.

You can also pick your favorite tool using this method, i.e. perl, awk, e.g.:

echo "$MYVAR" | perl -pe 's/[a-zA-Z]/X/g and s/[0-9]/N/g'

This may allow you to do more creative matches... For example, in the snip above, the numeric replacement would not be used unless there was a match on the first expression (due to lazy and evaluation). And of course, you have the full language support of Perl to do your bidding...

Converting int to bytes in Python 3

I was curious about performance of various methods for a single int in the range [0, 255], so I decided to do some timing tests.

Based on the timings below, and from the general trend I observed from trying many different values and configurations, struct.pack seems to be the fastest, followed by int.to_bytes, bytes, and with str.encode (unsurprisingly) being the slowest. Note that the results show some more variation than is represented, and int.to_bytes and bytes sometimes switched speed ranking during testing, but struct.pack is clearly the fastest.

Results in CPython 3.7 on Windows:

Testing with 63:
bytes_: 100000 loops, best of 5: 3.3 usec per loop
to_bytes: 100000 loops, best of 5: 2.72 usec per loop
struct_pack: 100000 loops, best of 5: 2.32 usec per loop
chr_encode: 50000 loops, best of 5: 3.66 usec per loop

Test module (named int_to_byte.py):

"""Functions for converting a single int to a bytes object with that int's value."""

import random
import shlex
import struct
import timeit

def bytes_(i):
    """From Tim Pietzcker's answer:
    https://stackoverflow.com/a/21017834/8117067
    """
    return bytes([i])

def to_bytes(i):
    """From brunsgaard's answer:
    https://stackoverflow.com/a/30375198/8117067
    """
    return i.to_bytes(1, byteorder='big')

def struct_pack(i):
    """From Andy Hayden's answer:
    https://stackoverflow.com/a/26920966/8117067
    """
    return struct.pack('B', i)

# Originally, jfs's answer was considered for testing,
# but the result is not identical to the other methods
# https://stackoverflow.com/a/31761722/8117067

def chr_encode(i):
    """Another method, from Quuxplusone's answer here:
    https://codereview.stackexchange.com/a/210789/140921

    Similar to g10guang's answer:
    https://stackoverflow.com/a/51558790/8117067
    """
    return chr(i).encode('latin1')

converters = [bytes_, to_bytes, struct_pack, chr_encode]

def one_byte_equality_test():
    """Test that results are identical for ints in the range [0, 255]."""
    for i in range(256):
        results = [c(i) for c in converters]
        # Test that all results are equal
        start = results[0]
        if any(start != b for b in results):
            raise ValueError(results)

def timing_tests(value=None):
    """Test each of the functions with a random int."""
    if value is None:
        # random.randint takes more time than int to byte conversion
        # so it can't be a part of the timeit call
        value = random.randint(0, 255)
    print(f'Testing with {value}:')
    for c in converters:
        print(f'{c.__name__}: ', end='')
        # Uses technique borrowed from https://stackoverflow.com/q/19062202/8117067
        timeit.main(args=shlex.split(
            f"-s 'from int_to_byte import {c.__name__}; value = {value}' " +
            f"'{c.__name__}(value)'"
        ))

Excel VBA function to print an array to the workbook

A more elegant way is to assign the whole array at once:

Sub PrintArray(Data, SheetName, StartRow, StartCol)

    Dim Rng As Range

    With Sheets(SheetName)
        Set Rng = .Range(.Cells(StartRow, StartCol), _
            .Cells(UBound(Data, 1) - LBound(Data, 1) + StartRow, _
            UBound(Data, 2) - LBound(Data, 2) + StartCol))
    End With
    Rng.Value2 = Data

End Sub

But watch out: it only works up to a size of about 8,000 cells. Then Excel throws a strange error. The maximum size isn't fixed and differs very much from Excel installation to Excel installation.

Are one-line 'if'/'for'-statements good Python style?

an example of a language feature that isn't just removing line breaks, although still not convinced this is clearer than the more verbose version

a = 1 if x > 15 else 2

Good ways to manage a changelog using git?

Based on bithavoc, it lists the last tag until HEAD. But I hope to list the logs between 2 tags.

// 2 or 3 dots between `YOUR_LAST_VERSION_TAG` and `HEAD`
git log YOUR_LAST_VERSION_TAG..HEAD --no-merges --format=%B

List logs between 2 tags.

// 2 or 3 dots between 2 tags
git log FROM_TAG...TO_TAG

For example, it will list logs from v1.0.0 to v1.0.1.

git log v1.0.0...v1.0.1 --oneline --decorate

Convert timestamp in milliseconds to string formatted time in Java

I'll show you three ways to (a) get the minute field from a long value, and (b) print it using the Date format you want. One uses java.util.Calendar, another uses Joda-Time, and the last uses the java.time framework built into Java 8 and later.

The java.time framework supplants the old bundled date-time classes, and is inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.

The java.time framework is the way to go when using Java 8 and later. Otherwise, such as Android, use Joda-Time. The java.util.Date/.Calendar classes are notoriously troublesome and should be avoided.

java.util.Date & .Calendar

final long timestamp = new Date().getTime();

// with java.util.Date/Calendar api
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
// here's how to get the minutes
final int minutes = cal.get(Calendar.MINUTE);
// and here's how to get the String representation
final String timeString =
    new SimpleDateFormat("HH:mm:ss:SSS").format(cal.getTime());
System.out.println(minutes);
System.out.println(timeString);

Joda-Time

// with JodaTime 2.4
final DateTime dt = new DateTime(timestamp);
// here's how to get the minutes
final int minutes2 = dt.getMinuteOfHour();
// and here's how to get the String representation
final String timeString2 = dt.toString("HH:mm:ss:SSS");
System.out.println(minutes2);
System.out.println(timeString2);

Output:

24
09:24:10:254
24
09:24:10:254

java.time

long millisecondsSinceEpoch = 1289375173771L;
Instant instant = Instant.ofEpochMilli ( millisecondsSinceEpoch );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , ZoneOffset.UTC );

DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "HH:mm:ss:SSS" );
String output = formatter.format ( zdt );

System.out.println ( "millisecondsSinceEpoch: " + millisecondsSinceEpoch + " instant: " + instant + " output: " + output );

millisecondsSinceEpoch: 1289375173771 instant: 2010-11-10T07:46:13.771Z output: 07:46:13:771

Vue component event after render

updated() should be what you're looking for:

Called after a data change causes the virtual DOM to be re-rendered and patched.

The component’s DOM will have been updated when this hook is called, so you can perform DOM-dependent operations here.

How can I auto hide alert box after it showing it?

You can also try Notification API. Here's an example:

function message(msg){
    if (window.webkitNotifications) {
        if (window.webkitNotifications.checkPermission() == 0) {
        notification = window.webkitNotifications.createNotification(
          'picture.png', 'Title', msg);
                    notification.onshow = function() { // when message shows up
                        setTimeout(function() {
                            notification.close();
                        }, 1000); // close message after one second...
                    };
        notification.show();
      } else {
        window.webkitNotifications.requestPermission(); // ask for permissions
      }
    }
    else {
        alert(msg);// fallback for people who does not have notification API; show alert box instead
    }
    }

To use this, simply write:

message("hello");

Instead of:

alert("hello");

Note: Keep in mind that it's only currently supported in Chrome, Safari, Firefox and some mobile web browsers (jan. 2014)

Find supported browsers here.

Best way to update an element in a generic List

AllDogs.First(d => d.Id == "2").Name = "some value";

However, a safer version of that might be this:

var dog = AllDogs.FirstOrDefault(d => d.Id == "2");
if (dog != null) { dog.Name = "some value"; }

MySQL show status - active or total connections?

SHOW STATUS WHERE `variable_name` = 'Threads_connected';

This will show you all the open connections.

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

You will have to provide a link to your file that is accessible through the browser, that is for instance:

<a href="http://my.domain.com/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">

versus

<a href="C:/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">

If you expose your "Projecten" folder directly to the public, then you may only have to provide the link as such:

<a href="/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">

But beware, that your files can then be indexed by search engines, can be accessed by anybody having this link, etc.

default value for struct member in C

Another approach, if the struct allows it, is to use a #define with the default values inside:

#define MYSTRUCT_INIT { 0, 0, true }

typedef struct
{
    int id;
    int flag;
    bool foo;
} MyStruct;

Use:

MyStruct val = MYSTRUCT_INIT;

Laravel Request::all() Should Not Be Called Statically

I was facing this problem even with use Illuminate\Http\Request; line at the top of my controller. Kept pulling my hair till I realized that I was doing $request::ip() instead of $request->ip(). Can happen to you if you didn't sleep all night and are looking at the code at 6am with half-opened eyes.

Hope this helps someone down the road.

How to get the Display Name Attribute of an Enum member via MVC Razor code?

Based on previous answers I've created this comfortable helper to support all DisplayAttribute properties in a readable way:

public static class EnumExtensions
    {
        public static DisplayAttributeValues GetDisplayAttributeValues(this Enum enumValue)
        {
            var displayAttribute = enumValue.GetType().GetMember(enumValue.ToString()).First().GetCustomAttribute<DisplayAttribute>();

            return new DisplayAttributeValues(enumValue, displayAttribute);
        }

        public sealed class DisplayAttributeValues
        {
            private readonly Enum enumValue;
            private readonly DisplayAttribute displayAttribute;

            public DisplayAttributeValues(Enum enumValue, DisplayAttribute displayAttribute)
            {
                this.enumValue = enumValue;
                this.displayAttribute = displayAttribute;
            }

            public bool? AutoGenerateField => this.displayAttribute?.GetAutoGenerateField();
            public bool? AutoGenerateFilter => this.displayAttribute?.GetAutoGenerateFilter();
            public int? Order => this.displayAttribute?.GetOrder();
            public string Description => this.displayAttribute != null ? this.displayAttribute.GetDescription() : string.Empty;
            public string GroupName => this.displayAttribute != null ? this.displayAttribute.GetGroupName() : string.Empty;
            public string Name => this.displayAttribute != null ? this.displayAttribute.GetName() : this.enumValue.ToString();
            public string Prompt => this.displayAttribute != null ? this.displayAttribute.GetPrompt() : string.Empty;
            public string ShortName => this.displayAttribute != null ? this.displayAttribute.GetShortName() : this.enumValue.ToString();
        }
    }

How to render a PDF file in Android

Since API Level 21 (Lollipop) Android provides a PdfRenderer class:

// create a new renderer
 PdfRenderer renderer = new PdfRenderer(getSeekableFileDescriptor());

 // let us just render all pages
 final int pageCount = renderer.getPageCount();
 for (int i = 0; i < pageCount; i++) {
     Page page = renderer.openPage(i);

     // say we render for showing on the screen
     page.render(mBitmap, null, null, Page.RENDER_MODE_FOR_DISPLAY);

     // do stuff with the bitmap

     // close the page
     page.close();
 }

 // close the renderer
 renderer.close();

For more information see the sample app.

For older APIs I recommend Android PdfViewer library, it is very fast and easy to use, licensed under Apache License 2.0:

pdfView.fromAsset(String)
  .pages(0, 2, 1, 3, 3, 3) // all pages are displayed by default
  .enableSwipe(true)
  .swipeHorizontal(false)
  .enableDoubletap(true)
  .defaultPage(0)
  .onDraw(onDrawListener)
  .onLoad(onLoadCompleteListener)
  .onPageChange(onPageChangeListener)
  .onPageScroll(onPageScrollListener)
  .onError(onErrorListener)
  .enableAnnotationRendering(false)
  .password(null)
  .scrollHandle(null)
  .load();

What does += mean in Python?

FYI: it looks like you might have an infinite loop in your example...

if cnt > 0 and len(aStr) > 1:
    while cnt > 0:                  
        aStr = aStr[1:]+aStr[0]
        cnt += 1
  • a condition of entering the loop is that cnt is greater than 0
  • the loop continues to run as long as cnt is greater than 0
  • each iteration of the loop increments cnt by 1

The net result is that cnt will always be greater than 0 and the loop will never exit.

Html.DropdownListFor selected value not being set

Make sure that you have trim the selected value before you assigning.

//Model

public class SelectType
{
    public string Text { get; set; }
    public string Value { get; set; }
}

//Controller

var types = new List<SelectType>();
types.Add(new SelectType() { Value =  0, Text = "Select a Type" });
types.Add(new SelectType() { Value =  1, Text = "Family Trust" });
types.Add(new SelectType() { Value =  2, Text = "Unit Trust"});
ViewBag.PartialTypes = types;

//View

@Html.DropDownListFor(m => m.PartialType, new SelectList(ViewBag.PartialTypes, "Value", "Text"), new { id = "Type" })

The Network Adapter could not establish the connection when connecting with Oracle DB

I had similar problem before. But this was resolved when I started using hostname instead of IP address in my connection string.

Apache shutdown unexpectedly

In my situation I had moved the htdocs to a new location updated in httpd.conf, which worked fine. I then received the same error after updating the httpd-vhost.conf file.

I found that the error was caused by a typo in the vhost configuration file. Previously I changed all "DocumentRoot" ’s to the new htdocs location, but had forgot to update the new location for "ErrorLog". After correcting the missing path, Apache was running smooth again.

How do I convert a PDF document to a preview image in PHP?

I install finished! It's worked!

You may be do base install imagemagick on windows.

In php (local) use call exec(<command line>) ex:

<?php
$pdf = "filename.pdf";
$info = pathinfo($pdf);
$file_name =  basename($pdf,'.'.$info['extension']);
echo $file_name;
$pdf = "filename.pdf[0]";
exec("convert $pdf convert-img/$file_name.jpg");    
?>

Besides, you may be use class imagick in PHP Imagick class

Thanks all helped me!

Get Element value with minidom with Python

Probably something like this if it's the text part you want...

from xml.dom.minidom import parse
dom = parse("C:\\eve.xml")
name = dom.getElementsByTagName('name')

print " ".join(t.nodeValue for t in name[0].childNodes if t.nodeType == t.TEXT_NODE)

The text part of a node is considered a node in itself placed as a child-node of the one you asked for. Thus you will want to go through all its children and find all child nodes that are text nodes. A node can have several text nodes; eg.

<name>
  blabla
  <somestuff>asdf</somestuff>
  znylpx
</name>

You want both 'blabla' and 'znylpx'; hence the " ".join(). You might want to replace the space with a newline or so, or perhaps by nothing.

how to remove time from datetime

First thing's first, if your dates are in varchar format change that, store dates as dates it will save you a lot of headaches and it is something that is best done sooner rather than later. The problem will only get worse.

Secondly, once you have a date DO NOT convert the date to a varchar! Keep it in date format and use formatting on the application side to get the required date format.

There are various methods to do this depending on your DBMS:


SQL-Server 2008 and later:

SELECT  CAST(CURRENT_TIMESTAMP AS DATE)

SQL-Server 2005 and Earlier

SELECT  DATEADD(DAY, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP), 0)

SQLite

SELECT  DATE(NOW())

Oracle

SELECT  TRUNC(CURRENT_TIMESTAMP)

Postgresql

SELECT  CURRENT_TIMESTAMP::DATE

If you need to use culture specific formatting in your report you can either explicitly state the format of the receiving text box (e.g. dd/MM/yyyy), or you can set the language so that it shows the relevant date format for that language.

Either way this is much better handled outside of SQL as converting to varchar within SQL will impact any sorting you may do in your report.

If you cannot/will not change the datatype to DATETIME, then still convert it to a date within SQL (e.g. CONVERT(DATETIME, yourField)) before sending to report services and handle it as described above.