Programs & Examples On #Getwindowlong

Format an Excel column (or cell) as Text in C#?

   if (dtCustomers.Columns[j - 1].DataType != typeof(decimal) && dtCustomers.Columns[j - 1].DataType != typeof(int))
   {
      myWorksheet.Cells[i + 2, j].NumberFormat = "@";
   }

Xcode/Simulator: How to run older iOS version?

To add previous iOS simulator to Xcode 4.2, you need old xcode_3.2.6_and_ios_sdk_4.3.dmg (or similar version) installer file and do as following:

  • Mount the xcode_3.2.6_and_ios_sdk_4.3.dmg file
  • Open mounting disk image and choose menu: Go->Go to Folder...
  • Type /Volumes/Xcode and iOS SDK/Packages/ then click Go. There are many packages and find to iPhoneSimulatorSDK(version).pkg
  • Double click to install package you want to add and wait for installer displays.
  • In Installer click Continue and choose destination, Choose folder...
  • Explorer shows and select Developer folder and click Choose
  • Install and repeat with other simulator as you need.
  • Restart Xcode.

Now there are a list of your installed simulator.

How can I create a Windows .exe (standalone executable) using Java/Eclipse?

Java doesn't natively allow building of an exe, that would defeat its purpose of being cross-platform.

AFAIK, these are your options:

  1. Make a runnable JAR. If the system supports it and is configured appropriately, in a GUI, double clicking the JAR will launch the app. Another option would be to write a launcher shell script/batch file which will start your JAR with the appropriate parameters

  2. There also executable wrappers - see How can I convert my Java program to an .exe file?

See also: Convert Java to EXE: Why, When, When Not and How

ORA-12528: TNS Listener: all appropriate instances are blocking new connections. Instance "CLRExtProc", status UNKNOWN

You have to know if the problem come from the listener or from the database.

  • So first, restart the listener, it could solve the problem.

  • Second, it could come from the db if it's not in open mode (nomount, mount, restrict). To check it, connect locally and do the following query:

    sqlplus /nolog

    connect / as sysdba

    SQL> select instance_name, status, database_status from v$instance;

how do you view macro code in access?

You can try the following VBA code to export Macro contents directly without converting them to VBA first. Unlike Tables, Forms, Reports, and Modules, the Macros are in a container called Scripts. But they are there and can be exported and imported using SaveAsText and LoadFromText

Option Compare Database

Option Explicit

Public Sub ExportDatabaseObjects()
On Error GoTo Err_ExportDatabaseObjects

    Dim db As Database
    Dim d As Document
    Dim c As Container
    Dim sExportLocation As String

    Set db = CurrentDb()

    sExportLocation = "C:\SomeFolder\"
    Set c = db.Containers("Scripts")
    For Each d In c.Documents
        Application.SaveAsText acMacro, d.Name, sExportLocation & "Macro_" & d.Name & ".txt"
    Next d

An alternative object to use is as follows:

  For Each obj In Access.Application.CurrentProject.AllMacros
    Access.Application.SaveAsText acMacro, obj.Name, strFilePath & "\Macro_" & obj.Name & ".txt"
  Next

ReactJS - Get Height of an element

You would also want to use refs on the element instead of using document.getElementById, it's just a slightly more robust thing.

Javascript array search and remove string?

use array.splice

/*array.splice(index , howMany[, element1[, ...[, elementN]]])

array.splice(index) // SpiderMonkey/Firefox extension*/

array.splice(1,1)

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

How to compare only date in moment.js

Meanwhile you can use the isSameOrAfter method:

moment('2010-10-20').isSameOrAfter('2010-10-20', 'day');

Docs: https://momentjs.com/docs/#/query/is-same-or-after/

jQuery: how to trigger anchor link's click event

It worked for me:

     window.location = $('#myanchor').attr('href');

How to use default Android drawables

To use the default android drawable resource, no need copy anything.. you can just import it first with..

import android.R;

but i will make your own resources will have an error if you want to use it. The error will be something like:

R. cannot be resolved

So, I prefer not to import android.R but import *my.own.package*.R;

then when I can normally use my own resource with R.drawable.*something* without error, and put android.R.*something_default* to use the default android resources.

How do I make a WPF TextBlock show my text on multiple lines?

Nesting a stackpanel will cause the textbox to wrap properly:

<Viewbox Margin="120,0,120,0">
    <StackPanel Orientation="Vertical" Width="400">
        <TextBlock x:Name="subHeaderText" 
                   FontSize="20" 
                   TextWrapping="Wrap" 
                   Foreground="Black"
                   Text="Lorem ipsum dolor, lorem isum dolor,Lorem ipsum dolor sit amet, lorem ipsum dolor sit amet " />
    </StackPanel>
</Viewbox>

Neither BindingResult nor plain target object for bean name available as request attribute

If you have Model or transfer object passed to GET method but still have this error, check naming of your variables. Use entity/transfer object names in camelcase. I had BusinessTripDTO object and named it 'trip' for short. It caused this error to occure, even I had all other parts in place. Renaming varaibles to businessTripDTO in Java and Thymeleaf solved this problem for me.

Android Studio Gradle Configuration with name 'default' not found

I had a git submodule problem when getting this error. Try running gradle tasks --info for a more detailed problem description. I first used gradle tasks --debug, which was not nearly as helpful as --info.

jQuery Validation plugin: disable validation for specified submit buttons

I have two button for form submission, button named save and exit bypasses the validation :

$('.save_exist').on('click', function (event) {
            $('#MyformID').removeData('validator');
            $('.form-control').removeClass('error');
            $('.form-control').removeClass('required');                
            $("#loanApplication").validate().cancelSubmit = true;
            $('#loanApplication').submit();
            event.preventDefault();
});

Floating point exception

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

http://en.wikipedia.org/wiki/Unix_signal#SIGFPE

This should give you a really good idea. Since a modulus is, in its basic sense, division with a remainder, something % 0 IS division by zero and as such, will trigger a SIGFPE being thrown.

typedef fixed length array

Arrays can't be passed as function parameters by value in C.

You can put the array in a struct:

typedef struct type24 {
    char byte[3];
} type24;

and then pass that by value, but of course then it's less convenient to use: x.byte[0] instead of x[0].

Your function type24_to_int32(char value[3]) actually passes by pointer, not by value. It's exactly equivalent to type24_to_int32(char *value), and the 3 is ignored.

If you're happy passing by pointer, you could stick with the array and do:

type24_to_int32(const type24 *value);

This will pass a pointer-to-array, not pointer-to-first-element, so you use it as:

(*value)[0]

I'm not sure that's really a gain, since if you accidentally write value[1] then something stupid happens.

How to find the path of Flutter SDK

All you need to do is to find a folder called "flutter" (lowecase), which is located inside a folder called "Flutter" (uppercase), select it, and browse it.

In my case it is located at:

C:\Users\Administrator\Flutter\flutter_windows_v1.12.13+hotfix.5-stable\flutter

enter image description here

Also make sure that your Flutter and Dart are of the latest version. If they are not, upgrade them and re-start the IDE.

Show/hide widgets in Flutter programmatically

Try the Offstage widget

if attribute offstage:true the not occupy the physical space and invisible,

if attribute offstage:false it will occupy the physical space and visible

Offstage(
   offstage: true,
   child: Text("Visible"),
),

Create a button programmatically and set a background image

Your code should look like below

let image = UIImage(named: "name") as UIImage?
let button   = UIButton(type: UIButtonType.Custom) as UIButton
button.frame = CGRectMake(100, 100, 100, 100)
button.setImage(image, forState: .Normal)
button.addTarget(self, action: "btnTouched:", forControlEvents:.TouchUpInside)
self.view.addSubview(button)

Entity Framework Query for inner join

In case anyone's interested in the Method syntax, if you have a navigation property, it's way easy:

db.Services.Where(s=>s.ServiceAssignment.LocationId == 1);

If you don't, unless there's some Join() override I'm unaware of, I think it looks pretty gnarly (and I'm a Method syntax purist):

db.Services.Join(db.ServiceAssignments, 
     s => s.Id,
     sa => sa.ServiceId, 
     (s, sa) => new {service = s, asgnmt = sa})
.Where(ssa => ssa.asgnmt.LocationId == 1)
.Select(ssa => ssa.service);

I am receiving warning in Facebook Application using PHP SDK

You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start(). The headers will be sent automatically when any HTML is output.

Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.

Move the session_start() to the top of your document :

<?php    session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php';    // more PHP code here. 

RegEx to exclude a specific string constant

You have to use a negative lookahead assertion.

(?!^ABC$)

You could for example use the following.

(?!^ABC$)(^.*$)

If this does not work in your editor, try this. It is tested to work in ruby and javascript:

^((?!ABC).)*$

'invalid value encountered in double_scalars' warning, possibly numpy

Zero-size array passed to numpy.mean raises this warning (as indicated in several comments).

For some other candidates:

  • median also raises this warning on zero-sized array.

other candidates do not raise this warning:

  • min,argmin both raise ValueError on empty array
  • randn takes *arg; using randn(*[]) returns a single random number
  • std,var return nan on an empty array

Statically rotate font-awesome icons

New Font-Awesome v5 has Power Transforms

You can rotate any icon by adding attribute data-fa-transform to icon

<i class="fas fa-magic" data-fa-transform="rotate-45"></i>

Here is a fiddle

For more information, check this out : Font-Awesome5 Power Tranforms

Set android shape color programmatically

Nothing work for me but when i set tint color it works on Shape Drawable

 Drawable background = imageView.getBackground();
 background.setTint(getRandomColor())

require android 5.0 API 21

How to JSON serialize sets?

If you need just quick dump and don't want to implement custom encoder. You can use the following:

json_string = json.dumps(data, iterable_as_array=True)

This will convert all sets (and other iterables) into arrays. Just beware that those fields will stay arrays when you parse the json back. If you want to preserve the types, you need to write custom encoder.

Create own colormap using matplotlib and plot color scale

If you want to automate the creating of a custom divergent colormap commonly used for surface plots, this module combined with @unutbu method worked well for me.

def diverge_map(high=(0.565, 0.392, 0.173), low=(0.094, 0.310, 0.635)):
    '''
    low and high are colors that will be used for the two
    ends of the spectrum. they can be either color strings
    or rgb color tuples
    '''
    c = mcolors.ColorConverter().to_rgb
    if isinstance(low, basestring): low = c(low)
    if isinstance(high, basestring): high = c(high)
    return make_colormap([low, c('white'), 0.5, c('white'), high])

The high and low values can be either string color names or rgb tuples. This is the result using the surface plot demo: enter image description here

Deleting DataFrame row in Pandas based on column value

I compiled and run my code. This is accurate code. You can try it your own.

data = pd.read_excel('file.xlsx')

If you have any special character or space in column name you can write it in '' like in the given code:

data = data[data['expire/t'].notnull()]
print (date)

If there is just a single string column name without any space or special character you can directly access it.

data = data[data.expire ! = 0]
print (date)

How to allow users to check for the latest app version from inside the app?

I know the OP was very old, at that time in-app-update was not available. But from API 21, you can use in-app-update checking. You may need to keep your eyes on some points which are nicely written up here:

Convert a timedelta to days, hours and minutes

timedeltas have a days and seconds attribute .. you can convert them yourself with ease.

How to find the path of the local git repository when I am possibly in a subdirectory

git rev-parse --show-toplevel

could be enough if executed within a git repo.
From git rev-parse man page:

--show-toplevel

Show the absolute path of the top-level directory.

For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

git rev-parse --git-dir

That would give the path of the .git directory.


The OP mentions:

git rev-parse --show-prefix

which returns the local path under the git repo root. (empty if you are at the git repo root)


Note: for simply checking if one is in a git repo, I find the following command quite expressive:

git rev-parse --is-inside-work-tree

And yes, if you need to check if you are in a .git git-dir folder:

git rev-parse --is-inside-git-dir

Why does ASP.NET webforms need the Runat="Server" attribute?

Microsoft Msdn article The Forgotten Controls: HTML Server Controls explains use of runat="server" with an example on text box <input type="text"> by converting it to <input type="text" id="Textbox1" runat="server">

Doing this will give you programmatic access to the HTML element on the server before the Web page is created and sent down to the client. The HTML element must contain an id attribute. This attribute serves as an identity for the element and enables you to program to elements by their specific IDs. In addition to this attribute, the HTML element must contain runat="server". This tells the processing server that the tag is processed on the server and is not to be considered a traditional HTML element.

In short, to enable programmatic access to the HTML element add runat="server" to it.

What is logits, softmax and softmax_cross_entropy_with_logits?

Whatever goes to softmax is logit, this is what J. Hinton repeats in coursera videos all the time.

How to get Bitmap from an Uri?

Here's the correct way of doing it:

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK)
    {
        Uri imageUri = data.getData();
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
    }
}

If you need to load very large images, the following code will load it in in tiles (avoiding large memory allocations):

BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(myStream, false);  
Bitmap region = decoder.decodeRegion(new Rect(10, 10, 50, 50), null);

See the answer here

PHP get dropdown value and text

Is there a reason you didn't just use this?

<select id="animal" name="animal">                      
  <option value="0">--Select Animal--</option>
  <option value="Cat">Cat</option>
  <option value="Dog">Dog</option>
  <option value="Cow">Cow</option>
</select>

if($_POST['submit'] && $_POST['submit'] != 0)
{
   $animal=$_POST['animal'];
}

HTML img tag: title attribute vs. alt attribute?

They are used for different things. The alt attribute is used instead of the image. If the image can't be shown, and in screen readers.

The title attribute is shown along with the image, typically as a hover tooltip.

One should not be used "instead" of the other. Each should be used properly, to do the things they were designed to do.

What are public, private and protected in object oriented programming?

They are access modifiers and help us implement Encapsulation (or information hiding). They tell the compiler which other classes should have access to the field or method being defined.

private - Only the current class will have access to the field or method.

protected - Only the current class and subclasses (and sometimes also same-package classes) of this class will have access to the field or method.

public - Any class can refer to the field or call the method.

This assumes these keywords are used as part of a field or method declaration within a class definition.

Git merge master into feature branch

Zimi's answer describes this process generally. Here are the specifics:

  1. Create and switch to a new branch. Make sure the new branch is based on master so it will include the recent hotfixes.

    git checkout master
    git branch feature1_new
    git checkout feature1_new
    
    # Or, combined into one command:
    git checkout -b feature1_new master
    
  2. After switching to the new branch, merge the changes from your existing feature branch. This will add your commits without duplicating the hotfix commits.

    git merge feature1
    
  3. On the new branch, resolve any conflicts between your feature and the master branch.

Done! Now use the new branch to continue to develop your feature.

How to parse a CSV file in Bash?

You need to use IFS instead of -d:

while IFS=, read -r col1 col2
do
    echo "I got:$col1|$col2"
done < myfile.csv

Note that for general purpose CSV parsing you should use a specialized tool which can handle quoted fields with internal commas, among other issues that Bash can't handle by itself. Examples of such tools are cvstool and csvkit.

Error message: "'chromedriver' executable needs to be available in the path"

If you are using remote interpreter you have to also check if its executable PATH is defined. In my case switching from remote Docker interpreter to local interpreter solved the problem.

How do I connect to mongodb with node.js (and authenticate)?

Here is new may to authenticate from "admin" and then switch to your desired DB for further operations:

   var MongoClient = require('mongodb').MongoClient;
var Db = require('mongodb').Db, Server = require('mongodb').Server ,
    assert = require('assert');

var user = 'user';
var password = 'password';

MongoClient.connect('mongodb://'+user+':'+password+'@localhost:27017/opsdb',{native_parser:true, authSource:'admin'}, function(err,db){
    if(err){
        console.log("Auth Failed");
        return;
    }
    console.log("Connected");
    db.collection("cols").find({loc:{ $eq: null } }, function(err, docs) {
        docs.each(function(err, doc) {
          if(doc) {
            console.log(doc['_id']);
          }
        });
    });

    db.close();

}); 

How to add a single item to a Pandas Series

  • ser1 = pd.Sereis(np.linspace(1, 10, 2))
  • element = np.nan
  • ser1 = ser1.append(pd.Series(element))

After MySQL install via Brew, I get the error - The server quit without updating PID file

None of the answers worked for me. However, I simply did sudo mysql.server start and it worked nicely.

Also, for me, it did NOT show permissions issue in *.err file.

Extracting double-digit months and days from a Python date

Look at the types of those properties:

In [1]: import datetime

In [2]: d = datetime.date.today()

In [3]: type(d.month)
Out[3]: <type 'int'>

In [4]: type(d.day)
Out[4]: <type 'int'>

Both are integers. So there is no automatic way to do what you want. So in the narrow sense, the answer to your question is no.

If you want leading zeroes, you'll have to format them one way or another. For that you have several options:

In [5]: '{:02d}'.format(d.month)
Out[5]: '03'

In [6]: '%02d' % d.month
Out[6]: '03'

In [7]: d.strftime('%m')
Out[7]: '03'

In [8]: f'{d.month:02d}'
Out[8]: '03'

Android Studio - debug keystore

It is at the same location: ~/.android/debug.keystore

How to connect to MongoDB in Windows?

The error occurs when trying to run mongo.exe WITHOUT having executed mongod.exe. The following batch script solved the problem:

@echo off
cd C:\mongodb\bin\
start mongod.exe
start mongo.exe
exit

How can I generate Javadoc comments in Eclipse?

You mean menu Project -> Generate Javadoc ?

Could not resolve this reference. Could not locate the assembly

This confused me for a while until I worked out that the dependencies of the various projects in the solution had been messed up. Get that straight and naturally your assembly appears in the right place.

How to install requests module in Python 3.4, instead of 2.7

while installing python packages in a global environment is doable, it is a best practice to isolate the environment between projects (creating virtual environments). Otherwise, confusion between Python versions will arise, just like your problem.

The simplest method is to use venv library in the project directory:

python3 -m venv venv

Where the first venv is to call the venv package, and the second venv defines the virtual environment directory name. Then activate the virtual environment:

source venv/bin/activate

Once the virtual environment has been activated, your pip install ... commands would not be interfered with any other Python version or pip version anymore. For installing requests:

pip install requests

Another benefit of the virtual environment is to have a concise list of libraries needed for that specific project.

*note: commands only work on Linux and Mac OS

RuntimeWarning: invalid value encountered in divide

I think your code is trying to "divide by zero" or "divide by NaN". If you are aware of that and don't want it to bother you, then you can try:

import numpy as np
np.seterr(divide='ignore', invalid='ignore')

For more details see:

400 BAD request HTTP error code meaning?

Using 400 status codes for any other purpose than indicating that the request is malformed is just plain wrong.

If the request payload contains a byte-sequence that could not be parsed as application/json (if the server expects that dataformat), the appropriate status code is 415:

The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.

If the request payload is syntactically correct but semantically incorrect, the non-standard 422 response code may be used, or the standard 403 status code:

The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated.

Find duplicate values in R

This will give you duplicate rows:

vocabulary[duplicated(vocabulary$id),]

This will give you the number of duplicates:

dim(vocabulary[duplicated(vocabulary$id),])[1]

Example:

vocabulary2 <-rbind(vocabulary,vocabulary[1,]) #creates a duplicate at the end
vocabulary2[duplicated(vocabulary2$id),]
#            id year    sex education vocabulary
#21639 20040001 2004 Female         9          3
dim(vocabulary2[duplicated(vocabulary2$id),])[1]
#[1] 1 #=1 duplicate

EDIT

OK, with the additional information, here's what you should do: duplicated has a fromLast option which allows you to get duplicates from the end. If you combine this with the normal duplicated, you get all duplicates. The following example adds duplicates to the original vocabulary object (line 1 is duplicated twice and line 5 is duplicated once). I then use table to get the total number of duplicates per ID.

#Create vocabulary object with duplicates
voc.dups <-rbind(vocabulary,vocabulary[1,],vocabulary[1,],vocabulary[5,])

#List duplicates
dups <-voc.dups[duplicated(voc.dups$id)|duplicated(voc.dups$id, fromLast=TRUE),]
dups
#            id year    sex education vocabulary
#1     20040001 2004 Female         9          3
#5     20040008 2004   Male        14          1
#21639 20040001 2004 Female         9          3
#21640 20040001 2004 Female         9          3
#51000 20040008 2004   Male        14          1

#Count duplicates by id
table(dups$id)
#20040001 20040008 
#       3        2 

How to decompile a whole Jar file?

Note: This solution only works for Mac and *nix users.

I also tried to find Jad with no luck. My quick solution was to download MacJad that contains jad. Once you downloaded it you can find jad in [where-you-downloaded-macjad]/MacJAD/Contents/Resources/jad.

How can I take a screenshot with Selenium WebDriver?

Python

You can capture the image from windows using the Python web driver. Use the code below which page need to capture the screenshot.

driver.save_screenshot('c:\foldername\filename.extension(png, jpeg)')

SCRIPT5: Access is denied in IE9 on xmlhttprequest

This example illustrate how to use AJAX to pull resourcess from any website. it works across browsers. i have tested it on IE8-IE10, safari, chrome, firefox, opera.

if (window.XDomainRequest) xmlhttp = new XDomainRequest();
else if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

xmlhttp.open("GET", "http://api.hostip.info/get_html.php", false);
xmlhttp.send();

hostipInfo = xmlhttp.responseText.split("\n");
var IP = false;
for (i = 0; hostipInfo.length >= i; i++) {
    if (hostipInfo[i]) {

        ipAddress = hostipInfo[i].split(":");
        if (ipAddress[0] == "IP") {
            IP = ipAddress[1];
        }
    }
}
return IP;

Android textview outline text

credit to @YGHM add shadow support enter image description here

package com.megvii.demo;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;

public class TextViewOutline extends android.support.v7.widget.AppCompatTextView {

// constants
private static final int DEFAULT_OUTLINE_SIZE = 0;
private static final int DEFAULT_OUTLINE_COLOR = Color.TRANSPARENT;

// data
private int mOutlineSize;
private int mOutlineColor;
private int mTextColor;
private float mShadowRadius;
private float mShadowDx;
private float mShadowDy;
private int mShadowColor;

public TextViewOutline(Context context) {
    this(context, null);
}

public TextViewOutline(Context context, AttributeSet attrs) {
    super(context, attrs);
    setAttributes(attrs);
}

private void setAttributes(AttributeSet attrs) {
    // set defaults
    mOutlineSize = DEFAULT_OUTLINE_SIZE;
    mOutlineColor = DEFAULT_OUTLINE_COLOR;
    // text color   
    mTextColor = getCurrentTextColor();
    if (attrs != null) {
        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.TextViewOutline);
        // outline size
        if (a.hasValue(R.styleable.TextViewOutline_outlineSize)) {
            mOutlineSize = (int) a.getDimension(R.styleable.TextViewOutline_outlineSize, DEFAULT_OUTLINE_SIZE);
        }
        // outline color
        if (a.hasValue(R.styleable.TextViewOutline_outlineColor)) {
            mOutlineColor = a.getColor(R.styleable.TextViewOutline_outlineColor, DEFAULT_OUTLINE_COLOR);
        }
        // shadow (the reason we take shadow from attributes is because we use API level 15 and only from 16 we have the get methods for the shadow attributes)
        if (a.hasValue(R.styleable.TextViewOutline_android_shadowRadius)
                || a.hasValue(R.styleable.TextViewOutline_android_shadowDx)
                || a.hasValue(R.styleable.TextViewOutline_android_shadowDy)
                || a.hasValue(R.styleable.TextViewOutline_android_shadowColor)) {
            mShadowRadius = a.getFloat(R.styleable.TextViewOutline_android_shadowRadius, 0);
            mShadowDx = a.getFloat(R.styleable.TextViewOutline_android_shadowDx, 0);
            mShadowDy = a.getFloat(R.styleable.TextViewOutline_android_shadowDy, 0);
            mShadowColor = a.getColor(R.styleable.TextViewOutline_android_shadowColor, Color.TRANSPARENT);
        }

        a.recycle();
    }

}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setPaintToOutline();
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

private void setPaintToOutline() {
    Paint paint = getPaint();
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeWidth(mOutlineSize);
    super.setTextColor(mOutlineColor);
    super.setShadowLayer(0, 0, 0, Color.TRANSPARENT);

}

private void setPaintToRegular() {
    Paint paint = getPaint();
    paint.setStyle(Paint.Style.FILL);
    paint.setStrokeWidth(0);
    super.setTextColor(mTextColor);
    super.setShadowLayer(mShadowRadius, mShadowDx, mShadowDy, mShadowColor);
}


@Override
public void setTextColor(int color) {
    super.setTextColor(color);
    mTextColor = color;
}


public void setOutlineSize(int size) {
    mOutlineSize = size;
}

public void setOutlineColor(int color) {
    mOutlineColor = color;
}

@Override
protected void onDraw(Canvas canvas) {
    setPaintToOutline();
    super.onDraw(canvas);

    setPaintToRegular();
    super.onDraw(canvas);
}

}

attr define

<declare-styleable name="TextViewOutline">
    <attr name="outlineSize" format="dimension"/>
    <attr name="outlineColor" format="color|reference"/>
    <attr name="android:shadowRadius"/>
    <attr name="android:shadowDx"/>
    <attr name="android:shadowDy"/>
    <attr name="android:shadowColor"/>
</declare-styleable>

xml code below

<com.megvii.demo.TextViewOutline
    android:id="@+id/product_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="110dp"
    android:background="#f4b222"
    android:fontFamily="@font/kidsmagazine"
    android:padding="10dp"
    android:shadowColor="#d7713200"
    android:shadowDx="0"
    android:shadowDy="8"
    android:shadowRadius="1"
    android:text="LIPSTICK SET"
    android:textColor="@android:color/white"
    android:textSize="30sp"
    app:outlineColor="#cb7800"
    app:outlineSize="3dp" />

CakePHP 3.0 installation: intl extension missing from system

If you are using latest version Ubuntu 16.04 or later just do

sudo apt-get install php-intl

Then restart your apache

sudo service apache2 restart

Inserting records into a MySQL table using Java

There is a mistake in your insert statement chage it to below and try : String sql = "insert into table_name values ('" + Col1 +"','" + Col2 + "','" + Col3 + "')";

Sass calculate percent minus px

There is a calc function in both SCSS [compile-time] and CSS [run-time]. You're likely invoking the former instead of the latter.

For obvious reasons mixing units won't work compile-time, but will at run-time.

You can force the latter by using unquote, a SCSS function.

.selector { height: unquote("-webkit-calc(100% - 40px)"); }

The total number of locks exceeds the lock table size

This answer below does not directly answer the OP's question. However, I'm adding this answer here because this page is the first result when you Google "The total number of locks exceeds the lock table size".


If the query you are running is parsing an entire table that spans millions of rows, you can try a while loop instead of changing limits in the configuration.

The while look will break it into pieces. Below is an example looping over an indexed column that is DATETIME.

# Drop
DROP TABLE IF EXISTS
new_table;

# Create (we will add keys later)
CREATE TABLE
new_table
(
    num INT(11),
    row_id VARCHAR(255),
    row_value VARCHAR(255),
    row_date DATETIME
);

# Change the delimimter
DELIMITER //

# Create procedure
CREATE PROCEDURE do_repeat(IN current_loop_date DATETIME)
BEGIN

    # Loops WEEK by WEEK until NOW(). Change WEEK to something shorter like DAY if you still get the lock errors like.
    WHILE current_loop_date <= NOW() DO

        # Do something
        INSERT INTO
            user_behavior_search_tagged_keyword_statistics_with_type
            (
                num,
                row_id,
                row_value,
                row_date
            )
        SELECT
            # Do something interesting here
            num,
            row_id,
            row_value,
            row_date
        FROM
            old_table
        WHERE
            row_date >= current_loop_date AND
            row_date < current_loop_date + INTERVAL 1 WEEK;

        # Increment
        SET current_loop_date = current_loop_date + INTERVAL 1 WEEK;

    END WHILE;

END//

# Run
CALL do_repeat('2017-01-01');

# Cleanup
DROP PROCEDURE IF EXISTS do_repeat//

# Change the delimimter back
DELIMITER ;

# Add keys
ALTER TABLE
    new_table
MODIFY COLUMN
    num int(11) NOT NULL,
ADD PRIMARY KEY
    (num),
ADD KEY
    row_id (row_id) USING BTREE,
ADD KEY
    row_date (row_date) USING BTREE;

You can also adapt it to loop over the "num" column if your table doesn't use a date.

Hope this helps someone!

Environment variables in Jenkins

What ultimately worked for me was the following steps:

  1. Configure the Environment Injector Plugin: https://wiki.jenkins-ci.org/display/JENKINS/EnvInject+Plugin
  2. Goto to the /job//configure screen
  3. In Build Environment section check "Inject environment variables to the build process"
  4. In "Properties Content" specified: TZ=America/New_York

How to catch and print the full exception traceback without halting/exiting the program?

I don't see this mentioned in any of the other answers. If you're passing around an Exception object for whatever reason...

In Python 3.5+ you can get a trace from an Exception object using traceback.TracebackException.from_exception(). For example:

import traceback


def stack_lvl_3():
    raise Exception('a1', 'b2', 'c3')


def stack_lvl_2():
    try:
        stack_lvl_3()
    except Exception as e:
        # raise
        return e


def stack_lvl_1():
    e = stack_lvl_2()
    return e

e = stack_lvl_1()

tb1 = traceback.TracebackException.from_exception(e)
print(''.join(tb1.format()))

However, the above code results in:

Traceback (most recent call last):
  File "exc.py", line 10, in stack_lvl_2
    stack_lvl_3()
  File "exc.py", line 5, in stack_lvl_3
    raise Exception('a1', 'b2', 'c3')
Exception: ('a1', 'b2', 'c3')

This is just two levels of the stack, as opposed to what would have been printed on screen had the exception been raised in stack_lvl_2() and not intercepted (uncomment the # raise line).

As I understand it, that's because an exception records only the current level of the stack when it is raised, stack_lvl_3() in this case. As it's passed back up through the stack, more levels are being added to its __traceback__. But we intercepted it in stack_lvl_2(), meaning all it got to record was levels 3 and 2. To get the full trace as printed on stdout we'd have to catch it at the highest (lowest?) level:

import traceback


def stack_lvl_3():
    raise Exception('a1', 'b2', 'c3')


def stack_lvl_2():
    stack_lvl_3()


def stack_lvl_1():
    stack_lvl_2()


try:
    stack_lvl_1()
except Exception as exc:
    tb = traceback.TracebackException.from_exception(exc)

print('Handled at stack lvl 0')
print(''.join(tb.stack.format()))

Which results in:

Handled at stack lvl 0
  File "exc.py", line 17, in <module>
    stack_lvl_1()
  File "exc.py", line 13, in stack_lvl_1
    stack_lvl_2()
  File "exc.py", line 9, in stack_lvl_2
    stack_lvl_3()
  File "exc.py", line 5, in stack_lvl_3
    raise Exception('a1', 'b2', 'c3')

Notice that the stack print is different, the first and last lines are missing. Because it's a different format().

Intercepting the exception as far away from the point where it was raised as possible makes for simpler code while also giving more information.

How to get image size (height & width) using JavaScript?

var imgSrc, imgW, imgH;
function myFunction(image){
    var img = new Image();
    img.src = image;
    img.onload = function() {   
        return {
            src:image,
            width:this.width,
            height:this.height};
        }
    return img;
}
var x = myFunction('http://www.google.com/intl/en_ALL/images/logo.gif');
    //Waiting for the image loaded. Otherwise, system returned 0 as both width and height.
x.addEventListener('load',function(){
    imgSrc = x.src;
    imgW = x.width;
    imgH = x.height;
});
x.addEventListener('load',function(){
    console.log(imgW+'x'+imgH);//276x110
});
console.log(imgW);//undefined.
console.log(imgH);//undefined.
console.log(imgSrc);//undefined.

This is my method, hope this helpful. :)

How to decrypt an encrypted Apple iTunes iPhone backup?

Sorry, but it might even be more complicated, involving pbkdf2, or even a variation of it. Listen to the WWDC 2010 session #209, which mainly talks about the security measures in iOS 4, but also mentions briefly the separate encryption of backups and how they're related.

You can be pretty sure that without knowing the password, there's no way you can decrypt it, even by brute force.

Let's just assume you want to try to enable people who KNOW the password to get to the data of their backups.

I fear there's no way around looking at the actual code in iTunes in order to figure out which algos are employed.

Back in the Newton days, I had to decrypt data from a program and was able to call its decryption function directly (knowing the password, of course) without the need to even undersand its algorithm. It's not that easy anymore, unfortunately.

I'm sure there are skilled people around who could reverse engineer that iTunes code - you just have to get them interested.

In theory, Apple's algos should be designed in a way that makes the data still safe (i.e. practically unbreakable by brute force methods) to any attacker knowing the exact encryption method. And in WWDC session 209 they went pretty deep into details about what they do to accomplish this. Maybe you can actually get answers directly from Apple's security team if you tell them your good intentions. After all, even they should know that security by obfuscation is not really efficient. Try their security mailing list. Even if they do not repond, maybe someone else silently on the list will respond with some help.

Good luck!

How do I make a JSON object with multiple arrays?

var cars = [
    manufacturer: [
        {
            color: 'gray',
            model: '1',
            nOfDoors: 4
        },
        {
            color: 'yellow',
            model: '2',
            nOfDoors: 4
        }
    ]
]

Write to UTF-8 file in Python

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

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

import codecs

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

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

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

How to do a background for a label will be without color?

If you picture box in the background then use this:

label1.Parent = pictureBox1;
label1.BackColor = Color.Transparent;

Put this code below InitializeComponent(); or in Form_Load Method.

Ref: https://www.c-sharpcorner.com/blogs/how-to-make-a-transparent-label-over-a-picturebox1

How do I create and read a value from cookie?

The chrome team has proposed a new way of managing cookies asynchronous with the Cookie Storage API (available in Google Chrome starting from version 87): https://wicg.github.io/cookie-store/

Use it already today with a polyfill for the other browsers: https://github.com/mkay581/cookie-store

// load polyfill
import 'cookie-store';

// set a cookie
await cookieStore.set('name', 'value');
// get a cookie
const savedValue = await cookieStore.get('name');

Execution failed for task ':app:processDebugResources' even with latest build tools

this issue comes up with 2 reasons

1) the android SDK has not been install 2) the build toold version corresponsind to the android SDK is not installed

to start open terminal and type android and install API 26(updated one) and build tools version 26.0.1 or 26.0.2 then try to run using command ionic cordova build android

Char array declaration and initialization in C

That's because your first code snippet is not performing initialization, but assignment:

char myarray[4] = "abc";  // Initialization.

myarray = "abc";          // Assignment.

And arrays are not directly assignable in C.

The name myarray actually resolves to the address of its first element (&myarray[0]), which is not an lvalue, and as such cannot be the target of an assignment.

Determine the number of NA values in a column

In the summary() output, the function also counts the NAs so one can use this function if one wants the sum of NAs in several variables.

How do I POST XML data with curl

I prefer the following command-line options:

cat req.xml | curl -X POST -H 'Content-type: text/xml' -d @- http://www.example.com

or

curl -X POST -H 'Content-type: text/xml' -d @req.xml http://www.example.com

or

curl -X POST -H 'Content-type: text/xml'  -d '<XML>data</XML>' http://www.example.com 

Why can't I declare static methods in an interface?

There are a few issues at play here. The first is the issue of declaring a static method without defining it. This is the difference between

public interface Foo {
  public static int bar();
}

and

public interface Foo {
  public static int bar() {
    ...
  }
}

The first is impossible for the reasons that Espo mentions: you don't know which implementing class is the correct definition.

Java could allow the latter; and in fact, starting in Java 8, it does!

How to detect when facebook's FB.init is complete

Here is a solution in case you use and Facebook Asynchronous Lazy Loading:

// listen to an Event
$(document).bind('fbInit',function(){
    console.log('fbInit complete; FB Object is Available');
});

// FB Async
window.fbAsyncInit = function() {
    FB.init({appId: 'app_id', 
         status: true, 
         cookie: true,
         oauth:true,
         xfbml: true});

    $(document).trigger('fbInit'); // trigger event
};

react button onClick redirect page

This can be done very simply, you don't need to use a different function or library for it.

onClick={event =>  window.location.href='/your-href'}

PRINT statement in T-SQL

So, if you have a statement something like the following, you're saying that you get no 'print' result?

select * from sysobjects
PRINT 'Just selected * from sysobjects'

If you're using SQL Query Analyzer, you'll see that there are two tabs down at the bottom, one of which is "Messages" and that's where the 'print' statements will show up.
If you're concerned about the timing of seeing the print statements, you may want to try using something like

raiserror ('My Print Statement', 10,1) with nowait

This will give you the message immediately as the statement is reached, rather than buffering the output, as the Query Analyzer will do under most conditions.

Android Studio installation on Windows 7 fails, no JDK found

I got the problem that the installation stopped by "$(^name) has stopped working" error. I have installed Java SE Development kit already, also set both SDK_HOME and JAVA_HOME that point to "C:\Program Files\Java\jdk1.7.0_21\"

My laptop installed with Windows 7 64 bits

So I tried to install the 32 bit version of Java SE Developement kit, set my JAVA_HOME to "C:\Program Files (x86)\Java\jdk1.7.0_21", restart and the installation worked OK.

Using PowerShell to write a file in UTF-8 without the BOM

When using Set-Content instead of Out-File, you can specify the encoding Byte, which can be used to write a byte array to a file. This in combination with a custom UTF8 encoding which does not emit the BOM gives the desired result:

# This variable can be reused
$utf8 = New-Object System.Text.UTF8Encoding $false

$MyFile = Get-Content $MyPath -Raw
Set-Content -Value $utf8.GetBytes($MyFile) -Encoding Byte -Path $MyPath

The difference to using [IO.File]::WriteAllLines() or similar is that it should work fine with any type of item and path, not only actual file paths.

Flutter: how to make a TextField with HintText but no Underline?

I was using the TextField flutter control.I got the user typed input using below methods.

onChanged:(value){
}

Print a string as hex bytes?

With f-string:

"".join(f"{ord(c):x}" for c in "Hello")

Create component to specific module with Angular-CLI

According to Angular docs the way to create a component for specific module is,

ng g component <directory name>/<component name>

"directory name" = where the CLI generated the feature module

Example :-

ng generate component customer-dashboard/CustomerDashboard

This generates a folder for the new component within the customer-dashboard folder and updates the feature module with the CustomerDashboardComponent

How to install pkg config in windows?

  1. Install mingw64 from https://sourceforge.net/projects/mingw-w64/. Avoid program files/(x86) folder for installation. Ex. c:/mingw-w64
  2. Download pkg-config__win64.zip from here
  3. Extract above zip file and copy paste all the files from pkg-config/bin folder to mingw-w64. In my case its 'C:\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\bin'
  4. Now set path = C:\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\bin taddaaa you are done.

If you find any security issue then follow steps as well

  1. Search for windows defender security center in system
  2. Navigate to apps & browser control> Exploit protection settings> Program setting> Click on '+add program customize'
  3. Select add program by name
  4. Enter program name: pkgconf.exe
  5. OK
  6. Now check all the settings and set it all the settings to off and apply.

Thats DONE!

On design patterns: When should I use the singleton?

Read only singletons storing some global state (user language, help filepath, application path) are reasonable. Be carefull of using singletons to control business logic - single almost always ends up being multiple

Setting a timeout for socket operations

You don't set a timeout for the socket, you set a timeout for the operations you perform on that socket.

For example socket.connect(otherAddress, timeout)

Or socket.setSoTimeout(timeout) for setting a timeout on read() operations.

See: http://docs.oracle.com/javase/7/docs/api/java/net/Socket.html

Best way to split string into lines

It's tricky to handle mixed line endings properly. As we know, the line termination characters can be "Line Feed" (ASCII 10, \n, \x0A, \u000A), "Carriage Return" (ASCII 13, \r, \x0D, \u000D), or some combination of them. Going back to DOS, Windows uses the two-character sequence CR-LF \u000D\u000A, so this combination should only emit a single line. Unix uses a single \u000A, and very old Macs used a single \u000D character. The standard way to treat arbitrary mixtures of these characters within a single text file is as follows:

  • each and every CR or LF character should skip to the next line EXCEPT...
  • ...if a CR is immediately followed by LF (\u000D\u000A) then these two together skip just one line.
  • String.Empty is the only input that returns no lines (any character entails at least one line)
  • The last line must be returned even if it has neither CR nor LF.

The preceding rule describes the behavior of StringReader.ReadLine and related functions, and the function shown below produces identical results. It is an efficient C# line breaking function that dutifully implements these guidelines to correctly handle any arbitrary sequence or combination of CR/LF. The enumerated lines do not contain any CR/LF characters. Empty lines are preserved and returned as String.Empty.

/// <summary>
/// Enumerates the text lines from the string.
///   ? Mixed CR-LF scenarios are handled correctly
///   ? String.Empty is returned for each empty line
///   ? No returned string ever contains CR or LF
/// </summary>
public static IEnumerable<String> Lines(this String s)
{
    int j = 0, c, i;
    char ch;
    if ((c = s.Length) > 0)
        do
        {
            for (i = j; (ch = s[j]) != '\r' && ch != '\n' && ++j < c;)
                ;

            yield return s.Substring(i, j - i);
        }
        while (++j < c && (ch != '\r' || s[j] != '\n' || ++j < c));
}

Note: If you don't mind the overhead of creating a StringReader instance on each call, you can use the following C# 7 code instead. As noted, while the example above may be slightly more efficient, both of these functions produce the exact same results.

public static IEnumerable<String> Lines(this String s)
{
    using (var tr = new StringReader(s))
        while (tr.ReadLine() is String L)
            yield return L;
}

Make a dictionary with duplicate keys in Python

You can't have a dict with duplicate keys for definition! Instead you can use a single key and, as value, a list of elements that had that key.

So you can follow these steps:

  1. See if the current element's (of your initial set) key is in the final dict. If it is, go to step 3
  2. Update dict with key
  3. Append the new value to the dict[key] list
  4. Repeat [1-3]

How to force ViewPager to re-instantiate its items

I have found a solution. It is just a workaround to my problem but currently the only solution.

ViewPager PagerAdapter not updating the View

public int getItemPosition(Object object) {
   return POSITION_NONE;
}

Does anyone know whether this is a bug or not?

Python 'If not' syntax

Yes, if bar is not None is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar: will execute if bar is any kind of zero or empty container, or False. Many people do use not bar where they really do mean bar is not None.

How to create new folder?

You probably want os.makedirs as it will create intermediate directories as well, if needed.

import os

#dir is not keyword
def makemydir(whatever):
  try:
    os.makedirs(whatever)
  except OSError:
    pass
  # let exception propagate if we just can't
  # cd into the specified directory
  os.chdir(whatever)

Removing legend on charts with chart.js v2

You simply need to add that line legend: { display: false }

Master Page Weirdness - "Content controls have to be top-level controls in a content page or a nested master page that references a master page."

Here's another way using Visual Studio: If you do New Item in Visual Studio and you select Web Form, it will create a standalone *.aspx web form, which is what you have for your current web form (is this what you did?). You need to select Web Content Form and then select the master page you want attached to it.

How can I upload fresh code at github?

Just to add on to the other answers, before i knew my way around git, i was looking for some way to upload existing code to a new github (or other git) repo. Here's the brief that would save time for newbs:-

Assuming you have your NEW empty github or other git repo ready:-

cd "/your/repo/dir"
git clone https://github.com/user_AKA_you/repoName # (creates /your/repo/dir/repoName)
cp "/all/your/existing/code/*" "/your/repo/dir/repoName/"
git add -A
git commit -m "initial commit"
git push origin master

Alternatively if you have an existing local git repo

cd "/your/repo/dir/repoName"
#add your remote github or other git repo
git remote set-url origin https://github.com/user_AKA_you/your_repoName
git commit -m "new origin commit"
git push origin master

C# Switch-case string starting with

Short answer: No.

The switch statement takes an expression that is only evaluated once. Based on the result, another piece of code is executed.

So what? => String.StartsWith is a function. Together with a given parameter, it is an expression. However, for your case you need to pass a different parameter for each case, so it cannot be evaluated only once.

Long answer #1 has been given by others.

Long answer #2:

Depending on what you're trying to achieve, you might be interested in the Command Pattern/Chain-of-responsibility pattern. Applied to your case, each piece of code would be represented by an implementation of a Command. In addition to the execute method, the command can provide a boolean Accept method, which checks whether the given string starts with the respective parameter.

Advantage: Instead of your hardcoded switch statement, hardcoded StartsWith evaluations and hardcoded strings, you'd have lot more flexibility.

The example you gave in your question would then look like this:

var commandList = new List<Command>() { new MyABCCommand() };

foreach (Command c in commandList)
{
    if (c.Accept(mystring))
    {
        c.Execute(mystring);
        break;
    }
}

class MyABCCommand : Command
{
    override bool Accept(string mystring)
    {
        return mystring.StartsWith("abc");
    }
}    

Is it better to use NOT or <> when comparing values?

Agreed, code readability is very important for others, but more importantly yourself. Imagine how difficult it would be to understand the first example in comparison to the second.

If code takes more than a few seconds to read (understand), perhaps there is a better way to write it. In this case, the second way.

Uses of Action delegate in C#

Well one thing you could do is if you have a switch:

switch(SomeEnum)
{
  case SomeEnum.One:
      DoThings(someUser);
      break;
  case SomeEnum.Two:
      DoSomethingElse(someUser);
      break;
}

And with the might power of actions you can turn that switch into a dictionary:

Dictionary<SomeEnum, Action<User>> methodList = 
    new Dictionary<SomeEnum, Action<User>>()

methodList.Add(SomeEnum.One, DoSomething);
methodList.Add(SomeEnum.Two, DoSomethingElse); 

...

methodList[SomeEnum](someUser);

Or you could take this farther:

SomeOtherMethod(Action<User> someMethodToUse, User someUser)
{
    someMethodToUse(someUser);
}  

....

var neededMethod = methodList[SomeEnum];
SomeOtherMethod(neededMethod, someUser);

Just a couple of examples. Of course the more obvious use would be Linq extension methods.

error : expected unqualified-id before return in c++

if (chapeau) {

You forgot the ending brace to this if statement, so the subsequent else if is considered a syntax error. You need to add the brace when the if statement body is complete:

if (chapeau) {
    cout << "le Professeur Violet";
}
else if (moustaches) {
    cout << "le Colonel Moutarde";
}
// ...

JavaScript - Get minutes between two dates

For those that like to work with small numbers

const today = new Date();
const endDate = new Date(startDate.setDate(startDate.getDate() + 7));
const days = parseInt((endDate - today) / (1000 * 60 * 60 * 24));
const hours = parseInt(Math.abs(endDate - today) / (1000 * 60 * 60) % 24);
const minutes = parseInt(Math.abs(endDate.getTime() - today.getTime()) / (1000 * 60) % 60);
const seconds = parseInt(Math.abs(endDate.getTime() - today.getTime()) / (1000) % 60); 

Simple Digit Recognition OCR in OpenCV-Python

OCR which stands for Optical Character Recognition is a computer vision technique used to identify the different types of handwritten digits that are used in common mathematics. To perform OCR in OpenCV we will use the KNN algorithm which detects the nearest k neighbors of a particular data point and then classifies that data point based on the class type detected for n neighbors.

Data Used


This data contains 5000 handwritten digits where there are 500 digits for every type of digit. Each digit is of 20×20 pixel dimensions. We will split the data such that 250 digits are for training and 250 digits are for testing for every class.

Below is the implementation.




import numpy as np
import cv2
   
      
# Read the image
image = cv2.imread('digits.png')
  
# gray scale conversion
gray_img = cv2.cvtColor(image,
                        cv2.COLOR_BGR2GRAY)
  
# We will divide the image
# into 5000 small dimensions 
# of size 20x20
divisions = list(np.hsplit(i,100) for i in np.vsplit(gray_img,50))
  
# Convert into Numpy array
# of size (50,100,20,20)
NP_array = np.array(divisions)
   
# Preparing train_data
# and test_data.
# Size will be (2500,20x20)
train_data = NP_array[:,:50].reshape(-1,400).astype(np.float32)
  
# Size will be (2500,20x20)
test_data = NP_array[:,50:100].reshape(-1,400).astype(np.float32)
  
# Create 10 different labels 
# for each type of digit
k = np.arange(10)
train_labels = np.repeat(k,250)[:,np.newaxis]
test_labels = np.repeat(k,250)[:,np.newaxis]
   
# Initiate kNN classifier
knn = cv2.ml.KNearest_create()
  
# perform training of data
knn.train(train_data,
          cv2.ml.ROW_SAMPLE, 
          train_labels)
   
# obtain the output from the
# classifier by specifying the
# number of neighbors.
ret, output ,neighbours,
distance = knn.findNearest(test_data, k = 3)
   
# Check the performance and
# accuracy of the classifier.
# Compare the output with test_labels
# to find out how many are wrong.
matched = output==test_labels
correct_OP = np.count_nonzero(matched)
   
#Calculate the accuracy.
accuracy = (correct_OP*100.0)/(output.size)
   
# Display accuracy.
print(accuracy)


Output

91.64


Well, I decided to workout myself on my question to solve the above problem. What I wanted is to implement a simple OCR using KNearest or SVM features in OpenCV. And below is what I did and how. (it is just for learning how to use KNearest for simple OCR purposes).

1) My first question was about letter_recognition.data file that comes with OpenCV samples. I wanted to know what is inside that file.

It contains a letter, along with 16 features of that letter.

And this SOF helped me to find it. These 16 features are explained in the paper Letter Recognition Using Holland-Style Adaptive Classifiers. (Although I didn't understand some of the features at the end)

2) Since I knew, without understanding all those features, it is difficult to do that method. I tried some other papers, but all were a little difficult for a beginner.

So I just decided to take all the pixel values as my features. (I was not worried about accuracy or performance, I just wanted it to work, at least with the least accuracy)

I took the below image for my training data:

enter image description here

(I know the amount of training data is less. But, since all letters are of the same font and size, I decided to try on this).

To prepare the data for training, I made a small code in OpenCV. It does the following things:

  1. It loads the image.
  2. Selects the digits (obviously by contour finding and applying constraints on area and height of letters to avoid false detections).
  3. Draws the bounding rectangle around one letter and wait for key press manually. This time we press the digit key ourselves corresponding to the letter in the box.
  4. Once the corresponding digit key is pressed, it resizes this box to 10x10 and saves all 100 pixel values in an array (here, samples) and corresponding manually entered digit in another array(here, responses).
  5. Then save both the arrays in separate .txt files.

At the end of the manual classification of digits, all the digits in the training data (train.png) are labeled manually by ourselves, image will look like below:

enter image description here

Below is the code I used for the above purpose (of course, not so clean):

import sys

import numpy as np
import cv2

im = cv2.imread('pitrain.png')
im3 = im.copy()

gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)

#################      Now finding Contours         ###################

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

samples =  np.empty((0,100))
responses = []
keys = [i for i in range(48,58)]

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            cv2.imshow('norm',im)
            key = cv2.waitKey(0)

            if key == 27:  # (escape to quit)
                sys.exit()
            elif key in keys:
                responses.append(int(chr(key)))
                sample = roismall.reshape((1,100))
                samples = np.append(samples,sample,0)

responses = np.array(responses,np.float32)
responses = responses.reshape((responses.size,1))
print "training complete"

np.savetxt('generalsamples.data',samples)
np.savetxt('generalresponses.data',responses)

Now we enter in to training and testing part.

For the testing part, I used the below image, which has the same type of letters I used for the training phase.

enter image description here

For training we do as follows:

  1. Load the .txt files we already saved earlier
  2. create an instance of the classifier we are using (it is KNearest in this case)
  3. Then we use KNearest.train function to train the data

For testing purposes, we do as follows:

  1. We load the image used for testing
  2. process the image as earlier and extract each digit using contour methods
  3. Draw a bounding box for it, then resize it to 10x10, and store its pixel values in an array as done earlier.
  4. Then we use KNearest.find_nearest() function to find the nearest item to the one we gave. ( If lucky, it recognizes the correct digit.)

I included last two steps (training and testing) in single code below:

import cv2
import numpy as np

#######   training part    ############### 
samples = np.loadtxt('generalsamples.data',np.float32)
responses = np.loadtxt('generalresponses.data',np.float32)
responses = responses.reshape((responses.size,1))

model = cv2.KNearest()
model.train(samples,responses)

############################# testing part  #########################

im = cv2.imread('pi.png')
out = np.zeros(im.shape,np.uint8)
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            roismall = roismall.reshape((1,100))
            roismall = np.float32(roismall)
            retval, results, neigh_resp, dists = model.find_nearest(roismall, k = 1)
            string = str(int((results[0][0])))
            cv2.putText(out,string,(x,y+h),0,1,(0,255,0))

cv2.imshow('im',im)
cv2.imshow('out',out)
cv2.waitKey(0)

And it worked, below is the result I got:

enter image description here


Here it worked with 100% accuracy. I assume this is because all the digits are of the same kind and the same size.

But anyway, this is a good start to go for beginners (I hope so).

Java executors: how to be notified, without blocking, when a task completes?

ThreadPoolExecutor also has beforeExecute and afterExecute hook methods that you can override and make use of. Here is the description from ThreadPoolExecutor's Javadocs.

Hook methods

This class provides protected overridable beforeExecute(java.lang.Thread, java.lang.Runnable) and afterExecute(java.lang.Runnable, java.lang.Throwable) methods that are called before and after execution of each task. These can be used to manipulate the execution environment; for example, reinitializing ThreadLocals, gathering statistics, or adding log entries. Additionally, method terminated() can be overridden to perform any special processing that needs to be done once the Executor has fully terminated. If hook or callback methods throw exceptions, internal worker threads may in turn fail and abruptly terminate.

What is the difference between i++ & ++i in a for loop?

They both increment the number. ++i is equivalent to i = i + 1.

i++ and ++i are very similar but not exactly the same. Both increment the number, but ++i increments the number before the current expression is evaluted, whereas i++ increments the number after the expression is evaluated.

int i = 3;
int a = i++; // a = 3, i = 4
int b = ++a; // b = 4, a = 4

Formatting struct timespec

I wanted to ask the same question. Here is my current solution to obtain a string like this: 2013-02-07 09:24:40.749355372 I am not sure if there is a more straight forward solution than this, but at least the string format is freely configurable with this approach.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define NANO 1000000000L

// buf needs to store 30 characters
int timespec2str(char *buf, uint len, struct timespec *ts) {
    int ret;
    struct tm t;

    tzset();
    if (localtime_r(&(ts->tv_sec), &t) == NULL)
        return 1;

    ret = strftime(buf, len, "%F %T", &t);
    if (ret == 0)
        return 2;
    len -= ret - 1;

    ret = snprintf(&buf[strlen(buf)], len, ".%09ld", ts->tv_nsec);
    if (ret >= len)
        return 3;

    return 0;
}

int main(int argc, char **argv) {
    clockid_t clk_id = CLOCK_REALTIME;
    const uint TIME_FMT = strlen("2012-12-31 12:59:59.123456789") + 1;
    char timestr[TIME_FMT];

    struct timespec ts, res;
    clock_getres(clk_id, &res);
    clock_gettime(clk_id, &ts);

    if (timespec2str(timestr, sizeof(timestr), &ts) != 0) {
        printf("timespec2str failed!\n");
        return EXIT_FAILURE;
    } else {
        unsigned long resol = res.tv_sec * NANO + res.tv_nsec;
        printf("CLOCK_REALTIME: res=%ld ns, time=%s\n", resol, timestr);
        return EXIT_SUCCESS;
    }
}

output:

gcc mwe.c -lrt 
$ ./a.out 
CLOCK_REALTIME: res=1 ns, time=2013-02-07 13:41:17.994326501

In Java, how do I convert a byte array to a string of hex digits while keeping leading zeros?

A simple approach would be to check how many digits are output by Integer.toHexString() and add a leading zero to each byte if needed. Something like this:

public static String toHexString(byte[] bytes) {
    StringBuilder hexString = new StringBuilder();

    for (int i = 0; i < bytes.length; i++) {
        String hex = Integer.toHexString(0xFF & bytes[i]);
        if (hex.length() == 1) {
            hexString.append('0');
        }
        hexString.append(hex);
    }

    return hexString.toString();
}

Make ABC Ordered List Items Have Bold Style

Are you sure you correctly applied the styles, or that there isn't another stylesheet interfering with your lists? I tried this:

<ol type="A">
<li><span class="label">Text</span></li>
<li><span class="label">Text</span></li>
<li><span class="label">Text</span></li>
</ol>

Then in the stylesheet:

ol {font-weight: bold;}
ol li span.label {font-weight:normal;}

And it bolded the A, B, C etc and not the text.

(Tested it in Opera 9.6, FF 3, Safari 3.2 and IE 7)

How do I include a JavaScript script file in Angular and call a function from that script?

In order to include a global library, eg jquery.js file in the scripts array from angular-cli.json (angular.json when using angular 6+):

"scripts": [
  "../node_modules/jquery/dist/jquery.js"
]

After this, restart ng serve if it is already started.

Redis - Connect to Remote Server

I was struggling with the remote connection to Redis for some days. Finally I made it. Here is the full check list I put together to follow to get connected. Some of solutions are given in the answers above. Yet I wanted my answer to be a nano-wiki on the subject:) I added some useful links too.

If redis works locally:

$ redis-cli
127.0.0.1:6379>ping
PONG
127.0.0.1:6379>

If the password is not set

See /etc/redis/redis.conf config (this is default locaion for Ubuntu 18.04, you may have it in the different location):

# The following line should be commented
# requirepass <some pass if any>

If the protected mode is set to 'no' in the config:

# The following line should be uncommented
protected-mode no

if the IP binding is open for an access from internet in the config:

# The following line should be commented
# bind 127.0.0.1 ::1

If the Linux firewall allows connections

(here for Ubuntu 18.04) Check it allows for incoming internet traffic to go to port 6379 (the Redis default port)

# To check if it the port is open
$ sudo ufw status
Status: active

To                         Action      From
--                         ------      ----
...
6379/tcp                   ALLOW       Anywhere
6379/tcp (v6)              ALLOW       Anywhere (v6)
...

# To open the port
$ sudo ufw allow 6379/tcp

Restart Redis service

Do not forget to restart the Redis service for changes to take effect and see it is running:

$ sudo systemctl restart redis.service
$ sudo systemctl status redis

Check if it works as a remote server

from your command line use redis-cli as if Redis server were on the remote server:

$ redis-cli -h <your-server-ip>
<your-server-ip>:6379> ping
PONG
<your-server-ip>:6379> exit
$

If you can ping-PONG your Redis server via your internet server connected as a remote server than the remote Redis connection works.

Security Warning

All the above makes your Redis data to be completely open to anybody from the internet.

To basically secure Redis use requirepass and protected-mode yes settings in Redis config (see above) and block the dangerous Redis commands (see the link above), for a deeper understanding see this article and Redis site security section ).

Useful links

Some links to help How to install and secure Redis on Ubuntu 18.04 and how to setup Ubuntu 18.04 firewall.

Hope it helps.

Present and dismiss modal view controller

Swift

Updated for Swift 3

enter image description here

Storyboard

Create two View Controllers with a button on each. For the second view controller, set the class name to SecondViewController and the storyboard ID to secondVC.

Code

ViewController.swift

import UIKit
class ViewController: UIViewController {

    @IBAction func presentButtonTapped(_ sender: UIButton) {
        
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let myModalViewController = storyboard.instantiateViewController(withIdentifier: "secondVC")
        myModalViewController.modalPresentationStyle = UIModalPresentationStyle.fullScreen
        myModalViewController.modalTransitionStyle = UIModalTransitionStyle.coverVertical
        self.present(myModalViewController, animated: true, completion: nil)
    }
}

SecondViewController.swift

import UIKit
class SecondViewController: UIViewController {
    
    @IBAction func dismissButtonTapped(_ sender: UIButton) {
        self.dismiss(animated: true, completion: nil)
    }
}

Source:

Git push requires username and password

If the SSH key or .netrc file did not work for you, then another simple, but less secure solution, that could work for you is git-credential-store - Helper to store credentials on disk:

git config --global credential.helper store

By default, credentials will be saved in file ~/.git-credentials. It will be created and written to.

Please note using this helper will store your passwords unencrypted on disk, protected only by filesystem permissions. If this may not be an acceptable security tradeoff.

X-Frame-Options on apache

I found that if the application within the httpd server has a rule like "if the X-Frame-Options header exists and has a value, leave it alone; otherwise add the header X-Frame-Options: SAMEORIGIN" then an httpd.conf mod_headers rule like "Header always unset X-Frame-Options" would not suffice. The SAMEORIGIN value would always reach the client.

To remedy this, I add two, not one, mod_headers rules (in the outermost httpd.conf file):

Header set X-Frame-Options ALLOW-FROM http://to.be.deleted.com early
Header unset X-Frame-Options

The first rule tells any internal request handler that some other agent has taken responsibility for clickjack prevention and it can skip its attempt to save the world. It runs with "early" processing. The second rule strips off the entirely unwanted X-Frame-Options header. It runs with "late" processing.

I also add the appropriate Content-Security-Policy headers so that the world remains protected yet multi-sourced Javascript from trusted sites still gets to run.

Imported a csv-dataset to R but the values becomes factors

By default, read.csv checks the first few rows of your data to see whether to treat each variable as numeric. If it finds non-numeric values, it assumes the variable is character data, and character variables are converted to factors.

It looks like the PTS and MP variables in your dataset contain non-numerics, which is why you're getting unexpected results. You can force these variables to numeric with

point <- as.numeric(as.character(point))
time <- as.numeric(as.character(time))

But any values that can't be converted will become missing. (The R FAQ gives a slightly different method for factor -> numeric conversion but I can never remember what it is.)

How to extract the substring between two markers?

import re
print re.search('AAA(.*?)ZZZ', 'gfgfdAAA1234ZZZuijjk').group(1)

ORA-01861: literal does not match format string

Just before executing the query: alter session set NLS_DATE_FORMAT = "DD.MM.YYYY HH24:MI:SS"; or whichever format you are giving the information to the date function. This should fix the ORA error

Difference between null and empty ("") Java String

A string can be empty or have a null value. If a string is null, it isn't referring to anything in memory. Try s.length()>0. This is because if a string is empty, it still returns a length of 0. So if you enter nothing for the same, then it will still continue looping since it doesn't register the string as null. Whereas if you check for length, then it will exit out of it's loop.

PostgreSQL delete with inner join

Another form that works with Postgres 9.1+ is combining a Common Table Expression with the USING statement for the join.

WITH prod AS (select m_product_id, upc from m_product where upc='7094')
DELETE FROM m_productprice B
USING prod C
WHERE B.m_product_id = C.m_product_id 
AND B.m_pricelist_version_id = '1000020';

iOS 7 - Failing to instantiate default view controller

Check if you have the window var in the AppDelegate.

var window: UIWindow? 

And also check the storyboard of your Info.plist file.

<key>UIMainStoryboardFile</key>
<string>Main</string>

Programmatically setting the rootViewController in the AppDelegate is not going to fix the warning. You should choose whether to let to the storyboard set the view controller or do it programmatically.

Get current NSDate in timestamp format

Can also use

@(time(nil)).stringValue);

for timestamp in seconds.

How to append a jQuery variable value inside the .html tag

HTML :

<div id="myDiv">
    <form id="myForm">
    </form> 
</div>

jQuery :

var chbx='<input type="checkbox" id="Mumbai" name="Mumbai" value="Mumbai" />Mumbai<br /> <input type="checkbox" id=" Delhi" name=" Delhi" value=" Delhi" /> Delhi<br/><input type="checkbox" id=" Bangalore" name=" Bangalore" value=" Bangalore"/>Bangalore<br />';

$("#myDiv form#myForm").html(chbx);

//to insert dynamically created form 
$("#myDiv").html("<form id='dynamicForm'>" +chbx + "'</form>");

Demo

Git push existing repo to a new and different remote repo server?

Try this How to move a full Git repository

  1. Create a local repository in the temp-dir directory using:

    git clone temp-dir

  2. Go into the temp-dir directory.

  3. To see a list of the different branches in ORI do:

    git branch -a
    
  4. Checkout all the branches that you want to copy from ORI to NEW using:

    git checkout branch-name
    
  5. Now fetch all the tags from ORI using:

    git fetch --tags
    
  6. Before doing the next step make sure to check your local tags and branches using the following commands:

    git tag
    
    
    git branch -a
    
  7. Now clear the link to the ORI repository with the following command:

    git remote rm origin
    
  8. Now link your local repository to your newly created NEW repository using the following command:

    git remote add origin <url to NEW repo>
    
  9. Now push all your branches and tags with these commands:

    git push origin --all
    
    
    git push --tags
    
  10. You now have a full copy from your ORI repo.

C# Form.Close vs Form.Dispose

As a general rule, I'd always advocate explicitly calling the Dispose method for any class that offers it, either by calling the method directly or wrapping in a "using" block.

Most often, classes that implement IDisposible do so because they wrap some unmanaged resource that needs to be freed. While these classes should have finalizers that act as a safeguard, calling Dispose will help free that memory earlier and with lower overhead.

In the case of the Form object, as the link fro Kyra noted, the Close method is documented to invoke Dispose on your behalf so you need not do so explicitly. However, to me, that has always felt like relying on an implementaion detail. I prefer to always call both Close and Dispose for classes that implement them, to guard against implementation changes/errors and for the sake of being clear. A properly implemented Dispose method should be safe to invoke multiple times.

ASP.NET Core - Swashbuckle not creating swagger.json file

Same problem - easy fix for me.

To find the underlying problem I navigated to the actual swagger.json file which gave me the real error

/swagger/v1/swagger.json

The actual error displayed from this Url was

NotSupportedException: Ambiguous HTTP method for action  ... Actions require an explicit HttpMethod binding for Swagger/OpenAPI 3.0

The point being

Actions require an explicit HttpMethod

I then decorated my controller methods with [HttpGet]

[Route("GetFlatRows")]
 [HttpGet]
 public IActionResult GetFlatRows()
 {

Problem solved

open program minimized via command prompt

Try:

start  "" "C:\Program Files (x86)\Microsoft Office\Office12\WINWORD.EXE" --new-window/min

I had the same problem, but I was trying to open chrome.exe maximized. If I put the /min anywhere else in the command line, like before or after the empty title, it was ignored.

Validation to check if password and confirm password are same is not working

The validate_required function seems to expect an HTML form control (e.g, text input field) as first argument, and check whether there is a value there at all. That is not what you want in this case.

Also, when you write ['password'].value, you create a new array of length one, containing the string 'password', and then read the non-existing property "value" from it, yielding the undefined value.

What you may want to try instead is:

if (password.value != cpassword.value) { cpassword.focus(); return false; }

(You also need to write the error message somehow, but I can't see from your code how that is done.).

Location of GlassFish Server Logs

Locate the installation path of GlassFish. Then move to domains/domain-dir/logs/ and you'll find there the log files. If you have created the domain with NetBeans, the domain-dir is most probably called domain1.

See this link for the official GlassFish documentation about logging.

Laravel 5 – Remove Public from URL

Create A .htaccess file in your root DIR and paste the below code. That's it :P

_x000D_
_x000D_
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ ^$1 [N]

RewriteCond %{REQUEST_URI} (\.\w+$) [NC]
RewriteRule ^(.*)$ public/$1 

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ server.php
_x000D_
_x000D_
_x000D_

jQuery: enabling/disabling datepicker

Well You can remove datepicker by simply remove hasDatepicker class from input.

Code

$( "#from" ).removeClass('hasDatepicker')

'sprintf': double precision in C

From your question it seems like you are using C99, as you have used %lf for double.

To achieve the desired output replace:

sprintf(aa, "%lf", a);

with

sprintf(aa, "%0.7f", a);

The general syntax "%A.B" means to use B digits after decimal point. The meaning of the A is more complicated, but can be read about here.

Insert a line at specific line number with sed or awk

POSIX sed (and for example OS X's sed, the sed below) require i to be followed by a backslash and a newline. Also at least OS X's sed does not include a newline after the inserted text:

$ seq 3|gsed '2i1.5'
1
1.5
2
3
$ seq 3|sed '2i1.5'
sed: 1: "2i1.5": command i expects \ followed by text
$ seq 3|sed $'2i\\\n1.5'
1
1.52
3
$ seq 3|sed $'2i\\\n1.5\n'
1
1.5
2
3

To replace a line, you can use the c (change) or s (substitute) commands with a numeric address:

$ seq 3|sed $'2c\\\n1.5\n'
1
1.5
3
$ seq 3|gsed '2c1.5'
1
1.5
3
$ seq 3|sed '2s/.*/1.5/'
1
1.5
3

Alternatives using awk:

$ seq 3|awk 'NR==2{print 1.5}1'
1
1.5
2
3
$ seq 3|awk '{print NR==2?1.5:$0}'
1
1.5
3

awk interprets backslashes in variables passed with -v but not in variables passed using ENVIRON:

$ seq 3|awk -v v='a\ba' '{print NR==2?v:$0}'
1
a
3
$ seq 3|v='a\ba' awk '{print NR==2?ENVIRON["v"]:$0}'
1
a\ba
3

Both ENVIRON and -v are defined by POSIX.

Formatting a double to two decimal places

Well, depending on your needs you can choose any of the following. Out put is written against each method

You can choose the one you need

This will round

decimal d = 2.5789m;
Console.WriteLine(d.ToString("#.##")); // 2.58

This will ensure that 2 decimal places are written.

d = 2.5m;
Console.WriteLine(d.ToString("F")); //2.50

if you want to write commas you can use this

d=23545789.5432m;
Console.WriteLine(d.ToString("n2")); //23,545,789.54

if you want to return the rounded of decimal value you can do this

d = 2.578m;
d = decimal.Round(d, 2, MidpointRounding.AwayFromZero); //2.58

How can I resize an image dynamically with CSS as the browser width/height changes?

Are you using jQuery?

Because I did a quickly search on the jQuery plugings and they seem to have some plugin to do this, check this one, should work:

http://plugins.jquery.com/project/jquery-afterresize

EDIT:

This is the CSS solution, I just add a style="width: 100%", and works for me at least in chrome and Safari. I dont have ie, so just test there, and let me know, here is the code:

            <div id="gallery" style="width: 100%">
                <img src="images/fullsize.jpg" alt="" id="fullsize" />
                <a href="#" id="prev">prev</a>
                <a href="#" id="next">next</a>
            </div>

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

(Edit) The previously recomended add-on is not available any longer, you may try this other one


For development purposes in Chrome, installing this add on will get rid of that specific error:

Access to XMLHttpRequest at 'http://192.168.1.42:8080/sockjs-node/info?t=1546163388687' 
from origin 'http://localhost:8080' has been blocked by CORS policy: The value of the 
'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' 
when the request's credentials mode is 'include'. The credentials mode of requests 
initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

After installing, make sure you add your url pattern to the Intercepted URLs by clicking on the AddOn's (CORS, green or red) icon and filling the appropriate textbox. An example URL pattern to add here that will work with http://localhost:8080 would be: *://*

Counter in foreach loop in C#

Not all collections have indexes. For instance, I can use a Dictionary with foreach (and iterate through all the keys and values), but I can't write get at individual elements using dictionary[0], dictionary[1] etc.

If I did want to iterate through a dictionary and keep track of an index, I'd have to use a separate variable that I incremented myself.

How to declare or mark a Java method as deprecated?

Take a look at the @Deprecated annotation.

Functions that return a function

Create a variable:

var thing1 = undefined;

Declare a Function:

function something1 () {
    return "Hi there, I'm number 1!";
}

Alert the value of thing1 (our first variable):

alert(thing1); // Outputs: "undefined".

Now, if we wanted thing1 to be a reference to the function something1, meaning it would be the same thing as our created function, we would do:

thing1 = something1;

However, if we wanted the return value of the function then we must assign it the return value of the executed function. You execute the function by using parenthesis:

thing1 = something1(); // Value of thing1: "Hi there, I'm number 1!" 

First letter capitalization for EditText

Programmatically

TextView firstline = (TextView) findViewById(R.id.firstline);
firstline.setAllCaps(true);

Difference between `npm start` & `node app.js`, when starting app?

From the man page, npm start:

runs a package's "start" script, if one was provided. If no version is specified, then it starts the "active" version.

Admittedly, that description is completely unhelpful, and that's all it says. At least it's more documented than socket.io.

Anyhow, what really happens is that npm looks in your package.json file, and if you have something like

"scripts": { "start": "coffee server.coffee" }

then it will do that. If npm can't find your start script, it defaults to:

node server.js

 

How to pass url arguments (query string) to a HTTP request on Angular?

Version 5+

With Angular 5 and up, you DON'T have to use HttpParams. You can directly send your json object as shown below.

let data = {limit: "2"};
this.httpClient.get<any>(apiUrl, {params: data});

Please note that data values should be string, ie; { params: {limit: "2"}}

Version 4.3.x+

Use HttpParams, HttpClient from @angular/common/http

import { HttpParams, HttpClient } from '@angular/common/http';
...
constructor(private httpClient: HttpClient) { ... }
...
let params = new HttpParams();
params = params.append("page", 1);
....
this.httpClient.get<any>(apiUrl, {params: params});

Also, try stringifying your nested object using JSON.stringify().

How can I print a quotation mark in C?

Besides escaping the character, you can also use the format %c, and use the character literal for a quotation mark.

printf("And I quote, %cThis is a quote.%c\n", '"', '"');

How to get an Android WakeLock to work?

WakeLock doesn't usually cause Reboot problems. There may be some other issues in your coding. WakeLock hogs battery heavily, if not released after usage.

WakeLock is an Inefficient way of keeping the screen on. Instead use the WindowManager to do the magic. The following one line will suffice the WakeLock. The WakeLock Permission is also needed for this to work. Also this code is more efficient than the wakeLock.

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

You need not relase the WakeLock Manually. This code will allow the Android System to handle the Lock Automatically. When your application is in the Foreground then WakeLock is held and else android System releases the Lock automatically.

Try this and post your comment...

How to Diff between local uncommitted changes and origin

To see non-staged (non-added) changes to existing files

git diff

Note that this does not track new files. To see staged, non-commited changes

git diff --cached

Your configuration specifies to merge with the <branch name> from the remote, but no such ref was fetched.?

You can easily link your local branch with remote one by running:

git checkout <your-local-branch>
git branch --set-upstream-to=origin/<correct-remote-branch> <your-local-branch>
git pull

How to get height and width of device display in angular2 using typescript?

You may use the typescript getter method for this scenario. Like this

public get height() {
  return window.innerHeight;
}

public get width() {
  return window.innerWidth;
}

And use that in template like this:

<section [ngClass]="{ 'desktop-view': width >= 768, 'mobile-view': width < 768 
}"></section>

Print the value

console.log(this.height, this.width);

You won't need any event handler to check for resizing of window, this method will check for size every time automatically.

The type must be a reference type in order to use it as parameter 'T' in the generic type or method

If you put constrains on a generic class or method, every other generic class or method that is using it need to have "at least" those constrains.

How to convert a string Date to long millseconds

Easiest way is used the Date Using Date() and getTime()

    Date dte=new Date();
    long milliSeconds = dte.getTime();
    String strLong = Long.toString(milliSeconds);
    System.out.println(milliSeconds)

What is a .pid file and what does it contain?

To understand pid files, refer this DOC

Some times there are certain applications that require additional support of extra plugins and utilities. So it keeps track of these utilities and plugin process running ids using this pid file for reference.

That is why whenever you restart an application all necessary plugins and dependant apps must be restarted since the pid file will become stale.

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

You state in the comments that the returned JSON is this:

{ 
  "dstOffset" : 3600, 
  "rawOffset" : 36000, 
  "status" : "OK", 
  "timeZoneId" : "Australia/Hobart", 
  "timeZoneName" : "Australian Eastern Daylight Time" 
}

You're telling Gson that you have an array of Post objects:

List<Post> postsList = Arrays.asList(gson.fromJson(reader,
                    Post[].class));

You don't. The JSON represents exactly one Post object, and Gson is telling you that.

Change your code to be:

Post post = gson.fromJson(reader, Post.class);

Can a shell script set environment variables of the calling shell?

Use the "dot space script" calling syntax. For example, here's how to do it using the full path to a script:

. /path/to/set_env_vars.sh

And here's how to do it if you're in the same directory as the script:

. set_env_vars.sh

These execute the script under the current shell instead of loading another one (which is what would happen if you did ./set_env_vars.sh). Because it runs in the same shell, the environmental variables you set will be available when it exits.

This is the same thing as calling source set_env_vars.sh, but it's shorter to type and might work in some places where source doesn't.

How to center a checkbox in a table cell?

My problem was that there was a parent style with position: absolute !important which I was not allowed to edit.

So I gave my specific checkbox position: relative !important and it fixed the vertical misalignment issue.

How do I show a message in the foreach loop?

You are looking to see if a single value is in an array. Use in_array.

However note that case is important, as are any leading or trailing spaces. Use var_dump to find out the length of the strings too, and see if they fit.

the best way to make codeigniter website multi-language. calling from lang arrays depends on lang session?

When managing the actual files, things can get out of sync pretty easily unless you're really vigilant. So we've launched a (beta) free service called String which allows you to keep track of your language files easily, and collaborate with translators.

You can either import existing language files (in PHP array, PHP Define, ini, po or .strings formats) or create your own sections from scratch and add content directly through the system.

String is totally free so please check it out and tell us what you think.

It's actually built on Codeigniter too! Check out the beta at http://mygengo.com/string

What does the "yield" keyword do?

Shortcut to understanding yield

When you see a function with yield statements, apply this easy trick to understand what will happen:

  1. Insert a line result = [] at the start of the function.
  2. Replace each yield expr with result.append(expr).
  3. Insert a line return result at the bottom of the function.
  4. Yay - no more yield statements! Read and figure out code.
  5. Compare function to the original definition.

This trick may give you an idea of the logic behind the function, but what actually happens with yield is significantly different than what happens in the list based approach. In many cases, the yield approach will be a lot more memory efficient and faster too. In other cases, this trick will get you stuck in an infinite loop, even though the original function works just fine. Read on to learn more...

Don't confuse your Iterables, Iterators, and Generators

First, the iterator protocol - when you write

for x in mylist:
    ...loop body...

Python performs the following two steps:

  1. Gets an iterator for mylist:

    Call iter(mylist) -> this returns an object with a next() method (or __next__() in Python 3).

    [This is the step most people forget to tell you about]

  2. Uses the iterator to loop over items:

    Keep calling the next() method on the iterator returned from step 1. The return value from next() is assigned to x and the loop body is executed. If an exception StopIteration is raised from within next(), it means there are no more values in the iterator and the loop is exited.

The truth is Python performs the above two steps anytime it wants to loop over the contents of an object - so it could be a for loop, but it could also be code like otherlist.extend(mylist) (where otherlist is a Python list).

Here mylist is an iterable because it implements the iterator protocol. In a user-defined class, you can implement the __iter__() method to make instances of your class iterable. This method should return an iterator. An iterator is an object with a next() method. It is possible to implement both __iter__() and next() on the same class, and have __iter__() return self. This will work for simple cases, but not when you want two iterators looping over the same object at the same time.

So that's the iterator protocol, many objects implement this protocol:

  1. Built-in lists, dictionaries, tuples, sets, files.
  2. User-defined classes that implement __iter__().
  3. Generators.

Note that a for loop doesn't know what kind of object it's dealing with - it just follows the iterator protocol, and is happy to get item after item as it calls next(). Built-in lists return their items one by one, dictionaries return the keys one by one, files return the lines one by one, etc. And generators return... well that's where yield comes in:

def f123():
    yield 1
    yield 2
    yield 3

for item in f123():
    print item

Instead of yield statements, if you had three return statements in f123() only the first would get executed, and the function would exit. But f123() is no ordinary function. When f123() is called, it does not return any of the values in the yield statements! It returns a generator object. Also, the function does not really exit - it goes into a suspended state. When the for loop tries to loop over the generator object, the function resumes from its suspended state at the very next line after the yield it previously returned from, executes the next line of code, in this case, a yield statement, and returns that as the next item. This happens until the function exits, at which point the generator raises StopIteration, and the loop exits.

So the generator object is sort of like an adapter - at one end it exhibits the iterator protocol, by exposing __iter__() and next() methods to keep the for loop happy. At the other end, however, it runs the function just enough to get the next value out of it, and puts it back in suspended mode.

Why Use Generators?

Usually, you can write code that doesn't use generators but implements the same logic. One option is to use the temporary list 'trick' I mentioned before. That will not work in all cases, for e.g. if you have infinite loops, or it may make inefficient use of memory when you have a really long list. The other approach is to implement a new iterable class SomethingIter that keeps the state in instance members and performs the next logical step in it's next() (or __next__() in Python 3) method. Depending on the logic, the code inside the next() method may end up looking very complex and be prone to bugs. Here generators provide a clean and easy solution.

How to search for a string in an arraylist

List <String> list = new ArrayList();  
           list.add("behold"); 
           list.add("bend"); 
           list.add("bet"); 
           list.add("bear"); 
           list.add("beat"); 
           list.add("become"); 
           list.add("begin");

           List <String> listClone = new ArrayList<String>(); 
           Pattern pattern = Pattern.compile("bea",Pattern.CASE_INSENSITIVE); //incase u r not concerned about upper/lower case
           for (String string : list) {
               if(pattern.matcher(string).find()) {
                   listClone.add(string);
                   continue;
               }
           }
        System.out.println(listClone);

How to right-align and justify-align in Markdown?

Aligning text in native markdown is not possible. However, you can align the text using inline HTML tags.

<div style="text-align: right"> your-text-here </div>

To justify, replace right with justify in the above.

How to set-up a favicon?

<head>
    <link rel="shortcut icon" href="favicon.ico">
</head>

Make view 80% width of parent in React Native

This is the way I got the solution. Simple and Sweet. Independent of Screen density:

export default class AwesomeProject extends Component {
    constructor(props){
        super(props);
        this.state = {text: ""}
    }
  render() {
    return (
       <View
          style={{
            flex: 1,
            backgroundColor: "#ececec",
            flexDirection: "column",
            justifyContent: "center",
            alignItems: "center"
          }}
        >
          <View style={{ padding: 10, flexDirection: "row" }}>
            <TextInput
              style={{ flex: 0.8, height: 40, borderWidth: 1 }}
              onChangeText={text => this.setState({ text })}
              placeholder="Text 1"
              value={this.state.text}
            />
          </View>
          <View style={{ padding: 10, flexDirection: "row" }}>
            <TextInput
              style={{ flex: 0.8, height: 40, borderWidth: 1 }}
              onChangeText={text => this.setState({ text })}
              placeholder="Text 2"
              value={this.state.text}
            />
          </View>
          <View style={{ padding: 10, flexDirection: "row" }}>
            <Button
              onPress={onButtonPress}
              title="Press Me"
              accessibilityLabel="See an Information"
            />
          </View>
        </View>
    );
  }
}

How do I create HTML table using jQuery dynamically?

An example with a little less stringified html:

var container = $('#my-container'),
  table = $('<table>');

users.forEach(function(user) {
  var tr = $('<tr>');
  ['ID', 'Name', 'Address'].forEach(function(attr) {
    tr.append('<td>' + user[attr] + '</td>');
  });
  table.append(tr);
});

container.append(table);

Auto line-wrapping in SVG text

Text wrapping is not part of SVG1.1, the currently implemented spec. You should rather use HTML via the <foreignObject/> element.

<svg ...>

<switch>
<foreignObject x="20" y="90" width="150" height="200">
<p xmlns="http://www.w3.org/1999/xhtml">Text goes here</p>
</foreignObject>

<text x="20" y="20">Your SVG viewer cannot display html.</text>
</switch>

</svg>

psql: FATAL: role "postgres" does not exist

If you installed postgres from brew, run this in your terminal :

/usr/local/opt/postgres/bin/createuser -s postgres

Connecting to remote MySQL server using PHP

  • firewall of the server must be set-up to enable incomming connections on port 3306
  • you must have a user in MySQL who is allowed to connect from % (any host) (see manual for details)

The current problem is the first one, but right after you resolve it you will likely get the second one.

What is the use of "using namespace std"?

When you make a call to using namespace <some_namespace>; all symbols in that namespace will become visible without adding the namespace prefix. A symbol may be for instance a function, class or a variable.

E.g. if you add using namespace std; you can write just cout instead of std::cout when calling the operator cout defined in the namespace std.

This is somewhat dangerous because namespaces are meant to be used to avoid name collisions and by writing using namespace you spare some code, but loose this advantage. A better alternative is to use just specific symbols thus making them visible without the namespace prefix. Eg:

#include <iostream>
using std::cout;

int main() {
  cout << "Hello world!";
  return 0;
}

The Android emulator is not starting, showing "invalid command-line parameter"

This don't work since Andoid SDK R12 update. I think is because SDK don't find the Java SDK Path. You can solve that by adding the Java SDK Path in your PATH environment variable.

Is the 'as' keyword required in Oracle to define an alias?

According to the select_list Oracle select documentation the AS is optional.

As a personal note I think it is easier to read with the AS

Meaning of 'const' last in a function declaration of a class?

The const keyword used with the function declaration specifies that it is a const member function and it will not be able to change the data members of the object.

Browser: Identifier X has already been declared

The problem solved when I don't use any declaration like var, let or const

Sass Variable in CSS calc() function

Here is a really simple solution using SASS/SCSS and a math formula style:

/* frame circle */
.container {
    position: relative;
    border-radius: 50%;
    background-color: white;
    overflow: hidden;
    width: 400px;
    height: 400px; }

/* circle sectors */
.menu-frame-sector {
    position: absolute;
    width: 50%;
    height: 50%;
    z-index: 10000;
    transform-origin: 100% 100%;
  }

$sector_count: 8;
$sector_width: 360deg / $sector_count;

.sec0 {
    transform: rotate(0 * $sector_width) skew($sector_width);
    background-color: red; }
.sec1 {
    transform: rotate(1 * $sector_width) skew($sector_width);
    background-color: blue; }
.sec2 {
    transform: rotate(2 * $sector_width) skew($sector_width);
    background-color: red; }
.sec3 {
    transform: rotate(3 * $sector_width) skew($sector_width);
    background-color: blue; }
.sec4 {
    transform: rotate(4 * $sector_width) skew($sector_width);
    background-color: red; }
.sec5 {
    transform: rotate(5 * $sector_width) skew($sector_width);
    background-color: blue; }
.sec6 {
    transform: rotate(6 * $sector_width) skew($sector_width);
    background-color: red; }
.sec7 {
    transform: rotate(7 * $sector_width) skew($sector_width);
    background-color: blue; }

To conclude, I strongly suggest you to understand transform-origin, rotate() and skew():

https://tympanus.net/codrops/2013/08/09/building-a-circular-navigation-with-css-transforms/

Node - was compiled against a different Node.js version using NODE_MODULE_VERSION 51

I deleted the node_modules folder and run npm install and my application started without any errors.

Making a list of evenly spaced numbers in a certain range in python

Similar to Howard's answer but a bit more efficient:

def my_func(low, up, leng):
    step = ((up-low) * 1.0 / leng)
    return [low+i*step for i in xrange(leng)]

print memory address of Python variable

According to the manual, in CPython id() is the actual memory address of the variable. If you want it in hex format, call hex() on it.

x = 5
print hex(id(x))

this will print the memory address of x.

Python decorators in classes

I use this type of decorator in some debugging situations, it allows overriding class properties by decorating, without having to find the calling function.

class myclass(object):
    def __init__(self):
        self.property = "HELLO"

    @adecorator(property="GOODBYE")
    def method(self):
        print self.property

Here is the decorator code

class adecorator (object):
    def __init__ (self, *args, **kwargs):
        # store arguments passed to the decorator
        self.args = args
        self.kwargs = kwargs

    def __call__(self, func):
        def newf(*args, **kwargs):

            #the 'self' for a method function is passed as args[0]
            slf = args[0]

            # replace and store the attributes
            saved = {}
            for k,v in self.kwargs.items():
                if hasattr(slf, k):
                    saved[k] = getattr(slf,k)
                    setattr(slf, k, v)

            # call the method
            ret = func(*args, **kwargs)

            #put things back
            for k,v in saved.items():
                setattr(slf, k, v)

            return ret
        newf.__doc__ = func.__doc__
        return newf 

Note: because I've used a class decorator you'll need to use @adecorator() with the brackets on to decorate functions, even if you don't pass any arguments to the decorator class constructor.

How to disable gradle 'offline mode' in android studio?

@mikepenz has the right one.

You could just hit SHIFT+COMMAND+A (if you're using OSX and 1.4 android studio) and enter OFFLINE in the search box.

Then you'll see what mike have shown you.

Just deselect offline.

Best Practice to Use HttpClient in Multithreaded Environment

I think you will want to use ThreadSafeClientConnManager.

You can see how it works here: http://foo.jasonhudgins.com/2009/08/http-connection-reuse-in-android.html

Or in the AndroidHttpClient which uses it internally.

Getting the index of the returned max or min item using max()/min() on a list

Say that you have a list values = [3,6,1,5], and need the index of the smallest element, i.e. index_min = 2 in this case.

Avoid the solution with itemgetter() presented in the other answers, and use instead

index_min = min(range(len(values)), key=values.__getitem__)

because it doesn't require to import operator nor to use enumerate, and it is always faster(benchmark below) than a solution using itemgetter().

If you are dealing with numpy arrays or can afford numpy as a dependency, consider also using

import numpy as np
index_min = np.argmin(values)

This will be faster than the first solution even if you apply it to a pure Python list if:

  • it is larger than a few elements (about 2**4 elements on my machine)
  • you can afford the memory copy from a pure list to a numpy array

as this benchmark points out: enter image description here

I have run the benchmark on my machine with python 2.7 for the two solutions above (blue: pure python, first solution) (red, numpy solution) and for the standard solution based on itemgetter() (black, reference solution). The same benchmark with python 3.5 showed that the methods compare exactly the same of the python 2.7 case presented above

Resolve Javascript Promise outside function scope

Accepted answer is wrong. It's pretty easy using scope and references, though it may make Promise purists angry:

const createPromise = () => {
    let resolver;
    return [
        new Promise((resolve, reject) => {
            resolver = resolve;
        }),
        resolver,
    ];
};

const [ promise, resolver ] = createPromise();
promise.then(value => console.log(value));
setTimeout(() => resolver('foo'), 1000);

We are essentially grabbing the reference to the resolve function when the promise is created, and we return that so it can be set externally.

In one second the console will output:

> foo

jQuery UI Slider (setting programmatically)

I wanted to update slider as well as the inputbox. For me following is working

a.slider('value',1520);
$("#labelAID").val(1520);

where a is object as following.

 var a= $( "<div id='slider' style='width:200px;margin-left:20px;'></div>" ).insertAfter( "#labelAID" ).slider({
            min: 0,
            max: 2000,
            range: "min",
            value: 111,
            slide: function( event, ui ) {

                $("#labelAID").val(ui.value    );
            }
        });

        $( "#labelAID" ).keyup(function() {
            a.slider( "value",$( "#labelAID" ).val()  );
        });

How can I remove a character from a string using JavaScript?

It only works if I replace it with another character. It will not simply remove it.

This is because when char is equal to "", char.length is 0, so your substrings combine to form the original string. Going with your code attempt, the following will work:

String.prototype.replaceAt = function (index, char) {
    return this.substr(0, index) + char + this.substr(index + 1);
    //   this will 'replace' the character at index with char ^
}

What is the functionality of setSoTimeout and how it works?

The JavaDoc explains it very well:

With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.

SO_TIMEOUT is the timeout that a read() call will block. If the timeout is reached, a java.net.SocketTimeoutException will be thrown. If you want to block forever put this option to zero (the default value), then the read() call will block until at least 1 byte could be read.

NOW() function in PHP

My answer is superfluous, but if you are OCD, visually oriented and you just have to see that now keyword in your code, use:

date( 'Y-m-d H:i:s', strtotime( 'now' ) );

How would you implement an LRU cache in Java?

This is the LRU cache I use, which encapsulates a LinkedHashMap and handles concurrency with a simple synchronize lock guarding the juicy spots. It "touches" elements as they are used so that they become the "freshest" element again, so that it is actually LRU. I also had the requirement of my elements having a minimum lifespan, which you can also think of as "maximum idle time" permitted, then you're up for eviction.

However, I agree with Hank's conclusion and accepted answer -- if I were starting this again today, I'd check out Guava's CacheBuilder.

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;


public class MaxIdleLRUCache<KK, VV> {

    final static private int IDEAL_MAX_CACHE_ENTRIES = 128;

    public interface DeadElementCallback<KK, VV> {
        public void notify(KK key, VV element);
    }

    private Object lock = new Object();
    private long minAge;
    private HashMap<KK, Item<VV>> cache;


    public MaxIdleLRUCache(long minAgeMilliseconds) {
        this(minAgeMilliseconds, IDEAL_MAX_CACHE_ENTRIES);
    }

    public MaxIdleLRUCache(long minAgeMilliseconds, int idealMaxCacheEntries) {
        this(minAgeMilliseconds, idealMaxCacheEntries, null);
    }

    public MaxIdleLRUCache(long minAgeMilliseconds, int idealMaxCacheEntries, final DeadElementCallback<KK, VV> callback) {
        this.minAge = minAgeMilliseconds;
        this.cache = new LinkedHashMap<KK, Item<VV>>(IDEAL_MAX_CACHE_ENTRIES + 1, .75F, true) {
            private static final long serialVersionUID = 1L;

            // This method is called just after a new entry has been added
            public boolean removeEldestEntry(Map.Entry<KK, Item<VV>> eldest) {
                // let's see if the oldest entry is old enough to be deleted. We don't actually care about the cache size.
                long age = System.currentTimeMillis() - eldest.getValue().birth;
                if (age > MaxIdleLRUCache.this.minAge) {
                    if ( callback != null ) {
                        callback.notify(eldest.getKey(), eldest.getValue().payload);
                    }
                    return true; // remove it
                }
                return false; // don't remove this element
            }
        };

    }

    public void put(KK key, VV value) {
        synchronized ( lock ) {
//          System.out.println("put->"+key+","+value);
            cache.put(key, new Item<VV>(value));
        }
    }

    public VV get(KK key) {
        synchronized ( lock ) {
//          System.out.println("get->"+key);
            Item<VV> item = getItem(key);
            return item == null ? null : item.payload;
        }
    }

    public VV remove(String key) {
        synchronized ( lock ) {
//          System.out.println("remove->"+key);
            Item<VV> item =  cache.remove(key);
            if ( item != null ) {
                return item.payload;
            } else {
                return null;
            }
        }
    }

    public int size() {
        synchronized ( lock ) {
            return cache.size();
        }
    }

    private Item<VV> getItem(KK key) {
        Item<VV> item = cache.get(key);
        if (item == null) {
            return null;
        }
        item.touch(); // idle the item to reset the timeout threshold
        return item;
    }

    private static class Item<T> {
        long birth;
        T payload;

        Item(T payload) {
            this.birth = System.currentTimeMillis();
            this.payload = payload;
        }

        public void touch() {
            this.birth = System.currentTimeMillis();
        }
    }

}

Nested attributes unpermitted parameters

or you can simply use

def question_params

  params.require(:question).permit(team_ids: [])

end

Vertical dividers on horizontal UL menu

A simpler solution would be to just add #navigation ul li~li { border-left: 1px solid #857D7A; }

How do I convert a float to an int in Objective C?

Here's a more terse approach that was introduced in 2012:

myInt = @(myFloat).intValue;

What is the max size of localStorage values?

I'm doing the following:

getLocalStorageSizeLimit = function () {

    var maxLength = Math.pow(2,24);
    var preLength = 0;
    var hugeString = "0";
    var testString;
    var keyName = "testingLengthKey";

    //2^24 = 16777216 should be enough to all browsers
    testString = (new Array(Math.pow(2, 24))).join("X");

    while (maxLength !== preLength) {
        try  {
            localStorage.setItem(keyName, testString);

            preLength = testString.length;
            maxLength = Math.ceil(preLength + ((hugeString.length - preLength) / 2));

            testString = hugeString.substr(0, maxLength);
        } catch (e) {
            hugeString = testString;

            maxLength = Math.floor(testString.length - (testString.length - preLength) / 2);
            testString = hugeString.substr(0, maxLength);
        }
    }

    localStorage.removeItem(keyName);

    maxLength = JSON.stringify(this.storageObject).length + maxLength + keyName.length - 2;

    return maxLength;
};

Checking if an object is a given type in Swift

for swift4:

if obj is MyClass{
    // then object type is MyClass Type
}

How to split a large text file into smaller files with equal number of lines?

use split

Split a file into fixed-size pieces, creates output files containing consecutive sections of INPUT (standard input if none is given or INPUT is `-')

Syntax split [options] [INPUT [PREFIX]]

http://ss64.com/bash/split.html

Hard reset of a single file

you can use the below command for reset of single file

git checkout HEAD -- path_to_file/file_name

List all changed files to get path_to_file/filename with below command

git status

Regular expression to match DNS hostname or IP Address?

on php: filter_var(gethostbyname($dns), FILTER_VALIDATE_IP) == true ? 'ip' : 'not ip'

PHP: How to check if image file exists?

A thing you have to understand first: you have no files.
A file is a subject of a filesystem, but you are making your request using HTTP protocol which supports no files but URLs.

So, you have to request an unexisting file using your browser and see the response code. if it's not 404, you are unable to use any wrappers to see if a file exists and you have to request your cdn using some other protocol, FTP for example

Delete column from SQLite table

In Python 3.8... Preserves primary key and column types.

Takes 3 inputs:

  1. a sqlite cursor: db_cur,
  2. table name: t and,
  3. list of columns to junk: columns_to_junk
def removeColumns(db_cur, t, columns_to_junk):

    # Obtain column information
    sql = "PRAGMA table_info(" + t + ")"
    record = query(db_cur, sql)

    # Initialize two strings: one for column names + column types and one just
    # for column names
    cols_w_types = "("
    cols = ""

    # Build the strings, filtering for the column to throw out
    for r in record:
        if r[1] not in columns_to_junk:
            if r[5] == 0:
                cols_w_types += r[1] + " " + r[2] + ","
            if r[5] == 1:
                cols_w_types += r[1] + " " + r[2] + " PRIMARY KEY,"
            cols += r[1] + ","

    # Cut potentially trailing commas
    if cols_w_types[-1] == ",":
        cols_w_types = cols_w_types[:-1]
    else:
        pass

    if cols[-1] == ",":
        cols = cols[:-1]
    else:
        pass

    # Execute SQL
    sql = "CREATE TEMPORARY TABLE xfer " + cols_w_types + ")"
    db_cur.execute(sql)
    sql = "INSERT INTO xfer SELECT " + cols + " FROM " + t
    db_cur.execute(sql)
    sql = "DROP TABLE " + t
    db_cur.execute(sql)
    sql = "CREATE TABLE " + t + cols_w_types + ")"
    db_cur.execute(sql)
    sql = "INSERT INTO " + t + " SELECT " + cols  + " FROM xfer"
    db_cur.execute(sql)

You'll find a reference to a query() function. Just a helper...

Takes two inputs:

  1. sqlite cursor db_cur and,
  2. the query string: query
def query(db_cur, query):

    r = db_cur.execute(query).fetchall()

    return r

Don't forget to include a "commit()"!

Can Flask have optional URL parameters?

I think you can use Blueprint and that's will make ur code look better and neatly.

example:

from flask import Blueprint

bp = Blueprint(__name__, "example")

@bp.route("/example", methods=["POST"])
def example(self):
   print("example")

Laravel 4 with Sentry 2 add user to a group on Registration

Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.

Do you have this:

use Cartalyst\Sentry\Sentry; 

In your code?

Ok, but if this line is working for you:

$user = $this->sentry->register(array(     'username' => e($data['username']),     'email' => e($data['email']),      'password' => e($data['password'])     )); 

So you already have it instantiated and you can surely do:

$adminGroup = $this->sentry->findGroupById(5); 

How to change button background image on mouseOver?

I think something like this:

btn.BackgroundImage = Properties.Resources.*Image_Identifier*;

Where *Image_Identifier* is an identifier of the image in your resources.

How can I see what I am about to push with git?

If you are using Mac OS X, I would recommend you get Tower, it's a wonderful program that has made dealing with Git a pleasure for me. I now longer have to remember terminal commands and it offers a great GUI to view, track and solve differences in files.

And no, I'm not affiliated with them, I just use their software and really like it.

http://www.git-tower.com/

Getting "NoSuchMethodError: org.hamcrest.Matcher.describeMismatch" when running test in IntelliJ 10.5

As of July, 2020 the following dependencies in pom.xml worked for me:

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13</version>
</dependency>
<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest</artifactId>
    <version>2.1</version>
</dependency>

With this 4.13 junit library and hamcrest, it uses hamcrest.MatcherAssert when asserting and throws exception- enter image description here

Convert time.Time to string

Please find the simple solution to convete Date & Time Format in Go Lang. Please find the example below.

Package Link: https://github.com/vigneshuvi/GoDateFormat.

Please find the plackholders:https://medium.com/@Martynas/formatting-date-and-time-in-golang-5816112bf098

package main


// Import Package
import (
    "fmt"
    "time"
    "github.com/vigneshuvi/GoDateFormat"
)

func main() {
    fmt.Println("Go Date Format(Today - 'yyyy-MM-dd HH:mm:ss Z'): ", GetToday(GoDateFormat.ConvertFormat("yyyy-MM-dd HH:mm:ss Z")))
    fmt.Println("Go Date Format(Today - 'yyyy-MMM-dd'): ", GetToday(GoDateFormat.ConvertFormat("yyyy-MMM-dd")))
    fmt.Println("Go Time Format(NOW - 'HH:MM:SS'): ", GetToday(GoDateFormat.ConvertFormat("HH:MM:SS")))
    fmt.Println("Go Time Format(NOW - 'HH:MM:SS tt'): ", GetToday(GoDateFormat.ConvertFormat("HH:MM:SS tt")))
}

func GetToday(format string) (todayString string){
    today := time.Now()
    todayString = today.Format(format);
    return
}

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.

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

One more reason for this error (assuming that gradle properly setup) is incompatibility between andorid.gradle tools and gradle itself - check out this answer for the complete compatibility table.

In my case the error was the same as in the question and the stacktrace as following:

java.lang.NullPointerException
    at java.util.Objects.requireNonNull(Objects.java:203)
    at com.android.build.gradle.BasePlugin.lambda$configureProject$1(BasePlugin.java:436)
    at sun.reflect.GeneratedMethodAccessor32.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:42)
    ...

I've fixed that by upgrading com.android.tools.build:gradle to the current latest 3.1.4

buildscript {
    repositories {
        ...
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.4'
    }
}

Gradle version is 4.6

Trouble Connecting to sql server Login failed. "The login is from an untrusted domain and cannot be used with Windows authentication"

As mentioned here, you might need to disable the loopback

Loopback check can be removed by adding a registry entry as follows:

  • Edit the registry using regedit. (Start –> Run > Regedit )
  • Navigate to: HKLM\System\CurrentControlSet\Control\LSA
  • Add a DWORD value called “DisableLoopbackCheck” Set this value to 1