Programs & Examples On #Field with errors

How to visualize an XML schema?

We use Liquid XML Studio, it provides a intuitive editable representation of an XSD schema. It also shows the annotations inline, which we find very useful and the split code/gfx view is invaluable when writting or editing an XSD.

Liquid XML Studio XSD Editor

H2 in-memory database. Table not found

Had the exact same issue, tried all the above, but without success. The rather funny cause of the error was that the JVM started too fast, before the DB table was created (using a data.sql file in src.main.resources). So I've put a Thread.sleep(1000) timer to wait for just a second before calling "select * from person". Working flawlessly now.

application.properties:

spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

data.sql:

create table person
(
id integer not null,
name varchar(255) not null,
location varchar(255),
birth_date timestamp,
primary key(id)
);

insert into person values (
10001, 'Tofu', 'home', sysdate()
);

PersonJdbcDAO.java:

    public List<Person> findAllPersons(){
    return jdbcTemplate.query("select * from person", 
        new BeanPropertyRowMapper<Person>(Person.class));
}

main class:

Thread.sleep(1000);
logger.info("All users -> {}", dao.findAllPersons());

Alter column, add default constraint

Actually you have to Do Like below Example, which will help to Solve the Issue...

drop table ABC_table

create table ABC_table
(
    names varchar(20),
    age int
)

ALTER TABLE ABC_table
ADD CONSTRAINT MyConstraintName
DEFAULT 'This is not NULL' FOR names

insert into ABC(age) values(10)

select * from ABC

Keyboard shortcuts in WPF

Although the top answers are correct, I personally like to work with attached properties to enable the solution to be applied to any UIElement, especially when the Window is not aware of the element that should be focused. In my experience I often see a composition of several view models and user controls, where the window is often nothing more that the root container.

Snippet

public sealed class AttachedProperties
{
    // Define the key gesture type converter
    [System.ComponentModel.TypeConverter(typeof(System.Windows.Input.KeyGestureConverter))]
    public static KeyGesture GetFocusShortcut(DependencyObject dependencyObject)
    {
        return (KeyGesture)dependencyObject?.GetValue(FocusShortcutProperty);
    }

    public static void SetFocusShortcut(DependencyObject dependencyObject, KeyGesture value)
    {
        dependencyObject?.SetValue(FocusShortcutProperty, value);
    }

    /// <summary>
    /// Enables window-wide focus shortcut for an <see cref="UIElement"/>.
    /// </summary>
    // Using a DependencyProperty as the backing store for FocusShortcut.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty FocusShortcutProperty =
        DependencyProperty.RegisterAttached("FocusShortcut", typeof(KeyGesture), typeof(AttachedProperties), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.None, new PropertyChangedCallback(OnFocusShortcutChanged)));

    private static void OnFocusShortcutChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (!(d is UIElement element) || e.NewValue == e.OldValue)
            return;

        var window = FindParentWindow(d);
        if (window == null)
            return;

        var gesture = GetFocusShortcut(d);
        if (gesture == null)
        {
            // Remove previous added input binding.
            for (int i = 0; i < window.InputBindings.Count; i++)
            {
                if (window.InputBindings[i].Gesture == e.OldValue && window.InputBindings[i].Command is FocusElementCommand)
                    window.InputBindings.RemoveAt(i--);
            }
        }
        else
        {
            // Add new input binding with the dedicated FocusElementCommand.
            // see: https://gist.github.com/shuebner20/349d044ed5236a7f2568cb17f3ed713d
            var command = new FocusElementCommand(element);
            window.InputBindings.Add(new InputBinding(command, gesture));
        }
    }
}

With this attached property you can define a focus shortcut for any UIElement. It will automatically register the input binding at the window containing the element.

Usage (XAML)

<TextBox x:Name="SearchTextBox"
         Text={Binding Path=SearchText}
         local:AttachedProperties.FocusShortcutKey="Ctrl+Q"/>

Source code

The full sample including the FocusElementCommand implementation is available as gist: https://gist.github.com/shuebner20/c6a5191be23da549d5004ee56bcc352d

Disclaimer: You may use this code everywhere and free of charge. Please keep in mind, that this is a sample that is not suitable for heavy usage. For example, there is no garbage collection of removed elements because the Command will hold a strong reference to the element.

Reporting Services export to Excel with Multiple Worksheets

I found a simple way around this in 2005. Here are my steps:

  1. Create a string parameter with values ‘Y’ and ‘N’ called ‘PageBreaks’.
  2. Add a group level above the group (value) which was used to split the data to the multiple sheets in Excel.
  3. Inserted into the first textbox field for this group, the expression for the ‘PageBreaks’ as such… =IIF(Parameters!PageBreaks.Value="Y",Fields!DISP_PROJECT.Value,"") Note: If the parameter =’Y’ then you will get the multiple sheets for each different value. Otherwise the field is NULL for every group record (which causes only one page break at the end).
  4. Change the visibility hidden value of the new grouping row to ‘True’.
  5. NOTE: When you do this it will also determine whether or not you have a page break in the view, but my users love it since they have the control.

What is Common Gateway Interface (CGI)?

A CGI is a program (or a Web API) you write, and save it on the Web Server site. CGI is a file.

This file sits and waits on the Web Server. When the client browser sends a request to the Web Server to execute your CGI file, the Web Server runs your CGI file on the server site. The inputs for this CGI program, if any, are from the client browser. The outputs of this CGI program are sent to the browser.

What language you use to write a CGI program? Other posts already mention c,java, php, perl, etc.

jquery-ui-dialog - How to hook into dialog close event

add option 'close' like under sample and do what you want inline function

close: function(e){
    //do something
}

Adding ASP.NET MVC5 Identity Authentication to an existing project

I recommend IdentityServer.This is a .NET Foundation project and covers many issues about authentication and authorization.

Overview

IdentityServer is a .NET/Katana-based framework and hostable component that allows implementing single sign-on and access control for modern web applications and APIs using protocols like OpenID Connect and OAuth2. It supports a wide range of clients like mobile, web, SPAs and desktop applications and is extensible to allow integration in new and existing architectures.

For more information, e.g.

  • support for MembershipReboot and ASP.NET Identity based user stores
  • support for additional Katana authentication middleware (e.g. Google, Twitter, Facebook etc)
  • support for EntityFramework based persistence of configuration
  • support for WS-Federation
  • extensibility

check out the documentation and the demo.

415 Unsupported Media Type - POST json to OData service in lightswitch 2012

It looks like this issue has to do with the difference between the Content-Type and Accept headers. In HTTP, Content-Type is used in request and response payloads to convey the media type of the current payload. Accept is used in request payloads to say what media types the server may use in the response payload.

So, having a Content-Type in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type does matter.

If a server is not able to process the Content-Type of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept header, it will return a 406 error.)

In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.

You could fix this in one of two ways:

  1. Make the Content-Type "application/json;odata=verbose" in your POST request, or
  2. Include the DataServiceVersion header in the request and set it be less than v3. For example:

    DataServiceVersion: 2.0;
    

(Option 2 assumes that you aren't using any v3 features in your request payload.)

Stopping a CSS3 Animation on last frame

If you want to add this behaviour to a shorthand animation property definition, the order of sub-properties is as follows

animation-name - default none

animation-duration - default 0s

animation-timing-function - default ease

animation-delay - default 0s

animation-iteration-count - default 1

animation-direction - default normal

animation-fill-mode - you need to set this to forwards

animation-play-state - default running

Therefore in the most common case, the result will be something like this

animation: colorchange 1s ease 0s 1 normal forwards;

See the MDN documentation here

Use of PUT vs PATCH methods in REST API real life scenarios

TLDR - Dumbed Down Version

PUT => Set all new attributes for an existing resource.

PATCH => Partially update an existing resource (not all attributes required).

How to format a JavaScript date

If you fancy a short, human-readable, function - this is easily adjustable to suit you.

The timeStamp parameter is milliseconds from 1970 - it is returned by new Date().getTime() and many other devices...

OK, I changed my mind. I included an extra function for zero padding. Curses!

 function zeroPad(aNumber) {
     return ("0"+aNumber).slice(-2);
 }
 function humanTime(timeStamp) {
    var M = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var D = new Date(timeStamp); // 23 Aug 2016 16:45:59 <-- Desired format.
    return D.getDate() + " " + M[D.getMonth()] + " " + D.getFullYear() + " " + D.getHours() + ":" + zeroPad(d.getMinutes()) + ":" + zeroPad(D.getSeconds());
 }

This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console

Here are the steps that worked for me:

  1. Enable Directions API; Geocoding API; Gelocation API console.cloud.google.com/google/maps-apis
  2. Enable APIS and Services to select APIs console.developers.google.com/apis/library

How to retrieve all keys (or values) from a std::map and put them into a vector?

//c++0x too
std::map<int,int> mapints;
std::vector<int> vints;
for(auto const& imap: mapints)
    vints.push_back(imap.first);

What does <![CDATA[]]> in XML mean?

The data contained therein will not be parsed as XML, and as such does not need to be valid XML or can contain elements that may appear to be XML but are not.

How to obtain Telegram chat_id for a specific user?

Whenever user communicate with bot it send information like below:

$response = {
        "update_id":640046715,
        "message":{
            "message_id":1665,
            "from":{"id":108177xxxx,"is_bot":false,"first_name":"Suresh","last_name":"Kamrushi","language_code":"en"},
            "chat":{"id":108xxxxxx,"first_name":"Suresh","last_name":"Kamrushi","type":"private"},
            "date":1604381276,
            "text":"1"            
            }        
        }

So you can access chat it like:
$update["message"]["chat"]["id"]

Assuming you are using PHP.

Display a angular variable in my html page

In your template, you have access to all the variables that are members of the current $scope. So, tobedone should be $scope.tobedone, and then you can display it with {{tobedone}}, or [[tobedone]] in your case.

How to stretch a table over multiple pages

You should \usepackage{longtable}.

How to use count and group by at the same select statement

Try the following code:

select ccode, count(empno) 
from company_details 
group by ccode;

semaphore implementation

Vary the consumer-rate and the producer-rate (using sleep), to better understand the operation of code. The code below is the consumer-producer simulation (over a max-limit on container).

Code for your reference:

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>

sem_t semP, semC;
int stock_count = 0;
const int stock_max_limit=5;

void *producer(void *arg) {
    int i, sum=0;
    for (i = 0; i < 10; i++) {

        while(stock_max_limit == stock_count){
            printf("stock overflow, production on wait..\n");
            sem_wait(&semC);
            printf("production operation continues..\n");
        }

        sleep(1);   //production decided here
        stock_count++;
        printf("P::stock-count : %d\n",stock_count);
        sem_post(&semP);
        printf("P::post signal..\n");
    }
 }

void *consumer(void *arg) {
    int i, sum=0;
    for (i = 0; i < 10; i++) {

        while(0 == stock_count){
            printf("stock empty, consumer on wait..\n");
            sem_wait(&semP);
            printf("consumer operation continues..\n");
        }

        sleep(2);   //consumer rate decided here
        stock_count--;
        printf("C::stock-count : %d\n", stock_count);
        sem_post(&semC);
        printf("C::post signal..\n");
        }
}

int main(void) {

    pthread_t tid0,tid1;
    sem_init(&semP, 0, 0);
    sem_init(&semC, 0, 0);

        pthread_create(&tid0, NULL, consumer, NULL);
        pthread_create(&tid1, NULL, producer, NULL);
        pthread_join(tid0, NULL);
        pthread_join(tid1, NULL);

    sem_destroy(&semC);
    sem_destroy(&semP);

    return 0;
}

How to use zIndex in react-native

I believe there are different ways to do this based on what you need exactly, but one way would be to just put both Elements A and B inside Parent A.

    <View style={{ position: 'absolute' }}>    // parent of A
        <View style={{ zIndex: 1 }} />  // element A
        <View style={{ zIndex: 1 }} />  // element A
        <View style={{ zIndex: 0, position: 'absolute' }} />  // element B
    </View>

Best font for coding

I like Consolas a lot. This top-10 list is a good resource for others. It includes examples and descriptions.

How to force a web browser NOT to cache images

I use PHP's file modified time function, for example:

echo <img  src='Images/image.png?" . filemtime('Images/image.png') . "'  />";

If you change the image then the new image is used rather than the cached one, due to having a different modified timestamp.

npm command to uninstall or prune unused packages in Node.js

You can use npm-prune to remove extraneous packages.

npm prune [[<@scope>/]<pkg>...] [--production] [--dry-run] [--json]

This command removes "extraneous" packages. If a package name is provided, then only packages matching one of the supplied names are removed.

Extraneous packages are packages that are not listed on the parent package's dependencies list.

If the --production flag is specified or the NODE_ENV environment variable is set to production, this command will remove the packages specified in your devDependencies. Setting --no-production will negate NODE_ENV being set to production.

If the --dry-run flag is used then no changes will actually be made.

If the --json flag is used then the changes npm prune made (or would have made with --dry-run) are printed as a JSON object.

In normal operation with package-locks enabled, extraneous modules are pruned automatically when modules are installed and you'll only need this command with the --production flag.

If you've disabled package-locks then extraneous modules will not be removed and it's up to you to run npm prune from time-to-time to remove them.

Use npm-dedupe to reduce duplication

npm dedupe
npm ddp

Searches the local package tree and attempts to simplify the overall structure by moving dependencies further up the tree, where they can be more effectively shared by multiple dependent packages.

For example, consider this dependency graph:

a
+-- b <-- depends on [email protected]
|    `-- [email protected]
`-- d <-- depends on c@~1.0.9
     `-- [email protected]

In this case, npm-dedupe will transform the tree to:

 a
 +-- b
 +-- d
 `-- [email protected]

Because of the hierarchical nature of node's module lookup, b and d will both get their dependency met by the single c package at the root level of the tree.

The deduplication algorithm walks the tree, moving each dependency as far up in the tree as possible, even if duplicates are not found. This will result in both a flat and deduplicated tree.

Bitbucket fails to authenticate on git pull

You can update your Bitbucket credentials from the OSX Keychain.

Updating your cached credentials via the command line:

$ git credential-osxkeychain erase
host=bitbucket.org
protocol=https
[press return]

If it's successful, nothing will print out. To test that it works, try and clone a repository from Bitbucket. If you are prompted for a password, the keychain entry was deleted.

How to convert Excel values into buckets?

I prefer to label buckets with a numeric formula. If the bucket size is 10 then this labels the buckets 0,1,2,...

=INT(A1/10)

If you put the bucket size 10 in a separate cell you can easily vary it.

If cell B1 contains the bucket (0,1,2,...) and column 6 contains the names Low, Medium, High then this formula converts a bucket to a name:

=INDIRECT(ADDRESS(1+B1,6))

Alternatively, this labels the buckets with the least value in the set, i.e. 0,10,20,...

=10*INT(A1/10)

or this labels them with the range 0-10,10-20,20-30,...

=10*INT(A1/10) & "-" & (10*INT(A1/10)+10)

How to add to the end of lines containing a pattern with sed or awk?

Solution with awk:

awk '{if ($1 ~ /^all/) print $0, "anotherthing"; else print $0}' file

Simply: if the row starts with all print the row plus "anotherthing", else print just the row.

Check box size change with CSS

You might want to do this.

input[type=checkbox] {

 -ms-transform: scale(2); /* IE */
 -moz-transform: scale(2); /* FF */
 -webkit-transform: scale(2); /* Safari and Chrome */
 -o-transform: scale(2); /* Opera */
  padding: 10px;
}

Some projects cannot be imported because they already exist in the workspace error in Eclipse

I had the same error because there was one more project under svn in workspace but with another name. So I've removed it.

What are the valid Style Format Strings for a Reporting Services [SSRS] Expression?

You can check the schema at http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition/ReportDefinition.xsd

Search for xsd:complexType name="StyleType"

This will list out all the possible Styles you can use.

Specific to your question however, you can use the Format style.

Format

Specify the data format to use for values that appear in the textbox.

Valid values include Default, Number, Date, Time, Percentage, and Currency.

Link to MSDN: http://msdn.microsoft.com/en-us/library/ms251684(VS.80).aspx

convert '1' to '0001' in JavaScript

String.prototype.padZero= function(len, c){
    var s= this, c= c || '0';
    while(s.length< len) s= c+ s;
    return s;
}

dispite the name, you can left-pad with any character, including a space. I never had a use for right side padding, but that would be easy enough.

Finding duplicate rows in SQL Server

You can do it like this:

SELECT
    o.id, o.orgName, d.intCount
FROM (
     SELECT orgName, COUNT(*) as intCount
     FROM organizations
     GROUP BY orgName
     HAVING COUNT(*) > 1
) AS d
    INNER JOIN organizations o ON o.orgName = d.orgName

If you want to return just the records that can be deleted (leaving one of each), you can use:

SELECT
    id, orgName
FROM (
     SELECT 
         orgName, id,
         ROW_NUMBER() OVER (PARTITION BY orgName ORDER BY id) AS intRow
     FROM organizations
) AS d
WHERE intRow != 1

Edit: SQL Server 2000 doesn't have the ROW_NUMBER() function. Instead, you can use:

SELECT
    o.id, o.orgName, d.intCount
FROM (
     SELECT orgName, COUNT(*) as intCount, MIN(id) AS minId
     FROM organizations
     GROUP BY orgName
     HAVING COUNT(*) > 1
) AS d
    INNER JOIN organizations o ON o.orgName = d.orgName
WHERE d.minId != o.id

Change link color of the current page with CSS

include this! on your page where you want to change the colors save as .php

<?php include("includes/navbar.php"); ?>

then add a new file in an includes folder.

includes/navbar.php

<div <?php //Using REQUEST_URI

$currentpage = $_SERVER['REQUEST_URI'];

if(preg_match("/index/i", $currentpage)||($currentpage=="/"))
    echo " class=\"navbarorange/*the css class for your nav div*/\" ";
elseif(preg_match("/about/*or second page name*//i", $currentpage))
    echo " class=\"navbarpink\" ";
elseif(preg_match("/contact/* or edit 3rd page name*//i", $currentpage))
    echo " class=\"navbargreen\" ";?> >
</div>

Adding space/padding to a UILabel

SWIFT 4

Easy to use solution, available for all UILabel child in project.

Example:

let label = UILabel()
    label.<Do something>
    label.padding = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 0)

UILabel Extension

import UIKit

extension UILabel {
    private struct AssociatedKeys {
        static var padding = UIEdgeInsets()
    }

    public var padding: UIEdgeInsets? {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.padding) as? UIEdgeInsets
        }
        set {
            if let newValue = newValue {
                objc_setAssociatedObject(self, &AssociatedKeys.padding, newValue as UIEdgeInsets?, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
        }
    }

    override open func draw(_ rect: CGRect) {
        if let insets = padding {
            self.drawText(in: rect.inset(by: insets))
        } else {
            self.drawText(in: rect)
        }
    }

    override open var intrinsicContentSize: CGSize {
        guard let text = self.text else { return super.intrinsicContentSize }

        var contentSize = super.intrinsicContentSize
        var textWidth: CGFloat = frame.size.width
        var insetsHeight: CGFloat = 0.0
        var insetsWidth: CGFloat = 0.0

        if let insets = padding {
            insetsWidth += insets.left + insets.right
            insetsHeight += insets.top + insets.bottom
            textWidth -= insetsWidth
        }

        let newSize = text.boundingRect(with: CGSize(width: textWidth, height: CGFloat.greatestFiniteMagnitude),
                                        options: NSStringDrawingOptions.usesLineFragmentOrigin,
                                        attributes: [NSAttributedString.Key.font: self.font], context: nil)

        contentSize.height = ceil(newSize.size.height) + insetsHeight
        contentSize.width = ceil(newSize.size.width) + insetsWidth

        return contentSize
    }
}

PHP function use variable from outside

Just put in the function using GLOBAL keyword:

 global $site_url;

Pull all images from a specified directory and then display them

You need to change the loop from for ($i=1; $i<count($files); $i++) to for ($i=0; $i<count($files); $i++):

So the correct code is

<?php
$files = glob("images/*.*");

for ($i=0; $i<count($files); $i++) {
    $image = $files[$i];
    print $image ."<br />";
    echo '<img src="'.$image .'" alt="Random image" />'."<br /><br />";
}

?>

Python Timezone conversion

For Python 3.2+ simple-date is a wrapper around pytz that tries to simplify things.

If you have a time then

SimpleDate(time).convert(tz="...")

may do what you want. But timezones are quite complex things, so it can get significantly more complicated - see the the docs.

FormData.append("key", "value") is not working

You say it's not working. What are you expecting to happen?

There's no way of getting the data out of a FormData object; it's just intended for you to use to send data along with an XMLHttpRequest object (for the send method).

Update almost five years later: In some newer browsers, this is no longer true and you can now see the data provided to FormData in addition to just stuffing data into it. See the accepted answer for more info.

How to output MySQL query results in CSV format?

To expand on previous answers, the following one-liner exports a single table as a tab-separated file. It's suitable for automation, exporting the database every day or so.

mysql -B -D mydatabase -e 'select * from mytable'

Conveniently, we can use the same technique to list out MySQL's tables, and to describe the fields on a single table:

mysql -B -D mydatabase -e 'show tables'

mysql -B -D mydatabase -e 'desc users'

Field   Type    Null    Key Default Extra
id  int(11) NO  PRI NULL    auto_increment
email   varchar(128)    NO  UNI NULL    
lastName    varchar(100)    YES     NULL    
title   varchar(128)    YES UNI NULL    
userName    varchar(128)    YES UNI NULL    
firstName   varchar(100)    YES     NULL    

How do I combine two dataframes?

I believe you can use the append method

bigdata = data1.append(data2, ignore_index=True)

to keep their indexes just dont use the ignore_index keyword ...

How can I get double quotes into a string literal?

Thankfully, with C++11 there is also the more pleasing approach of using raw string literals.

printf("She said \"time flies like an arrow, but fruit flies like a banana\".");

Becomes:

printf(R"(She said "time flies like an arrow, but fruit flies like a banana".)");

With respect to the addition of brackets after the opening quote, and before the closing quote, note that they can be almost any combination of up to 16 characters, helping avoid the situation where the combination is present in the string itself. Specifically:

any member of the basic source character set except: space, the left parenthesis (, the right parenthesis ), the backslash , and the control characters representing horizontal tab, vertical tab, form feed, and newline" (N3936 §2.14.5 [lex.string] grammar) and "at most 16 characters" (§2.14.5/2)

How much clearer it makes this short strings might be debatable, but when used on longer formatted strings like HTML or JSON, it's unquestionably far clearer.

Why split the <script> tag when writing it with document.write()?

Here's another variation I've used when wanting to generate a script tag inline (so it executes immediately) without needing any form of escapes:

<script>
    var script = document.createElement('script');
    script.src = '/path/to/script.js';
    document.write(script.outerHTML);
</script>

(Note: contrary to most examples on the net, I'm not setting type="text/javascript" on neither the enclosing tag, nor the generated one: there is no browser not having that as the default, and so it is redundant, but will not hurt either, if you disagree).

What is the difference between <jsp:include page = ... > and <%@ include file = ... >?

In one reusable piece of code I use the directive <%@include file="reuse.html"%> and in the second I use the standard action <jsp:include page="reuse.html" />.

Let the code in the reusable file be:

<html>
<head>
    <title>reusable</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
    <img src="candle.gif" height="100" width="50"/> <br />
    <p><b>As the candle burns,so do I</b></p>
</body>

After running both the JSP files you see the same output and think if there was any difference between the directive and the action tag. But if you look at the generated servlet of the two JSP files, you will see the difference.

Here is what you will see when you use the directive:

out.write("<html>\r\n");
out.write("    <head>\r\n");
out.write("        <title>reusable</title>\r\n");
out.write("        <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n");
out.write("    </head>\r\n");
out.write("    <body>\r\n");
out.write("        <img src=\"candle.gif\" height=\"100\" width=\"50\"/> <br />\r\n");
out.write("        <p><b>As the candle burns,so do I</b></p>\r\n");
out.write("    </body>\r\n");
out.write("</html>\r\n");
 

And this is what you will see for the used standard action in the second JSP file :

org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "reusable.html", out, false);

So now you know that the include directive inserts the source of reuse.html at translation time, but the action tag inserts the response of reuse.html at runtime.

If you think about it, there is an extra performance hit with every action tag (<jsp:include>). It means you can guarantee you will always have the latest content, but it increases performance cost.

Is there a portable way to get the current username in Python?

If you are needing this to get user's home dir, below could be considered as portable (win32 and linux at least), part of a standard library.

>>> os.path.expanduser('~')
'C:\\Documents and Settings\\johnsmith'

Also you could parse such string to get only last path component (ie. user name).

See: os.path.expanduser

How to check a string for specific characters?

This will test if strings are made up of some combination or digits, the dollar sign, and a commas. Is that what you're looking for?

import re

s1 = 'Testing string'
s2 = '1234,12345$'

regex = re.compile('[0-9,$]+$')

if ( regex.match(s1) ):
   print "s1 matched"
else:
   print "s1 didn't match"

if ( regex.match(s2) ):
   print "s2 matched"
else:
   print "s2 didn't match"

Simulate limited bandwidth from within Chrome?

If you are running Linux, the following command is really useful for this:

trickle -s -d 50 -w 100 firefox

The -s tells the command to run standalone, the -d 50 tells it to limit bandwidth to 50 KB/s, the -w 100 set the peak detection window size to 100 KB. firefox tells the command to start firefox with all of this rate limiting applied to any sites it attempts to load.

Update

Chrome 38 is out now and includes throttling. To find it, bring up the Developer Tools: Ctrl+Shift+I does it on my machine, otherwise Menu->More Tools->Developer Tools will bring you there.

Then Toggle Device Mode by clicking the phone in the upper left of the Developer Tools Panel (see the tooltip below).

Toggle device mode

Then activate throttling like so.

Activate Chrome throttling

If you find this a bit clunky, my suggestion above works for both Chrome and Firefox.

SQL error "ORA-01722: invalid number"

Oracle does automatic String2number conversion, for String column values! However, for the textual comparisons in SQL, the input must be delimited as a String explicitly: The opposite conversion number2String is not performed automatically, not on the SQL-query level.

I had this query:

select max(acc_num) from ACCOUNTS where acc_num between 1001000 and 1001999;

That one presented a problem: Error: ORA-01722: invalid number

I have just surrounded the "numerical" values, to make them 'Strings', just making them explicitly delimited:

select max(acc_num) from ACCOUNTS where acc_num between '1001000' and '1001999';

...and voilà: It returns the expected result.

edit: And indeed: the col acc_num in my table is defined as String. Although not numerical, the invalid number was reported. And the explicit delimiting of the string-numbers resolved the problem.

On the other hand, Oracle can treat Strings as numbers. So the numerical operations/functions can be applied on the Strings, and these queries work:

select max(string_column) from TABLE;

select string_column from TABLE where string_column between '2' and 'z';

select string_column from TABLE where string_column > '1';

select string_column from TABLE where string_column <= 'b';

I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?

Converting to unix timestamps makes doing date math easier in php:

$startTime = strtotime( '2010-05-01 12:00' );
$endTime = strtotime( '2010-05-10 12:00' );

// Loop between timestamps, 24 hours at a time
for ( $i = $startTime; $i <= $endTime; $i = $i + 86400 ) {
  $thisDate = date( 'Y-m-d', $i ); // 2010-05-01, 2010-05-02, etc
}

When using PHP with a timezone having DST, make sure to add a time that is not 23:00, 00:00 or 1:00 to protect against days skipping or repeating.

Kendo grid date column not formatting

Try formatting the date in the kendo grid as:

columns.Bound(x => x.LastUpdateDate).ClientTemplate("#= kendo.toString(LastUpdateDate, \"MM/dd/yyyy hh:mm tt\") #");

CSS3 Spin Animation

For the guys who still search some cool and easy spinner, we have multiple exemples of spinner on fontawesome site : https://fontawesome.com/v4.7.0/examples/

You just have to inspect the spinner you want with your debugger and copy the css styles.

jQuery `.is(":visible")` not working in Chrome

A cross browser/version solution to determine whether an element is visible, is to add/remove a css class to the element on show/hide. The default(visible) state of the element could be for example like this:

<span id="span1" class="visible">Span text</span>

Then on hide, remove the class:

$("#span1").removeClass("visible").hide();

On show, add it again:

$("#span1").addClass("visible").show();

Then to determine whether the element is visible, use this:

if ($("#span1").hasClass("visible")) { // do something }

This also solves the performance implications, which may occur on heavy usage of the ":visible" selector, which are pointed in jQuery's documentation:

Using this selector heavily can have performance implications, as it may force the browser to re-render the page before it can determine visibility. Tracking the visibility of elements via other methods, using a class for example, can provide better performance.

Official jQuery API Documentation for ":visible" selector

How to navigate through textfields (Next / Done Buttons)

In Cocoa for Mac OS X, you have the next responder chain, where you can ask the text field what control should have focus next. This is what makes tabbing between text fields work. But since iOS devices do not have a keyboard, only touch, this concept has not survived the transition to Cocoa Touch.

This can be easily done anyway, with two assumptions:

  1. All "tabbable" UITextFields are on the same parent view.
  2. Their "tab-order" is defined by the tag property.

Assuming this you can override textFieldShouldReturn: as this:

-(BOOL)textFieldShouldReturn:(UITextField*)textField
{
  NSInteger nextTag = textField.tag + 1;
  // Try to find next responder
  UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
  if (nextResponder) {
    // Found next responder, so set it.
    [nextResponder becomeFirstResponder];
  } else {
    // Not found, so remove keyboard.
    [textField resignFirstResponder];
  }
  return NO; // We do not want UITextField to insert line-breaks.
}

Add some more code, and the assumptions can be ignored as well.

Swift 4.0

 func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    let nextTag = textField.tag + 1
    // Try to find next responder
    let nextResponder = textField.superview?.viewWithTag(nextTag) as UIResponder!

    if nextResponder != nil {
        // Found next responder, so set it
        nextResponder?.becomeFirstResponder()
    } else {
        // Not found, so remove keyboard
        textField.resignFirstResponder()
    }

    return false
}

If the superview of the text field will be a UITableViewCell then next responder will be

let nextResponder = textField.superview?.superview?.superview?.viewWithTag(nextTag) as UIResponder!

How to set a cookie to expire in 1 hour in Javascript?

You can write this in a more compact way:

var now = new Date();
now.setTime(now.getTime() + 1 * 3600 * 1000);
document.cookie = "name=value; expires=" + now.toUTCString() + "; path=/";

And for someone like me, who wasted an hour trying to figure out why the cookie with expiration is not set up (but without expiration can be set up) in Chrome, here is in answer:

For some strange reason Chrome team decided to ignore cookies from local pages. So if you do this on localhost, you will not be able to see your cookie in Chrome. So either upload it on the server or use another browser.

Can't get ScriptManager.RegisterStartupScript in WebControl nested in UpdatePanel to work

I try many things and finally found that the last parameter must be false and you must add <SCRIPT> tag to the java script :

string script = "< SCRIPT >alert('hello!');< /SCRIPT>";

ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), key, script, **false**);

How to download folder from putty using ssh client

You cannot use PuTTY to download the files, but you can use PSCP from the PuTTY developers to get the files or dump any directory that you want.

Please see the following link on how to download a file/folder: https://the.earth.li/~sgtatham/putty/0.60/htmldoc/Chapter5.html

Controlling a USB power supply (on/off) with Linux

The reason why folks post questions such as this is due to the dreaded- indeed "EVIL"- USB Auto-Suspend "feature".

Auto suspend winds-down the power to an "idle" USB device and unless the device's driver supports this feature correctly, the device can become uncontactable. So powering a USB port on/off is a symptom of the problem, not the problem in itself.

I'll show you how to GLOBALLY disable auto-suspend, negating the need to manually toggle the USB ports on & off:

Short Answer:

You do NOT need to edit "autosuspend_delay_ms" individually: USB autosuspend can be disabled globally and PERSISTENTLY using the following commands:

sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/&usbcore.autosuspend=-1 /' /etc/default/grub

update-grub

systemctl reboot

An Ubuntu 18.04 screen-grab follows at the end of the "Long Answer" illustrating how my results were achieved.

Long Answer:

It's true that the USB Power Management Kernel Documentation states autosuspend is to be deprecated and in in its' place "autosuspend_delay_ms" used to disable USB autosuspend:

"In 2.6.38 the "autosuspend" file will be deprecated
and replaced by the "autosuspend_delay_ms" file."

HOWEVER my testing reveals that setting usbcore.autosuspend=-1 in /etc/default/grub as below can be used as a GLOBAL toggle for USB autosuspend functionality- you do NOT need to edit individual "autosuspend_delay_ms" files.

The same document linked above states a value of "0" is ENABLED and a negative value is DISABLED:

power/autosuspend_delay_ms

    <snip> 0 means to autosuspend
    as soon as the device becomes idle, and negative
    values mean never to autosuspend.  You can write a
    number to the file to change the autosuspend
    idle-delay time.

In the annotated Ubuntu 18.04 screen-grab below illustrating how my results were achieved (and reproducible), please remark the default is "0" (enabled) in autosuspend_delay_ms.

Then note that after ONLY setting usbcore.autosuspend=-1 in Grub, these values are now negative (disabled) after reboot. This will save me the bother of editing individual values and can now script disabling USB autosuspend.

screengrab: autosuspend values Before and after globally editing

Hope this makes disabling USB autosuspend a little easier and more scriptable-

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

Your can use DataSourceBuilder for this purpose.

@Primary
@Bean(name = "dataSource")
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource(Environment env) {
    final String datasourceUsername = env.getRequiredProperty("spring.datasource.username");
    final String datasourcePassword = env.getRequiredProperty("spring.datasource.password");
    final String datasourceUrl = env.getRequiredProperty("spring.datasource.url");
    final String datasourceDriver = env.getRequiredProperty("spring.datasource.driver-class-name");
    return DataSourceBuilder
            .create()
            .username(datasourceUsername)
            .password(datasourcePassword)
            .url(datasourceUrl)
            .driverClassName(datasourceDriver)
            .build();
}

hibernate - get id after save object

By default, hibernate framework will immediately return id , when you are trying to save the entity using Save(entity) method. There is no need to do it explicitly.

In case your primary key is int you can use below code:

int id=(Integer) session.save(entity);

In case of string use below code:

String str=(String)session.save(entity);

Override browser form-filling and input highlighting with HTML/CSS

Add this CSS rule, and yellow background color will disapear. :)

input:-webkit-autofill {
    -webkit-box-shadow: 0 0 0px 1000px white inset;
}

How can I remove space (margin) above HTML header?

Try margin-top:

<header style="margin-top: -20px;">
    ...

Edit:

Now I found relative position probably a better choice:

<header style="position: relative; top: -20px;">
    ...

Import SQL file into mysql

In Windows OS the following commands works for me.

mysql>Use <DatabaseName>
mysql>SOURCE C:/data/ScriptFile.sql;

No single quotes or double quotes around file name. Path would contain '/' instead of '\'.

Convert String To date in PHP

Simple exploding should do the trick:

$monthNamesToInt = array('Jan'=>1,'Feb'=>2, 'Mar'=>3 /*, [...]*/ );
$datetime = '05/Feb/2010:14:00:01';
list($date,$hour,$minute,$second) = explode(':',$datetime);
list($day,$month,$year) = explode('/',$date);

$unixtime = mktime((int)$hour, (int)$minute, (int)$second, $monthNamesToInt[$month], (int)$day, (int)$year);

Default behavior of "git push" without a branch specified

You can push current branch with command

git push origin HEAD

(took from here)

Wrap text in <td> tag

use word-break it can be used without styling table to table-layout: fixed

_x000D_
_x000D_
table {_x000D_
  width: 140px;_x000D_
  border: 1px solid #bbb_x000D_
}_x000D_
_x000D_
.tdbreak {_x000D_
  word-break: break-all_x000D_
}
_x000D_
<p>without word-break</p>_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>LOOOOOOOOOOOOOOOOOOOOOOOOOOOOGGG</td>_x000D_
  </tr>_x000D_
</table>_x000D_
_x000D_
<p>with word-break</p>_x000D_
<table>_x000D_
  <tr>_x000D_
    <td class="tdbreak">LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOGGG</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

The maximum recursion 100 has been exhausted before statement completion

it is just a sample to avoid max recursion error. we have to use option (maxrecursion 365); or option (maxrecursion 0);

DECLARE @STARTDATE datetime; 
DECLARE @EntDt datetime; 
set @STARTDATE = '01/01/2009';  
set @EntDt = '12/31/2009'; 
declare @dcnt int; 
;with DateList as   
 (   
    select @STARTDATE DateValue   
    union all   
    select DateValue + 1 from    DateList      
    where   DateValue + 1 < convert(VARCHAR(15),@EntDt,101)   
 )   
  select count(*) as DayCnt from (   
  select DateValue,DATENAME(WEEKDAY, DateValue ) as WEEKDAY from DateList
  where DATENAME(WEEKDAY, DateValue ) not IN ( 'Saturday','Sunday' )     
  )a
option (maxrecursion 365);

Using C# to read/write Excel files (.xls/.xlsx)

You can use Excel Automation (it is basically a COM Base stuff) e.g:

Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;


xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open("1.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

Link to the full tutorial

How to generate Class Diagram (UML) on Android Studio (IntelliJ Idea)

There is Code Iris which you can install by going to File -> Settings -> Plugins -> Browse Repositories, then find and choose Code Iris. Restart then you will have a new Code Iris tab.

Handle file download from ajax post

Here is my solution, gathered from different sources: Server side implementation :

    String contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
    // Set headers
    response.setHeader("content-disposition", "attachment; filename =" + fileName);
    response.setContentType(contentType);
    // Copy file to output stream
    ServletOutputStream servletOutputStream = response.getOutputStream();
    try (InputStream inputStream = new FileInputStream(file)) {
        IOUtils.copy(inputStream, servletOutputStream);
    } finally {
        servletOutputStream.flush();
        Utils.closeQuitely(servletOutputStream);
        fileToDownload = null;
    }

Client side implementation (using jquery):

$.ajax({
type: 'POST',
contentType: 'application/json',
    url: <download file url>,
    data: JSON.stringify(postObject),
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert(errorThrown);
    },
    success: function(message, textStatus, response) {
       var header = response.getResponseHeader('Content-Disposition');
       var fileName = header.split("=")[1];
       var blob = new Blob([message]);
       var link = document.createElement('a');
       link.href = window.URL.createObjectURL(blob);
       link.download = fileName;
       link.click();
    }
});   

How can I shrink the drawable on a button?

Using Kotlin Extension

val drawable = ContextCompat.getDrawable(context, R.drawable.my_icon)
// or resources.getDrawable(R.drawable.my_icon, theme)
val sizePx = 25
drawable?.setBounds(0, 0, sizePx, sizePx)
//                            (left,     top,  right, bottom)
my_button.setCompoundDrawables(drawable, null, null, null)

I suggest creating an extension function on TextView (Button extends it) for easy reuse.

button.leftDrawable(R.drawable.my_icon, 25)

// Button extends TextView
fun TextView.leftDrawable(@DrawableRes id: Int = 0, @DimenRes sizeRes: Int) {
    val drawable = ContextCompat.getDrawable(context, id)
    val size = context.resources.getDimensionPixelSize(sizeRes)
    drawable?.setBounds(0, 0, size, size)
    this.setCompoundDrawables(drawable, null, null, null)
}

What is the best data type to use for money in C#?

Another option (especially if you're rolling you own class) is to use an int or a int64, and designate the lower four digits (or possibly even 2) as "right of the decimal point". So "on the edges" you'll need some "* 10000" on the way in and some "/ 10000" on the way out. This is the storage mechanism used by Microsoft's SQL Server, see http://msdn.microsoft.com/en-au/library/ms179882.aspx

The nicity of this is that all your summation can be done using (fast) integer arithmetic.

How to silence output in a Bash script?

If you want STDOUT and STDERR both [everything], then the simplest way is:

#!/bin/bash
myprogram >& sample.s

then run it like ./script, and you will get no output to your terminal. :)

the ">&" means STDERR and STDOUT. the & also works the same way with a pipe: ./script |& sed that will send everything to sed

"Use of undeclared type" in Swift, even though type is internal, and exists in same module

In XCode menu Product->Clean and then Product->Build worked for me. I encountered this issue when added new ViewController to my project in new Group/Folder.

Inserting an item in a Tuple

Since tuples are immutable, this will result in a new tuple. Just place it back where you got the old one.

sometuple + (someitem,)

How do you convert epoch time in C#?

In case you need to convert a timeval struct (seconds, microseconds) containing UNIX time to DateTime without losing precision, this is how:

DateTime _epochTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private DateTime UnixTimeToDateTime(Timeval unixTime)
{
    return _epochTime.AddTicks(
        unixTime.Seconds * TimeSpan.TicksPerSecond +
        unixTime.Microseconds * TimeSpan.TicksPerMillisecond/1000);
}

XMLHttpRequest status 0 (responseText is empty)

Add setRequestHeader("Access-Control-Allow-Origin","*") to your server response.

How can I have linebreaks in my long LaTeX equations?

Without configuring your math environment to clip, you could force a new line with two backslashes in a sequence like this:

Bla Bla \\ Bla Bla in another line

The problem with this is that you will need to determine where a line is likely to end and force to always have a line break there. With equations, rather than text, I prefer this manual way.

You could also use \\* to prevent a new page from being started.

Check for special characters (/*-+_@&$#%) in a string?

String test_string = "tesintg#$234524@#";
if (System.Text.RegularExpressions.Regex.IsMatch(test_string, "^[a-zA-Z0-9\x20]+$"))
{
  // Good-to-go
}

An example can be found here: http://ideone.com/B1HxA

Access an arbitrary element in a dictionary in Python

No external libraries, works on both Python 2.7 and 3.x:

>>> list(set({"a":1, "b": 2}.values()))[0]
1

For aribtrary key just leave out .values()

>>> list(set({"a":1, "b": 2}))[0]
'a'

How to programmatically empty browser cache?

use html itself.There is one trick that can be used.The trick is to append a parameter/string to the file name in the script tag and change it when you file changes.

<script src="myfile.js?version=1.0.0"></script>

The browser interprets the whole string as the file path even though what comes after the "?" are parameters. So wat happens now is that next time when you update your file just change the number in the script tag on your website (Example <script src="myfile.js?version=1.0.1"></script>) and each users browser will see the file has changed and grab a new copy.

Format y axis as percent

This is a few months late, but I have created PR#6251 with matplotlib to add a new PercentFormatter class. With this class you just need one line to reformat your axis (two if you count the import of matplotlib.ticker):

import ...
import matplotlib.ticker as mtick

ax = df['myvar'].plot(kind='bar')
ax.yaxis.set_major_formatter(mtick.PercentFormatter())

PercentFormatter() accepts three arguments, xmax, decimals, symbol. xmax allows you to set the value that corresponds to 100% on the axis. This is nice if you have data from 0.0 to 1.0 and you want to display it from 0% to 100%. Just do PercentFormatter(1.0).

The other two parameters allow you to set the number of digits after the decimal point and the symbol. They default to None and '%', respectively. decimals=None will automatically set the number of decimal points based on how much of the axes you are showing.

Update

PercentFormatter was introduced into Matplotlib proper in version 2.1.0.

How to get all of the immediate subdirectories in Python

I have to mention the path.py library, which I use very often.

Fetching the immediate subdirectories become as simple as that:

my_dir.dirs()

The full working example is:

from path import Path

my_directory = Path("path/to/my/directory")

subdirs = my_directory.dirs()

NB: my_directory still can be manipulated as a string, since Path is a subclass of string, but providing a bunch of useful methods for manipulating paths

Why does my sorting loop seem to append an element where it shouldn't?

" Hello " , " This " , "is ", "Sorting ", "Example"

First of all you provided spaces in " Hello " and " This ", spaces have a lower value than alphabetic characters in Unicode, so it gets printed first. (The rest of the characters were sorted alphabetically).

Now upper case letters have a lower value than lower case letter in Unicode, so "Example" and "Sorting" gets printed, then at last "is " which has the highest value.

C# Double - ToString() formatting with two decimal places but no rounding

The following rounds the numbers, but only shows up to 2 decimal places (removing any trailing zeros), thanks to .##.

decimal d0 = 24.154m;
decimal d1 = 24.155m;
decimal d2 = 24.1m;
decimal d3 = 24.0m;

d0.ToString("0.##");   //24.15
d1.ToString("0.##");   //24.16 (rounded up)
d2.ToString("0.##");   //24.1  
d3.ToString("0.##");   //24

http://dobrzanski.net/2009/05/14/c-decimaltostring-and-how-to-get-rid-of-trailing-zeros/

Changing iframe src with Javascript

change onselect to onchange in inputs and use

calendar.src = loc

_x000D_
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
_x000D_
<head>_x000D_
  <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />_x000D_
  <title>Untitled 1</title>_x000D_
_x000D_
  <script>_x000D_
  function go(loc) {_x000D_
    calendar.src = loc;_x000D_
  }_x000D_
  </script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <iframe id="calendar" src="about:blank" width="1000" height="450" frameborder="0" scrolling="no"></iframe>_x000D_
_x000D_
  <form method="post">_x000D_
    <input name="calendarSelection" type="radio" onchange="go('https://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Day_x000D_
    <input name="calendarSelection" type="radio" onchange="go('https://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Week_x000D_
    <input name="calendarSelection" type="radio" onchange="go('https://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Month_x000D_
  </form>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Child with max-height: 100% overflows parent

Maybe someone else can explain the reasons behind your problem but you can solve it by specifying the height of the container and then setting the height of the image to be 100%. It is important that the width of the image appears before the height.

<html>
    <head>
        <style>
            .container {  
                background: blue; 
                padding: 10px;
                height: 100%;
                max-height: 200px; 
                max-width: 300px; 
            }

            .container img {
                width: 100%;
                height: 100%
            }
        </style>
    </head>
    <body>
        <div class="container">
            <img src="http://placekitten.com/400/500" />
        </div>
    </body>
</html>

How do I get indices of N maximum values in a NumPy array?

Newer NumPy versions (1.8 and up) have a function called argpartition for this. To get the indices of the four largest elements, do

>>> a = np.array([9, 4, 4, 3, 3, 9, 0, 4, 6, 0])
>>> a
array([9, 4, 4, 3, 3, 9, 0, 4, 6, 0])
>>> ind = np.argpartition(a, -4)[-4:]
>>> ind
array([1, 5, 8, 0])
>>> a[ind]
array([4, 9, 6, 9])

Unlike argsort, this function runs in linear time in the worst case, but the returned indices are not sorted, as can be seen from the result of evaluating a[ind]. If you need that too, sort them afterwards:

>>> ind[np.argsort(a[ind])]
array([1, 8, 5, 0])

To get the top-k elements in sorted order in this way takes O(n + k log k) time.

Passing HTML input value as a JavaScript Function Parameter

do you use jquery? if then:

$('#xx').val();

or use original javascript(DOM)

document.getElementById('xx').value

or

xxxform.xx.value;

if you want to learn more, w3chool can help you a lot.

Loop through each cell in a range of cells when given a Range object

You could use Range.Rows, Range.Columns or Range.Cells. Each of these collections contain Range objects.

Here's how you could modify Dick's example so as to work with Rows:

Sub LoopRange()

    Dim rCell As Range
    Dim rRng As Range

    Set rRng = Sheet1.Range("A1:A6")

    For Each rCell In rRng.Rows
        Debug.Print rCell.Address, rCell.Value
    Next rCell

End Sub

And Columns:

Sub LoopRange()

    Dim rCell As Range
    Dim rRng As Range

    Set rRng = Sheet1.Range("A1:A6")

    For Each rCol In rRng.Columns
        For Each rCell In rCol.Rows
            Debug.Print rCell.Address, rCell.Value
        Next rCell
    Next rCol

End Sub

CSS text-align: center; is not centering things

To make a inline-block element align center horizontally in its parent, add text-align:center to its parent.

What is AF_INET, and why do I need it?

it defines the protocols address family.this determines the type of socket created. pocket pc support AF_INET.

the content in the following page is quite decent http://etutorials.org/Programming/Pocket+pc+network+programming/Chapter+1.+Winsock/Streaming+TCP+Sockets/

Align <div> elements side by side

_x000D_
_x000D_
.section {
  display: flex;
}

.element-left {
  width: 94%;
}

.element-right {
  flex-grow: 1;
}
_x000D_
<div class="section">
  <div id="dB" class="element-left" }>
    <a href="http://notareallink.com" title="Download" id="buyButton">Download</a>
  </div>
  <div id="gB" class="element-right">
    <a href="#" title="Gallery" onclick="$j('#galleryDiv').toggle('slow');return false;" id="galleryButton">Gallery</a>
  </div>
</div>
_x000D_
_x000D_
_x000D_

or

_x000D_
_x000D_
.section {
  display: flex;
  flex-wrap: wrap;
}

.element-left {
  flex: 2;
}

.element-right {
  width: 100px;
}
_x000D_
<div class="section">
  <div id="dB" class="element-left" }>
    <a href="http://notareallink.com" title="Download" id="buyButton">Download</a>
  </div>
  <div id="gB" class="element-right">
    <a href="#" title="Gallery" onclick="$j('#galleryDiv').toggle('slow');return false;" id="galleryButton">Gallery</a>
  </div>
</div>
_x000D_
_x000D_
_x000D_

Running a cron job on Linux every six hours

0 */6 * * *

crontab every 6 hours is a commonly used cron schedule.

Python Pandas: Get index of rows which column matches certain value

Can be done using numpy where() function:

import pandas as pd
import numpy as np

In [716]: df = pd.DataFrame({"gene_name": ['SLC45A1', 'NECAP2', 'CLIC4', 'ADC', 'AGBL4'] , "BoolCol": [False, True, False, True, True] },
       index=list("abcde"))

In [717]: df
Out[717]: 
  BoolCol gene_name
a   False   SLC45A1
b    True    NECAP2
c   False     CLIC4
d    True       ADC
e    True     AGBL4

In [718]: np.where(df["BoolCol"] == True)
Out[718]: (array([1, 3, 4]),)

In [719]: select_indices = list(np.where(df["BoolCol"] == True)[0])

In [720]: df.iloc[select_indices]
Out[720]: 
  BoolCol gene_name
b    True    NECAP2
d    True       ADC
e    True     AGBL4

Though you don't always need index for a match, but incase if you need:

In [796]: df.iloc[select_indices].index
Out[796]: Index([u'b', u'd', u'e'], dtype='object')

In [797]: df.iloc[select_indices].index.tolist()
Out[797]: ['b', 'd', 'e']

Wait until boolean value changes it state

Ok maybe this one should solve your problem. Note that each time you make a change you call the change() method that releases the wait.

Integer any = new Integer(0);

public synchronized boolean waitTillChange() {
    any.wait();
    return true;
}

public synchronized void change() {
    any.notify();
}

Cast object to interface in TypeScript

Here's another way to force a type-cast even between incompatible types and interfaces where TS compiler normally complains:

export function forceCast<T>(input: any): T {

  // ... do runtime checks here

  // @ts-ignore <-- forces TS compiler to compile this as-is
  return input;
}

Then you can use it to force cast objects to a certain type:

import { forceCast } from './forceCast';

const randomObject: any = {};
const typedObject = forceCast<IToDoDto>(randomObject);

Note that I left out the part you are supposed to do runtime checks before casting for the sake of reducing complexity. What I do in my project is compiling all my .d.ts interface files into JSON schemas and using ajv to validate in runtime.

Python 3 - ValueError: not enough values to unpack (expected 3, got 2)

You probably want to assign the lastname you are reading out here

lastname = sheet.cell(row=r, column=3).value

to something; currently the program just forgets it

you could do that two lines after, like so

unpaidMembers[name] = lastname, email

your program will still crash at the same place, because .items() still won't give you 3-tuples but rather something that has this structure: (name, (lastname, email))

good news is, python can handle this

for name, (lastname, email) in unpaidMembers.items():

etc.

Example of SOAP request authenticated with WS-UsernameToken

Check this one (Password should be password):

<wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="SecurityToken-6138db82-5a4c-4bf7-915f-af7a10d9ae96">
  <wsse:Username>user</wsse:Username>
  <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">CBb7a2itQDgxVkqYnFtggUxtuqk=</wsse:Password>
  <wsse:Nonce>5ABcqPZWb6ImI2E6tob8MQ==</wsse:Nonce>
  <wsu:Created>2010-06-08T07:26:50Z</wsu:Created>
</wsse:UsernameToken>

How to change cursor from pointer to finger using jQuery?

It is very straight forward

HTML

<input type="text" placeholder="some text" />
<input type="button" value="button" class="button"/>
<button class="button">Another button</button>

jQuery

$(document).ready(function(){
  $('.button').css( 'cursor', 'pointer' );

  // for old IE browsers
  $('.button').css( 'cursor', 'hand' ); 
});

Check it out on JSfiddle

Iframe positioning

Try adding the css style property

position:relative;

to the div tag , it works ,

How to run a function when the page is loaded?

As soon as the page load the function will be ran:

(*your function goes here*)(); 

Alternatively:

document.onload = functionName();
window.onload = functionName(); 

How can I check if a Perl module is installed on my system from the command line?

while (<@INC>)

This joins the paths in @INC together in a string, separated by spaces, then calls glob() on the string, which then iterates through the space-separated components (unless there are file-globbing meta-characters.)

This doesn't work so well if there are paths in @INC containing spaces, \, [], {}, *, ?, or ~, and there seems to be no reason to avoid the safe alternative:

for (@INC)

Use of REPLACE in SQL Query for newline/ carriage return characters

There are probably embedded tabs (CHAR(9)) etc. as well. You can find out what other characters you need to replace (we have no idea what your goal is) with something like this:

DECLARE @var NVARCHAR(255), @i INT;

SET @i = 1;

SELECT @var = AccountType FROM dbo.Account
  WHERE AccountNumber = 200
  AND AccountType LIKE '%Daily%';

CREATE TABLE #x(i INT PRIMARY KEY, c NCHAR(1), a NCHAR(1));

WHILE @i <= LEN(@var)
BEGIN
  INSERT #x 
    SELECT SUBSTRING(@var, @i, 1), ASCII(SUBSTRING(@var, @i, 1));

  SET @i = @i + 1;
END

SELECT i,c,a FROM #x ORDER BY i;

You might also consider doing better cleansing of this data before it gets into your database. Cleaning it every time you need to search or display is not the best approach.

Link to download apache http server for 64bit windows.

An unofficial 64-bit Windows build is available from Apache Lounge.

dll missing in JDBC

Friends I had the same problem because of the different bit version Make sure following point * Your jdk bit 64 or 32 * Your Path for sqljdbc_4.0\enu\auth\x64 or x86 this directory depend on your jdk bit * sqljdbc_auth.dll select this file based on your bit x64 or x86 and put this in system32 folder and it will works for me

indexOf Case Sensitive?

Yes, indexOf is case sensitive.

The best way to do case insensivity I have found is:

String original;
int idx = original.toLowerCase().indexOf(someStr.toLowerCase());

That will do a case insensitive indexOf().

How do we update URL or query strings using javascript/jQuery without reloading the page?

Use

window.history.replaceState({}, document.title, updatedUri);

To update Url without reloading the page

 var url = window.location.href;
 var urlParts = url.split('?');
 if (urlParts.length > 0) {
     var baseUrl = urlParts[0];
     var queryString = urlParts[1];

     //update queryString in here...I have added a new string at the end in this example
     var updatedQueryString = queryString + 'this_is_the_new_url' 

     var updatedUri = baseUrl + '?' + updatedQueryString;
     window.history.replaceState({}, document.title, updatedUri);
 }

To remove Query string without reloading the page

var url = window.location.href;
if (url.indexOf("?") > 0) {
     var updatedUri = url.substring(0, url.indexOf("?"));
     window.history.replaceState({}, document.title, updatedUri);
}

How to send parameters with jquery $.get()

Try this:

$.ajax({
    type: 'get',
    url: 'manageproducts.do',
    data: 'option=1',
    success: function(data) {

        availableProductNames = data.split(",");

        alert(availableProductNames);

    }
});

Also You have a few errors in your sample code, not sure if that was causing the error or it was just a typo upon entering the question.

Add default value of datetime field in SQL Server to a timestamp

This can also be done through the SSMS GUI.

  1. Put your table in design view (Right click on table in object explorer->Design)
  2. Add a column to the table (or click on the column you want to update if it already exists)
  3. In Column Properties, enter (getdate()) in Default Value or Binding field as pictured below

Image of table in design view

Select max value of each group

SELECT
  b.name,
  MAX(b.value) as MaxValue,
  MAX(b.Anothercolumn) as AnotherColumn
FROM out_pumptabl
INNER JOIN (SELECT 
              name,
              MAX(value) as MaxValue
            FROM out_pumptabl
            GROUP BY Name) a ON 
  a.name = b.name AND a.maxValue = b.value
GROUP BY b.Name

Note this would be far easier if you had a primary key. Here is an Example

SELECT * FROM out_pumptabl c
WHERE PK in 
    (SELECT
      MAX(PK) as MaxPK
    FROM out_pumptabl b
    INNER JOIN (SELECT 
                  name,
                  MAX(value) as MaxValue
                FROM out_pumptabl
                GROUP BY Name) a ON 
      a.name = b.name AND a.maxValue = b.value) 

How to use a global array in C#?

Your class shoud look something like this:

class Something {     int[] array; //global array, replace type of course     void function1() {        array = new int[10]; //let say you declare it here that will be 10 integers in size     }     void function2() {        array[0] = 12; //assing value at index 0 to 12.     } } 

That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.

Plot Normal distribution with Matplotlib

Assuming you're getting norm from scipy.stats, you probably just need to sort your list:

import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt

h = [186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
     187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
     161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180]
h.sort()
hmean = np.mean(h)
hstd = np.std(h)
pdf = stats.norm.pdf(h, hmean, hstd)
plt.plot(h, pdf) # including h here is crucial

And so I get: enter image description here

How to generate java classes from WSDL file

You can use the eclipse plugin as suggested by Oscar earlier. Or if you are a command line person, you can use Apache Axis WSDL2Java tool from command prompt. You can find more details here http://axis.apache.org/axis/java/reference.html#WSDL2JavaReference

Difference between a script and a program?

A framework or other similar schema will run/interpret a script to do a task. A program is compiled and run by a machine to do a task

Creating files in C++

use c methods FILE *fp =fopen("filename","mode"); fclose(fp); mode means a for appending r for reading ,w for writing

   / / using ofstream constructors.
      #include <iostream>
       #include <fstream>  
      std::string input="some text to write"
     std::ofstream outfile ("test.txt");

    outfile <<input << std::endl;

       outfile.close();

JavaScript string and number conversion

Simplest is when you want to make a integer a string do

var a,b, c;
a = 1;
b = a.toString(); // This will give you string

Now, from the variable b which is of type string we can get the integer

c = b *1; //This will give you integer value of number :-)

If you want to check above is a number. If you are not sure if b contains integer then you can use

if(isNaN(c*1)) {
  //NOt a number
}
else //number

What is the meaning of "Failed building wheel for X" in pip install?

(pip maintainer here!)

If the package is not a wheel, pip tries to build a wheel for it (via setup.py bdist_wheel). If that fails for any reason, you get the "Failed building wheel for pycparser" message and pip falls back to installing directly (via setup.py install).

Once we have a wheel, pip can install the wheel by unpacking it correctly. pip tries to install packages via wheels as often as it can. This is because of various advantages of using wheels (like faster installs, cache-able, not executing code again etc).


Your error message here is due to the wheel package being missing, which contains the logic required to build the wheels in setup.py bdist_wheel. (pip install wheel can fix that.)


The above is the legacy behavior that is currently the default; we'll switch to PEP 517 by default, sometime in the future, moving us to a standards-based process for this. We also have isolated builds for that so, you'd have wheel installed in those environments by default. :)

Create a custom event in Java

There are 3 different ways you may wish to set this up:

  1. Thrower inside of Catcher
  2. Catcher inside of Thrower
  3. Thrower and Catcher inside of another class in this example Test

THE WORKING GITHUB EXAMPLE I AM CITING Defaults to Option 3, to try the others simply uncomment the "Optional" code block of the class you want to be main, and set that class as the ${Main-Class} variable in the build.xml file:

4 Things needed on throwing side code:

import java.util.*;//import of java.util.event

//Declaration of the event's interface type, OR import of the interface,
//OR declared somewhere else in the package
interface ThrowListener {
    public void Catch();
}
/*_____________________________________________________________*/class Thrower {
//list of catchers & corresponding function to add/remove them in the list
    List<ThrowListener> listeners = new ArrayList<ThrowListener>();
    public void addThrowListener(ThrowListener toAdd){ listeners.add(toAdd); }
    //Set of functions that Throw Events.
        public void Throw(){ for (ThrowListener hl : listeners) hl.Catch();
            System.out.println("Something thrown");
        }
////Optional: 2 things to send events to a class that is a member of the current class
. . . go to github link to see this code . . .
}

2 Things needed in a class file to receive events from a class

/*_______________________________________________________________*/class Catcher
implements ThrowListener {//implement added to class
//Set of @Override functions that Catch Events
    @Override public void Catch() {
        System.out.println("I caught something!!");
    }
////Optional: 2 things to receive events from a class that is a member of the current class
. . . go to github link to see this code . . .
}

[Ljava.lang.Object; cannot be cast to

You need to add query.addEntity(SwitcherServiceSource.class) before calling the .list() on query.

Pandas DataFrame Groupby two columns and get counts

Inserting data into a pandas dataframe and providing column name.

import pandas as pd
df = pd.DataFrame([['A','C','A','B','C','A','B','B','A','A'], ['ONE','TWO','ONE','ONE','ONE','TWO','ONE','TWO','ONE','THREE']]).T
df.columns = [['Alphabet','Words']]
print(df)   #printing dataframe.

This is our printed data:

enter image description here

For making a group of dataframe in pandas and counter,
You need to provide one more column which counts the grouping, let's call that column as, "COUNTER" in dataframe.

Like this:

df['COUNTER'] =1       #initially, set that counter to 1.
group_data = df.groupby(['Alphabet','Words'])['COUNTER'].sum() #sum function
print(group_data)

OUTPUT:

enter image description here

Checking the form field values before submitting that page

While you have a return value in checkform, it isn't being used anywhere - try using onclick="return checkform()" instead.

You may want to considering replacing this method with onsubmit="return checkform()" in the form tag instead, though both will work for clicking the button.

What is the use of the JavaScript 'bind' method?

In addition to what have been said, the bind() method allows an object to borrow a method from another object without making a copy of that method. This is known as function borrowing in JavaScript.

Get selected value in dropdown list using JavaScript

The previous answers still leave room for improvement because of the possibilities, the intuitiveness of the code, and the use of id versus name. One can get a read-out of three data of a selected option -- its index number, its value and its text. This simple, cross-browser code does all three:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Demo GetSelectOptionData</title>
</head>
<body>
    <form name="demoForm">
        <select name="demoSelect" onchange="showData()">
            <option value="zilch">Select:</option>
            <option value="A">Option 1</option>
            <option value="B">Option 2</option>
            <option value="C">Option 3</option>
        </select>
    </form>

    <p id="firstP">&nbsp;</p>
    <p id="secondP">&nbsp;</p>
    <p id="thirdP">&nbsp;</p>

    <script>
    function showData() {
        var theSelect = demoForm.demoSelect;
        var firstP = document.getElementById('firstP');
        var secondP = document.getElementById('secondP');
        var thirdP = document.getElementById('thirdP');
        firstP.innerHTML = ('This option\'s index number is: ' + theSelect.selectedIndex + ' (Javascript index numbers start at 0)');
        secondP.innerHTML = ('Its value is: ' + theSelect[theSelect.selectedIndex].value);
        thirdP.innerHTML = ('Its text is: ' + theSelect[theSelect.selectedIndex].text);
    }
     </script>
</body>
</html>

Live demo: http://jsbin.com/jiwena/1/edit?html,output .

id should be used for make-up purposes. For functional form purposes, name is still valid, also in HTML5, and should still be used. Lastly, mind the use of square versus round brackets in certain places. As was explained before, only (older versions of) Internet Explorer will accept round ones in all places.

How can I pass a reference to a function, with parameters?

What you are after is called partial function application.

Don't be fooled by those that don't understand the subtle difference between that and currying, they are different.

Partial function application can be used to implement, but is not currying. Here is a quote from a blog post on the difference:

Where partial application takes a function and from it builds a function which takes fewer arguments, currying builds functions which take multiple arguments by composition of functions which each take a single argument.

This has already been answered, see this question for your answer: How can I pre-set arguments in JavaScript function call?

Example:

var fr = partial(f, 1, 2, 3);

// now, when you invoke fr() it will invoke f(1,2,3)
fr();

Again, see that question for the details.

How do I set a ViewModel on a window in XAML using DataContext property?

Try this instead.

<Window x:Class="BuildAssistantUI.BuildAssistantWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:VM="clr-namespace:BuildAssistantUI.ViewModels">
    <Window.DataContext>
        <VM:MainViewModel />
    </Window.DataContext>
</Window>

HTML Entity Decode

Like Robert K said, don't use jQuery.html().text() to decode html entities as it's unsafe because user input should never have access to the DOM. Read about XSS for why this is unsafe.

Instead try the Underscore.js utility-belt library which comes with escape and unescape methods:

_.escape(string)

Escapes a string for insertion into HTML, replacing &, <, >, ", `, and ' characters.

_.escape('Curly, Larry & Moe');
=> "Curly, Larry &amp; Moe"

_.unescape(string)

The opposite of escape, replaces &amp;, &lt;, &gt;, &quot;, &#96; and &#x27; with their unescaped counterparts.

_.unescape('Curly, Larry &amp; Moe');
=> "Curly, Larry & Moe"

To support decoding more characters, just copy the Underscore unescape method and add more characters to the map.

Combine GET and POST request methods in Spring

@RequestMapping(value = "/testonly", method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter,
        @RequestParam(required = false) String parameter1,
        @RequestParam(required = false) String parameter2, 
        BindingResult result, HttpServletRequest request) 
        throws ParseException {

    LONG CODE and SAME LONG CODE with a minor difference
}

if @RequestParam(required = true) then you must pass parameter1,parameter2

Use BindingResult and request them based on your conditions.

The Other way

@RequestMapping(value = "/books", method = RequestMethod.GET)
public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter,  
    two @RequestParam parameters, HttpServletRequest request) throws ParseException {

    myMethod();

}


@RequestMapping(value = "/books", method = RequestMethod.POST)
public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter, 
        BindingResult result) throws ParseException {

    myMethod();

    do here your minor difference
}

private returntype myMethod(){
    LONG CODE
}

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

if you try it in Inline, you wont succeed unless:

in your inline:

class AddInline(admin.TabularInline):
    readonly_fields = ['localname',]
    model = MyModel
    fields = ('localname',)

in your model (MyModel):

class MyModel(models.Model):
    localization = models.ForeignKey(Localizations)

    def localname(self):
        return self.localization.name

Why do I get "Exception; must be caught or declared to be thrown" when I try to compile my Java code?

The first error

java.lang.Exception; must be caught or declared to be thrown byte[] encrypted = encrypt(concatURL);

means that your encrypt method throws an exception that is not being handled or declared by the actionPerformed method where you are calling it. Read all about it at the Java Exceptions Tutorial.

You have a couple of choices that you can pick from to get the code to compile.

  • You can remove throws Exception from your encrypt method and actually handle the exception inside encrypt.
  • You can remove the try/catch block from encrypt and add throws Exception and the exception handling block to your actionPerformed method.

It's generally better to handle an exception at the lowest level that you can, instead of passing it up to a higher level.

The second error just means that you need to add a return statement to whichever method contains line 109 (also encrypt, in this case). There is a return statement in the method, but if an exception is thrown it might not be reached, so you either need to return in the catch block, or remove the try/catch from encrypt, as I mentioned before.

How to install and run Typescript locally in npm?

As of npm 5.2.0, once you've installed locally via

npm i typescript --save-dev

...you no longer need an entry in the scripts section of package.json -- you can now run the compiler with npx:

npx tsc

Now you don't have to update your package.json file every time you want to compile with different arguments.

Pretty git branch graphs

some aliases in ~/.oh-my-zsh/plugins/git/git.plugin.zsh

gke='\gitk --all $(git log -g --pretty=%h)'
glg='git log --stat'
glgg='git log --graph'
glgga='git log --graph --decorate --all'
glgm='git log --graph --max-count=10'
glgp='git log --stat -p'
glo='git log --oneline --decorate'
glog='git log --oneline --decorate --graph'
gloga='git log --oneline --decorate --graph --all'
glol='git log --graph --pretty='\''%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset'\'' --abbrev-commit'
glola='git log --graph --pretty='\''%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset'\'' --abbrev-commit --all'

View stored procedure/function definition in MySQL

If you want to know the list of procedures you can run the following command -

show procedure status;

It will give you the list of procedures and their definers Then you can run the show create procedure <procedurename>;

How do I register a DLL file on Windows 7 64-bit?

If the DLL is 32 bit:

  1. Copy the DLL to C:\Windows\SysWoW64\
  2. In elevated cmd: %windir%\SysWoW64\regsvr32.exe %windir%\SysWoW64\namedll.dll

if the DLL is 64 bit:

  1. Copy the DLL to C:\Windows\System32\
  2. In elevated cmd: %windir%\System32\regsvr32.exe %windir%\System32\namedll.dll

How to filter multiple values (OR operation) in angularJS

Lets assume you have two array, one for movie and one for genre

Just use the filter as: filter:{genres: genres.type}

Here genres being the array and type has value for genre

Using sendmail from bash script for multiple recipients

Use option -t for sendmail.

in your case - echo -e $mail | /usr/sbin/sendmail -t and add yout Recepient list to message itself like To: [email protected] [email protected] right after the line From:.....

-t option means - Read message for recipients. To:, Cc:, and Bcc: lines will be scanned for recipient addresses. The Bcc: line will be deleted before transmission.

String literals and escape characters in postgresql

Really stupid question: Are you sure the string is being truncated, and not just broken at the linebreak you specify (and possibly not showing in your interface)? Ie, do you expect the field to show as

This will be inserted \n This will not be

or

This will be inserted

This will not be

Also, what interface are you using? Is it possible that something along the way is eating your backslashes?

java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory

If you are facing java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory

Add slf4j-log4j12 jar in the library folder of the project

jQuery: How can I create a simple overlay?

Please check this jQuery plugin,

blockUI

with this you can overlay all the page or elements, works great for me,

Examples: Block a div: $('div.test').block({ message: null });

Block the page: $.blockUI({ message: '<h1><img src="busy.gif" /> Just a moment...</h1>' }); Hope that help someone

Greetings

In Perl, how can I read an entire file into a string?

All the posts are slightly non-idiomatic. The idiom is:

open my $fh, '<', $filename or die "error opening $filename: $!";
my $data = do { local $/; <$fh> };

Mostly, there is no need to set $/ to undef.

Calling Scalar-valued Functions in SQL

You are using an inline table value function. Therefore you must use Select * From function. If you want to use select function() you must use a scalar function.

https://msdn.microsoft.com/fr-fr/library/ms186755%28v=sql.120%29.aspx

Can regular expressions be used to match nested patterns?

Probably working Perl solution, if the string is on one line:

my $NesteD ;
$NesteD = qr/ \{( [^{}] | (??{ $NesteD }) )* \} /x ;

if ( $Stringy =~ m/\b( \w+$NesteD )/x ) {
    print "Found: $1\n" ;
  }

HTH

EDIT: check:

And one more thing by Torsten Marek (who had pointed out correctly, that it's not a regex anymore):

Exception : AAPT2 error: check logs for details

I fixed the ERROR with three steps
1. I checked for the problem SOURCE
2. Provided the correct string/text, because it was the CAUSE
3. I cleaned the project, you ll see it under BUILD.

enter image description here

Toggle show/hide on click with jQuery

You can use this code for toggle your element var ele = jQuery("yourelementid"); ele.slideToggle('slow'); this will work for you :)

SQL - HAVING vs. WHERE

First we should know the order of execution of Clauses i.e FROM > WHERE > GROUP BY > HAVING > DISTINCT > SELECT > ORDER BY. Since WHERE Clause gets executed before GROUP BY Clause the records cannot be filtered by applying WHERE to a GROUP BY applied records.

"HAVING is same as the WHERE clause but is applied on grouped records".

first the WHERE clause fetches the records based on the condition then the GROUP BY clause groups them accordingly and then the HAVING clause fetches the group records based on the having condition.

Calculate percentage Javascript

It seems working :

HTML :

 <input type='text' id="pointspossible"/>
<input type='text' id="pointsgiven" />
<input type='text' id="pointsperc" disabled/>

JavaScript :

    $(function(){

    $('#pointspossible').on('input', function() {
      calculate();
    });
    $('#pointsgiven').on('input', function() {
     calculate();
    });
    function calculate(){
        var pPos = parseInt($('#pointspossible').val()); 
        var pEarned = parseInt($('#pointsgiven').val());
        var perc="";
        if(isNaN(pPos) || isNaN(pEarned)){
            perc=" ";
           }else{
           perc = ((pEarned/pPos) * 100).toFixed(3);
           }

        $('#pointsperc').val(perc);
    }

});

Demo : http://jsfiddle.net/vikashvverma/1khs8sj7/1/

Return a "NULL" object if search result not found

As you have figured out that you cannot do it the way you have done in Java (or C#). Here is another suggestion, you could pass in the reference of the object as an argument and return bool value. If the result is found in your collection, you could assign it to the reference being passed and return ‘true’, otherwise return ‘false’. Please consider this code.

typedef std::map<string, Operator> OPERATORS_MAP;

bool OperatorList::tryGetOperator(string token, Operator& op)
{
    bool val = false;

    OPERATORS_MAP::iterator it = m_operators.find(token);
    if (it != m_operators.end())
    {
        op = it->second;
        val = true;
    }
    return val;
}

The function above has to find the Operator against the key 'token', if it finds the one it returns true and assign the value to parameter Operator& op.

The caller code for this routine looks like this

Operator opr;
if (OperatorList::tryGetOperator(strOperator, opr))
{
    //Do something here if true is returned.
}

Save byte array to file

You can use:

File.WriteAllBytes("Foo.txt", arrBytes); // Requires System.IO

If you have an enumerable and not an array, you can use:

File.WriteAllBytes("Foo.txt", arrBytes.ToArray()); // Requires System.Linq

How to change color and font on ListView

If you just need to change some parameters of the View and the default behavior of ArrayAdapter its OK for you:

 import android.content.Context;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.ArrayAdapter;

 public class CustomArrayAdapter<T> extends ArrayAdapter<T> {

    public CustomArrayAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);

            // Here all your customization on the View
            view.setBackgroundColor(.......);
            ...

        return view;
    }


 }

django MultiValueDictKeyError error, how do I deal with it

Choose what is best for you:

1

is_private = request.POST.get('is_private', False);

If is_private key is present in request.POST the is_private variable will be equal to it, if not, then it will be equal to False.

2

if 'is_private' in request.POST:
    is_private = request.POST['is_private']
else:
    is_private = False

3

from django.utils.datastructures import MultiValueDictKeyError
try:
    is_private = request.POST['is_private']
except MultiValueDictKeyError:
    is_private = False

Is it possible to set a timeout for an SQL query on Microsoft SQL server?

Humm! did you try LOCK_TIMEOUT
Note down what it was orginally before running the query
set it for your query
after running your query set it back to original value

SET LOCK_TIMEOUT 1800;  
SELECT @@LOCK_TIMEOUT AS [Lock Timeout];  

How to Pass Parameters to Activator.CreateInstance<T>()

public class AssemblyLoader<T>  where T:class
{
    public void(){
        var res = Load(@"C:\test\paquete.uno.dos.test.dll", "paquete.uno.dos.clasetest.dll") 
    }

    public T Load(string assemblyFile, string objectToInstantiate) 
    {
        var loaded = Activator.CreateInstanceFrom(assemblyFile, objectToInstantiate).Unwrap();

        return loaded as T;
    }
}

Django: TemplateSyntaxError: Could not parse the remainder

This error usually means you've forgotten a closing quote somewhere in the template you're trying to render. For example: {% url 'my_view %} (wrong) instead of {% url 'my_view' %} (correct). In this case it's the colon that's causing the problem. Normally you'd edit the template to use the correct {% url %} syntax.

But there's no reason why the django admin site would throw this, since it would know it's own syntax. My best guess is therefore that grapelli is causing your problem since it changes the admin templates. Does removing grappelli from installed apps help?

Adding an arbitrary line to a matplotlib plot in ipython notebook

Matplolib now allows for 'annotation lines' as the OP was seeking. The annotate() function allows several forms of connecting paths and a headless and tailess arrow, i.e., a simple line, is one of them.

ax.annotate("",
            xy=(0.2, 0.2), xycoords='data',
            xytext=(0.8, 0.8), textcoords='data',
            arrowprops=dict(arrowstyle="-",
                      connectionstyle="arc3, rad=0"),
            )

In the documentation it says you can draw only an arrow with an empty string as the first argument.

From the OP's example:

%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(5)
x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
plt.plot(x, y, "o")


# draw vertical line from (70,100) to (70, 250)
plt.annotate("",
              xy=(70, 100), xycoords='data',
              xytext=(70, 250), textcoords='data',
              arrowprops=dict(arrowstyle="-",
                              connectionstyle="arc3,rad=0."), 
              )

# draw diagonal line from (70, 90) to (90, 200)
plt.annotate("",
              xy=(70, 90), xycoords='data',
              xytext=(90, 200), textcoords='data',
              arrowprops=dict(arrowstyle="-",
                              connectionstyle="arc3,rad=0."), 
              )

plt.show()

Example inline image

Just as in the approach in gcalmettes's answer, you can choose the color, line width, line style, etc..

Here is an alteration to a portion of the code that would make one of the two example lines red, wider, and not 100% opaque.

# draw vertical line from (70,100) to (70, 250)
plt.annotate("",
              xy=(70, 100), xycoords='data',
              xytext=(70, 250), textcoords='data',
              arrowprops=dict(arrowstyle="-",
                              edgecolor = "red",
                              linewidth=5,
                              alpha=0.65,
                              connectionstyle="arc3,rad=0."), 
              )

You can also add curve to the connecting line by adjusting the connectionstyle.

Simple search MySQL database using php

If you do mysqli_fetch_array(), you must put integer in $row index ex.($row[3]).If you read $row['id'] or $row['example'], you must use mysqli_fetch_assoc.

How to get correlation of two vectors in python

The docs indicate that numpy.correlate is not what you are looking for:

numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
  Cross-correlation of two 1-dimensional sequences.
  This function computes the correlation as generally defined in signal processing texts:
     z[k] = sum_n a[n] * conj(v[n+k])
  with a and v sequences being zero-padded where necessary and conj being the conjugate.

Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:

from scipy.stats.stats import pearsonr   
a = [1,4,6]
b = [1,2,3]   
print pearsonr(a,b)

This gives

(0.99339926779878274, 0.073186395040328034)

You can also use numpy.corrcoef:

import numpy
print numpy.corrcoef(a,b)

This gives:

[[ 1.          0.99339927]
 [ 0.99339927  1.        ]]

Exception in thread "main" java.lang.UnsupportedClassVersionError: a (Unsupported major.minor version 51.0)

Assuming you are using Eclipse, on a MAC you can:

  1. Launch Eclipse.app
  2. Choose Eclipse -> Preferences
  3. Choose Java -> Installed JREs
  4. Click the Add... button
  5. Choose MacOS X VM as the JRE type. Press Next.
  6. In the "JRE Home:" field, type /Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home
  7. You should see the system libraries in the list titled "JRE system libraries:"
  8. Give the JRE a name. The recommended name is JDK 1.7. Click Finish.
  9. Check the checkbox next to the JRE entry you just created. This will cause Eclipse to use it as the default JRE for all new Java projects. Click OK.
  10. Now, create a new project. For this verification, from the menu, select File -> New -> Java Project.
  11. In the dialog that appears, enter a new name for your project. For this verification, type Test17Project
  12. In the JRE section of the dialog, select Use default JRE (currently JDK 1.7)
  13. Click Finish.

Hope this helps

How do I debug "Error: spawn ENOENT" on node.js?

I ran into the same problem, but I found a simple way to fix it. It appears to be spawn() errors if the program has been added to the PATH by the user (e.g. normal system commands work).

To fix this, you can use the which module (npm install --save which):

// Require which and child_process
const which = require('which');
const spawn = require('child_process').spawn;
// Find npm in PATH
const npm = which.sync('npm');
// Execute
const noErrorSpawn = spawn(npm, ['install']);

Xcode 7.2 no matching provisioning profiles found

Using Xcode 7.3, I spent way too much time trying to figure this out -- none of the answers here or elsewhere did the trick -- and ultimately stumbled into a ridiculously easy solution.

  1. In the Xcode preferences team settings, delete all provisioning profiles as mentioned in several other answers. I do this with right click, "Show in Finder," Command+A, delete -- it seems these details have changed over different Xcode versions.
  2. Do not re-download any profiles. Instead, exit your preferences and rebuild your project (I built it for my connected iPhone). A little while into the build sequence there will be an alert informing you no provisioning profiles were found, and it will ask if you want this to be fixed automatically. Choose to fix it automatically.
  3. After Xcode does some stuff, you will magically have a new provisioning profile providing what your app needs. I have since uploaded my app for TestFlight and it works great.

Hope this helps someone.

Background color not showing in print preview

FOR THOSE USING BOOTSTRAP.CSS, this is the fix!

I have tried all the solutions and they weren't working... until I discovered that bootstrap.css had a super annoying @media print that resets all your colors, background-colors, shadows, etc...

@media print{*,:after,:before{color:#000!important;text-shadow:none!important;background:0 0!important;-webkit-box-shadow:none!important;box-shadow:none!important}

So either remove this section from bootstrap.css (or bootstrap.min.css)

Or override these values in the css of the page you want to print in your own @media print

@media print {
  body { 
    -webkit-print-color-adjust: exact; 
  }
  .customClass{
     //customCss + !important;
  }
  //more of your custom css
}

How to create an integer-for-loop in Ruby?

Try Below Simple Ruby Magics :)

(1..x).each { |n| puts n }
x.times { |n| puts n }
1.upto(x) { |n| print n }

How to set session timeout in web.config

If it's not working from web.config, you need to set it from IIS.

Asus Zenfone 5 not detected by computer

Settings > Storage > Click the USB Icon at the upper right corner > Check your choice

What JSON library to use in Scala?

Rapture seems to be missing in the list of the answers. It can be obtained from http://rapture.io/ and allows you (among other thing) to:

  • select JSON back-end, which is very useful if you already use one (in import)
  • decide if you work with Try, Future, Option, Either, etc. (also in import)
  • do a lot of work in a single line of code.

I don't want to copy/paste Rapture examples from it's page. A nice presentation about Rapture's features was given by Jon Pretty at SBTB 2014: https://www.youtube.com/watch?v=ka5-OLJgybI

How to set the height of an input (text) field in CSS?

Don't use height property in input field.

Example:

.heighttext{
    display:inline-block;
    padding:15px 10px;
    line-height:140%;
}

Always use padding and line-height css property. Its work perfect for all mobile device and all browser.

How to read multiple text files into a single RDD?

You can use this

First You can get a Buffer/List of S3 Paths :

import scala.collection.JavaConverters._
import java.util.ArrayList
import com.amazonaws.services.s3.AmazonS3Client
import com.amazonaws.services.s3.model.ObjectListing
import com.amazonaws.services.s3.model.S3ObjectSummary
import com.amazonaws.services.s3.model.ListObjectsRequest

def listFiles(s3_bucket:String, base_prefix : String) = {
    var files = new ArrayList[String]

    //S3 Client and List Object Request
    var s3Client = new AmazonS3Client();
    var objectListing: ObjectListing = null;
    var listObjectsRequest = new ListObjectsRequest();

    //Your S3 Bucket
    listObjectsRequest.setBucketName(s3_bucket)

    //Your Folder path or Prefix
    listObjectsRequest.setPrefix(base_prefix)

    //Adding s3:// to the paths and adding to a list
    do {
      objectListing = s3Client.listObjects(listObjectsRequest);
      for (objectSummary <- objectListing.getObjectSummaries().asScala) {
        files.add("s3://" + s3_bucket + "/" + objectSummary.getKey());
      }
      listObjectsRequest.setMarker(objectListing.getNextMarker());
    } while (objectListing.isTruncated());

    //Removing Base Directory Name
    files.remove(0)

    //Creating a Scala List for same
    files.asScala
  }

Now Pass this List object to the following piece of code, note : sc is an object of SQLContext

var df: DataFrame = null;
  for (file <- files) {
    val fileDf= sc.textFile(file)
    if (df!= null) {
      df= df.unionAll(fileDf)
    } else {
      df= fileDf
    }
  }

Now you got a final Unified RDD i.e. df

Optional, And You can also repartition it in a single BigRDD

val files = sc.textFile(filename, 1).repartition(1)

Repartitioning always works :D

ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)

Maybe this is useful to anyone in the future, I have implemented a custom Authorize Attribute like this:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class ClaimAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
    private readonly string _claim;

    public ClaimAuthorizeAttribute(string Claim)
    {
        _claim = Claim;
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var user = context.HttpContext.User;
        if(user.Identity.IsAuthenticated && user.HasClaim(ClaimTypes.Name, _claim))
        {
            return;
        }

        context.Result = new ForbidResult();
    }
}

Insert Multiple Rows Into Temp Table With SQL Server 2012

When using SQLFiddle, make sure that the separator is set to GO. Also the schema build script is executed in a different connection from the run script, so a temp table created in the one is not visible in the other. This fiddle shows that your code is valid and working in SQL 2012:

SQL Fiddle

MS SQL Server 2012 Schema Setup:

Query 1:

CREATE TABLE #Names
  ( 
    Name1 VARCHAR(100),
    Name2 VARCHAR(100)
  ) 

INSERT INTO #Names
  (Name1, Name2)
VALUES
  ('Matt', 'Matthew'),
  ('Matt', 'Marshal'),
  ('Matt', 'Mattison')

SELECT * FROM #NAMES

Results:

| NAME1 |    NAME2 |
--------------------
|  Matt |  Matthew |
|  Matt |  Marshal |
|  Matt | Mattison |

Here a SSMS 2012 screenshot: enter image description here

S3 Static Website Hosting Route All Paths to Index.html

Just to put the extremely simple answer. Just use the hash location strategy for the router if you are hosting on S3.

export const AppRoutingModule: ModuleWithProviders = RouterModule.forRoot(routes, { useHash: true, scrollPositionRestoration: 'enabled' });

Getting values from query string in an url using AngularJS $location

Not sure if it has changed since the accepted answer was accepted, but it is possible.

$location.search() will return an object of key-value pairs, the same pairs as the query string. A key that has no value is just stored in the object as true. In this case, the object would be:

{"test_user_bLzgB": true}

You could access this value directly with $location.search().test_user_bLzgB

Example (with larger query string): http://fiddle.jshell.net/TheSharpieOne/yHv2p/4/show/?test_user_bLzgB&somethingElse&also&something=Somethingelse

Note: Due to hashes (as it will go to http://fiddle.jshell.net/#/url, which would create a new fiddle), this fiddle will not work in browsers that do not support js history (will not work in IE <10)

Edit:
As pointed out in the comments by @Naresh and @DavidTchepak, the $locationProvider also needs to be configured properly: https://code.angularjs.org/1.2.23/docs/guide/$location#-location-service-configuration

Can vue-router open a link in a new tab?

I think that you can do something like this:

let routeData = this.$router.resolve({name: 'routeName', query: {data: "someData"}});
window.open(routeData.href, '_blank');

It worked for me.

String to Binary in C#

Here you go:

public static byte[] ConvertToByteArray(string str, Encoding encoding)
{
    return encoding.GetBytes(str);
}

public static String ToBinary(Byte[] data)
{
    return string.Join(" ", data.Select(byt => Convert.ToString(byt, 2).PadLeft(8, '0')));
}

// Use any sort of encoding you like. 
var binaryString = ToBinary(ConvertToByteArray("Welcome, World!", Encoding.ASCII));

Delete column from SQLite table

Instead of dropping the backup table, just rename it...

BEGIN TRANSACTION;
CREATE TABLE t1_backup(a,b);
INSERT INTO t1_backup SELECT a,b FROM t1;
DROP TABLE t1;
ALTER TABLE t1_backup RENAME TO t1;
COMMIT;

Pip Install not installing into correct directory?

Virtualenv is your friend

Even if you want to add a package to your primary install, it's still best to do it in a virtual environment first, to ensure compatibility with your other packages. However, if you get familiar with virtualenv, you'll probably find there's really no reason to install anything in your base install.

How to parse month full form string using DateFormat in Java?

You are probably using a locale where the month names are not "January", "February", etc. but some other words in your local language.

Try specifying the locale you wish to use, for example Locale.US:

DateFormat fmt = new SimpleDateFormat("MMMM dd, yyyy", Locale.US);
Date d = fmt.parse("June 27,  2007");

Also, you have an extra space in the date string, but actually this has no effect on the result. It works either way.

Unfamiliar symbol in algorithm: what does ? mean?

yes, these are the well-known quantifiers used in math. Another example is ? which reads as "exists".

http://en.wikipedia.org/wiki/Quantification

Java: Check if enum contains a given string?

Use the Apache commons lang3 lib instead

 EnumUtils.isValidEnum(MyEnum.class, myValue)

Tomcat Servlet: Error 404 - The requested resource is not available

Writing Java servlets is easy if you use Java EE 7

@WebServlet("/hello-world")
public class HelloWorld extends HttpServlet {
  @Override
  public void doGet(HttpServletRequest request, 
                  HttpServletResponse response) {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   out.println("Hello World");
   out.flush();
  }
}

Since servlet 3.0

The good news is the deployment descriptor is no longer required!

Read the tutorial for Java Servlets.

How to get last inserted row ID from WordPress database?

Straight after the $wpdb->insert() that does the insert, do this:

$lastid = $wpdb->insert_id;

More information about how to do things the WordPress way can be found in the WordPress codex. The details above were found here on the wpdb class page

Change a Django form field to a hidden field

For normal form you can do

class MyModelForm(forms.ModelForm):
    slug = forms.CharField(widget=forms.HiddenInput())

If you have model form you can do the following

class MyModelForm(forms.ModelForm):
    class Meta:
        model = TagStatus
        fields = ('slug', 'ext')
        widgets = {'slug': forms.HiddenInput()}

You can also override __init__ method

class Myform(forms.Form):
    def __init__(self, *args, **kwargs):
        super(Myform, self).__init__(*args, **kwargs)
        self.fields['slug'].widget = forms.HiddenInput()

Keep overflow div scrolled to bottom unless user scrolls up

I couldn't get the top two answers to work, and none of the other answers were helpful to me. So I paid three people $30 from Reddit r/forhire and Upwork and got some really good answers. This answer should save you $90.



Justin Hundley / The Site Bros' solution

HTML

<div id="chatscreen">
  <div id="inner">
  
  </div>
</div>

CSS

#chatscreen {
  width: 300px;
  overflow-y: scroll;
  max-height:100px;
}

Javascript

$(function(){
    var scrolled = false;
  var lastScroll = 0;
  var count = 0;
    $("#chatscreen").on("scroll", function() {
    var nextScroll = $(this).scrollTop();

    if (nextScroll <= lastScroll) {
        scrolled = true;
    }
    lastScroll = nextScroll;
    
    console.log(nextScroll, $("#inner").height())
    if ((nextScroll + 100) == $("#inner").height()) {
        scrolled = false;
    }
  });
 
  function updateScroll(){
      if(!scrolled){
          var element = document.getElementById("chatscreen");
          var inner = document.getElementById("inner");
          element.scrollTop = inner.scrollHeight;
      }
  }

  // Now let's load our messages
  function load_messages(){
      $( "#inner" ).append( "Test" + count + "<br/>" );
      count = count + 1;
      updateScroll();
  }

    setInterval(load_messages,300); 
});

Preview the site bros' solution

portfolio



Lermex / Sviatoslav Chumakov's solution

HTML

<div id="chatscreen">

</div>

CSS

#chatscreen {
  height: 300px;
  border: 1px solid purple;
  overflow: scroll;
}

Javascript

$(function(){
var isScrolledToBottom = false;
// Now let's load our messages
function load_messages(){
    $( "#chatscreen" ).append( "<br>Test" );
    updateScr();
}

var out = document.getElementById("chatscreen");
var c = 0;

$("#chatscreen").on('scroll', function(){
        console.log(out.scrollHeight);
    isScrolledToBottom = out.scrollHeight - out.clientHeight <= out.scrollTop + 10;
});

function updateScr() {
        // allow 1px inaccuracy by adding 1
    //console.log(out.scrollHeight - out.clientHeight,  out.scrollTop + 1);
    var newElement = document.createElement("div");

    newElement.innerHTML = c++;
    out.appendChild(newElement);
    
    console.log(isScrolledToBottom);

    // scroll to bottom if isScrolledToBotto
    if(isScrolledToBottom) {out.scrollTop = out.scrollHeight - out.clientHeight; }
}

var add = setInterval(updateScr, 1000);

setInterval(load_messages,300); // change to 300 to show the latest message you sent after pressing enter // comment this line and it works, uncomment and it fails
                                // leaving it on 1000 shows the second to last message
setInterval(updateScroll,30);
});

Preview Sviatoslav's solution

portfolio



Igor Rusinov's Solution

HTML

<div id="chatscreen"></div>

CSS

#chatscreen {
  height: 100px;
  overflow: scroll;
  border: 1px solid #000;
}

Javascript

$(function(){

// Now let's load our messages
function load_messages(){
    $( "#chatscreen" ).append( "<br>Test" );
}

var out = document.getElementById("chatscreen");
var c = 0;
var add = setInterval(function() {
    // allow 1px inaccuracy by adding 1
    var isScrolledToBottom = out.scrollHeight - out.clientHeight <= out.scrollTop + 1;
    load_messages();

    // scroll to bottom if isScrolledToBotto
    if(isScrolledToBottom) {out.scrollTop = out.scrollHeight - out.clientHeight; }
}, 1000);
setInterval(updateScroll,30);
});

Preview Igor's solution

portfolio

Margin while printing html page

I also recommend pt versus cm or mm as it's more precise. Also, I cannot get @page to work in Chrome (version 30.0.1599.69 m) It ignores anything I put for the margins, large or small. But, you can get it to work with body margins on the document, weird.

What is the best IDE for PHP?

http://www.ibm.com/developerworks/opensource/library/os-php-ide/index.html

Personally, I love Notepad++... :D . The above link compares some of the better IDEs and the best ones aren't free.

I'd recommend Komodo 4.4 though (I used the trial version) since it was awesome. Better than Notepad++, but not free... :(

Razor/CSHTML - Any Benefit over what we have?

  1. Everything is encoded by default!!! This is pretty huge.

  2. Declarative helpers can be compiled so you don't need to do anything special to share them. I think they will replace .ascx controls to some extent. You have to jump through some hoops to use an .ascx control in another project.

  3. You can make a section required which is nice.

ImportError: No Module named simplejson

@noskio is correct... it just means that simplejson isn't found on your system and you need to install it for Python older than 2.6. one way is to use the setuptools easy_install tool. with it, you can install it as easily as: easy_install simplejson

UPDATE (Feb 2014): this is probably old news to many of you, but pip is a more modern tool that works in a similar way (i.e., pip install simplejson), only it can also uninstall apps.

Background image jumps when address bar hides iOS/Android/Mobile Chrome

I am using this workaround: Fix bg1's height on page load by:

var BG = document.getElementById('bg1');
BG.style.height = BG.parentElement.clientHeight;

Then attach a resize event listener to Window which does this: if difference in height after resizing is less than 60px (anything more than url bar height) then do nothing and if it is greater than 60px then set bg1's height again to its parent's height! complete code:

window.addEventListener("resize", onResize, false);
var BG = document.getElementById('bg1');
BG.style.height = BG.parentElement.clientHeight;
var oldH = BG.parentElement.clientHeight;

function onResize() {
    if(Math.abs(oldH - BG.parentElement.clientHeight) > 60){
      BG.style.height = BG.parentElement.clientHeight + 'px';
      oldH = BG.parentElement.clientHeight;
    }
}

PS: This bug is so irritating!

Commit only part of a file in Git

Adding on a previous answer, if you prefer using the command line, entering git add -e myfile gives you the choice to choose line by line what you want to commit because this command will open an editor with the differences, like so:

enter image description here

As you may known lines that start with + are addtions, lines that start with - are deletions. So:

  • To not stage an addition just delete that line.
  • To not stage a deletion just replace - with space .

This is what git add -h says about adding files this way (patching files):

added content Added content is represented by lines beginning with "+". You can prevent staging any addition lines by deleting them.

removed content: Removed content is represented by lines beginning with "-". You can prevent staging their removal by converting the "-" to a " " (space).

modified content: Modified content is represented by "-" lines (removing the old content) followed by "+" lines (adding the replacement content). You can prevent staging the modification by converting "-" lines to " ", and removing "+" lines. Beware that modifying only half of the pair is likely to introduce confusing changes to the index.

Caution: do not change the content of the file, this is not a good place to do so. Just change the operators of deleted or added lines.

Java: JSON -> Protobuf & back conversion

Adding to Ophirs answer, JsonFormat is available even before protobuf 3.0. However, the way to do it differs a little bit.

In Protobuf 3.0+, the JsonFormat class is a singleton and therefore do something like the below

String jsonString = "";
JsonFormat.parser().ignoringUnknownFields().merge(jsonString,yourObjectBuilder);

In Protobuf 2.5+, the below should work

String jsonString = "";
JsonFormat jsonFormat = new JsonFormat();
jsonString = jsonFormat.printToString(yourProtobufMessage);

Here is a link to a tutorial I wrote that uses the JsonFormat class in a TypeAdapter that can be registered to a GsonBuilder object. You can then use Gson's toJson and fromJson methods to convert the proto data to Java and back.

Replying to jean . If we have the protobuf data in a file and want to parse it into a protobuf message object, use the merge method TextFormat class. See the below snippet:

// Let your proto text data be in a file MessageDataAsProto.prototxt
// Read it into string  
String protoDataAsString = FileUtils.readFileToString(new File("MessageDataAsProto.prototxt"));

// Create an object of the message builder
MyMessage.Builder myMsgBuilder = MyMessage.newBuilder();

// Use text format to parse the data into the message builder
TextFormat.merge(protoDataAsString, ExtensionRegistry.getEmptyRegistry(), myMsgBuilder);

// Build the message and return
return myMsgBuilder.build();

How to check if a string starts with one of several prefixes?

When you say you tried to use OR, how exactly did you try and use it? In your case, what you will need to do would be something like so:

String newStr4 = strr.split("2012")[0];
if(newStr4.startsWith("Mon") || newStr4.startsWith("Tues")...)
str4.add(newStr4);

Should I use <i> tag for icons instead of <span>?

I'm jumping in here a little late, but came across this page when pondering it myself. Of course I don't know how Facebook or Twitter justified it, but here is my own thought process for what it's worth.

In the end, I concluded that this practice is not that unsemantic (is that a word?). In fact, besides shortness and the nice association of "i is for icon," I think it's actually the most semantic choice for an icon when a straightforward <img> tag is not practical.

1. The usage is consistent with the spec.

While it may not be what the W3 mainly had in mind, it seems to me the official spec for <i> could accommodate an icon pretty easily. After all, the reply-arrow symbol is saying "reply" in another way. It expresses a technical term that may be unfamiliar to the reader and would be typically italicized. ("Here at Twitter, this is what we call a reply arrow.") And it is a term from another language: a symbolic language.

If, instead of the arrow symbol, Twitter used <i>shout out</i> or <i>[Japanese character for reply]</i> (on an English page), that would be consistent with the spec. Then why not <i>[reply arrow]</i>? (I'm talking strictly HTML semantics here, not accessibility, which I'll get to.)

As far as I can see, the only part of the spec explicitly violated by icon usage is the "span of text" phrase (when the tag doesn't contain text also). It is clear that the <i> tag is mainly meant for text, but that's a pretty small detail compared with the overall intent of the tag. The important question for this tag is not what format of content it contains, but what the meaning of that content is.

This is especially true when you consider that the line between "text" and "icon" can be almost nonexistent on websites. Text may look like more like an icon (as in the Japanese example) or an icon may look like text (as in a jpg button that says "Submit" or a cat photo with an overlaid caption) or text may be replaced or enhanced with an image via CSS. Text, image - who cares? It's all content. As long as everyone - humans with impairments, browsers with impairments, search engine spiders, and other machines of various kinds can understand that meaning, we've done our job.

So the fact that the writers of the spec didn't think (or choose) to clarify this shouldn't tie our hands from doing what makes sense and is consistent with the spirit of the tag. The <a> tag was originally intended to take the user somewhere else, but now it might pop up a lightbox. Big whoop, right? If someone had figured out how to pop up a lightbox on click before the spec caught up, they still should have used the <a> tag, not a <span>, even if it wasn't entirely consistent with the current definition - because it came the closest and was still consistent with the spirit of the tag ("something will happen when you click here"). Same deal with <i> - whatever type of thing you put inside it, or however creatively you use it, it expresses the general idea of an alternate or set-apart term.

2. The <i> tag adds semantic meaning to an icon element.

The alternative option to carry an icon class by itself is <span>, which of course has no semantic meaning whatsoever. When a machine asks the <span> what it contains, it says, "I don't know. Could be anything." But the <i> tag says, "I contain a different way of saying something than the usual way, or maybe an unfamiliar term." That's not the same as "I contain an icon," but it's a lot closer to it than <span> got!

3. Eventually, common usage makes right.

In addition to the above, it's worth considering that machine readers (whether search engine, screen reader, or whatever) may at any time begin to take into account that Facebook, Twitter, and other websites use the <i> tag for icons. They don't care about the spec as much as they care about extracting meaning from code by whatever means necessary. So they might use this knowledge of common usage to simply record that "there may be an icon here" or do something more advanced like triggering a look into the CSS for a hint to meaning, or who knows what. So if you choose to use the <i> for icons on your website, you may be providing more meaning than the spec does.

Moreover, if this usage becomes widespread, it will likely be included in the spec in the future. Then you'll be going through your code, replacing <span>s with <i>'s! So it may make sense to get on board with what seems to be the direction of the spec, especially when it doesn't clearly conflict with the current spec. Common usage tends to dictate language rules more than the other way around. If you're old enough, do you remember that "Web site" was the official spelling when the word was new? Dictionaries insisted there must be a space and Web must be capitalized. There were semantic reasons for that. But common usage said, "Whatever, that's stupid. I'm using 'website' because it's more concise and looks better." And before long, dictionaries officially acknowledged that spelling as correct.

4. So I'm going ahead and using it.

So, <i> provides more meaning to machines because of the spec, it provides more meaning to humans because we easily associate "i" with "icon", and it's only one letter long. Win! And if you make sure to include equivalent text either inside the <i> tag or right next to it (as Twitter does), then screen readers understand where to click to reply, the link is usable if CSS doesn't load, and human readers with good eyesight and a decent browser see a pretty icon. With all this in mind, I don't see the downside.

Select rows with same id but different value in another column

This is an old question yet I find that I also need a solution for this from time to time. The previous answers are all good and works well, I just personally prefer using CTE, for example:

DECLARE @T TABLE (ARIDNR INT, LIEFNR varchar(5)) --table variable for loading sample data
INSERT INTO @T (ARIDNR, LIEFNR) VALUES (1,'A'),(2,'A'),(3,'A'),(1,'B'),(2,'B'); --add your sample data to it
WITH duplicates AS --the CTE portion to find the duplicates
(
    SELECT ARIDNR FROM @T GROUP BY ARIDNR HAVING COUNT(*) > 1
)
SELECT t.* FROM @T t --shows results from main table
INNER JOIN duplicates d on t.ARIDNR = d.ARIDNR --where the main table can be joined to the duplicates CTE

Yields the following results:

1|A
1|B
2|B
2|A

Vuex - passing multiple parameters to mutation

i think this can be as simple let as assume that you are going to pass multiple parameters to you action as you read up there actions accept only two parameters context and payload which is your data you want to pass in action so let take an example

Setting up Action

instead of

actions: {
        authenticate: ({ commit }, token, expiration) => commit('authenticate', token, expiration)
    }

do

actions: {
        authenticate: ({ commit }, {token, expiration}) => commit('authenticate', token, expiration)
    }

Calling (dispatching) Action

instead of

this.$store.dispatch({
                  type: 'authenticate',
                  token: response.body.access_token,
                  expiration: response.body.expires_in + Date.now()
              })

do

this.$store.dispatch('authenticate',{
                  token: response.body.access_token,
                  expiration: response.body.expires_in + Date.now()
              })

hope this gonna help

Delete/Reset all entries in Core Data?

Delete the persistent store file and setup a new persistent store coordinator?

How to customize a Spinner in Android

This worked for me :

ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),R.layout.simple_spinner_item,areas);
            Spinner areasSpinner = (Spinner) view.findViewById(R.id.area_spinner);
            areasSpinner.setAdapter(adapter);

and in my layout folder I created simple_spinner_item:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
// add custom fields here 
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
android:paddingStart="?android:attr/listPreferredItemPaddingStart"
android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:paddingLeft="?android:attr/listPreferredItemPaddingLeft"
android:paddingRight="?android:attr/listPreferredItemPaddingRight" />

error TS2339: Property 'x' does not exist on type 'Y'

The correct fix is to add the property in the type definition as explained by @Nitzan Tomer. But also you can just define property as any, if you want to write code almost as in JavaScript:

arr.filter((item:any) => {
    return item.isSelected == true;
}

How do I install cygwin components from the command line?

For a more convenient installer, you may want to use apt-cyg as your package manager. Its syntax similar to apt-get, which is a plus. For this, follow the above steps and then use Cygwin Bash for the following steps

wget https://raw.githubusercontent.com/transcode-open/apt-cyg/master/apt-cyg
chmod +x apt-cyg
mv apt-cyg /usr/local/bin

Now that apt-cyg is installed. Here are few examples of installing some packages

apt-cyg install nano
apt-cyg install git
apt-cyg install ca-certificates

Using Sockets to send and receive data

    //Client

    import java.io.*;
    import java.net.*;

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

        String hostname = "localhost";
        int port = 6789;

        // declaration section:
        // clientSocket: our client socket
        // os: output stream
        // is: input stream

            Socket clientSocket = null;  
            DataOutputStream os = null;
            BufferedReader is = null;

        // Initialization section:
        // Try to open a socket on the given port
        // Try to open input and output streams

            try {
                clientSocket = new Socket(hostname, port);
                os = new DataOutputStream(clientSocket.getOutputStream());
                is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            } catch (UnknownHostException e) {
                System.err.println("Don't know about host: " + hostname);
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to: " + hostname);
            }

        // If everything has been initialized then we want to write some data
        // to the socket we have opened a connection to on the given port

        if (clientSocket == null || os == null || is == null) {
            System.err.println( "Something is wrong. One variable is null." );
            return;
        }

        try {
            while ( true ) {
            System.out.print( "Enter an integer (0 to stop connection, -1 to stop server): " );
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String keyboardInput = br.readLine();
            os.writeBytes( keyboardInput + "\n" );

            int n = Integer.parseInt( keyboardInput );
            if ( n == 0 || n == -1 ) {
                break;
            }

            String responseLine = is.readLine();
            System.out.println("Server returns its square as: " + responseLine);
            }

            // clean up:
            // close the output stream
            // close the input stream
            // close the socket

            os.close();
            is.close();
            clientSocket.close();   
        } catch (UnknownHostException e) {
            System.err.println("Trying to connect to unknown host: " + e);
        } catch (IOException e) {
            System.err.println("IOException:  " + e);
        }
        }           
    }





//Server




import java.io.*;
import java.net.*;

public class Server1 {
    public static void main(String args[]) {
    int port = 6789;
    Server1 server = new Server1( port );
    server.startServer();
    }

    // declare a server socket and a client socket for the server

    ServerSocket echoServer = null;
    Socket clientSocket = null;
    int port;

    public Server1( int port ) {
    this.port = port;
    }

    public void stopServer() {
    System.out.println( "Server cleaning up." );
    System.exit(0);
    }

    public void startServer() {
    // Try to open a server socket on the given port
    // Note that we can't choose a port less than 1024 if we are not
    // privileged users (root)

        try {
        echoServer = new ServerSocket(port);
        }
        catch (IOException e) {
        System.out.println(e);
        }   

    System.out.println( "Waiting for connections. Only one connection is allowed." );

    // Create a socket object from the ServerSocket to listen and accept connections.
    // Use Server1Connection to process the connection.

    while ( true ) {
        try {
        clientSocket = echoServer.accept();
        Server1Connection oneconnection = new Server1Connection(clientSocket, this);
        oneconnection.run();
        }   
        catch (IOException e) {
        System.out.println(e);
        }
    }
    }
}

class Server1Connection {
    BufferedReader is;
    PrintStream os;
    Socket clientSocket;
    Server1 server;

    public Server1Connection(Socket clientSocket, Server1 server) {
    this.clientSocket = clientSocket;
    this.server = server;
    System.out.println( "Connection established with: " + clientSocket );
    try {
        is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        os = new PrintStream(clientSocket.getOutputStream());
    } catch (IOException e) {
        System.out.println(e);
    }
    }

    public void run() {
        String line;
    try {
        boolean serverStop = false;

            while (true) {
                line = is.readLine();
        System.out.println( "Received " + line );
                int n = Integer.parseInt(line);
        if ( n == -1 ) {
            serverStop = true;
            break;
        }
        if ( n == 0 ) break;
                os.println("" + n*n ); 
            }

        System.out.println( "Connection closed." );
            is.close();
            os.close();
            clientSocket.close();

        if ( serverStop ) server.stopServer();
    } catch (IOException e) {
        System.out.println(e);
    }
    }
}

What is the difference between supervised learning and unsupervised learning?

I'll try to keep it simple.

Supervised Learning: In this technique of learning, we are given a data set and the system already knows the correct output of the data set. So here, our system learns by predicting a value of its own. Then, it does an accuracy check by using a cost function to check how close its prediction was to the actual output.

Unsupervised Learning: In this approach, we have little or no knowledge of what our result would be. So instead, we derive structure from the data where we don't know effect of variable. We make structure by clustering the data based on relationship among the variable in data. Here, we don't have a feedback based on our prediction.

SQL LEFT-JOIN on 2 fields for MySQL

select a.ip, a.os, a.hostname, a.port, a.protocol,
       b.state
from a
left join b on a.ip = b.ip 
           and a.port = b.port