Programs & Examples On #Rubular

SQL - How to find the highest number in a column?

If you are using AUTOINCREMENT, use:

SELECT LAST\_INSERT\_ID();

Assumming that you are using Mysql: http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

Postgres handles this similarly via the currval(sequence_name) function.

Note that using MAX(ID) is not safe, unless you lock the table, since it's possible (in a simplified case) to have another insert that occurs before you call MAX(ID) and you lose the id of the first insert. The functions above are session based so if another session inserts you still get the ID that you inserted.

How do I simulate a low bandwidth, high latency environment?

i think i found what i need. maybe you can use charles proxy or slowy. hope it helps.

String comparison using '==' vs. 'strcmp()'

You should never use == for string comparison. === is OK.

$something = 0;
echo ('password123' == $something) ? 'true' : 'false';

Just run the above code and you'll see why.

$something = 0;
echo ('password123' === $something) ? 'true' : 'false';

Now, that's a little better.

How do you redirect HTTPS to HTTP?

For those that are using a .conf file.

<VirtualHost *:443>
    ServerName domain.com
    RewriteEngine On
    RewriteCond %{HTTPS} on
    RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}

    SSLEngine on
    SSLCertificateFile /etc/apache2/ssl/domain.crt
    SSLCertificateKeyFile /etc/apache2/ssl/domain.key
    SSLCACertificateFile /etc/apache2/ssl/domain.crt

</VirtualHost>

Checking whether a string starts with XXXX

Can also be done this way..

regex=re.compile('^hello')

## THIS WAY YOU CAN CHECK FOR MULTIPLE STRINGS
## LIKE
## regex=re.compile('^hello|^john|^world')

if re.match(regex, somestring):
    print("Yes")

unknown type name 'uint8_t', MinGW

EDIT:

To Be Clear: If the order of your #includes matters and it is not part of your design pattern (read: you don't know why), then you need to rethink your design. Most likely, this just means you need to add the #include to the header file causing problems.

At this point, I have little interest in discussing/defending the merits of the example but will leave it up as it illustrates some nuances in the compilation process and why they result in errors.

END EDIT

You need to #include the stdint.h BEFORE you #include any other library interfaces that need it.

Example:

My LCD library uses uint8_t types. I wrote my library with an interface (Display.h) and an implementation (Display.c)

In display.c, I have the following includes.

#include <stdint.h>
#include <string.h>
#include <avr/io.h>
#include <Display.h>
#include <GlobalTime.h>

And this works.

However, if I re-arrange them like so:

#include <string.h>
#include <avr/io.h>
#include <Display.h>
#include <GlobalTime.h>
#include <stdint.h>

I get the error you describe. This is because Display.h needs things from stdint.h but can't access it because that information is compiled AFTER Display.h is compiled.

So move stdint.h above any library that need it and you shouldn't get the error anymore.

Jersey stopped working with InjectionManagerFactory not found

The only way I could solve it was via:

org.glassfish.jersey.core jersey-server ${jersey-2-version}

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet</artifactId>
    <version>${jersey-2-version}</version>
</dependency>

<dependency>
    <groupId>org.glassfish.jersey.inject</groupId>
    <artifactId>jersey-hk2</artifactId>
    <version>${jersey-2-version}</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-common -->
<dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-common</artifactId>
    <version>${jersey-2-version}</version>
</dependency>

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet-core</artifactId>
    <version>${jersey-2-version}</version>
</dependency>

So, only if I added jersey-container-servlet and jersey-hk2 would it run without errors

how to update the multiple rows at a time using linq to sql?

This is what I did:

EF:

using (var context = new SomeDBContext())
{
    foreach (var item in model.ShopItems)  // ShopItems is a posted list with values 
    {    
        var feature = context.Shop
                             .Where(h => h.ShopID == 123 && h.Type == item.Type).ToList();

        feature.ForEach(a => a.SortOrder = item.SortOrder);
    }

    context.SaveChanges();
}

Hope helps someone.

Function for C++ struct

Structs can have functions just like classes. The only difference is that they are public by default:

struct A {
    void f() {}
};

Additionally, structs can also have constructors and destructors.

struct A {
    A() : x(5) {}
    ~A() {}

    private: int x;
};

plot different color for different categorical levels using matplotlib

Here a combination of markers and colors from a qualitative colormap in matplotlib:

import itertools
import numpy as np
from matplotlib import markers
import matplotlib.pyplot as plt

m_styles = markers.MarkerStyle.markers
N = 60
colormap = plt.cm.Dark2.colors  # Qualitative colormap
for i, (marker, color) in zip(range(N), itertools.product(m_styles, colormap)):
    plt.scatter(*np.random.random(2), color=color, marker=marker, label=i)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., ncol=4);

enter image description here

jQuery multiselect drop down menu

I was also looking for a simple multi select for my company. I wanted something simple, highly customizable and with no big dependencies others than jQuery.

I didn't found one fitting my needs so I decided to code my own.
I use it in production.

Here's some demos and documentation: loudev.com

If you want to contribute, check the github repository

AngularJS Folder Structure

enter image description here

Sort By Type

On the left we have the app organized by type. Not too bad for smaller apps, but even here you can start to see it gets more difficult to find what you are looking for. When I want to find a specific view and its controller, they are in different folders. It can be good to start here if you are not sure how else to organize the code as it is quite easy to shift to the technique on the right: structure by feature.

Sort By Feature (preferred)

On the right the project is organized by feature. All of the layout views and controllers go in the layout folder, the admin content goes in the admin folder, and the services that are used by all of the areas go in the services folder. The idea here is that when you are looking for the code that makes a feature work, it is located in one place. Services are a bit different as they “service” many features. I like this once my app starts to take shape as it becomes a lot easier to manage for me.

A well written blog post: http://www.johnpapa.net/angular-growth-structure/

Example App: https://github.com/angular-app/angular-app

How can I switch themes in Visual Studio 2012

For those who are using "High Contrast" windows themes but still want a regular Visual Studio theme you might notice that the theme selector drop down is disabled. You can still change it by doing the following...

  1. Going to the registry key: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0_Config\Themes (or whichever version of VS you are using)
  2. Export the key of the theme you want (it's a bunch of random letters / numbers) to a .reg file.
  3. Then copy the "high contrast" key's name (again random letters / numbers)
  4. Delete the high contrast key and then rename the dark theme to the copied name
  5. Then import the exported theme from the reg file.

This permanently sets the theme to the one you've chosen.

Customizing the template within a Directive

angular.module('formComponents', [])
  .directive('formInput', function() {
    return {
        restrict: 'E',
        compile: function(element, attrs) {
            var type = attrs.type || 'text';
            var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
            var htmlText = '<div class="control-group">' +
                '<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
                    '<div class="controls">' +
                    '<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
                    '</div>' +
                '</div>';
            element.replaceWith(htmlText);
        }
    };
})

How to check if one of the following items is in a list?

Think about what the code actually says!

>>> (1 or 2)
1
>>> (2 or 1)
2

That should probably explain it. :) Python apparently implements "lazy or", which should come as no surprise. It performs it something like this:

def or(x, y):
    if x: return x
    if y: return y
    return False

In the first example, x == 1 and y == 2. In the second example, it's vice versa. That's why it returns different values depending on the order of them.

RegExp matching string not starting with my

You could either use a lookahead assertion like others have suggested. Or, if you just want to use basic regular expression syntax:

^(.?$|[^m].+|m[^y].*)

This matches strings that are either zero or one characters long (^.?$) and thus can not be my. Or strings with two or more characters where when the first character is not an m any more characters may follow (^[^m].+); or if the first character is a m it must not be followed by a y (^m[^y]).

XSLT string replace

The rouine is pretty good, however it causes my app to hang, so I needed to add the case:

  <xsl:when test="$text = '' or $replace = ''or not($replace)" >
    <xsl:value-of select="$text" />
    <!-- Prevent thsi routine from hanging -->
  </xsl:when>

before the function gets called recursively.

I got the answer from here: When test hanging in an infinite loop

Thank you!

SyntaxError: "can't assign to function call"

Syntactically, this line makes no sense:

invest(initial_amount,top_company(5,year,year+1)) = subsequent_amount

You are attempting to assign a value to a function call, as the error says. What are you trying to accomplish? If you're trying set subsequent_amount to the value of the function call, switch the order:

subsequent_amount = invest(initial_amount,top_company(5,year,year+1))

html/css buttons that scroll down to different div sections on a webpage

For something really basic use this:

<a href="#middle">Go To Middle</a>

Or for something simple in javascript check out this jQuery plugin ScrollTo. Quite useful for scrolling smoothly.

How to target only IE (any version) within a stylesheet?

Another working solution for IE specific styling is

<html data-useragent="Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)">

And then your selector

html[data-useragent*='MSIE 10.0'] body .my-class{
        margin-left: -0.4em;
    }

Select multiple elements from a list

mylist[c(5,7,9)] should do it.

You want the sublists returned as sublists of the result list; you don't use [[]] (or rather, the function is [[) for that -- as Dason mentions in comments, [[ grabs the element.

Removing duplicate elements from an array in Swift

You can convert to a Set and back to an Array again quite easily:

let unique = Array(Set(originals))

This is not guaranteed to maintain the original order of the array.

Top 5 time-consuming SQL queries in Oracle

You could take the average buffer gets per execution during a period of activity of the instance:

SELECT username,
       buffer_gets,
       disk_reads,
       executions,
       buffer_get_per_exec,
       parse_calls,
       sorts,
       rows_processed,
       hit_ratio,
       module,
       sql_text
       -- elapsed_time, cpu_time, user_io_wait_time, ,
  FROM (SELECT sql_text,
               b.username,
               a.disk_reads,
               a.buffer_gets,
               trunc(a.buffer_gets / a.executions) buffer_get_per_exec,
               a.parse_calls,
               a.sorts,
               a.executions,
               a.rows_processed,
               100 - ROUND (100 * a.disk_reads / a.buffer_gets, 2) hit_ratio,
               module
               -- cpu_time, elapsed_time, user_io_wait_time
          FROM v$sqlarea a, dba_users b
         WHERE a.parsing_user_id = b.user_id
           AND b.username NOT IN ('SYS', 'SYSTEM', 'RMAN','SYSMAN')
           AND a.buffer_gets > 10000
         ORDER BY buffer_get_per_exec DESC)
 WHERE ROWNUM <= 20

How to pretty print XML from Java?

Here's an answer to my own question. I combined the answers from the various results to write a class that pretty prints XML.

No guarantees on how it responds with invalid XML or large documents.

package ecb.sdw.pretty;

import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;

/**
 * Pretty-prints xml, supplied as a string.
 * <p/>
 * eg.
 * <code>
 * String formattedXml = new XmlFormatter().format("<tag><nested>hello</nested></tag>");
 * </code>
 */
public class XmlFormatter {

    public XmlFormatter() {
    }

    public String format(String unformattedXml) {
        try {
            final Document document = parseXmlFile(unformattedXml);

            OutputFormat format = new OutputFormat(document);
            format.setLineWidth(65);
            format.setIndenting(true);
            format.setIndent(2);
            Writer out = new StringWriter();
            XMLSerializer serializer = new XMLSerializer(out, format);
            serializer.serialize(document);

            return out.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private Document parseXmlFile(String in) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputSource is = new InputSource(new StringReader(in));
            return db.parse(is);
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        } catch (SAXException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        String unformattedXml =
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?><QueryMessage\n" +
                        "        xmlns=\"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message\"\n" +
                        "        xmlns:query=\"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/query\">\n" +
                        "    <Query>\n" +
                        "        <query:CategorySchemeWhere>\n" +
                        "   \t\t\t\t\t         <query:AgencyID>ECB\n\n\n\n</query:AgencyID>\n" +
                        "        </query:CategorySchemeWhere>\n" +
                        "    </Query>\n\n\n\n\n" +
                        "</QueryMessage>";

        System.out.println(new XmlFormatter().format(unformattedXml));
    }

}

How to add an item to an ArrayList in Kotlin?

If you have a MUTABLE collection:

val list = mutableListOf(1, 2, 3)
list += 4

If you have an IMMUTABLE collection:

var list = listOf(1, 2, 3)
list += 4

note that I use val for the mutable list to emphasize that the object is always the same, but its content changes.

In case of the immutable list, you have to make it var. A new object is created by the += operator with the additional value.

Safe Area of Xcode 9

Apple introduced the topLayoutGuide and bottomLayoutGuide as properties of UIViewController way back in iOS 7. They allowed you to create constraints to keep your content from being hidden by UIKit bars like the status, navigation or tab bar. These layout guides are deprecated in iOS 11 and replaced by a single safe area layout guide.

Refer link for more information.

Styling a input type=number

I modified @LcSalazar's answer a bit... it's still not perfect because the background of the default buttons can still be seen in both Firefox, Chrome & Opera (not tested in Safari); but clicking on the arrows still works

Notes:

  • Adding pointer-events: none; allows you to click through the overlapping button, but then you can not style the button while hovered.
  • The arrows are visible in Edge, but don't work because Edge doesn't use arrows. It only adds an "x" to clear the input.

_x000D_
_x000D_
.number-wrapper {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.number-wrapper:after,_x000D_
.number-wrapper:before {_x000D_
  position: absolute;_x000D_
  right: 5px;_x000D_
  width: 1.6em;_x000D_
  height: .9em;_x000D_
  font-size: 10px;_x000D_
  pointer-events: none;_x000D_
  background: #fff;_x000D_
}_x000D_
_x000D_
.number-wrapper:after {_x000D_
  color: blue;_x000D_
  content: "\25B2";_x000D_
  margin-top: 1px;_x000D_
}_x000D_
_x000D_
.number-wrapper:before {_x000D_
  color: red;_x000D_
  content: "\25BC";_x000D_
  margin-bottom: 5px;_x000D_
  bottom: -.5em;_x000D_
}
_x000D_
<span class='number-wrapper'>_x000D_
    <input type="number" />_x000D_
</span>
_x000D_
_x000D_
_x000D_

$(form).ajaxSubmit is not a function

Drupal 8

Drupal 8 does not include JS-libraries to pages automaticly. So most probably if you meet this error you need to attach 'core/jquery.form' library to your page (or form). Add something like this to your render array:

$form['#attached']['library'][] = 'core/jquery.form';

Javascript - validation, numbers only

here is how to validate the input to only accept numbers this will accept numbers like 123123123.41212313

<input type="text" 
onkeypress="if ( isNaN(this.value + String.fromCharCode(event.keyCode) )) return false;"
/>

and this will not accept entering the dot (.), so it will only accept integers

<input type="text" 
onkeypress="if ( isNaN( String.fromCharCode(event.keyCode) )) return false;"
/>

this way you will not permit the user to input anything but numbers

Properties private set;

This is normally the case then the ID is not a natural part of the entity, but a database artifact that needs be abstracted away.

It is a design decision - to only allow setting the ID during construction or through method invocation, so it is managed internally by the class.

You can write a setter yourself, assuming you have a backing field:

private int Id = 0;
public void SetId (int id)
{
  this.Id = id;
}

Or through a constructor:

private int Id = 0;
public Person (int id)
{
  this.Id = id;
}

What causing this "Invalid length for a Base-64 char array"

As others have mentioned this can be caused when some firewalls and proxies prevent access to pages containing a large amount of ViewState data.

ASP.NET 2.0 introduced the ViewState Chunking mechanism which breaks the ViewState up into manageable chunks, allowing the ViewState to pass through the proxy / firewall without issue.

To enable this feature simply add the following line to your web.config file.

<pages maxPageStateFieldLength="4000">

This should not be used as an alternative to reducing your ViewState size but it can be an effective backstop against the "Invalid length for a Base-64 char array" error resulting from aggressive proxies and the like.

How to disable a ts rule for a specific line?

@ts-expect-error

TS 3.9 introduces a new magic comment. @ts-expect-error will:

  • have same functionality as @ts-ignore
  • trigger an error, if actually no compiler error has been suppressed (= indicates useless flag)
if (false) {
  // @ts-expect-error: Let's ignore a single compiler error like this unreachable code 
  console.log("hello"); // compiles
}

// If @ts-expect-error didn't suppress anything at all, we now get a nice warning 
let flag = true;
// ...
if (flag) {
  // @ts-expect-error
  // ^~~~~~~~~~~~~~~^ error: "Unused '@ts-expect-error' directive.(2578)"
  console.log("hello"); 
}

Alternatives

@ts-ignore and @ts-expect-error can be used for all sorts of compiler errors. For type issues (like in OP), I recommend one of the following alternatives due to narrower error suppression scope:

? Use any type

// type assertion for single expression
delete ($ as any).summernote.options.keyMap.pc.TAB;

// new variable assignment for multiple usages
const $$: any = $
delete $$.summernote.options.keyMap.pc.TAB;
delete $$.summernote.options.keyMap.mac.TAB;

? Augment JQueryStatic interface

// ./global.d.ts
interface JQueryStatic {
  summernote: any;
}

// ./main.ts
delete $.summernote.options.keyMap.pc.TAB; // works

In other cases, shorthand module declarations or module augmentations for modules with no/extendable types are handy utilities. A viable strategy is also to keep not migrated code in .js and use --allowJs with checkJs: false.

How to set image to UIImage

Just Follow This

UIImageView *imgview = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 300, 400)];
[imgview setImage:[UIImage imageNamed:@"YourImageName"]];
[imgview setContentMode:UIViewContentModeScaleAspectFit];
[self.view addSubview:imgview];

How to loop through all elements of a form jQuery

As taken from the #jquery Freenode IRC channel:

$.each($(form).serializeArray(), function(_, field) { /* use field.name, field.value */ });

Thanks to @Cork on the channel.

how to convert image to byte array in java?

Try this code snippet

BufferedImage image = ImageIO.read(new File("filename.jpg"));

// Process image

ImageIO.write(image, "jpg", new File("output.jpg"));

SimpleDateFormat parse loses timezone

tl;dr

what is the way to retrieve a Date object so that its always in GMT?

Instant.now() 

Details

You are using troublesome confusing old date-time classes that are now supplanted by the java.time classes.

Instant = UTC

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = Instant.now() ; // Current moment in UTC.

ISO 8601

To exchange this data as text, use the standard ISO 8601 formats exclusively. These formats are sensibly designed to be unambiguous, easy to process by machine, and easy to read across many cultures by people.

The java.time classes use the standard formats by default when parsing and generating strings.

String output = instant.toString() ;  

2017-01-23T12:34:56.123456789Z

Time zone

If you want to see that same moment as presented in the wall-clock time of a particular region, apply a ZoneId to get a ZonedDateTime.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "Asia/Singapore" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;  // Same simultaneous moment, same point on the timeline.

See this code live at IdeOne.com.

Notice the eight hour difference, as the time zone of Asia/Singapore currently has an offset-from-UTC of +08:00. Same moment, different wall-clock time.

instant.toString(): 2017-01-23T12:34:56.123456789Z

zdt.toString(): 2017-01-23T20:34:56.123456789+08:00[Asia/Singapore]

Convert

Avoid the legacy java.util.Date class. But if you must, you can convert. Look to new methods added to the old classes.

java.util.Date date = Date.from( instant ) ;

…going the other way…

Instant instant = myJavaUtilDate.toInstant() ;

Date-only

For date-only, use LocalDate.

LocalDate ld = zdt.toLocalDate() ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

What is the meaning of the CascadeType.ALL for a @ManyToOne JPA association

If you just want to delete the address assigned to the user and not to affect on User entity class you should try something like that:

@Entity
public class User {
   @OneToMany(mappedBy = "addressOwner", cascade = CascadeType.ALL)
   protected Set<Address> userAddresses = new HashSet<>();
}

@Entity 
public class Addresses {
   @ManyToOne(cascade = CascadeType.REFRESH) @JoinColumn(name = "user_id")
   protected User addressOwner;
}

This way you dont need to worry about using fetch in annotations. But remember when deleting the User you will also delete connected address to user object.

How to do error logging in CodeIgniter (PHP)

To simply put a line in the server's error log, use PHP's error_log() function. However, that method will not send an e-mail.

First, to trigger an error:

trigger_error("Error message here", E_USER_ERROR);

By default, this will go in the server's error log file. See the ErrorLog directive for Apache. To set your own log file:

ini_set('error_log', 'path/to/log/file');

Note that the log file you choose must already exist and be writable by the server process. The simplest way to make the file writable is to make the server user the owner of the file. (The server user may be nobody, _www, apache, or something else, depending on your OS distribution.)

To e-mail the error, you need to set up a custom error handler:

function mail_error($errno, $errstr, $errfile, $errline) {
  $message = "[Error $errno] $errstr - Error on line $errline in file $errfile";
  error_log($message); // writes the error to the log file
  mail('[email protected]', 'I have an error', $message);
}
set_error_handler('mail_error', E_ALL^E_NOTICE);

Please see the relevant PHP documentation for more info.

How can I check if a string contains ANY letters from the alphabet?

You can use islower() on your string to see if it contains some lowercase letters (amongst other characters). or it with isupper() to also check if contains some uppercase letters:

below: letters in the string: test yields true

>>> z = "(555) 555 - 5555 ext. 5555"
>>> z.isupper() or z.islower()
True

below: no letters in the string: test yields false.

>>> z= "(555).555-5555"
>>> z.isupper() or z.islower()
False
>>> 

Not to be mixed up with isalpha() which returns True only if all characters are letters, which isn't what you want.

Note that Barm's answer completes mine nicely, since mine doesn't handle the mixed case well.

How can I make my layout scroll both horizontally and vertically?

I was able to find a simple way to achieve both scrolling behaviors.

Here is the xml for it:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:scrollbars="vertical">

    <HorizontalScrollView 
        android:layout_width="320px" android:layout_height="fill_parent">

        <TableLayout
            android:id="@+id/linlay" android:layout_width="320px"
            android:layout_height="fill_parent" android:stretchColumns="1"
            android:background="#000000"/>

    </HorizontalScrollView>

</ScrollView>

How to retrieve unique count of a field using Kibana + Elastic Search

For Kibana 4 go to this answer

This is easy to do with a terms panel:

Adding a terms panel to Kibana

If you want to select the count of distinct IP that are in your logs, you should specify in the field clientip, you should put a big enough number in length (otherwise, it will join different IP under the same group) and specify in the style table. After adding the panel, you will have a table with IP, and the count of that IP:

Table with IP and count

OpenJDK8 for windows

Go to this link

Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download

Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.

JDK vs OpenJDK

How to fix warning from date() in PHP"

Try to set date.timezone in php.ini file. Or you can manually set it using ini_set() or date_default_timezone_set().

Send a base64 image in HTML email

An alternative approach may be to embed images in the email using the cid method. (Basically including the image as an attachment, and then embedding it). In my experience, this approach seems to be well supported these days.

enter image description here

Source: https://www.campaignmonitor.com/blog/how-to/2008/08/embedding-images-revisited/

Example JavaScript code to parse CSV data

Regular expressions to the rescue! These few lines of code handle properly quoted fields with embedded commas, quotes, and newlines based on the RFC 4180 standard.

function parseCsv(data, fieldSep, newLine) {
    fieldSep = fieldSep || ',';
    newLine = newLine || '\n';
    var nSep = '\x1D';
    var qSep = '\x1E';
    var cSep = '\x1F';
    var nSepRe = new RegExp(nSep, 'g');
    var qSepRe = new RegExp(qSep, 'g');
    var cSepRe = new RegExp(cSep, 'g');
    var fieldRe = new RegExp('(?<=(^|[' + fieldSep + '\\n]))"(|[\\s\\S]+?(?<![^"]"))"(?=($|[' + fieldSep + '\\n]))', 'g');
    var grid = [];
    data.replace(/\r/g, '').replace(/\n+$/, '').replace(fieldRe, function(match, p1, p2) {
        return p2.replace(/\n/g, nSep).replace(/""/g, qSep).replace(/,/g, cSep);
    }).split(/\n/).forEach(function(line) {
        var row = line.split(fieldSep).map(function(cell) {
            return cell.replace(nSepRe, newLine).replace(qSepRe, '"').replace(cSepRe, ',');
        });
        grid.push(row);
    });
    return grid;
}

const csv = 'A1,B1,C1\n"A ""2""","B, 2","C\n2"';
const separator = ',';      // field separator, default: ','
const newline = ' <br /> '; // newline representation in case a field contains newlines, default: '\n' 
var grid = parseCsv(csv, separator, newline);
// expected: [ [ 'A1', 'B1', 'C1' ], [ 'A "2"', 'B, 2', 'C <br /> 2' ] ]

You don't need a parser-generator such as lex/yacc. The regular expression handles RFC 4180 properly thanks to positive lookbehind, negative lookbehind, and positive lookahead.

Clone/download code at https://github.com/peterthoeny/parse-csv-js

How to add include and lib paths to configure/make cycle?

Set LDFLAGS and CFLAGS when you run make:

$ LDFLAGS="-L/home/me/local/lib" CFLAGS="-I/home/me/local/include" make

If you don't want to do that a gazillion times, export these in your .bashrc (or your shell equivalent). Also set LD_LIBRARY_PATH to include /home/me/local/lib:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/me/local/lib

Passing arrays as parameters in bash

Note: This is the somewhat crude solution I posted myself, after not finding an answer here on Stack Overflow. It allows for only one array being passed, and it being the last element of the parameter list. Actually, it is not passing the array at all, but a list of its elements, which are re-assembled into an array by called_function(), but it worked for me. Somewhat later Ken posted his solution, but I kept mine here for "historic" reference.

calling_function()
{
    variable="a"
    array=( "x", "y", "z" )
    called_function "${variable}" "${array[@]}"
}

called_function()
{
    local_variable="${1}"
    shift
    local_array=("${@}")
}

The opposite of Intersect()

I'm not 100% sure what your NonIntersect method is supposed to do (regarding set theory) - is it
B \ A (everything from B that does not occur in A)?
If yes, then you should be able to use the Except operation (B.Except(A)).

error: (-215) !empty() in function detectMultiScale

the error may be due to, the required xml files has not been loaded properly. Search for the file haarcascade_frontalface_default.xml by using the search engine of ur OS get the full path and put it as the argument to cv2.CascadeClassifier as string

What is "not assignable to parameter of type never" error in typescript?

All you have to do is define your result as a string array, like the following:

const result : string[] = [];

Without defining the array type, it by default will be never. So when you tried to add a string to it, it was a type mismatch, and so it threw the error you saw.

Pandas: drop a level from a multi-level column index?

I have struggled with this problem since I don’t know why my droplevel() function does not work. Work through several and learn that ‘a’ in your table is columns name and ‘b’, ‘c’ are index. Do like this will help

df.columns.name = None
df.reset_index() #make index become label

Auto-redirect to another HTML page

One of these will work...

_x000D_
_x000D_
<head>_x000D_
  <meta http-equiv='refresh' content='0; URL=http://example.com/'>_x000D_
</head>
_x000D_
_x000D_
_x000D_

...or it can done with JavaScript:

_x000D_
_x000D_
window.location.href = 'https://example.com/';
_x000D_
_x000D_
_x000D_

How to set the context path of a web application in Tomcat 7.0

It's not recommended to update the server configuration like server.xml or ROOT.xml.

You can put a context.xml configuration file under your web-application META-INF directory, with the context path setting included. This will override the default server setting?

i.e.:

<Context docBase="yourAppName" path="/yourAppPath" reloadable="true">

How to Install Sublime Text 3 using Homebrew

An update

Turns out now brew cask install sublime-text installs the most up to date version (e.g. 3) by default and brew cask is now part of the standard brew-installation.

Simple timeout in java

    @Singleton
    @AccessTimeout(value=120000)
    public class StatusSingletonBean {
      private String status;
    
      @Lock(LockType.WRITE)
      public void setStatus(String new Status) {
        status = newStatus;
      }
      @Lock(LockType.WRITE)
      @AccessTimeout(value=360000)
      public void doTediousOperation {
        //...
      }
    }
    //The following singleton has a default access timeout value of 60 seconds, specified //using the TimeUnit.SECONDS constant:
    @Singleton
    @AccessTimeout(value=60, timeUnit=SECONDS) 
    public class StatusSingletonBean { 
    //... 
    }  
    //The Java EE 6 Tutorial

//https://docs.oracle.com/javaee/6/tutorial/doc/gipvi.html

Can I perform a DNS lookup (hostname to IP address) using client-side Javascript?

If the client has Java installed, you could do something like this:

ipAddress = java.net.InetAddress.getLocalHost().getHostAddress();

Other than that, you will probably have to use a server side script.

How to access the GET parameters after "?" in Express?

const express = require('express')
const bodyParser = require('body-parser')
const { usersNdJobs, userByJob, addUser , addUserToCompany } = require ('./db/db.js')

const app = express()
app.set('view engine', 'pug')
app.use(express.static('public'))
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

app.get('/', (req, res) => {
  usersNdJobs()
    .then((users) => {
      res.render('users', { users })
    })
    .catch(console.error)
})

app.get('/api/company/users', (req, res) => {
  const companyname = req.query.companyName
  console.log(companyname)
  userByJob(companyname)
    .then((users) => {
      res.render('job', { users })
    }).catch(console.error)
})

app.post('/api/users/add', (req, res) => {
  const userName = req.body.userName
  const jobName = req.body.jobName
  console.log("user name = "+userName+", job name : "+jobName)
  addUser(userName, jobName)
    .then((result) => {
      res.status(200).json(result)
    })
    .catch((error) => {
      res.status(404).json({ 'message': error.toString() })
    })
})
app.post('/users/add', (request, response) => {
  const { userName, job } = request.body
  addTeam(userName, job)
  .then((user) => {
    response.status(200).json({
      "userName": user.name,
      "city": user.job
    })
  .catch((err) => {
    request.status(400).json({"message": err})
  })
})

app.post('/api/user/company/add', (req, res) => {
  const userName = req.body.userName
  const companyName = req.body.companyName
  console.log(userName, companyName)
  addUserToCompany(userName, companyName)
  .then((result) => {
    res.json(result)
  })
  .catch(console.error)
})

app.get('/api/company/user', (req, res) => {
 const companyname = req.query.companyName
 console.log(companyname)
 userByJob(companyname)
 .then((users) => {
   res.render('jobs', { users })
 })
})

app.listen(3000, () =>
  console.log('Example app listening on port 3000!')
)

Identify duplicate values in a list in Python

The following list comprehension will yield the duplicate values:

[x for x in mylist if mylist.count(x) >= 2]

Change Toolbar color in Appcompat 21

Hey if you want to apply Material theme for only android 5.0 then you can add this theme in it

<style name="AppHomeTheme" parent="@android:style/Theme.Material.Light">

        <!-- customize the color palette -->
        <item name="android:colorPrimary">@color/blue_dark_bg</item>
        <item name="android:colorPrimaryDark">@color/blue_status_bar</item>
        <item name="android:colorAccent">@color/blue_color_accent</item>
        <item name="android:textColor">@android:color/white</item>
        <item name="android:textColorPrimary">@android:color/white</item>
        <item name="android:actionMenuTextColor">@android:color/black</item>
    </style> 

Here below line is responsibly for text color of Actionbar of Material design.

<item name="android:textColorPrimary">@android:color/white</item>

$('body').on('click', '.anything', function(){})

You can try this:

You must follow the following format

    $('element,id,class').on('click', function(){....});

*JQuery code*

    $('body').addClass('.anything').on('click', function(){
      //do some code here i.e
      alert("ok");
    });

Is there a simple way to remove unused dependencies from a maven pom.xml?

You can use dependency:analyze -DignoreNonCompile

This will print a list of used undeclared and unused declared dependencies (while ignoring runtime/provided/test/system scopes for unused dependency analysis.)

** Be careful while using this, some libraries used at runtime are considered as unused **

For more details refer this link

BigDecimal to string

The BigDecimal can not be a double. you can use Int number. if you want to display exactly own number, you can use the String constructor of BigDecimal .

like this:

BigDecimal bd1 = new BigDecimal("10.0001");

now, you can display bd1 as 10.0001

So simple. GOOD LUCK.

Is it possible to center text in select box?

_x000D_
_x000D_
select {_x000D_
  text-align: center;_x000D_
  text-align-last: center;_x000D_
}_x000D_
option {_x000D_
  text-align: left;_x000D_
}
_x000D_
<select>_x000D_
   <option value="">(please select a state)</option>_x000D_
   <option class="lt" value="--">none</option>_x000D_
   <option class="lt" value="AL">Alabama</option>_x000D_
   <option class="lt" value="AK">Alaska</option>_x000D_
   <option class="lt" value="AZ">Arizona</option>_x000D_
   <option class="lt" value="AR">Arkansas</option>_x000D_
   <option class="lt" value="CA">California</option>_x000D_
   <option class="lt" value="CO">Colorado</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Rails: How can I set default values in ActiveRecord?

I've found that using a validation method provides a lot of control over setting defaults. You can even set defaults (or fail validation) for updates. You even set a different default value for inserts vs updates if you really wanted to. Note that the default won't be set until #valid? is called.

class MyModel
  validate :init_defaults

  private
  def init_defaults
    if new_record?
      self.some_int ||= 1
    elsif some_int.nil?
      errors.add(:some_int, "can't be blank on update")
    end
  end
end

Regarding defining an after_initialize method, there could be performance issues because after_initialize is also called by each object returned by :find : http://guides.rubyonrails.org/active_record_validations_callbacks.html#after_initialize-and-after_find

How to create an Array, ArrayList, Stack and Queue in Java?

Just a small correction to the first answer in this thread.

Even for Stack, you need to create new object with generics if you are using Stack from java util packages.

Right usage:
    Stack<Integer> s = new Stack<Integer>();
    Stack<String> s1 = new Stack<String>();

    s.push(7);
    s.push(50);

    s1.push("string");
    s1.push("stack");

if used otherwise, as mentioned in above post, which is:

    /*
    Stack myStack = new Stack();
    // add any type of elements (String, int, etc..)
    myStack.push("Hello");
    myStack.push(1);
    */

Although this code works fine, has unsafe or unchecked operations which results in error.

Remove Safari/Chrome textinput/textarea glow

I experienced this on a div that had a click event and after 20 some searches I found this snippet that saved my day.

-webkit-tap-highlight-color: rgba(0,0,0,0);

This disables the default button highlighting in webkit mobile browsers

Detect HTTP or HTTPS then force HTTPS in JavaScript

You should check this: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/upgrade-insecure-requests

Add this meta tag to your index.html inside head

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">

Hope it helped.

Getting "TypeError: failed to fetch" when the request hasn't actually failed

Note that there is an unrelated issue in your code but that could bite you later: you should return res.json() or you will not catch any error occurring in JSON parsing or your own function processing data.

Back to your error: You cannot have a TypeError: failed to fetch with a successful request. You probably have another request (check your "network" panel to see all of them) that breaks and causes this error to be logged. Also, maybe check "Preserve log" to be sure the panel is not cleared by any indelicate redirection. Sometimes I happen to have a persistent "console" panel, and a cleared "network" panel that leads me to have error in console which is actually unrelated to the visible requests. You should check that.

Or you (but that would be vicious) actually have a hardcoded console.log('TypeError: failed to fetch') in your final .catch ;) and the error is in reality in your .then() but it's hard to believe.

How do I use .woff fonts for my website?

After generation of woff files, you have to define font-family, which can be used later in all your css styles. Below is the code to define font families (for normal, bold, bold-italic, italic) typefaces. It is assumed, that there are 4 *.woff files (for mentioned typefaces), placed in fonts subdirectory.

In CSS code:

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font.woff") format('woff');
}

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font-bold.woff") format('woff');
    font-weight: bold;
}

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font-boldoblique.woff") format('woff');
    font-weight: bold;
    font-style: italic;
}

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font-oblique.woff") format('woff');
    font-style: italic;
}

After having that definitions, you can just write, for example,

In HTML code:

<div class="mydiv">
    <b>this will be written with awesome-font-bold.woff</b>
    <br/>
    <b><i>this will be written with awesome-font-boldoblique.woff</i></b>
    <br/>
    <i>this will be written with awesome-font-oblique.woff</i>
    <br/>
    this will be written with awesome-font.woff
</div>

In CSS code:

.mydiv {
    font-family: myfont
}

The good tool for generation woff files, which can be included in CSS stylesheets is located here. Not all woff files work correctly under latest Firefox versions, and this generator produces 'correct' fonts.

Why are arrays of references illegal?

An array is implicitly convertable to a pointer, and pointer-to-reference is illegal in C++

How can I write maven build to add resources to classpath?

A cleaner alternative of putting your config file into a subfolder of src/main/resources would be to enhance your classpath locations. This is extremely easy to do with Maven.

For instance, place your property file in a new folder src/main/config, and add the following to your pom:

 <build>
    <resources>
        <resource>
            <directory>src/main/config</directory>
        </resource>
    </resources>
 </build>

From now, every files files under src/main/config is considered as part of your classpath (note that you can exclude some of them from the final jar if needed: just add in the build section:

    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
                <excludes>
                    <exclude>my-config.properties</exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>

so that my-config.properties can be found in your classpath when you run your app from your IDE, but will remain external from your jar in your final distribution).

Detect a finger swipe through JavaScript on the iPhone and Android

threshold, timeout swipe, swipeBlockElems add.

document.addEventListener('touchstart', handleTouchStart, false);
document.addEventListener('touchmove', handleTouchMove, false);
document.addEventListener('touchend', handleTouchEnd, false);     

const SWIPE_BLOCK_ELEMS = [
  'swipBlock',
  'handle',
  'drag-ruble'
]

let xDown = null;
let yDown = null; 
let xDiff = null;
let yDiff = null;
let timeDown = null;
const  TIME_THRESHOLD = 200;
const  DIFF_THRESHOLD = 130;

function handleTouchEnd() {

let timeDiff = Date.now() - timeDown; 
if (Math.abs(xDiff) > Math.abs(yDiff)) { /*most significant*/
  if (Math.abs(xDiff) > DIFF_THRESHOLD && timeDiff < TIME_THRESHOLD) {
    if (xDiff > 0) {
      // console.log(xDiff, TIME_THRESHOLD, DIFF_THRESHOLD)
      SWIPE_LEFT(LEFT) /* left swipe */
    } else {
      // console.log(xDiff)
      SWIPE_RIGHT(RIGHT) /* right swipe */
    }
  } else {
    console.log('swipeX trashhold')
  }
} else {
  if (Math.abs(yDiff) > DIFF_THRESHOLD && timeDiff < TIME_THRESHOLD) {
    if (yDiff > 0) {
      /* up swipe */
    } else {
      /* down swipe */
    }
  } else {
    console.log('swipeY trashhold')
  }
 }
 /* reset values */
 xDown = null;
 yDown = null;
 timeDown = null; 
}
function containsClassName (evntarget , classArr) {
 for (var i = classArr.length - 1; i >= 0; i--) {
   if( evntarget.classList.contains(classArr[i]) ) {
      return true;
    }
  }
}
function handleTouchStart(evt) {
  let touchStartTarget = evt.target;
  if( containsClassName(touchStartTarget, SWIPE_BLOCK_ELEMS) ) {
    return;
  }
  timeDown = Date.now()
  xDown = evt.touches[0].clientX;
  yDown = evt.touches[0].clientY;
  xDiff = 0;
  yDiff = 0;

}

function handleTouchMove(evt) {
  if (!xDown || !yDown) {
    return;
  }

  var xUp = evt.touches[0].clientX;
  var yUp = evt.touches[0].clientY;


  xDiff = xDown - xUp;
  yDiff = yDown - yUp;
}

Query to get the names of all tables in SQL Server 2008 Database

To get the fields info too, you can use the following:

SELECT TABLE_SCHEMA, TABLE_NAME, 
       COLUMN_NAME, substring(DATA_TYPE, 1,1) AS DATA_TYPE
FROM information_schema.COLUMNS 
WHERE TABLE_SCHEMA NOT IN("information_schema", "mysql", "performance_schema") 
ORDER BY TABLE_SCHEMA, TABLE_NAME, ORDINAL_POSITION

How to right-align form input boxes?

You can use floating to the right and clear them.

_x000D_
_x000D_
form {_x000D_
  overflow: hidden;_x000D_
}_x000D_
input {_x000D_
  float: right;_x000D_
  clear: both;_x000D_
}
_x000D_
<form>_x000D_
  <input name="declared_first" value="above" />_x000D_
  <input name="declared_second" value="below" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

You can also set a right-to-left direction to the parent and restore the default left-to-right on the inputs. With display: block you can force them to be on different lines.

_x000D_
_x000D_
form {_x000D_
  direction: rtl;_x000D_
}_x000D_
input {_x000D_
  display: block;_x000D_
  direction: ltr;_x000D_
}
_x000D_
<form>_x000D_
  <input name="declared_first" value="above" />_x000D_
  <input name="declared_second" value="below" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Or the modern way, flexbox layout

_x000D_
_x000D_
form {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  align-items: flex-end;_x000D_
}
_x000D_
<form>_x000D_
  <input name="declared_first" value="above" />_x000D_
  <input name="declared_second" value="below" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Converting JavaScript object with numeric keys into array

This is best solution. I think so.

Object.keys(obj).map(function(k){return {key: k, value: obj[k]}})

Generate a unique id

Why don't use GUID?

Guid guid = Guid.NewGuid();
string str = guid.ToString();

Which .NET Dependency Injection frameworks are worth looking into?

Spring.Net is quite solid, but the documentation took some time to wade through. Autofac is good, and while .Net 2.0 is supported, you need VS 2008 to compile it, or else use the command line to build your app.

How to show git log history (i.e., all the related commits) for a sub directory of a git repo?

For tracking changes to a folder where the folder was moved, I started using:

git rev-list --all --pretty=oneline -- "*/foo/subfoo/*"

This isn't perfect as it will grab other folders with the same name, but if it is unique, then it seems to work.

How to export all collections in MongoDB?

Follow the steps below to create a mongodump from the server and import it another server/local machine which has a username and a password

1. mongodump -d dbname -o dumpname -u username -p password
2. scp -r user@remote:~/location/of/dumpname ./
3. mongorestore -d dbname dumpname/dbname/ -u username -p password

How can I uninstall npm modules in Node.js?

In case you are on Windows, run CMD as administrator and type:

npm -g uninstall <package name>

Why does integer division in C# return an integer and not a float?

As a little trick to know what you are obtaining you can use var, so the compiler will tell you the type to expect:

int a = 1;
int b = 2;
var result = a/b;

your compiler will tell you that result would be of type int here.

Chrome ignores autocomplete="off"

I managed to disable autocomple exploiting this rule:

Fields that are not passwords, but should be obscured, such as credit card numbers, may also have a type="password" attribute, but should contain the relevant autocomplete attribute, such as "cc-number" or "cc-csc". https://www.chromium.org/developers/design-documents/create-amazing-password-forms

<input id="haxed" type="password" autocomplete="cc-number">

However it comes with the great responsibility :)

Don’t try to fool the browser Password managers (either built into the browser, or external) are designed to ease the user experience. Inserting fake fields, using incorrect autocomplete attributes or taking advantage of the weaknesses of the existing password managers simply leads to frustrated users.

Removing items from a list

Besides all the excellent solutions offered here I would like to offer a different solution.

I'm not sure if you're free to add dependencies, but if you can, you could add the https://code.google.com/p/guava-libraries/ as a dependency. This library adds support for many basic functional operations to Java and can make working with collections a lot easier and more readable.

In the code I replaced the type of the List by T, since I don't know what your list is typed to.

This problem can with guava be solved like this:

List<T> filteredList = new Arraylist<>(filter(list, not(XXX_EQUAL_TO_AAA)));

And somewhere else you then define XXX_EQUAL_TO_AAA as:

public static final Predicate<T> XXX_EQUAL_TO_AAA = new Predicate<T>() {
    @Override
    public boolean apply(T input) {
        return input.getXXX().equalsIgnoreCase("AAA");
    }
}

However, this is probably overkill in your situation. It's just something that becomes increasingly powerful the more you work with collections.

Ohw, also, you need these static imports:

import static com.google.common.base.Predicates.not;
import static com.google.common.collect.Collections2.filter;

Getting data-* attribute for onclick event for an html element

I simply use this jQuery trick:

$("a:focus").attr('data-id');

It gets the focused a element and gets the data-id attribute from it.

How can I add "href" attribute to a link dynamically using JavaScript?

document.getElementById('link-id').href = "new-href";

I know this is an old post, but here's a one-liner that might be more suitable for some folks.

Correct way to pause a Python program

I work with non-programmers who like a simple solution:

import code
code.interact(banner='Paused. Press ^D (Ctrl+D) to continue.', local=globals()) 

This produces an interpreter that acts almost exactly like the real interpreter, including the current context, with only the output:

Paused. Press ^D (Ctrl+D) to continue.
>>>

The Python Debugger is also a good way to pause.

import pdb
pdb.set_trace() # Python 2

or

breakpoint() # Python 3

How do I get my solution in Visual Studio back online in TFS?

(Additional step from solution above for if you are missing the AutoReconnect or Offline registry value)

For Visual Studio 2015, Version 14

  1. Turn off all VS instances
  2. HKEY_CURRENT_USER\SOFTWARE\Microsoft\VisualStudio\14.0\TeamFoundation\Instances{YourServerName}\Collections{TheCollectionName} (To get to this directory on Windows, hit the Windows + R key and search for "regedit")
  3. Set both the Offline and AutoReconnect values to 0.
  4. If you are missing one of those attributes (in my case I was missing AutoReconnect), right click and and create a new DWORD(32-bit) value with the desired missing name, AutoReconnect or Offline.
  5. Again, make sure both values are set to zero.
  6. Restart your solution

Additional info: blog MSDN - When and how does my solution go offline?

postgresql duplicate key violates unique constraint

For future searchs, use ON CONFLICT DO NOTHING.

How to decompile a whole Jar file?

Something like:

jar -xf foo.jar && find . -iname "*.class" | xargs /opt/local/bin/jad -r

maybe?

How do I redirect users after submit button click?

// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com/SpecificAction.php");

// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com/SpecificAction.php";

Loading a properties file from Java package

The following two cases relate to loading a properties file from an example class named TestLoadProperties.

Case 1: Loading the properties file using ClassLoader

InputStream inputStream = TestLoadProperties.class.getClassLoader()
                          .getResourceAsStream("A.config");
properties.load(inputStream);

In this case the properties file must be in the root/src directory for successful loading.

Case 2: Loading the properties file without using ClassLoader

InputStream inputStream = getClass().getResourceAsStream("A.config");
properties.load(inputStream);

In this case the properties file must be in the same directory as the TestLoadProperties.class file for successful loading.

Note: TestLoadProperties.java and TestLoadProperties.class are two different files. The former, .java file, is usually found in a project's src/ directory, while the latter, .class file, is usually found in its bin/ directory.

Is there an equivalent of 'which' on the Windows command line?

Just have to post this Windows' one liner batch file:

C:>type wh.cmd
@for %%f in (%*) do for %%e in (%PATHEXT% .dll .lnk) do for %%b in (%%f%%e) do for %%d in (%PATH%) do if exist %%d\%%b echo %%d\%%b

A test:

C:>wh ssh
C:\cygwin64\bin\ssh.EXE
C:\Windows\System32\OpenSSH\\ssh.EXE

Not quite a one-liner if you wrap the code in setlocal enableextensions and endlocal.

How to automatically indent source code?

In Visual Studio 2010

Ctrl +k +d indent the complete page.

Ctrl +k +f indent the selected Code.

For more help visit : http://msdn.microsoft.com/en-us/library/da5kh0wa.aspx

every thing is there.

Round button with text and icon in flutter

If you need a button like this:

You can use RaisedButton and use the child property to do this. You need to add a Row and inside row you can add a Text widget and an Icon Widget to achieve this. If you want to use png image, you can use similar widget to achieve this.

RaisedButton(
    onPressed: () {},
    color: Theme.of(context).accentColor,
    child: Padding(
      padding: EdgeInsets.fromLTRB(
          SizeConfig.safeBlockHorizontal * 5,
          0,
          SizeConfig.safeBlockHorizontal * 5,
          0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text(
            'Continue',
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.w700,
              color: Colors.white,
            ),
          ),
          Icon(
            Icons.arrow_forward,
            color: Colors.white,
          )
        ],
      ),
    ),
  ),

Text File Parsing with Python

There are a few ways to go about this. One option would be to use inputfile.read() instead of inputfile.readlines() - you'd need to write separate code to strip the first four lines, but if you want the final output as a single string anyway, this might make the most sense.

A second, simpler option would be to rejoin the strings after striping the first four lines with my_text = ''.join(my_text). This is a little inefficient, but if speed isn't a major concern, the code will be simplest.

Finally, if you actually want the output as a list of strings instead of a single string, you can just modify your data parser to iterate over the list. That might looks something like this:

def data_parser(lines, dic):
    for i, j in dic.iteritems():
        for (k, line) in enumerate(lines):
            lines[k] = line.replace(i, j)
    return lines

Single Form Hide on Startup

static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    MainUIForm mainUiForm = new MainUIForm();
    mainUiForm.Visible = false;
    Application.Run();
}

How to add an extra source directory for maven to compile and include in the build jar?

With recent Maven versions (3) and recent version of the maven compiler plugin (3.7.0), I notice that adding a source folder with the build-helper-maven-plugin is not required if the folder that contains the source code to add in the build is located in the target folder or a subfolder of it.
It seems that the compiler maven plugin compiles any java source code located inside this folder whatever the directory that contains them.
For example having some (generated or no) source code in target/a, target/generated-source/foo will be compiled and added in the outputDirectory : target/classes.

JSON encode MySQL results

One more option using FOR loop:

 $sth = mysql_query("SELECT ...");
 for($rows = array(); $row = mysql_fetch_assoc($sth); $rows[] = $row);
 print json_encode($rows);

The only disadvantage is that loop for is slower then e.g. while or especially foreach

How to tell which disk Windows Used to Boot

You can use WMI to figure this out. The Win32_BootConfiguration class will tell you both the logical drive and the physical device from which Windows boots. Specifically, the Caption property will tell you which device you're booting from.

For example, in powershell, just type gwmi Win32_BootConfiguration to get your answer.

Get battery level and state in Android

To check battery percentage we use BatteryManager, the following method will return battery percentage.

Source Link

public static float getBatteryLevel(Context context, Intent intent) {
    Intent batteryStatus = context.registerReceiver(null,
            new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    int batteryLevel = -1;
    int batteryScale = 1;
    if (batteryStatus != null) {
        batteryLevel = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, batteryLevel);
        batteryScale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, batteryScale);
    }
    return batteryLevel / (float) batteryScale * 100;
}

XML Parser for C

How about one written in pure assembler :-) Don't forget to check out the benchmarks.

This could be due to the service endpoint binding not using the HTTP protocol

I had this problem because I configured my WCF Service to return a System.Data.DataTable.

It worked fine in my test HTML page, but blew up when I put this in my Windows Form application.

I had to go in and change the Service's Operational Contract signature from DataTable to DataSet and return the data accordingly.

If you have this problem, you may want to add an additional Operational Contract to your Service so you do not have to worry about breaking code that rely on existing Services.

jQuery Refresh/Reload Page if Ajax Success after time

I prefer this way Using ajaxStop + setInterval,, this will refresh the page after any XHR[ajax] request in the same page

    $(document).ajaxStop(function() {
        setInterval(function() {
            location.reload();
        }, 3000);
    });

EL access a map value by Integer key

Initial answer (EL 2.1, May 2009)

As mentioned in this java forum thread:

Basically autoboxing puts an Integer object into the Map. ie:

map.put(new Integer(0), "myValue")

EL (Expressions Languages) evaluates 0 as a Long and thus goes looking for a Long as the key in the map. ie it evaluates:

map.get(new Long(0))

As a Long is never equal to an Integer object, it does not find the entry in the map.
That's it in a nutshell.


Update since May 2009 (EL 2.2)

Dec 2009 saw the introduction of EL 2.2 with JSP 2.2 / Java EE 6, with a few differences compared to EL 2.1.
It seems ("EL Expression parsing integer as long") that:

you can call the method intValue on the Long object self inside EL 2.2:

<c:out value="${map[(1).intValue()]}"/>

That could be a good workaround here (also mentioned below in Tobias Liefke's answer)


Original answer:

EL uses the following wrappers:

Terms                  Description               Type
null                   null value.               -
123                    int value.                java.lang.Long
123.00                 real value.               java.lang.Double
"string" ou 'string'   string.                   java.lang.String
true or false          boolean.                  java.lang.Boolean

JSP page demonstrating this:

 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

 <%@ page import="java.util.*" %>

 <h2> Server Info</h2>
Server info = <%= application.getServerInfo() %> <br>
Servlet engine version = <%=  application.getMajorVersion() %>.<%= application.getMinorVersion() %><br>
Java version = <%= System.getProperty("java.vm.version") %><br>
<%
  Map map = new LinkedHashMap();
  map.put("2", "String(2)");
  map.put(new Integer(2), "Integer(2)");
  map.put(new Long(2), "Long(2)");
  map.put(42, "AutoBoxedNumber");

  pageContext.setAttribute("myMap", map);  
  Integer lifeInteger = new Integer(42);
  Long lifeLong = new Long(42);  
%>
  <h3>Looking up map in JSTL - integer vs long </h3>

  This page demonstrates how JSTL maps interact with different types used for keys in a map.
  Specifically the issue relates to autoboxing by java using map.put(1, "MyValue") and attempting to display it as ${myMap[1]}
  The map "myMap" consists of four entries with different keys: A String, an Integer, a Long and an entry put there by AutoBoxing Java 5 feature.       

  <table border="1">
    <tr><th>Key</th><th>value</th><th>Key Class</th></tr>
    <c:forEach var="entry" items="${myMap}" varStatus="status">
    <tr>      
      <td>${entry.key}</td>
      <td>${entry.value}</td>
      <td>${entry.key.class}</td>
    </tr>
    </c:forEach>
</table>

    <h4> Accessing the map</h4>    
    Evaluating: ${"${myMap['2']}"} = <c:out value="${myMap['2']}"/><br>
    Evaluating: ${"${myMap[2]}"}   = <c:out value="${myMap[2]}"/><br>    
    Evaluating: ${"${myMap[42]}"}   = <c:out value="${myMap[42]}"/><br>    

    <p>
    As you can see, the EL Expression for the literal number retrieves the value against the java.lang.Long entry in the map.
    Attempting to access the entry created by autoboxing fails because a Long is never equal to an Integer
    <p>

    lifeInteger = <%= lifeInteger %><br/>
    lifeLong = <%= lifeLong %><br/>
    lifeInteger.equals(lifeLong) : <%= lifeInteger.equals(lifeLong) %> <br>

React: why child component doesn't update when prop changes

Use the setState function. So you could do

       this.setState({this.state.foo.bar:123}) 

inside the handle event method.

Once, the state is updated, it will trigger changes, and re-render will take place.

Using git to get just the latest revision

Alternate solution to doing shallow clone (git clone --depth=1 <URL>) would be, if remote side supports it, to use --remote option of git archive:

$ git archive --format=tar --remote=<repository URL> HEAD | tar xf -

Or, if remote repository in question is browse-able using some web interface like gitweb or GitHub, then there is a chance that it has 'snapshot' feature, and you can download latest version (without versioning information) from web interface.

How do I include a JavaScript file in another JavaScript file?

Step 1: Declare the function in another class.

    export const myreport = (value) => {
    color = value.color;
    name = value.name;
    
    var mytext = name + " | " + color;
    return mytext;
    }

Step 2:- Import that function which is needed to be used.

    import {myreport} from '../../Test'

Step 3:- Use that function.

let val = { color: "red", name: "error" }
var resultText = myreport(val)
console.log("resultText :- ", resultText)

TypeError: 'float' object is not subscriptable

It looks like you are trying to set elements 0 through 11 of PriceList to new values. The syntax would usually look like this:

prompt = "What would you like the new price for all standard pizzas to be? "
PizzaChange = float(input(prompt))
for i in [0, 1, 2, 3, 4, 5, 6]: PriceList[i] = PizzaChange
for i in [7, 8, 9, 10, 11]: PriceList[i] = PizzaChange + 3

If they are always consecutive ranges, then it's even simpler to write:

prompt = "What would you like the new price for all standard pizzas to be? "
PizzaChange = float(input(prompt))
for i in range(0, 7): PriceList[i] = PizzaChange
for i in range(7, 12): PriceList[i] = PizzaChange + 3

For reference, PriceList[0][1][2][3][4][5][6] refers to "Element 6 of element 5 of element 4 of element 3 of element 2 of element 1 of element 0 of PriceList. Put another way, it's the same as ((((((PriceList[0])[1])[2])[3])[4])[5])[6].

Maven compile with multiple src directories

This worked for me

<build>
    <sourceDirectory>.</sourceDirectory>
    <plugins>
        <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
        <includes>
            <include>src/main/java/**/*.java</include>
            <include>src/main2/java/**/*.java</include>
        </includes>
        </configuration>
        </plugin>
    </plugins>
</build>

How to print a dictionary line by line in Python?

for car,info in cars.items():
    print(car)
    for key,value in info.items():
        print(key, ":", value)

HTML table sort

Flexbox-based tables can easily be sorted by using flexbox property "order".

Here's an example:

_x000D_
_x000D_
function sortTable() {_x000D_
  let table = document.querySelector("#table")_x000D_
  let children = [...table.children]_x000D_
  let sortedArr = children.map(e => e.innerText).sort((a, b) => a.localeCompare(b));_x000D_
_x000D_
  children.forEach(child => {_x000D_
    child.style.order = sortedArr.indexOf(child.innerText)_x000D_
  })_x000D_
}_x000D_
_x000D_
document.querySelector("#sort").addEventListener("click", sortTable)
_x000D_
#table {_x000D_
  display: flex;_x000D_
  flex-direction: column_x000D_
}
_x000D_
<div id="table">_x000D_
  <div>Melissa</div>_x000D_
  <div>Justin</div>_x000D_
  <div>Judy</div>_x000D_
  <div>Skipper</div>_x000D_
  <div>Alex</div>_x000D_
</div>_x000D_
<button id="sort"> sort </button>
_x000D_
_x000D_
_x000D_

Explanation

The sortTable function extracts the data of the table into an array, which is then sorted in alphabetic order. After that we loop through the table items and assign the CSS property order equal to index of an item's data in our sorted array.

What is the point of "Initial Catalog" in a SQL Server connection string?

If the user name that is in the connection string has access to more then one database you have to specify the database you want the connection string to connect to. If your user has only one database available then you are correct that it doesn't matter. But it is good practice to put this in your connection string.

Difference between FetchType LAZY and EAGER in Java Persistence API?

Basically,

LAZY = fetch when needed
EAGER = fetch immediately

Change primary key column in SQL Server

Assuming that your current primary key constraint is called pk_history, you can replace the following lines:

ALTER TABLE history ADD PRIMARY KEY (id)

ALTER TABLE history
DROP CONSTRAINT userId
DROP CONSTRAINT name

with these:

ALTER TABLE history DROP CONSTRAINT pk_history

ALTER TABLE history ADD CONSTRAINT pk_history PRIMARY KEY (id)

If you don't know what the name of the PK is, you can find it with the following query:

SELECT * 
  FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
 WHERE TABLE_NAME = 'history'

TypeError: a bytes-like object is required, not 'str'

This code is probably good for Python 2. But in Python 3, this will cause an issue, something related to bit encoding. I was trying to make a simple TCP server and encountered the same problem. Encoding worked for me. Try this with sendto command.

clientSocket.sendto(message.encode(),(serverName, serverPort))

Similarly you would use .decode() to receive the data on the UDP server side, if you want to print it exactly as it was sent.

Remove style attribute from HTML tags

I commented on @Mayerln 's function. It does work but DOMDocument really stuffs with encoding. Here's my simplehtmldom version

function stripAttributes($html,$attribs) {
    $dom = new simple_html_dom();
    $dom->load($html);
    foreach($attribs as $attrib)
        foreach($dom->find("*[$attrib]") as $e)
            $e->$attrib = null; 
    $dom->load($dom->save());
    return $dom->save();
}

How to get raw text from pdf file using java

You can use iText for do such things

//iText imports

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;

for example:

try {     
    PdfReader reader = new PdfReader(INPUTFILE);
    int n = reader.getNumberOfPages(); 
    String str=PdfTextExtractor.getTextFromPage(reader, 2); //Extracting the content from a particular page.
    System.out.println(str);
    reader.close();
} catch (Exception e) {
    System.out.println(e);
}

another one

try {

    PdfReader reader = new PdfReader("c:/temp/test.pdf");
    System.out.println("This PDF has "+reader.getNumberOfPages()+" pages.");
    String page = PdfTextExtractor.getTextFromPage(reader, 2);
    System.out.println("Page Content:\n\n"+page+"\n\n");
    System.out.println("Is this document tampered: "+reader.isTampered());
    System.out.println("Is this document encrypted: "+reader.isEncrypted());
} catch (IOException e) {
    e.printStackTrace();
}

the above examples can only extract the text, but you need to do some more to remove hyperlinks, bullets, heading & numbers.

Unable to capture screenshot. Prevented by security policy. Galaxy S6. Android 6.0

You must have either disabled, froze or uninstalled FaceProvider in settings>applications>all
This will only happen if it's frozen, either uninstall it, or enable it.

Remove empty array elements

foreach($arr as $key => $val){
   if (empty($val)) unset($arr[$key];
}

How do I convert an integer to binary in JavaScript?

The binary in 'convert to binary' can refer to three main things. The positional number system, the binary representation in memory or 32bit bitstrings. (for 64bit bitstrings see Patrick Roberts' answer)

1. Number System

(123456).toString(2) will convert numbers to the base 2 positional numeral system. In this system negative numbers are written with minus signs just like in decimal.

2. Internal Representation

The internal representation of numbers is 64 bit floating point and some limitations are discussed in this answer. There is no easy way to create a bit-string representation of this in javascript nor access specific bits.

3. Masks & Bitwise Operators

MDN has a good overview of how bitwise operators work. Importantly:

Bitwise operators treat their operands as a sequence of 32 bits (zeros and ones)

Before operations are applied the 64 bit floating points numbers are cast to 32 bit signed integers. After they are converted back.

Here is the MDN example code for converting numbers into 32-bit strings.

function createBinaryString (nMask) {
  // nMask must be between -2147483648 and 2147483647
  for (var nFlag = 0, nShifted = nMask, sMask = ""; nFlag < 32;
       nFlag++, sMask += String(nShifted >>> 31), nShifted <<= 1);
  return sMask;
}

createBinaryString(0) //-> "00000000000000000000000000000000"
createBinaryString(123) //-> "00000000000000000000000001111011"
createBinaryString(-1) //-> "11111111111111111111111111111111"
createBinaryString(-1123456) //-> "11111111111011101101101110000000"
createBinaryString(0x7fffffff) //-> "01111111111111111111111111111111"

How to pipe list of files returned by find command to cat to view all the files

This will print the name and contents of files-only recursively..

find . -type f -printf '\n\n%p:\n' -exec cat {} \;

Edit (Improved version): This will print the name and contents of text (ascii) files-only recursively..

find . -type f -exec grep -Iq . {} \; -print | xargs awk 'FNR==1{print FILENAME ":" $0; }'

One more attempt

find . -type f -exec grep -Iq . {} \; -printf "\n%p:" -exec cat {} \;

How to use "Share image using" sharing Intent to share images in android?

Strring temp="facebook",temp="whatsapp",temp="instagram",temp="googleplus",temp="share";

    if(temp.equals("facebook"))
    {
        Intent intent = getPackageManager().getLaunchIntentForPackage("com.facebook.katana");
        if (intent != null) {

            Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
            shareIntent.setType("image/png");
            shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + "/sdcard/folder name/abc.png"));
            shareIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            shareIntent.setPackage("com.facebook.katana");
            startActivity(shareIntent);

        }
        else
        {
            Toast.makeText(MainActivity.this, "Facebook require..!!", Toast.LENGTH_SHORT).show();
        }
    }
    if(temp.equals("whatsapp"))
    {

        try {
            File filePath = new File("/sdcard/folder name/abc.png");
            final ComponentName name = new ComponentName("com.whatsapp", "com.whatsapp.ContactPicker");
            Intent oShareIntent = new Intent();
            oShareIntent.setComponent(name);
            oShareIntent.setType("text/plain");
            oShareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Website : www.google.com");
            oShareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(filePath));
            oShareIntent.setType("image/jpeg");
            oShareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            MainActivity.this.startActivity(oShareIntent);


        } catch (Exception e) {
            Toast.makeText(MainActivity.this, "WhatsApp require..!!", Toast.LENGTH_SHORT).show();
        }
    }
    if(temp.equals("instagram"))
    {
        Intent intent = getPackageManager().getLaunchIntentForPackage("com.instagram.android");
        if (intent != null)
        {
            File filePath =new File("/sdcard/folder name/"abc.png");
            Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
            shareIntent.setType("image");
            shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + "/sdcard/Chitranagari/abc.png"));
            shareIntent.setPackage("com.instagram.android");
            startActivity(shareIntent);

        }
        else
        {
            Toast.makeText(MainActivity.this, "Instagram require..!!", Toast.LENGTH_SHORT).show();

        }
    }
    if(temp.equals("googleplus"))
    {

        try
        {

            Calendar c = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
            String strDate = sdf.format(c.getTime());
            Intent shareIntent = ShareCompat.IntentBuilder.from(MainActivity.this).getIntent();
            shareIntent.setType("text/plain");
            shareIntent.putExtra(Intent.EXTRA_TEXT, "Website : www.google.com");
            shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + "/sdcard/folder name/abc.png"));
            shareIntent.setPackage("com.google.android.apps.plus");
            shareIntent.setAction(Intent.ACTION_SEND);
            startActivity(shareIntent);
        }catch (Exception e)
        {
            e.printStackTrace();
            Toast.makeText(MainActivity.this, "Googleplus require..!!", Toast.LENGTH_SHORT).show();
        }
    }
    if(temp.equals("share")) {

        File filePath =new File("/sdcard/folder name/abc.png");  //optional //internal storage
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_TEXT, "Website : www.google.com");
        shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(filePath));  //optional//use this when you want to send an image
        shareIntent.setType("image/jpeg");
        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(Intent.createChooser(shareIntent, "send"));

    }

C compiling - "undefined reference to"?

As stated by a few others, this is a linking error. The section of code where this function is being called doesn't know what this function is. It either needs to be declared in a header file an defined in its own source file, or defined or declared in the same source file, above where it's being called.

Edit: In older versions of C, C89/C90, function declarations weren't actually required. So, you could just add the definition anywhere in the file in which you're using the function, even after the call and the compiler would infer the declaration. For example,

int main()
{
  int a = func();
}

int func()
{
   return 1;
}

However, this isn't good practice today and most languages, C++ for example, won't allow it. One way to get away with defining the function in the same source file in which you're using it, is to declare it at the beginning of the file. So, the previous example would look like this instead.

int func();

int main()
{
   int a = func();
}

int func()
{
  return 1;
}

jQuery .search() to any string

Ah, that would be because RegExp is not jQuery. :)

Try this page. jQuery.attr doesn't return a String so that would certainly cause in this regard. Fortunately I believe you can just use .text() to return the String representation.

Something like:

$("li").val("title").search(/sometext/i));

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

I have been getting similar error, and just want to share with you. maybe it will help someone.

If you want to use EntityManagerFactory to get an EntityManager, make sure that you will use:

<persistence-unit name="name" transaction-type="RESOURCE_LOCAL">

and not:

<persistence-unit name="name" transaction-type="JPA">

in persistance.xml

clean and rebuild project, it should help.

How to print a specific row of a pandas DataFrame?

When you call loc with a scalar value, you get a pd.Series. That series will then have one dtype. If you want to see the row as it is in the dataframe, you'll want to pass an array like indexer to loc.

Wrap your index value with an additional pair of square brackets

print(df.loc[[159220]])

How can I easily view the contents of a datatable or dataview in the immediate window

To beautify adinas's debugger output I made some simple formattings:

    public void DebugTable(DataTable table)
    {
        Debug.WriteLine("--- DebugTable(" + table.TableName + ") ---");
        int zeilen = table.Rows.Count;
        int spalten = table.Columns.Count;

        // Header
        for (int i = 0; i < table.Columns.Count; i++)
        {
            string s = table.Columns[i].ToString();
            Debug.Write(String.Format("{0,-20} | ", s));
        }
        Debug.Write(Environment.NewLine);
        for (int i = 0; i < table.Columns.Count; i++)
        {
            Debug.Write("---------------------|-");
        }
        Debug.Write(Environment.NewLine);

        // Data
        for (int i = 0; i < zeilen; i++)
        {
            DataRow row = table.Rows[i];
            //Debug.WriteLine("{0} {1} ", row[0], row[1]);
            for (int j = 0; j < spalten; j++)
            {
                string s = row[j].ToString();
                if (s.Length > 20) s = s.Substring(0, 17) + "...";
                Debug.Write(String.Format("{0,-20} | ", s));
            }
            Debug.Write(Environment.NewLine);
        }
        for (int i = 0; i < table.Columns.Count; i++)
        {
            Debug.Write("---------------------|-");
        }
        Debug.Write(Environment.NewLine);
    }

Best of this solution: You don't need Visual Studio! Here my example output:

SELECT PackKurz, PackName, PackGewicht FROM verpackungen

PackKurz             | PackName             | PackGewicht          | 
---------------------|----------------------|----------------------|-
BB205                | BigBag 205 kg        | 205                  | 
BB300                | BigBag 300 kg        | 300                  | 
BB365                | BigBag 365 kg        | 365                  | 
CO                   | Container, Alteru... |                      | 
EP                   | Palette              |                      | 
IBC                  | Chemikaliengefäß ... |                      | 
lose                 | nicht verpackungs... | 0                    | 
---------------------|----------------------|----------------------|-

Python argparse command line flags without arguments

Your script is right. But by default is of None type. So it considers true of any other value other than None is assigned to args.argument_name variable.

I would suggest you to add a action="store_true". This would make the True/False type of flag. If used its True else False.

import argparse
parser = argparse.ArgumentParser('parser-name')
parser.add_argument("-f","--flag",action="store_true",help="just a flag argument")

usage

$ python3 script.py -f

After parsing when checked with args.f it returns true,

args = parser.parse_args()
print(args.f)
>>>true

Configuration Error: <compilation debug="true" targetFramework="4.0"> ASP.NET MVC3

Have you tried the aspnet_regiis tool to register .Net 4.0 for IIS? You can check more at msdn

fatal: git-write-tree: error building trees

This worked for me:

Do

$ git status

And check if you have Unmerged paths

# Unmerged paths:
#   (use "git reset HEAD <file>..." to unstage)
#   (use "git add <file>..." to mark resolution)
#
#   both modified:      app/assets/images/logo.png
#   both modified:      app/models/laundry.rb

Fix them with git add to each of them and try git stash again.

git add app/assets/images/logo.png

Killing a process using Java

On Windows, you could use this command.

taskkill /F /IM <processname>.exe 

To kill it forcefully, you may use;

Runtime.getRuntime().exec("taskkill /F /IM <processname>.exe")

Abort Ajax requests using jQuery

I was doing a live search solution and needed to cancel pending requests that may have taken longer than the latest/most current request.

In my case I used something like this:

//On document ready
var ajax_inprocess = false;

$(document).ajaxStart(function() {
ajax_inprocess = true;
});

$(document).ajaxStop(function() {
ajax_inprocess = false;
});

//Snippet from live search function
if (ajax_inprocess == true)
{
    request.abort();
}
//Call for new request 

How does Subquery in select statement work in oracle

It's simple-

SELECT empname,
       empid,
       (SELECT COUNT (profileid)
          FROM profile
         WHERE profile.empid = employee.empid)
           AS number_of_profiles
  FROM employee;

It is even simpler when you use a table join like this:

  SELECT e.empname, e.empid, COUNT (p.profileid) AS number_of_profiles
    FROM employee e LEFT JOIN profile p ON e.empid = p.empid
GROUP BY e.empname, e.empid;

Explanation for the subquery:

Essentially, a subquery in a select gets a scalar value and passes it to the main query. A subquery in select is not allowed to pass more than one row and more than one column, which is a restriction. Here, we are passing a count to the main query, which, as we know, would always be only a number- a scalar value. If a value is not found, the subquery returns null to the main query. Moreover, a subquery can access columns from the from clause of the main query, as shown in my query where employee.empid is passed from the outer query to the inner query.


Edit:

When you use a subquery in a select clause, Oracle essentially treats it as a left join (you can see this in the explain plan for your query), with the cardinality of the rows being just one on the right for every row in the left.


Explanation for the left join

A left join is very handy, especially when you want to replace the select subquery due to its restrictions. There are no restrictions here on the number of rows of the tables in either side of the LEFT JOIN keyword.

For more information read Oracle Docs on subqueries and left join or left outer join.

find vs find_by vs where

Suppose I have a model User

  1. User.find(id)

Returns a row where primary key = id. The return type will be User object.

  1. User.find_by(email:"[email protected]")

Returns first row with matching attribute or email in this case. Return type will be User object again.

Note :- User.find_by(email: "[email protected]") is similar to User.find_by_email("[email protected]")

  1. User.where(project_id:1)

Returns all users in users table where attribute matches.

Here return type will be ActiveRecord::Relation object. ActiveRecord::Relation class includes Ruby's Enumerable module so you can use it's object like an array and traverse on it.

How to get on scroll events?

// @HostListener('scroll', ['$event']) // for scroll events of the current element
@HostListener('window:scroll', ['$event']) // for window scroll events
onScroll(event) {
  ...
}

or

<div (scroll)="onScroll($event)"></div>

php timeout - set_time_limit(0); - don't work

Check the php.ini

ini_set('max_execution_time', 300); //300 seconds = 5 minutes

ini_set('max_execution_time', 0); //0=NOLIMIT

Excel 2007: How to display mm:ss format not as a DateTime (e.g. 73:07)?

5.In the Format Cells box, click Custom in the Category list. 6.In the Type box, at the top of the list of formats, type [h]:mm;@ and then click OK. (That’s a colon after [h], and a semicolon after mm.) YOu can then add hours. The format will be in the Type list the next time you need it.

From MS, works well.

http://office.microsoft.com/en-us/excel-help/add-or-subtract-time-HA102809662.aspx

Disable eslint rules for folder

The previous answers were in the right track, but the complete answer for this is going to Disabling rules only for a group of files, there you'll find the documentation needed to disable/enable rules for certain folders (Because in some cases you don't want to ignore the whole thing, only disable certain rules). Example:

{
    "env": {},
    "extends": [],
    "parser": "",
    "plugins": [],
    "rules": {},
    "overrides": [
      {
        "files": ["test/*.spec.js"], // Or *.test.js
        "rules": {
          "require-jsdoc": "off"
        }
      }
    ],
    "settings": {}
}

Mysql select distinct

You can use group by instead of distinct. Because when you use distinct, you'll get struggle to select all values from table. Unlike when you use group by, you can get distinct values and also all fields in table.

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

How do I get the RootViewController from a pushed controller?

A slightly less ugly version of the same thing mentioned in pretty much all these answers:

UIViewController *rootViewController = [[self.navigationController viewControllers] firstObject];

in your case, I'd probably do something like:

inside your UINavigationController subclass:

- (UIViewController *)rootViewController
{
    return [[self viewControllers] firstObject];
}

then you can use:

UIViewController *rootViewController = [self.navigationController rootViewController];

edit

OP asked for a property in the comments.

if you like, you can access this via something like self.navigationController.rootViewController by just adding a readonly property to your header:

@property (nonatomic, readonly, weak) UIViewController *rootViewController;

How to go back to previous page if back button is pressed in WebView?

Official Kotlin Way:

override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
    // Check if the key event was the Back button and if there's history
    if (keyCode == KeyEvent.KEYCODE_BACK && myWebView.canGoBack()) {
        myWebView.goBack()
        return true
    }
    // If it wasn't the Back key or there's no web page history, bubble up to the default
    // system behavior (probably exit the activity)
    return super.onKeyDown(keyCode, event)
}

https://developer.android.com/guide/webapps/webview.html#NavigatingHistory

Pandas convert dataframe to array of tuples

list(data_set.itertuples(index=False))

As of 17.1, the above will return a list of namedtuples.

If you want a list of ordinary tuples, pass name=None as an argument:

list(data_set.itertuples(index=False, name=None))

here-document gives 'unexpected end of file' error

The line that starts or ends the here-doc probably has some non-printable or whitespace characters (for example, carriage return) which means that the second "EOF" does not match the first, and doesn't end the here-doc like it should. This is a very common error, and difficult to detect with just a text editor. You can make non-printable characters visible for example with cat:

cat -A myfile.sh

Once you see the output from cat -A the solution will be obvious: remove the offending characters.

How to render a DateTime object in a Twig template

You can use date filter:

{{ game.gameDate|date("m/d/Y") }}

Best way to get child nodes

Don't let white space fool you. Just test this in a console browser.

Use native javascript. Here is and example with two 'ul' sets with the same class. You don't need to have your 'ul' list all in one line to avoid white space just use your array count to jump over white space.

How to get around white space with querySelector() then childNodes[] js fiddle link: https://jsfiddle.net/aparadise/56njekdo/

var y = document.querySelector('.list');
var myNode = y.childNodes[11].style.backgroundColor='red';

<ul class="list">
    <li>8</li>
    <li>9</li>
    <li>100</li>
</ul>

<ul class="list">
    <li>ABC</li>
    <li>DEF</li>
    <li>XYZ</li>
</ul>

Listen to changes within a DIV and act accordingly

There is an excellent jquery plugin, LiveQuery, that does just this.

Live Query utilizes the power of jQuery selectors by binding events or firing callbacks for matched elements auto-magically, even after the page has been loaded and the DOM updated.

For example you could use the following code to bind a click event to all A tags, even any A tags you might add via AJAX.

$('a').livequery('click', function(event) { 
    alert('clicked'); 
    return false; 
}); 

Once you add new A tags to your document, Live Query will bind the click event and there is nothing else that needs to be called or done.

Here is a working example of its magic...

enter image description here

Python display text with font & color?

There are 2 possibilities. In either case PyGame has to be initialized by pygame.init.

import pygame
pygame.init()

Use either the pygame.font module and create a pygame.font.SysFont or pygame.font.Font object. render() a pygame.Surface with the text and blit the Surface to the screen:

my_font = pygame.font.SysFont(None, 50)
text_surface = myfont.render("Hello world!", True, (255, 0, 0))
screen.blit(text_surface, (10, 10))

Or use the pygame.freetype module. Create a pygame.freetype.SysFont() or pygame.freetype.Font object. render() a pygame.Surface with the text or directly render_to() the text to the screen:

my_ft_font = pygame.freetype.SysFont('Times New Roman', 50)
my_ft_font.render_to(screen, (10, 10), "Hello world!", (255, 0, 0))

See also Text and font


Minimal pygame.font example: repl.it/@Rabbid76/PyGame-Text

import pygame

pygame.init()
window = pygame.display.set_mode((500, 150))
clock = pygame.time.Clock()

font = pygame.font.SysFont(None, 100)
text = font.render('Hello World', True, (255, 0, 0))

background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *window.get_size(), (128, 128, 128), (64, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
for rect, color in tiles:
    pygame.draw.rect(background, color, rect)

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window.blit(background, (0, 0))
    window.blit(text, text.get_rect(center = window.get_rect().center))
    pygame.display.flip()

pygame.quit()
exit()

Minimal pygame.freetype example: repl.it/@Rabbid76/PyGame-FreeTypeText

import pygame
import pygame.freetype

pygame.init()
window = pygame.display.set_mode((500, 150))
clock = pygame.time.Clock()

ft_font = pygame.freetype.SysFont('Times New Roman', 80)

background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *window.get_size(), (128, 128, 128), (64, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
for rect, color in tiles:
    pygame.draw.rect(background, color, rect)

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window.blit(background, (0, 0))
    text_rect = ft_font.get_rect('Hello World')
    text_rect.center = window.get_rect().center
    ft_font.render_to(window, text_rect.topleft, 'Hello World', (255, 0, 0))
    pygame.display.flip()

pygame.quit()
exit()

Only read selected columns

You do it like this:

df = read.table("file.txt", nrows=1, header=TRUE, sep="\t", stringsAsFactors=FALSE)
colClasses = as.list(apply(df, 2, class))
needCols = c("Year", "Jan", "Feb", "Mar", "Apr", "May", "Jun")
colClasses[!names(colClasses) %in% needCols] = list(NULL)
df = read.table("file.txt", header=TRUE, colClasses=colClasses, sep="\t", stringsAsFactors=FALSE)

String, StringBuffer, and StringBuilder

Difference between String and the other two classes is that String is immutable and the other two are mutable classes.

But why we have two classes for same purpose?

Reason is that StringBuffer is Thread safe and StringBuilder is not. StringBuilder is a new class on StringBuffer Api and it was introduced in JDK5 and is always recommended if you are working in a Single threaded environment as it is much Faster

For complete Details you can read http://www.codingeek.com/java/stringbuilder-and-stringbuffer-a-way-to-create-mutable-strings-in-java/

Google Chrome default opening position and size

Maybe a little late, but I found an easier way to set the defaults! You have to right-click on the right of your tab and choose "size", then click on your window, and it should keep it as the default size.

Inserting a tab character into text using C#

In addition to the anwsers above you can use PadLeft or PadRight:

string name = "John";
string surname = "Smith";

Console.WriteLine("Name:".PadRight(15)+"Surname:".PadRight(15));
Console.WriteLine( name.PadRight(15) + surname.PadRight(15));

This will fill in the string with spaces to the left or right.

Cannot connect to the Docker daemon on macOS

Try this to create default.

docker-machine create default

IntelliJ cannot find any declarations

In my case I was using a gradle project with subprojects. The reason IntelliJ couldn't find declarations was that the subprojects were not built.

After investigating why subprojects were not built, I found out that using "auto-import" was breaking the subprojects.

After importing the project from build.gradle without auto-import, it worked for me.

What is the difference between persist() and merge() in JPA and Hibernate?

This is coming from JPA. In a very simple way:

  • persist(entity) should be used with totally new entities, to add them to DB (if entity already exists in DB there will be EntityExistsException throw).

  • merge(entity) should be used, to put entity back to persistence context if the entity was detached and was changed.

Checking if an object is null in C#

  public static bool isnull(object T)
  {
      return T == null ? true : false;
  }

use:

isnull(object.check.it)

Conditional use:

isnull(object.check.it) ? DoWhenItsTrue : DoWhenItsFalse;

Update (another way) updated 08/31/2017 and 01/25/2021. Thanks for the comment.

public static bool IsNull(object T)
{
    return (bool)T ? true : false;
}

Demostration Demostration on Visual Studio console application

And for the records, you have my code on Github, go check it out: https://github.com/j0rt3g4/ValidateNull PS: This one is especially for you Chayim Friedman, don't use beta software assuming that is all true. Wait for final versions or use your own environment to test, before assuming true beta software without any sort of documentation or demonstration from your end.

How do I perform an insert and return inserted identity with Dapper?

If you're using Dapper.SimpleSave:

 //no safety checks
 public static int Create<T>(object param)
    {
        using (SqlConnection conn = new SqlConnection(GetConnectionString()))
        {
            conn.Open();
            conn.Create<T>((T)param);
            return (int) (((T)param).GetType().GetProperties().Where(
                    x => x.CustomAttributes.Where(
                        y=>y.AttributeType.GetType() == typeof(Dapper.SimpleSave.PrimaryKeyAttribute).GetType()).Count()==1).First().GetValue(param));
        }
    }

one line if statement in php

You can use Ternary operator logic Ternary operator logic is the process of using "(condition)? (true return value) : (false return value)" statements to shorten your if/else structures. i.e

/* most basic usage */
$var = 5;
$var_is_greater_than_two = ($var > 2 ? true : false); // returns true

IF Statement multiple conditions, same statement

I always try to factor out complex boolean expressions into meaningful variables (you could probably think of better names based on what these columns are used for):

bool notColumnsABC = (columnname != a && columnname != b && columnname != c);
bool notColumnA2OrBoxIsChecked = ( columnname != A2 || checkbox.checked );

if (   notColumnsABC 
    && notColumnA2OrBoxIsChecked )
  {
      "statement 1"
  }

https with WCF error: "Could not find base address that matches scheme https"

It turned out that my problem was that I was using a load balancer to handle the SSL, which then sent it over http to the actual server, which then complained.

Description of a fix is here: http://blog.hackedbrain.com/2006/09/26/how-to-ssl-passthrough-with-wcf-or-transportwithmessagecredential-over-plain-http/

Edit: I fixed my problem, which was slightly different, after talking to microsoft support.

My silverlight app had its endpoint address in code going over https to the load balancer. The load balancer then changed the endpoint address to http and to point to the actual server that it was going to. So on each server's web config I added a listenUri for the endpoint that was http instead of https

<endpoint address="" listenUri="http://[LOAD_BALANCER_ADDRESS]" ... />

Parsing a pcap file in python

I would use python-dpkt. Here is the documentation: http://www.commercialventvac.com/dpkt.html

This is all I know how to do though sorry.

#!/usr/local/bin/python2.7

import dpkt

counter=0
ipcounter=0
tcpcounter=0
udpcounter=0

filename='sampledata.pcap'

for ts, pkt in dpkt.pcap.Reader(open(filename,'r')):

    counter+=1
    eth=dpkt.ethernet.Ethernet(pkt) 
    if eth.type!=dpkt.ethernet.ETH_TYPE_IP:
       continue

    ip=eth.data
    ipcounter+=1

    if ip.p==dpkt.ip.IP_PROTO_TCP: 
       tcpcounter+=1

    if ip.p==dpkt.ip.IP_PROTO_UDP:
       udpcounter+=1

print "Total number of packets in the pcap file: ", counter
print "Total number of ip packets: ", ipcounter
print "Total number of tcp packets: ", tcpcounter
print "Total number of udp packets: ", udpcounter

Update:

Project on GitHub, documentation here

What is the difference between Scala's case class and class?

Apart from what people have already said, there are some more basic differences between class and case class

1.Case Class doesn't need explicit new, while class need to be called with new

val classInst = new MyClass(...)  // For classes
val classInst = MyClass(..)       // For case class

2.By Default constructors parameters are private in class , while its public in case class

// For class
class MyClass(x:Int) { }
val classInst = new MyClass(10)

classInst.x   // FAILURE : can't access

// For caseClass
case class MyClass(x:Int) { }
val classInst = MyClass(10)

classInst.x   // SUCCESS

3.case class compare themselves by value

// case Class
class MyClass(x:Int) { }

val classInst = new MyClass(10)
val classInst2 = new MyClass(10)

classInst == classInst2 // FALSE

// For Case Class
case class MyClass(x:Int) { }

val classInst = MyClass(10)
val classInst2 = MyClass(10)

classInst == classInst2 // TRUE

How to align checkboxes and their labels consistently cross-browsers

try this code

input[type="checkbox"] {
    -moz-appearance: checkbox;
    -webkit-appearance: checkbox;
    margin-left:3px;
    border:0;
    vertical-align: middle;
    top: -1px;
    bottom: 1px;
    *overflow: hidden;
    box-sizing: border-box; /* 1 */
    *height: 13px; /* Removes excess padding in IE 7 */
    *width: 13px;
    background: #fff;
}

How to reset radiobuttons in jQuery so that none is checked

<div id="radio">
<input type="radio" id="radio1" name="radio"/><label for="radio1">Bar Chart</label>
<input type="radio" id="radio2" name="radio"/><label for="radio2">Pie Chart</label>
<input type="radio" id="radio3" name="radio"/><label for="radio3">Datapoint Chart</label>
</div>

$('#radio input').removeAttr('checked');
// Refresh the jQuery UI buttonset.                  
$( "#radio" ).buttonset('refresh');

Bash: Strip trailing linebreak from output

One way:

wc -l < log.txt | xargs echo -n

Android Studio Rendering Problems : The following classes could not be found

Please see the following link - here is where I found a solution that worked for me.

Rendering problems in Android Studio v 1.1 / 1.2

Changing the Android Version when rendering layouts worked for me - I flipped it back to 21 and my "Hello World" app then rendered the basic activity_main.xml OK - at 22 I got this error. I borrowed the image from this posting to show you where to click in the Design tab of the XML preview. What is wierd is that when I flip back to 22 the problem is still gone :-).

enter image description here

javascript toISOString() ignores timezone offset

My solution without using moment is to convert it to a timestamp, add the timezone offset, then convert back to a date object, and then run the toISOString()

var date = new Date(); // Or the date you'd like converted.
var isoDateTime = new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString();

Replace whole line containing a string using Sed

To do this without relying on any GNUisms such as -i without a parameter or c without a linebreak:

sed '/TEXT_TO_BE_REPLACED/c\
This line is removed by the admin.
' infile > tmpfile && mv tmpfile infile

In this (POSIX compliant) form of the command

c\
text

text can consist of one or multiple lines, and linebreaks that should become part of the replacement have to be escaped:

c\
line1\
line2
s/x/y/

where s/x/y/ is a new sed command after the pattern space has been replaced by the two lines

line1
line2

Git log out user from command line

On a Mac, credentials are stored in Keychain Access. Look for Github and remove that credential. More info: https://help.github.com/articles/updating-credentials-from-the-osx-keychain/

Downgrade npm to an older version

npm install -g npm@4

This will install the latest version on the major release 4, no no need to specify version number. Replace 4 with whatever major release you want.

Change color of Label in C#

I am going to assume this is a WinForms questions (which it feels like, based on it being a "program" rather than a website/app). In which case you can simple do the following to change the text colour of a label:

myLabel.ForeColor = System.Drawing.Color.Red;

Or any other colour of your choice. If you want to be more specific you can use an RGB value like so:

myLabel.ForeColor = Color.FromArgb(0, 0, 0);//(R, G, B) (0, 0, 0 = black)

Having different colours for different users can be done a number of ways. For example, you could allow each user to specify their own RGB value colours, store these somewhere and then load them when the user "connects".

An alternative method could be to just use 2 colours - 1 for the current user (running the app) and another colour for everyone else. This would help the user quickly identify their own messages above others.

A third approach could be to generate the colour randomly - however you will likely get conflicting values that do not show well against your background, so I would suggest not taking this approach. You could have a pre-defined list of "acceptable" colours and just pop one from that list for each user that joins.

Are complex expressions possible in ng-hide / ng-show?

I generally try to avoid expressions with ng-show and ng-hide as they were designed as booleans, not conditionals. If I need both conditional and boolean logic, I prefer to put in the conditional logic using ng-if as the first check, then add in an additional check for the boolean logic with ng-show and ng-hide

Howerver, if you want to use a conditional for ng-show or ng-hide, here is a link with some examples: Conditional Display using ng-if, ng-show, ng-hide, ng-include, ng-switch

The page cannot be displayed because an internal server error has occurred on server

In my case, setting httpErrors and the like in Web.config did not help to identify the issue.

Instead I did:

  1. Activate "Failed Request Tracing" for the website with the error.
  2. Configured a trace for HTTP errors 350-999 (just in case), although I suspected 500.
  3. Called the erroneous URL again.
  4. Watched in the log folder ("%SystemDrive%\inetpub\logs\FailedReqLogFiles" in my case).
  5. Opened one of the XML files in Internet Explorer.

I then saw an entry with a detailed exception information. In my case it was

\?\C:\Websites\example.com\www\web.config ( 592) :Cannot add duplicate collection entry of type 'mimeMap' with unique key attribute 'fileExtension' set to '.json'

I now was able to resolve it and fix the error. After that I deactivated "Failed Request Tracing" again.

jQuery selector for id starts with specific text

Let me offer a more extensive answer considering things that you haven't mentioned as yet but will find useful.

For your current problem the answer is

$("div[id^='editDialog']");

The caret (^) is taken from regular expressions and means starts with.

Solution 1

// Select elems where 'attribute' ends with 'Dialog'
$("[attribute$='Dialog']"); 

// Selects all divs where attribute is NOT equal to value    
$("div[attribute!='value']"); 

// Select all elements that have an attribute whose value is like
$("[attribute*='value']"); 

// Select all elements that have an attribute whose value has the word foobar
$("[attribute~='foobar']"); 

// Select all elements that have an attribute whose value starts with 'foo' and ends
//  with 'bar'
$("[attribute^='foo'][attribute$='bar']");

attribute in the code above can be changed to any attribute that an element may have, such as href, name, id or src.

Solution 2

Use classes

// Matches all items that have the class 'classname'
$(".className");

// Matches all divs that have the class 'classname'
$("div.className");

Solution 3

List them (also noted in previous answers)

$("#id1,#id2,#id3");

Solution 4

For when you improve, regular expression (Never actually used these, solution one has always been sufficient, but you never know!

// Matches all elements whose id takes the form editDialog-{one_or_more_integers}
$('div').filter(function () {this.id.match(/editDialog\-\d+/)});

How to set Google Chrome in WebDriver

public void setUp() throws Exception {

 System.setProperty("webdriver.chrome.driver","Absolute path of Chrome driver");

 driver =new ChromeDriver();
 baseUrl = "URL/";

    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
  }

Regular Expressions and negating a whole character group

Just search for "ab" in the string then negate the result:

!/ab/.test("bamboo"); // true
!/ab/.test("baobab"); // false

It seems easier and should be faster too.

pandas dataframe groupby datetime month

(update: 2018)

Note that pd.Timegrouper is depreciated and will be removed. Use instead:

 df.groupby(pd.Grouper(freq='M'))

Simple If/Else Razor Syntax

To get rid of the if/else awkwardness you could use a using block:

@{
    var count = 0;
    foreach (var item in Model)
    {
        using(Html.TableRow(new { @class = (count++ % 2 == 0) ? "alt-row" : "" }))
        {
            <td>
                @Html.DisplayFor(modelItem => item.Title)
            </td>
            <td>
                @Html.Truncate(item.Details, 75)
            </td>
            <td>
                <img src="@Url.Content("~/Content/Images/Projects/")@item.Images.Where(i => i.IsMain == true).Select(i => i.Name).Single()" 
                    alt="@item.Images.Where(i => i.IsMain == true).Select(i => i.AltText).Single()" class="thumb" />
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id=item.ProjectId }) |
                @Html.ActionLink("Details", "Details", new { id = item.ProjectId }) |
                @Html.ActionLink("Delete", "Delete", new { id=item.ProjectId })
            </td>
        }
    }
}

Reusable element that make it easier to add attributes:

//Block is take from http://www.codeducky.org/razor-trick-using-block/
public class TableRow : Block
{
    private object _htmlAttributes;
    private TagBuilder _tr;

    public TableRow(HtmlHelper htmlHelper, object htmlAttributes) : base(htmlHelper)
    {
        _htmlAttributes = htmlAttributes;
    }

    public override void BeginBlock()
    {
        _tr = new TagBuilder("tr");
        _tr.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(_htmlAttributes));
        this.HtmlHelper.ViewContext.Writer.Write(_tr.ToString(TagRenderMode.StartTag));
    }

    protected override void EndBlock()
    {
        this.HtmlHelper.ViewContext.Writer.Write(_tr.ToString(TagRenderMode.EndTag));
    }
}

Helper method to make razor syntax clearer:

public static TableRow TableRow(this HtmlHelper self, object htmlAttributes)
{
    var tableRow = new TableRow(self, htmlAttributes);
    tableRow.BeginBlock();
    return tableRow;
}

Moq, SetupGet, Mocking a property

ColumnNames is a property of type List<String> so when you are setting up you need to pass a List<String> in the Returns call as an argument (or a func which return a List<String>)

But with this line you are trying to return just a string

input.SetupGet(x => x.ColumnNames).Returns(temp[0]);

which is causing the exception.

Change it to return whole list:

input.SetupGet(x => x.ColumnNames).Returns(temp);

Getting "Cannot call a class as a function" in my React Project

I received this error by making small mistake. My error was exporting the class as a function instead of as a class. At the bottom of my class file I had:

export default InputField();

when it should have been:

export default InputField;

How to print variables without spaces between values

>>> value=42

>>> print "Value is %s"%('"'+str(value)+'"') 

Value is "42"

How to output git log with the first line only?

You can define a global alias so you can invoke a short log in a more comfortable way:

git config --global alias.slog "log --pretty=oneline --abbrev-commit"

Then you can call it using git slog (it even works with autocompletion if you have it enabled).

What's the whole point of "localhost", hosts and ports at all?

Port: In simple language, "Port" is a number used by a particular software to identify its data coming from internet.

Each software, like Skype, Chrome, Youtube has its own port number and that's how they know which internet data is for itself.

Socket: "IP address and Port " together is called "Socket". It is used by another computer to send data to one particular computer's particular software.

IP address is used to identify the computer and Port is to identify the software such as IE, Chrome, Skype etc.

In every home, there is one mailbox and multiple people. The mailbox is a host. Your own home mailbox is a localhost. Each person in a home has a room. All letters for that person are sent to his room, hence the room number is a port.

Adding custom radio buttons in android

Best way to add custom drawable is:

<RadioButton
    android:id="@+id/radiocar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:background="@android:color/transparent"
    android:button="@drawable/yourbuttonbackground"
    android:checked="true"
    android:drawableRight="@mipmap/car"
    android:paddingLeft="5dp"
    android:paddingRight="5dp"
    android:text="yourtexthere"/>

Shadow overlay by custom drawable is removed here.

Android Push Notifications: Icon not displaying in notification, white square shown instead

You can use different icon for different versions. Simply set logic on your icon like this:

int icon = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? R.drawable.colored_: R.drawable.white_tint_icon_for_lolipop_or_upper;

Unable to connect PostgreSQL to remote database using pgAdmin

I didn't have to change my prostgresql.conf file but, i did have to do the following based on my psql via command line was connecting and pgAdmin not connecting on RDS with AWS.

I did have my RDS set to Publicly Accessible. I made sure my ACL and security groups were wide open and still problem so, I did the following: sudo find . -name *.conf then sudo nano ./data/pg_hba.conf then added to top of directives in pg_hba.conf file host all all 0.0.0.0/0 md5 and pgAdmin automatically logged me in.

This also worked in pg_hba.conf file host all all md5 without any IP address and this also worked with my IP address host all all <myip>/32 md5

As a side note, my RDS was in my default VPC. I had an identical RDS instance in my non-default VPC with identical security group, ACL and security group settings to my default VPC and I could not get it to work. Not sure why but, that's for another day.

How to dynamically allocate memory space for a string and get that string from user?

First, define a new function to read the input (according to the structure of your input) and store the string, which means the memory in stack used. Set the length of string to be enough for your input.

Second, use strlen to measure the exact used length of string stored before, and malloc to allocate memory in heap, whose length is defined by strlen. The code is shown below.

int strLength = strlen(strInStack);
if (strLength == 0) {
    printf("\"strInStack\" is empty.\n");
}
else {
    char *strInHeap = (char *)malloc((strLength+1) * sizeof(char));
    strcpy(strInHeap, strInStack);
}
return strInHeap;

Finally, copy the value of strInStack to strInHeap using strcpy, and return the pointer to strInHeap. The strInStack will be freed automatically because it only exits in this sub-function.

Which ORM should I use for Node.js and MySQL?

First off, please note that I haven't used either of them (but have used Node.js).

Both libraries are documented quite well and have a stable API. However, persistence.js seems to be used in more projects. I don't know if all of them still use it, though.

The developer of sequelize sometimes blogs about it at blog.depold.com. When you'd like to use primary keys as foreign keys, you'll need the patch that's described in this blog post. If you'd like help for persistence.js there is a google group devoted to it.

From the examples I gather that sequelize is a bit more JavaScript-like (more sugar) than persistance.js but has support for fewer datastores (only MySQL, while persistance.js can even use in-browser stores).

I think that sequelize might be the way to go for you, as you only need MySQL support. However, if you need some convenient features (for instance search) or want to use a different database later on you'd need to use persistence.js.

IF formula to compare a date with current date and return result

You can enter the following formula in the cell where you want to see the Overdue or Not due result:

=IF(ISBLANK(O10),"",IF(O10<TODAY(),"Overdue","Not due"))

This formula first tests if the source cell is blank. If it is, then the result cell will be filled with the empty string. If the source is not blank, then the formula tests if the date in the source cell is before the current day. If it is, then the value is set to Overdue, otherwise it is set to Not due.

How to check if bootstrap modal is open, so I can use jquery validate?

Bootstrap 2 , 3 Check is any modal open in page :

if($('.modal.in').length)

compatible version Bootstrap 2 , 3 , 4+

if($('.modal.in, .modal.show').length)

Only Bootstrap 4+

if($('.modal.show').length)

How to make a custom LinkedIn share button

You can make your own sharing button using the LinkedIn ShareArticle URL, which can have the following parameters:

https://www.linkedin.com/shareArticle?mini=true&url={articleUrl}&title={articleTitle}&summary={articleSummary}&source={articleSource}

You can find the documentation here, just choose "Customized URL" to see the details.

When to use 'npm start' and when to use 'ng serve'?

There are more than that. The executed executables are different.

npm run start

will run your projects local executable which is located in your node_modules/.bin.

ng serve

will run another executable which is global.

It means if you clone and install an Angular project which is created with angular-cli version 5 and your global cli version is 7, then you may have problems with ng build.

Laravel migration default value

Might be a little too late to the party, but hope this helps someone with similar issue.

The reason why your default value doesnt't work is because the migration file sets up the default value in your database (MySQL or PostgreSQL or whatever), and not in your Laravel application.

Let me illustrate with an example.

This line means Laravel is generating a new Book instance, as specified in your model. The new Book object will have properties according to the table associated with the model. Up until this point, nothing is written on the database.

$book = new Book();

Now the following lines are setting up the values of each property of the Book object. Same still, nothing is written on the database yet.

$book->author = 'Test'
$book->title = 'Test'

This line is the one writing to the database. After passing on the object to the database, then the empty fields will be filled by the database (may be default value, may be null, or whatever you specify on your migration file).

$book->save();

And thus, the default value will not pop up before you save it to the database.

But, that is not enough. If you try to access $book->price, it will still be null (or 0, i'm not sure). Saving it is only adding the defaults to the record in the database, and it won't affect the Object you are carrying around.

So, to get the instance with filled-in default values, you have to re-fetch the instance. You may use the

Book::find($book->id);

Or, a more sophisticated way by refreshing the instance

$book->refresh();

And then, the next time you try to access the object, it will be filled with the default values.

$("#form1").validate is not a function

youll need to use the latest http://ajax.microsoft.com/ajax/jquery.validate/1.5.5/jquery.validate.js in conjunction with one of the Microsoft's CDN for getting your validation file.

How to execute two mysql queries as one in PHP/MYSQL?

It says on the PHP site that multiple queries are NOT permitted (EDIT: This is only true for the mysql extension. mysqli and PDO allow multiple queries) . So you can't do it in PHP, BUT, why can't you just execute that query in another mysql_query call, (like Jon's example)? It should still give you the correct result if you use the same connection. Also, mysql_num_rows may help also.

Referring to a Column Alias in a WHERE Clause

You could refer to column alias but you need to define it using CROSS/OUTER APPLY:

SELECT s.logcount, s.logUserID, s.maxlogtm, c.daysdiff
FROM statslogsummary s
CROSS APPLY (SELECT DATEDIFF(day, s.maxlogtm, GETDATE()) AS daysdiff) c
WHERE c.daysdiff > 120;

DBFiddle Demo

Pros:

  • single definition of expression(easier to maintain/no need of copying-paste)
  • no need for wrapping entire query with CTE/outerquery
  • possibility to refer in WHERE/GROUP BY/ORDER BY
  • possible better performance(single execution)

Show dialog from fragment?

You should use a DialogFragment instead.

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

It is good practice when you start creating website to reset all the margins and paddings. So I recommend on start just to simple do:

* { margin: 0, padding: 0 }

This will make margins and paddings of all elements to be 0, and then you can style them as you wish, because each browser has a different default margin and padding of the elements.