Programs & Examples On #Language construct

?: operator (the 'Elvis operator') in PHP

See the docs:

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

Work on a remote project with Eclipse via SSH

My solution is similar to the SAMBA one except using sshfs. Mount my remote server with sshfs, open my makefile project on the remote machine. Go from there.

It seems I can run a GUI frontend to mercurial this way as well.

Building my remote code is as simple as: ssh address remote_make_command

I am looking for a decent way to debug though. Possibly via gdbserver?

Backporting Python 3 open(encoding="utf-8") to Python 2

I think

from io import open

should do.

long long in C/C++

It depends in what mode you are compiling. long long is not part of the C++ standard but only (usually) supported as extension. This affects the type of literals. Decimal integer literals without any suffix are always of type int if int is big enough to represent the number, long otherwise. If the number is even too big for long the result is implementation-defined (probably just a number of type long int that has been truncated for backward compatibility). In this case you have to explicitly use the LL suffix to enable the long long extension (on most compilers).

The next C++ version will officially support long long in a way that you won't need any suffix unless you explicitly want the force the literal's type to be at least long long. If the number cannot be represented in long the compiler will automatically try to use long long even without LL suffix. I believe this is the behaviour of C99 as well.

SQL to add column and comment in table in single command

You can use below query to update or create comment on already created table.

SYNTAX:

COMMENT ON COLUMN TableName.ColumnName IS 'comment text';

Example:

COMMENT ON COLUMN TAB_SAMBANGI.MY_COLUMN IS 'This is a comment on my column...';

ERROR Android emulator gets killed

This issue happens when you have two Android SDK installations on your machine and the environment variable "ANDROID_HOME" points to the wrong location.

To fix it go to Android Studio settings, find the proper Android SDK location, update the environment variable and restart Android Studio / your PC.

enter image description here

REST, HTTP DELETE and parameters

In addition to Alex's answer:

Note that http://server/resource/id?force_delete=true identifies a different resource than http://server/resource/id. For example, it is a huge difference whether you delete /customers/?status=old or /customers/.

"npm config set registry https://registry.npmjs.org/" is not working in windows bat file

You shouldn't change the npm registry using .bat files. Instead try to use modify the .npmrc file which is the configuration for npm. The correct command for changing registry is

npm config set registry <registry url>

you can find more information with npm help config command, also check for privileges when and if you are running .bat files this way.

Insert string in beginning of another string

import java.lang.StringBuilder;

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

    // Create a new StringBuilder.
    StringBuilder builder = new StringBuilder();

    // Loop and append values.
    for (int i = 0; i < 5; i++) {
        builder.append("abc ");
    }
    // Convert to string.
    String result = builder.toString();

    // Print result.
    System.out.println(result);
    }
}

How do I parse a YAML file in Ruby?

Maybe I'm missing something, but why try to parse the file? Why not just load the YAML and examine the object(s) that result?

If your sample YAML is in some.yml, then this:

require 'yaml'
thing = YAML.load_file('some.yml')
puts thing.inspect

gives me

{"javascripts"=>[{"fo_global"=>["lazyload-min", "holla-min"]}]}

How to sort an ArrayList in Java

Use a Comparator like this:

List<Fruit> fruits= new ArrayList<Fruit>();

Fruit fruit;
for(int i = 0; i < 100; i++)
{
  fruit = new Fruit();
  fruit.setname(...);
  fruits.add(fruit);
}

// Sorting
Collections.sort(fruits, new Comparator<Fruit>() {
        @Override
        public int compare(Fruit fruit2, Fruit fruit1)
        {

            return  fruit1.fruitName.compareTo(fruit2.fruitName);
        }
    });

Now your fruits list is sorted based on fruitName.

HTML Code for text checkbox '?'

Use the Unicode Character

&#10004;   =   ✔


Entity Framework 6 Code first Default value

It's been a while, but leaving a note for others. I achieved what is needed with an attribute and I decorated my model class fields with that attribute as I want.

[SqlDefaultValue(DefaultValue = "getutcdate()")]
public DateTime CreatedDateUtc { get; set; }

Got the help of these 2 articles:

What I did:

Define Attribute

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class SqlDefaultValueAttribute : Attribute
{
    public string DefaultValue { get; set; }
}

In the "OnModelCreating" of the context

modelBuilder.Conventions.Add( new AttributeToColumnAnnotationConvention<SqlDefaultValueAttribute, string>("SqlDefaultValue", (p, attributes) => attributes.Single().DefaultValue));

In the custom SqlGenerator

private void SetAnnotatedColumn(ColumnModel col)
{
    AnnotationValues values;
    if (col.Annotations.TryGetValue("SqlDefaultValue", out values))
    {
         col.DefaultValueSql = (string)values.NewValue;
    }
}

Then in the Migration Configuration constructor, register the custom SQL generator.

SetSqlGenerator("System.Data.SqlClient", new CustomMigrationSqlGenerator());

Draw in Canvas by finger, Android

In addition to Ishan's answer, if you want to draw programatically without user interaction, you can edit the class just a little like this.

public class DrawingCanvas extends View {

private Paint mPaint;
private Path mPath;
private boolean isUserInteractionEnabled = false;

public DrawingCanvas(Context context, AttributeSet attrs) {
    super(context, attrs);
    mPaint = new Paint();
    mPaint.setColor(Color.RED);
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setStrokeJoin(Paint.Join.ROUND);
    mPaint.setStrokeCap(Paint.Cap.ROUND);
    mPaint.setStrokeWidth(10);
    mPath = new Path();
}


@Override
protected void onDraw(Canvas canvas) {
    canvas.drawPath(mPath, mPaint);
    super.onDraw(canvas);
}


@Override
public boolean onTouchEvent(MotionEvent event) {
    if (isUserInteractionEnabled) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mPath.moveTo(event.getX(), event.getY());
                break;
            case MotionEvent.ACTION_MOVE:
                mPath.lineTo(event.getX(), event.getY());
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                break;
        }
    }

    return true;
}

public void moveCursorTo(float x, float y) {
    mPath.moveTo(x, y);
}

public void makeLine(float toX, float toY) {
    mPath.lineTo(toX, toY);
}

public void setUserInteractionEnabled(boolean userInteractionEnabled) {
    isUserInteractionEnabled = userInteractionEnabled;
}
}

And then use it like

drawingCanvas.setUserInteractionEnabled(true) // to enable user interaction
drawingCanvas.setUserInteractionEnabled(true) // to disable user interaction

To Draw programatically

drawingCanvas.moveCursorTo(70f, 70f) // Move the cursor (Define starting point)
drawingCanvas.makeLine(200f, 200f) // End point (To where you need to draw)

How do I view the SQL generated by the Entity Framework?

EF Core 5.0

This loooong-awaited feature is available in EF Core 5.0! This is from the weekly status updates:

var query = context.Set<Customer>().Where(c => c.City == city);
Console.WriteLine(query.ToQueryString())

results in this output when using the SQL Server database provider:

DECLARE p0 nvarchar(4000) = N'London';

SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName],
[c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone],
[c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE [c].[City] = @__city_0

Notice that declarations for parameters of the correct type are also included in the output. This allows copy/pasting to SQL Server Management Studio, or similar tools, such that the query can be executed for debugging/analysis.

woohoo!!!

Formula px to dp, dp to px android

Efficient way ever

DP to Pixel:

private int dpToPx(int dp)
{
    return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
}

Pixel to DP:

private int pxToDp(int px)
{
    return (int) (px / Resources.getSystem().getDisplayMetrics().density);
}

Hope this will help you.

CFLAGS vs CPPFLAGS

The CPPFLAGS macro is the one to use to specify #include directories.

Both CPPFLAGS and CFLAGS work in your case because the make(1) rule combines both preprocessing and compiling in one command (so both macros are used in the command).

You don't need to specify . as an include-directory if you use the form #include "...". You also don't need to specify the standard compiler include directory. You do need to specify all other include-directories.

Height of status bar in Android

To solve this, I used a combination approach. This is necessary as on tablets the system bar already subtracts it's pixels when display.getHeight() is called. So I first check if a system bar is present, and then Ben Claytons approach, which works fine on phones.

public int getStatusBarHeight() {
    int statusBarHeight = 0;

    if (!hasOnScreenSystemBar()) {
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            statusBarHeight = getResources().getDimensionPixelSize(resourceId);
        }
    }

    return statusBarHeight;
}

private boolean hasOnScreenSystemBar() {
    Display display = getWindowManager().getDefaultDisplay();
    int rawDisplayHeight = 0;
    try {
        Method getRawHeight = Display.class.getMethod("getRawHeight");
        rawDisplayHeight = (Integer) getRawHeight.invoke(display);
    } catch (Exception ex) {
    }

    int UIRequestedHeight = display.getHeight();

    return rawDisplayHeight - UIRequestedHeight > 0;
}

How to see JavaDoc in IntelliJ IDEA?

Use View | Quick Documentation or the corresponding keyboard shortcut (by default: Ctrl+Q on Windows/Linux and Ctrl+J on macOS or F1 in the recent IDE versions). See the documentation for more information.

It's also possible to enable automatic JavaDoc popup on explicit (invoked by a shortcut) code completion in Settings | Editor | General | Code completion (Autopopup documentation):

autopopup documentation

Yet another way to see the quick doc is on mouse move:

on mouse move

Mysql 1050 Error "Table already exists" when in fact, it does not

I've just had the same error but I knew the table already existed and wanted to add to it. I'm adding my answer as this question comes up as no.1 for me on google when looking for the same error but for a slightly different scenario. Basically I needed to tick

"Add DROP TABLE / VIEW / PROCEDURE / FUNCTION / EVENT / TRIGGER statement"

And this solved the error for me.

How to disable GCC warnings for a few lines of code

It appears this can be done. I'm unable to determine the version of GCC that it was added, but it was sometime before June 2010.

Here's an example:

#pragma GCC diagnostic error "-Wuninitialized"
    foo(a);         /* error is given for this one */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wuninitialized"
    foo(b);         /* no diagnostic for this one */
#pragma GCC diagnostic pop
    foo(c);         /* error is given for this one */
#pragma GCC diagnostic pop
    foo(d);         /* depends on command line options */

Disabling radio buttons with jQuery

code:

function writeData() {
    jQuery("#chatTickets input:radio[id^=ticketID]:first").attr('disabled', true);
    return false;
}

See also: Selector/radio, Selector/attributeStartsWith, Selector/first

Keyboard shortcut to change font size in Eclipse?

Found a great plugin that works in Juno and Kepler. It puts shortcuts on the quick access bar for increasing or decreasing text size.

Install New Software -> http://eclipse-fonts.googlecode.com/svn/trunk/FontsUpdate/

Aliases in Windows command prompt

If you'd like to enable aliases on per-directory/per-project basis, try the following:

  1. First, create a batch file that will look for a file named aliases in the current directory and initialize aliases from it, let’s call it make-aliases.cmd

    @echo off
    if not exist aliases goto:eof
    echo [Loading aliases...]
    for /f "tokens=1* delims=^=" %%i in (aliases) do (
       echo   %%i ^<^=^> %%j
       doskey %%i=%%j
    )
    doskey aliases=doskey /macros
    echo   --------------------
    echo   aliases ^=^> list  all
    echo   alt+F10 ^=^> clear all
    echo [Done]
    
  2. Then, create aliases wherever you need them using the following format:

    alias1 = command1
    alias2 = command2
    ...
    

    for example:

    b = nmake
    c = nmake clean
    r = nmake rebuild
    
  3. Then, add the location of make-aliases.cmd to your %PATH% variable to make it system-wide or just keep it in a known place.

  4. Make it start automatically with cmd.

    • I would definitely advise against using HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun for this, because some development tools would trigger the autorun script multiple times per session.

    • If you use ConEmu you could go another way and start the script from the startup task (Settings > Startup > Tasks), for example, I created an entry called {MSVC}:

      cmd.exe /k "vcvars64 && make-aliases",

      and then registered it in Explorer context menu via Settings > Integration> with Command: {MSVC} -cur_console:n, so that now I can right-click a folder and launch a VS developer prompt inside it with my aliases loaded automatically, if they happen to be in that folder.

      Without ConEmu, you may just want to create a shortcut to cmd.exe with the corresponding command or simply run make-aliases manually every time.

Should you happen to forget your aliases, use the aliases macro, and if anything goes wrong, just reset the current session by pressing Alt+F10, which is a built-in command in cmd.

How to get complete month name from DateTime

You can do as mservidio suggested, or even better, keep track of your culture using this overload:

DateTime.Now.ToString("MMMM", CultureInfo.InvariantCulture);

What's the difference between SHA and AES encryption?

SHA isn't encryption, it's a one-way hash function. AES (Advanced_Encryption_Standard) is a symmetric encryption standard.

AES Reference

Copying files into the application folder at compile time

I found this question searching for "copy files into the application folder at compile time". OP seems to have this sorted already, but if you don't:

In Visual Studio right-click the file, select properties, then change the option 'copy to output' to 'always'. See http://msdn.microsoft.com/en-us/library/0c6xyb66.aspx

HTML span align center not working?

Just use word-wrap:break-word; in the css. It works.

Array to Hash Ruby

Or if you have an array of [key, value] arrays, you can do:

[[1, 2], [3, 4]].inject({}) do |r, s|
  r.merge!({s[0] => s[1]})
end # => { 1 => 2, 3 => 4 }

Transpose a matrix in Python

If we wanted to return the same matrix we would write:

return [[ m[row][col] for col in range(0,width) ] for row in range(0,height) ]

What this does is it iterates over a matrix m by going through each row and returning each element in each column. So the order would be like:

[[1,2,3],
[4,5,6],
[7,8,9]]

Now for question 3, we instead want to go column by column, returning each element in each row. So the order would be like:

[[1,4,7],
[2,5,8],
[3,6,9]]

Therefore just switch the order in which we iterate:

return [[ m[row][col] for row in range(0,height) ] for col in range(0,width) ]

Setting an HTML text input box's "default" value. Revert the value when clicking ESC

See the defaultValue property of a text input, it's also used when you reset the form by clicking an <input type="reset"/> button (http://www.w3schools.com/jsref/prop_text_defaultvalue.asp )

btw, defaultValue and placeholder text are different concepts, you need to see which one better fits your needs

Making PHP var_dump() values display one line per value

var_export will give you a nice output. Examples from the docs:

$a = array (1, 2, array ("a", "b", "c"));
echo '<pre>' . var_export($a, true) . '</pre>';

Will output:

array (
  0 => 1,
  1 => 2,
  2 => 
  array (
    0 => 'a',
    1 => 'b',
    2 => 'c',
  ),
)

How do I set the request timeout for one controller action in an asp.net mvc application

You can set this programmatically in the controller:-

HttpContext.Current.Server.ScriptTimeout = 300;

Sets the timeout to 5 minutes instead of the default 110 seconds (what an odd default?)

How to get element by classname or id

@tasseKATT's Answer is great, but if you don't want to make a directive, why not use $document?

.controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  var dumb = function (id) {
  var queryResult = $document[0].getElementById(id)
  var wrappedID = angular.element(queryResult);
  return wrappedID;
};

PLUNKR

How to customize the background/border colors of a grouped table view cell?

UPDATE: In iPhone OS 3.0 and later UITableViewCell now has a backgroundColor property that makes this really easy (especially in combination with the [UIColor colorWithPatternImage:] initializer). But I'll leave the 2.0 version of the answer here for anyone that needs it…


It's harder than it really should be. Here's how I did this when I had to do it:

You need to set the UITableViewCell's backgroundView property to a custom UIView that draws the border and background itself in the appropriate colors. This view needs to be able to draw the borders in 4 different modes, rounded on the top for the first cell in a section, rounded on the bottom for the last cell in a section, no rounded corners for cells in the middle of a section, and rounded on all 4 corners for sections that contain one cell.

Unfortunately I couldn't figure out how to have this mode set automatically, so I had to set it in the UITableViewDataSource's -cellForRowAtIndexPath method.

It's a real PITA but I've confirmed with Apple engineers that this is currently the only way.

Update Here's the code for that custom bg view. There's a drawing bug that makes the rounded corners look a little funny, but we moved to a different design and scrapped the custom backgrounds before I had a chance to fix it. Still this will probably be very helpful for you:

//
//  CustomCellBackgroundView.h
//
//  Created by Mike Akers on 11/21/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import <UIKit/UIKit.h>

typedef enum  {
    CustomCellBackgroundViewPositionTop, 
    CustomCellBackgroundViewPositionMiddle, 
    CustomCellBackgroundViewPositionBottom,
    CustomCellBackgroundViewPositionSingle
} CustomCellBackgroundViewPosition;

@interface CustomCellBackgroundView : UIView {
    UIColor *borderColor;
    UIColor *fillColor;
    CustomCellBackgroundViewPosition position;
}

    @property(nonatomic, retain) UIColor *borderColor, *fillColor;
    @property(nonatomic) CustomCellBackgroundViewPosition position;
@end

//
//  CustomCellBackgroundView.m
//
//  Created by Mike Akers on 11/21/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "CustomCellBackgroundView.h"

static void addRoundedRectToPath(CGContextRef context, CGRect rect,
                                 float ovalWidth,float ovalHeight);

@implementation CustomCellBackgroundView
@synthesize borderColor, fillColor, position;

- (BOOL) isOpaque {
    return NO;
}

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // Initialization code
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    // Drawing code
    CGContextRef c = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(c, [fillColor CGColor]);
    CGContextSetStrokeColorWithColor(c, [borderColor CGColor]);

    if (position == CustomCellBackgroundViewPositionTop) {
        CGContextFillRect(c, CGRectMake(0.0f, rect.size.height - 10.0f, rect.size.width, 10.0f));
        CGContextBeginPath(c);
        CGContextMoveToPoint(c, 0.0f, rect.size.height - 10.0f);
        CGContextAddLineToPoint(c, 0.0f, rect.size.height);
        CGContextAddLineToPoint(c, rect.size.width, rect.size.height);
        CGContextAddLineToPoint(c, rect.size.width, rect.size.height - 10.0f);
        CGContextStrokePath(c);
        CGContextClipToRect(c, CGRectMake(0.0f, 0.0f, rect.size.width, rect.size.height - 10.0f));
    } else if (position == CustomCellBackgroundViewPositionBottom) {
        CGContextFillRect(c, CGRectMake(0.0f, 0.0f, rect.size.width, 10.0f));
        CGContextBeginPath(c);
        CGContextMoveToPoint(c, 0.0f, 10.0f);
        CGContextAddLineToPoint(c, 0.0f, 0.0f);
        CGContextStrokePath(c);
        CGContextBeginPath(c);
        CGContextMoveToPoint(c, rect.size.width, 0.0f);
        CGContextAddLineToPoint(c, rect.size.width, 10.0f);
        CGContextStrokePath(c);
        CGContextClipToRect(c, CGRectMake(0.0f, 10.0f, rect.size.width, rect.size.height));
    } else if (position == CustomCellBackgroundViewPositionMiddle) {
        CGContextFillRect(c, rect);
        CGContextBeginPath(c);
        CGContextMoveToPoint(c, 0.0f, 0.0f);
        CGContextAddLineToPoint(c, 0.0f, rect.size.height);
        CGContextAddLineToPoint(c, rect.size.width, rect.size.height);
        CGContextAddLineToPoint(c, rect.size.width, 0.0f);
        CGContextStrokePath(c);
        return; // no need to bother drawing rounded corners, so we return
    }

    // At this point the clip rect is set to only draw the appropriate
    // corners, so we fill and stroke a rounded rect taking the entire rect

    CGContextBeginPath(c);
    addRoundedRectToPath(c, rect, 10.0f, 10.0f);
    CGContextFillPath(c);  

    CGContextSetLineWidth(c, 1);  
    CGContextBeginPath(c);
    addRoundedRectToPath(c, rect, 10.0f, 10.0f);  
    CGContextStrokePath(c); 
}


- (void)dealloc {
    [borderColor release];
    [fillColor release];
    [super dealloc];
}


@end

static void addRoundedRectToPath(CGContextRef context, CGRect rect,
                                float ovalWidth,float ovalHeight)

{
    float fw, fh;

    if (ovalWidth == 0 || ovalHeight == 0) {// 1
        CGContextAddRect(context, rect);
        return;
    }

    CGContextSaveGState(context);// 2

    CGContextTranslateCTM (context, CGRectGetMinX(rect),// 3
                           CGRectGetMinY(rect));
    CGContextScaleCTM (context, ovalWidth, ovalHeight);// 4
    fw = CGRectGetWidth (rect) / ovalWidth;// 5
    fh = CGRectGetHeight (rect) / ovalHeight;// 6

    CGContextMoveToPoint(context, fw, fh/2); // 7
    CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1);// 8
    CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1);// 9
    CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1);// 10
    CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1); // 11
    CGContextClosePath(context);// 12

    CGContextRestoreGState(context);// 13
}

ValueError: object too deep for desired array while using convolution

np.convolve needs a flattened array as one of it's inputs, you can use numpy.ndarray.flatten() which is quite fast, find it here.

Angular 2: 404 error occur when I refresh through the browser

If you're running Angular 2 through ASP.NET Core 1 in Visual Studio 2015, you might find this solution from Jürgen Gutsch helpful. He describes it in a blog post. It was the best solution for me. Place the C# code provided below in your Startup.cs public void Configure() just before app.UseStaticFiles();

app.Use( async ( context, next ) => {
    await next();

    if( context.Response.StatusCode == 404 && !Path.HasExtension( context.Request.Path.Value ) ) {
        context.Request.Path = "/index.html";
        await next();
    }
});

Can not deserialize instance of java.lang.String out of START_OBJECT token

You're mapping this JSON

{
    "id": 2,
    "socket": "0c317829-69bf-43d6-b598-7c0c550635bb",
    "type": "getDashboard",
    "data": {
        "workstationUuid": "ddec1caa-a97f-4922-833f-632da07ffc11"
    },
    "reply": true
}

that contains an element named data that has a JSON object as its value. You are trying to deserialize the element named workstationUuid from that JSON object into this setter.

@JsonProperty("workstationUuid")
public void setWorkstation(String workstationUUID) {

This won't work directly because Jackson sees a JSON_OBJECT, not a String.

Try creating a class Data

public class Data { // the name doesn't matter 
    @JsonProperty("workstationUuid")
    private String workstationUuid;
    // getter and setter
}

the switch up your method

@JsonProperty("data")
public void setWorkstation(Data data) {
    // use getter to retrieve it

How do I login and authenticate to Postgresql after a fresh install?

you can also connect to database as "normal" user (not postgres):

postgres=# \connect opensim Opensim_Tester localhost;

Password for user Opensim_Tester:    

You are now connected to database "opensim" as user "Opensim_Tester" on host "localhost" at port "5432"

How to Run Terminal as Administrator on Mac Pro

Add sudo to your command line, like:

$ sudo firebase init

Best way to check if an PowerShell Object exist?

I would stick with the $null check since any value other than '' (empty string), 0, $false and $null will pass the check: if ($ie) {...}.

Webpack "OTS parsing error" loading fonts

As of 2018,

use MiniCssExtractPlugin

for Webpack(> 4.0) will solve this problem.

https://github.com/webpack-contrib/mini-css-extract-plugin

Using extract-text-webpack-plugin in the accepted answer is NOT recommended for Webpack 4.0+.

Convert boolean result into number/integer

Javascript has a ternary operator you could use:

var i = result ? 1 : 0;

Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

I had problems with the same error on more than one Spring project. For me a general solution was, to split my service Method, that each INSERT, UPDATE and DELETE action got an own Method with @Transactional. I think this problem relates to the internal Spring managment, where database interactions are executed at the end of the method and, in my oppinion, this is the point, where the Exception is triggered.

An existing connection was forcibly closed by the remote host

For anyone getting this exception while reading data from the stream, this may help. I was getting this exception when reading the HttpResponseMessage in a loop like this:

using (var remoteStream = await response.Content.ReadAsStreamAsync())
using (var content = File.Create(DownloadPath))
{
    var buffer = new byte[1024];
    int read;

    while ((read = await remoteStream.ReadAsync(buffer, 0, buffer.Length)) != 0)
    {
        await content.WriteAsync(buffer, 0, read);
        await content.FlushAsync();
    }
}

After some time I found out the culprit was the buffer size, which was too small and didn't play well with my weak Azure instance. What helped was to change the code to:

using (Stream remoteStream = await response.Content.ReadAsStreamAsync())
using (FileStream content = File.Create(DownloadPath))
{
    await remoteStream.CopyToAsync(content);
}

CopyTo() method has a default buffer size of 81920. The bigger buffer sped up the process and the errors stopped immediately, most likely because the overall download speeds increased. But why would download speed matter in preventing this error?

It is possible that you get disconnected from the server because the download speeds drop below minimum threshold the server is configured to allow. For example, in case the application you are downloading the file from is hosted on IIS, it can be a problem with http.sys configuration:

"Http.sys is the http protocol stack that IIS uses to perform http communication with clients. It has a timer called MinBytesPerSecond that is responsible for killing a connection if its transfer rate drops below some kb/sec threshold. By default, that threshold is set to 240 kb/sec."

The issue is described in this old blogpost from TFS development team and concerns IIS specifically, but may point you in a right direction. It also mentions an old bug related to this http.sys attribute: link

In case you are using Azure app services and increasing the buffer size does not eliminate the problem, try to scale up your machine as well. You will be allocated more resources including connection bandwidth.

How do I replace all line breaks in a string with <br /> elements?

If the accepted answer isn't working right for you then you might try.

str.replace(new RegExp('\n','g'), '<br />')

It worked for me.

IOException: The process cannot access the file 'file path' because it is being used by another process

I had the following scenario that was causing the same error:

  • Upload files to the server
  • Then get rid of the old files after they have been uploaded

Most files were small in size, however, a few were large, and so attempting to delete those resulted in the cannot access file error.

It was not easy to find, however, the solution was as simple as Waiting "for the task to complete execution":

using (var wc = new WebClient())
{
   var tskResult = wc.UploadFileTaskAsync(_address, _fileName);
   tskResult.Wait(); 
}

Batch File; List files in directory, only filenames?

The full command is:

dir /b /a-d

Let me break it up;

Basically the /b is what you look for.

/a-d will exclude the directory names.


For more information see dir /? for other arguments that you can use with the dir command.

C# Equivalent of SQL Server DataTypes

This is for SQL Server 2005. There are updated versions of the table for SQL Server 2008, SQL Server 2008 R2, SQL Server 2012 and SQL Server 2014.

SQL Server Data Types and Their .NET Framework Equivalents

The following table lists Microsoft SQL Server data types, their equivalents in the common language runtime (CLR) for SQL Server in the System.Data.SqlTypes namespace, and their native CLR equivalents in the Microsoft .NET Framework.

SQL Server data type          CLR data type (SQL Server)    CLR data type (.NET Framework)  
varbinary                     SqlBytes, SqlBinary           Byte[]  
binary                        SqlBytes, SqlBinary           Byte[]  
varbinary(1), binary(1)       SqlBytes, SqlBinary           byte, Byte[] 
image                         None                          None

varchar                       None                          None
char                          None                          None
nvarchar(1), nchar(1)         SqlChars, SqlString           Char, String, Char[]     
nvarchar                      SqlChars, SqlString           String, Char[] 
nchar                         SqlChars, SqlString           String, Char[] 
text                          None                          None
ntext                         None                          None

uniqueidentifier              SqlGuid                       Guid 
rowversion                    None                          Byte[]  
bit                           SqlBoolean                    Boolean 
tinyint                       SqlByte                       Byte 
smallint                      SqlInt16                      Int16  
int                           SqlInt32                      Int32  
bigint                        SqlInt64                      Int64 

smallmoney                    SqlMoney                      Decimal  
money                         SqlMoney                      Decimal  
numeric                       SqlDecimal                    Decimal  
decimal                       SqlDecimal                    Decimal  
real                          SqlSingle                     Single  
float                         SqlDouble                     Double  

smalldatetime                 SqlDateTime                   DateTime  
datetime                      SqlDateTime                   DateTime 

sql_variant                   None                          Object  
User-defined type(UDT)        None                          user-defined type     
table                         None                          None 
cursor                        None                          None
timestamp                     None                          None 
xml                           SqlXml                        None

Tensorflow r1.0 : could not a find a version that satisfies the requirement tensorflow

The TensorFlow package couldn't be found by the latest version of the "pip".
To be honest, I really don't know why this is...
but, the quick fix that worked out for me was:
[In case you are using a virtual environment]
downgrade the virtual environment to python-3.8.x and pip-20.2.x In case of anaconda, try:

conda install python=3.8

This should install the latest version of python-3.8 and pip-20.2.x for you.
And then, try

pip install tensorflow

Again, this worked fine for me, not sure if it'll work the same for you.

How to redirect the output of DBMS_OUTPUT.PUT_LINE to a file?

As a side note, remember that all this output is generated in the server side.

Using DBMS_OUTPUT, the text is generated in the server while it executes your query and stored in a buffer. It is then redirected to your client app when the server finishes the query data retrieval. That is, you only get this info when the query ends.

With UTL_FILE all the information logged will be stored in a file in the server. When the execution finishes you will have to navigate to this file to get the information.

Hope this helps.

React onClick function fires on render

I had similar issue, my code was:

function RadioInput(props) {
    return (
    <div className="form-check form-check-inline">
        <input className="form-check-input" type="radio" name="inlineRadioOptions" id={props.id} onClick={props.onClick} value={props.label}></input>
        <label className="form-check-label" htmlFor={props.id}>{props.label}</label>
    </div>
    );
  }
class ScheduleType extends React.Component
{
    renderRadioInput(id,label)
    {
        id = "inlineRadio"+id;
        return(
            <RadioInput
                id = {id}
                label = {label}
                onClick = {this.props.onClick}
            />
        );

    }

Where it should be

onClick = {() => this.props.onClick()}

in RenderRadioInput

It fixed the issue for me.

Capture Video of Android's Screen

I have not used the app, but I've seen Rec. referenced as a way to do this, but you need root the phone.

ruby 1.9: invalid byte sequence in UTF-8

The accepted answer nor the other answer work for me. I found this post which suggested

string.encode!('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')

This fixed the problem for me.

Getting the exception value in Python

For python2, It's better to use e.message to get the exception message, this will avoid possible UnicodeDecodeError. But yes e.message will be empty for some kind of exceptions like OSError, in which case we can add a exc_info=True to our logging function to not miss the error.
For python3, I think it's safe to use str(e).

How to load a xib file in a UIView

For swift 3 & 4

let customView = Bundle.main.loadNibNamed("CustomView", owner: nil, options: nil)?.first as? CustomView

What does "control reaches end of non-void function" mean?

Compiler by itself would not know that the conditions you have given are optimum .. meaning of this is you have covered all cases .. So therefore it always wants a return statement ... So either you can change last else if with else or just write return 0 after last else if ;`int binary(int val, int sorted[], int low, int high) { int mid = (low+high)/2;

if(high < low)
    return -1;

if(val < sorted[mid])
    return binary(val, sorted, low, mid-1);

else if(val > sorted[mid])
    return binary(val, sorted, mid+1, high);

else if(val == sorted[mid])
    return mid;
return 0; }`

HTML5 File API read as text and binary

Note in 2018: readAsBinaryString is outdated. For use cases where previously you'd have used it, these days you'd use readAsArrayBuffer (or in some cases, readAsDataURL) instead.


readAsBinaryString says that the data must be represented as a binary string, where:

...every byte is represented by an integer in the range [0..255].

JavaScript originally didn't have a "binary" type (until ECMAScript 5's WebGL support of Typed Array* (details below) -- it has been superseded by ECMAScript 2015's ArrayBuffer) and so they went with a String with the guarantee that no character stored in the String would be outside the range 0..255. (They could have gone with an array of Numbers instead, but they didn't; perhaps large Strings are more memory-efficient than large arrays of Numbers, since Numbers are floating-point.)

If you're reading a file that's mostly text in a western script (mostly English, for instance), then that string is going to look a lot like text. If you read a file with Unicode characters in it, you should notice a difference, since JavaScript strings are UTF-16** (details below) and so some characters will have values above 255, whereas a "binary string" according to the File API spec wouldn't have any values above 255 (you'd have two individual "characters" for the two bytes of the Unicode code point).

If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between readAsText and readAsBinaryString, but with readAsBinaryString you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use readAsText, because readAsText will use an encoding determination to try to figure out what the file's encoding is and then map it to JavaScript's UTF-16 strings.

You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
    font-family: sans-serif;
}
</style>
<script type='text/javascript'>

    function loadFile() {
        var input, file, fr;

        if (typeof window.FileReader !== 'function') {
            bodyAppend("p", "The file API isn't supported on this browser yet.");
            return;
        }

        input = document.getElementById('fileinput');
        if (!input) {
            bodyAppend("p", "Um, couldn't find the fileinput element.");
        }
        else if (!input.files) {
            bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
        }
        else if (!input.files[0]) {
            bodyAppend("p", "Please select a file before clicking 'Load'");
        }
        else {
            file = input.files[0];
            fr = new FileReader();
            fr.onload = receivedText;
            fr.readAsText(file);
        }

        function receivedText() {
            showResult(fr, "Text");

            fr = new FileReader();
            fr.onload = receivedBinary;
            fr.readAsBinaryString(file);
        }

        function receivedBinary() {
            showResult(fr, "Binary");
        }
    }

    function showResult(fr, label) {
        var markup, result, n, aByte, byteStr;

        markup = [];
        result = fr.result;
        for (n = 0; n < result.length; ++n) {
            aByte = result.charCodeAt(n);
            byteStr = aByte.toString(16);
            if (byteStr.length < 2) {
                byteStr = "0" + byteStr;
            }
            markup.push(byteStr);
        }
        bodyAppend("p", label + " (" + result.length + "):");
        bodyAppend("pre", markup.join(" "));
    }

    function bodyAppend(tagName, innerHTML) {
        var elm;

        elm = document.createElement(tagName);
        elm.innerHTML = innerHTML;
        document.body.appendChild(elm);
    }

</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</form>
</body>
</html>

If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:

Text (13):

54 65 73 74 69 6e 67 20 31 20 32 20 33

Binary (28):

ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00

As you can see, readAsText interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and readAsBinaryString didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).


* XMLHttpRequest.response with responseType = "arraybuffer" is supported in HTML 5.

** "JavaScript strings are UTF-16" may seem like an odd statement; aren't they just Unicode? No, a JavaScript string is a series of UTF-16 code units; you see surrogate pairs as two individual JavaScript "characters" even though, in fact, the surrogate pair as a whole is just one character. See the link for details.

how to check if item is selected from a comboBox in C#

You seem to be using Windows Forms. Look at the SelectedIndex or SelectedItem properties.

if (this.combo1.SelectedItem == MY_OBJECT)
{
    // do stuff
}

Error: "setFile(null,false) call failed" when using log4j

Try executing your command with sudo(Super User), this worked for me :)
Run : $ sudo your_command
After than enter the super user password. Thats All..

How to call MVC Action using Jquery AJAX and then submit form in MVC?

Assuming that your button is in a form, you are not preventing the default behaviour of the button click from happening i.e. Your AJAX call is made in addition to the form submission; what you're very likely seeing is one of

  1. the form submission happens faster than the AJAX call returns
  2. the form submission causes the browser to abort the AJAX request and continues with submitting the form.

So you should prevent the default behaviour of the button click

$('#btnSave').click(function (e) {

    // prevent the default event behaviour    
    e.preventDefault();

    $.ajax({
        url: "/Home/SaveDetailedInfo",
        type: "POST",
        data: JSON.stringify({ 'Options': someData}),
        dataType: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        success: function (data) {

            // perform your save call here

            if (data.status == "Success") {
                alert("Done");
            } else {
                alert("Error occurs on the Database level!");
            }
        },
        error: function () {
            alert("An error has occured!!!");
        }
    });
});

Pagination using MySQL LIMIT, OFFSET

First off, don't have a separate server script for each page, that is just madness. Most applications implement pagination via use of a pagination parameter in the URL. Something like:

http://yoursite.com/itempage.php?page=2

You can access the requested page number via $_GET['page'].

This makes your SQL formulation really easy:

// determine page number from $_GET
$page = 1;
if(!empty($_GET['page'])) {
    $page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
    if(false === $page) {
        $page = 1;
    }
}

// set the number of items to display per page
$items_per_page = 4;

// build query
$offset = ($page - 1) * $items_per_page;
$sql = "SELECT * FROM menuitem LIMIT " . $offset . "," . $items_per_page;

So for example if input here was page=2, with 4 rows per page, your query would be"

SELECT * FROM menuitem LIMIT 4,4

So that is the basic problem of pagination. Now, you have the added requirement that you want to understand the total number of pages (so that you can determine if "NEXT PAGE" should be shown or if you wanted to allow direct access to page X via a link).

In order to do this, you must understand the number of rows in the table.

You can simply do this with a DB call before trying to return your actual limited record set (I say BEFORE since you obviously want to validate that the requested page exists).

This is actually quite simple:

$sql = "SELECT your_primary_key_field FROM menuitem";
$result = mysqli_query($con, $sql);
if(false === $result) {
   throw new Exception('Query failed with: ' . mysqli_error());
} else {
   $row_count = mysqli_num_rows($result);
   // free the result set as you don't need it anymore
   mysqli_free_result($result);
}

$page_count = 0;
if (0 === $row_count) {  
    // maybe show some error since there is nothing in your table
} else {
   // determine page_count
   $page_count = (int)ceil($row_count / $items_per_page);
   // double check that request page is in range
   if($page > $page_count) {
        // error to user, maybe set page to 1
        $page = 1;
   }
}

// make your LIMIT query here as shown above


// later when outputting page, you can simply work with $page and $page_count to output links
// for example
for ($i = 1; $i <= $page_count; $i++) {
   if ($i === $page) { // this is current page
       echo 'Page ' . $i . '<br>';
   } else { // show link to other page   
       echo '<a href="/menuitem.php?page=' . $i . '">Page ' . $i . '</a><br>';
   }
}

Adding Multiple Values in ArrayList at a single index

How about

  1. First adding your desired result as arraylist and
  2. and convert to double array as you want.

Try like this..

import java.util.ArrayList;
import java.util.List;

    public class ArrayTest {

        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub

            // Your Prepared data. 
            List<double[]> values = new ArrayList<double[]>(2);

            double[] element1 = new double[] { 100, 100, 100, 100, 100 };
            double[] element2 = new double[] { 50, 35, 25, 45, 65 };

            values.add(element1);
            values.add(element2);

            // Add the result to arraylist.
            List<Double> temp = new ArrayList<Double>();
            for(int j=0;j<values.size(); j++) {
                for (int i = 0; i < values.get(0).length; i++) {
                    temp.add(values.get(0)[i]);
                    temp.add(values.get(1)[i]);
                }
            }

            // Convert arraylist to int[].
            Double[] result = temp.toArray(new Double[temp.size()]);
            double[] finalResult = new double[result.length]; // This hold final result.
            for (int i = 0; i < result.length; i++) {
                finalResult[i] = result[i].doubleValue();
            }

            for (int i = 0; i < finalResult.length; i++) {
                System.out.println(finalResult[i]);
            }
        }
    }

Add marker to Google Map on Click

In 2017, the solution is:

map.addListener('click', function(e) {
    placeMarker(e.latLng, map);
});

function placeMarker(position, map) {
    var marker = new google.maps.Marker({
        position: position,
        map: map
    });
    map.panTo(position);
}

In CSS what is the difference between "." and "#" when declaring a set of styles?

Like pretty much everyone has stated already:

A period (.) indicates a class, and a hash (#) indicates an ID.

The fundamental difference between is that you can reuse a class on your page over and over, whereas an ID can be used once. That is, of course, if you are sticking to WC3 standards.

A page will still render if you have multiple elements with the same ID, but you will run into problems if/when you try to dynamically update said elements by calling them with their ID, since they are not unique.

It is also useful to note that ID properties will supersede class properties.

ln (Natural Log) in Python

Here is the correct implementation using numpy (np.log() is the natural logarithm)

import numpy as np
p = 100
r = 0.06 / 12
FV = 4000

n = np.log(1 + FV * r/ p) / np.log(1 + r)

print ("Number of periods = " + str(n))

Output:

Number of periods = 36.55539635919235

Extract a page from a pdf as a jpeg

I found this simple solution, PyMuPDF, output to png file. Note the library is imported as "fitz", a historical name for the rendering engine it uses.

import fitz

pdffile = "infile.pdf"
doc = fitz.open(pdffile)
page = doc.loadPage(0)  # number of page
pix = page.getPixmap()
output = "outfile.png"
pix.writePNG(output)

C# : changing listbox row color?

Once you've added your listbox item to your form, change DrawMode with OwnerDrawFixed option from the Properties panel. If you forget to do this, none of the codes below will work. Then click DrawItem event from the Events area.

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
   // 1. Get the item
   string selectedItem = listBox1.Items[e.Index].ToString();
                    
   // 2. Choose font 
   Font font = new Font("Arial", 12);
        
   // 3. Choose colour
   SolidBrush solidBrush = new SolidBrush(Color.Red);
        
   // 4. Get bounds
   int left = e.Bounds.Left;
   int top = e.Bounds.Top;
                    
   // 5. Use Draw the background within the bounds
   e.DrawBackground();
        
   // 6. Colorize listbox items
   e.Graphics.DrawString(selectedItem, font, solidBrush, left, top);
}

NoClassDefFoundError while trying to run my jar with java.exe -jar...what's wrong?

You can omit the -jar option and start the jar file like this:

java -cp MyJar.jar;C:\externalJars\* mainpackage.MyMainClass

Change default date time format on a single database in SQL Server

In order to avoid dealing with these very boring issues, I advise you to always parse your data with the standard and unique SQL/ISO date format which is YYYY-MM-DD. Your queries will then work internationally, no matter what the date parameters are on your main server or on the querying clients (where local date settings might be different than main server settings)!

What does "SyntaxError: Missing parentheses in call to 'print'" mean in Python?

In Python 3, you can only print as:

print("STRING")

But in Python 2, the parentheses are not necessary.

AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

When you get this error, it basically means that it's already in the process of updating your view. You really shouldn't need to call $apply() within your controller. If your view isn't updating as you would expect, and then you get this error after calling $apply(), it most likely means you're not updating the the model correctly. If you post some specifics, we could figure out the core problem.

scp with port number specified

To backup all files in all directories to a remote Synology NAS using a different remote port:

scp -P 10022 -r /media/data/somedata/* [email protected]:/var/services/homes/user/directory/

How to get only time from date-time C#

You can use this

lblTime.Text = DateTime.Now.TimeOfDay.ToString(); 

It is realtime with milliseconds value and it sets to time only.

How to add form validation pattern in Angular 2?

Without make validation patterns, You can easily trim begin and end spaces using these modules.Try this.

https://www.npmjs.com/package/ngx-trim-directive https://www.npmjs.com/package/ng2-trim-directive

Thank you.

Empty set literal?

No, there's no literal syntax for the empty set. You have to write set().

'mvn' is not recognized as an internal or external command, operable program or batch file

After setting the path with the Maven bin location close the prompt window and restart it. Use the echo %path% command to make sure the path is set with Maven variables then run the command mvn -version. Somehow if the path is set when the prompt window is running it does not pick the new variables.

How can I pad an integer with zeros on the left?

Use the class DecimalFormat, like so:

NumberFormat formatter = new DecimalFormat("0000"); //i use 4 Zero but you can also another number
System.out.println("OUTPUT : "+formatter.format(811)); 

OUTPUT : 0000811

What is the function of FormulaR1C1?

FormulaR1C1 has the same behavior as Formula, only using R1C1 style annotation, instead of A1 annotation. In A1 annotation you would use:

Worksheets("Sheet1").Range("A5").Formula = "=A4+A10"

In R1C1 you would use:

Worksheets("Sheet1").Range("A5").FormulaR1C1 = "=R4C1+R10C1"

It doesn't act upon row 1 column 1, it acts upon the targeted cell or range. Column 1 is the same as column A, so R4C1 is the same as A4, R5C2 is B5, and so forth.

The command does not change names, the targeted cell changes. For your R2C3 (also known as C2) example :

Worksheets("Sheet1").Range("C2").FormulaR1C1 = "=your formula here"

ImportError: No module named Image

The PIL distribution is mispackaged for egg installation.

Install Pillow instead, the friendly PIL fork.

Windows 10 SSH keys

Also, you can try (for Windows 10 Pro) Run Powershell as administrator and type ssh-keygen -t rsa -b 4096 -C "[email protected]"

What's the difference between TRUNCATE and DELETE in SQL

DELETE Statement: This command deletes only the rows from the table based on the condition given in the where clause or deletes all the rows from the table if no condition is specified. But it does not free the space containing the table.

The Syntax of a SQL DELETE statement is:

DELETE FROM table_name [WHERE condition];

TRUNCATE statement: This command is used to delete all the rows from the table and free the space containing the table.

I want to align the text in a <td> to the top

https://developer.mozilla.org/en/CSS/vertical-align

<table style="height: 275px; width: 188px">
    <tr>
        <td style="width: 259px; vertical-align:top">
            main page
        </td>
    </tr>
</table>

?

jquery $(window).width() and $(window).height() return different values when viewport has not been resized

Note that if the problem is being caused by appearing scrollbars, putting

body {
  overflow: hidden;
}

in your CSS might be an easy fix (if you don't need the page to scroll).

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

I have the same problem

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

I applied the answer by neo but it did not work until I change the provider to “Provider=Microsoft.ACE.OLEDB.12.0;” in connection string.

Hope this will help if some one face the same issue.

Overlapping Views in Android

Visible gallery changes visibility which is how you get the gallery over other view overlap. the Home sample app has some good examples of this technique.

How to loop through all elements of a form jQuery

What happens, if you do this way:-

$('#new_user_form input, #new_user_form select').each(function(key, value) {

Refer LIVE DEMO

Get 2 Digit Number For The Month

Alternative to DATEPART

SELECT LEFT(CONVERT(CHAR(20), GETDATE(), 101), 2)

Boolean operators && and ||

The answer about "short-circuiting" is potentially misleading, but has some truth (see below). In the R/S language, && and || only evaluate the first element in the first argument. All other elements in a vector or list are ignored regardless of the first ones value. Those operators are designed to work with the if (cond) {} else{} construction and to direct program control rather than construct new vectors.. The & and the | operators are designed to work on vectors, so they will be applied "in parallel", so to speak, along the length of the longest argument. Both vectors need to be evaluated before the comparisons are made. If the vectors are not the same length, then recycling of the shorter argument is performed.

When the arguments to && or || are evaluated, there is "short-circuiting" in that if any of the values in succession from left to right are determinative, then evaluations cease and the final value is returned.

> if( print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(FALSE && print(1) ) {print(2)} else {print(3)} # `print(1)` not evaluated
[1] 3
> if(TRUE && print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(TRUE && !print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 3
> if(FALSE && !print(1) ) {print(2)} else {print(3)}
[1] 3

The advantage of short-circuiting will only appear when the arguments take a long time to evaluate. That will typically occur when the arguments are functions that either process larger objects or have mathematical operations that are more complex.

What is the difference between square brackets and parentheses in a regex?

The first 2 examples act very differently if you are REPLACING them by something. If you match on this:

str = str.replace(/^(7|8|9)/ig,''); 

you would replace 7 or 8 or 9 by the empty string.

If you match on this

str = str.replace(/^[7|8|9]/ig,''); 

you will replace 7 or 8 or 9 OR THE VERTICAL BAR!!!! by the empty string.

I just found this out the hard way.

Display JSON as HTML

For the syntax highlighting, use code prettify. I believe this is what StackOverflow uses for its code highlighting.

  1. Wrap your formatted JSON in code blocks and give them the "prettyprint" class.
  2. Include prettify.js in your page.
  3. Make sure your document's body tag calls prettyPrint() when it loads

You will have syntax highlighted JSON in the format you have laid out in your page. See here for an example. So if you had a code block like this:

<code class="prettyprint">
    var jsonObj = {
        "height" : 6.2,
        "width" : 7.3,
        "length" : 9.1,
        "color" : {
            "r" : 255,
            "g" : 200,
            "b" : 10
        }
    }
</code>

It would look like this:

var jsonObj = {
    "height" : 6.2,
    "width" : 7.3,
    "length" : 9.1,
    "color" : {
        "r" : 255,
        "g" : 200,
        "b" : 10
    }
}

This doesn't help with the indenting, but the other answers seem to be addressing that.

How can I replace a regex substring match in Javascript?

I think the simplest way to achieve your goal is this:

var str   = 'asd-0.testing';
var regex = /(asd-)(\d)(\.\w+)/;
var anyNumber = 1;
var res = str.replace(regex, `$1${anyNumber}$3`);

What is the optimal way to compare dates in Microsoft SQL server?

Converting to a DATE or using an open-ended date range in any case will yield the best performance. FYI, convert to date using an index are the best performers. More testing a different techniques in article: What is the most efficient way to trim time from datetime? Posted by Aaron Bertrand

From that article:

DECLARE @dateVar datetime = '19700204';

-- Quickest when there is an index on t.[DateColumn], 
-- because CONVERT can still use the index.
SELECT t.[DateColumn]
FROM MyTable t
WHERE = CONVERT(DATE, t.[DateColumn]) = CONVERT(DATE, @dateVar);

-- Quicker when there is no index on t.[DateColumn]
DECLARE @dateEnd datetime = DATEADD(DAY, 1, @dateVar);
SELECT t.[DateColumn] 
FROM MyTable t
WHERE t.[DateColumn] >= @dateVar AND 
      t.[DateColumn] < @dateEnd;

Also from that article: using BETWEEN, DATEDIFF or CONVERT(CHAR(8)... are all slower.

How to dismiss notification after action has been clicked

Just put this line :

 builder.setAutoCancel(true);

And the full code is :

NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setSmallIcon(android.R.drawable.ic_dialog_alert);
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.co.in/"));
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
    builder.setContentIntent(pendingIntent);
    builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.misti_ic));
    builder.setContentTitle("Notifications Title");
    builder.setContentText("Your notification content here.");
    builder.setSubText("Tap to view the website.");
    Toast.makeText(getApplicationContext(), "The notification has been created!!", Toast.LENGTH_LONG).show();

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    builder.setAutoCancel(true);
    // Will display the notification in the notification bar
    notificationManager.notify(1, builder.build());

Round button with text and icon in flutter

Screenshot:

enter image description here

SizedBox.fromSize(
  size: Size(56, 56), // button width and height
  child: ClipOval(
    child: Material(
      color: Colors.orange, // button color
      child: InkWell(
        splashColor: Colors.green, // splash color
        onTap: () {}, // button pressed
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Icon(Icons.call), // icon
            Text("Call"), // text
          ],
        ),
      ),
    ),
  ),
)

How to get active user's UserDetails

Starting with Spring Security version 3.2, the custom functionality that has been implemented by some of the older answers, exists out of the box in the form of the @AuthenticationPrincipal annotation that is backed by AuthenticationPrincipalArgumentResolver.

An simple example of it's use is:

@Controller
public class MyController {
   @RequestMapping("/user/current/show")
   public String show(@AuthenticationPrincipal CustomUser customUser) {
        // do something with CustomUser
       return "view";
   }
}

CustomUser needs to be assignable from authentication.getPrincipal()

Here are the corresponding Javadocs of AuthenticationPrincipal and AuthenticationPrincipalArgumentResolver

What is the list of supported languages/locales on Android?

http://developer.android.com/reference/java/util/Locale.html

See CLDR for specific language support.

Ex : CLDR 1.8 for 2.3

http://cldr.unicode.org/index/downloads/cldr-1-8

Languages:

Afar [Qafar];
Afrikaans;
Akan;
Albanian [shqipe];
Amharic [????];
Arabic [?????????];
Armenian [???????];
Assamese [??????];
Asu [Kipare];
Atsam [cch];
Azerbaijani (Arabic) [az?rbaycanca (?r?b)];
Azerbaijani (Cyrillic) [?????????? (kiril)];
Azerbaijani (Latin) [az?rbaycanca (latin)];
Bambara [bamanakan];
Basque [euskara];
Belarusian [??????????];
Bemba [Ichibemba];
Bena [Hibena];
Bengali [?????];
Blin [???];
Bosnian [Bosanski];
Breton [br];
Bulgarian [?????????];
Burmese [???];
Catalan [català];
Central Morocco Tamazight (Latin) [Tamazi?t (Latn)];
Cherokee [???];
Chiga [Rukiga];
Colognian [ksh];
Cornish [kernewek];
Croatian [hrvatski];
Czech [ceština];
Danish [dansk];
Divehi [????????????];
Dutch [Nederlands];
Dzongkha [??????];
Embu [Kiembu];
English (Deseret) [ ()];
English (Shavian);
Esperanto;
Estonian [eesti];
Ewe [E?egbe];
Faroese [føroyskt];
Filipino;
Finnish [suomi];
French [français];
Friulian [furlan];
Fulah [Pulaar];
Ga [gaa];
Galician [galego];
Ganda [Luganda];
Geez [????];
Georgian [???????];
German [Deutsch];
Greek [????????];
Gujarati [???????];
Gusii [Ekegusii];
Hausa (Arabic) [Hausa (Arab)];
Hausa (Latin) [Hausa (Latn)];
Hawaiian [?olelo Hawai?i];
Hebrew [???????];
Hindi [??????];
Hungarian [magyar];
Icelandic [íslenska];
Igbo;
Indonesian [Bahasa Indonesia];
Interlingua;
Inuktitut [?????? ??????];
Irish [Gaeilge];
Italian [italiano];
Japanese [???];
Jju [kaj];
Kabuverdianu;
Kabyle [Taqbaylit];
Kalaallisut;
Kalenjin;
Kamba [Kikamba];
Kannada [?????];
Kazakh (Cyrillic) [????? (Cyrl)];
Khmer [?????????];
Kikuyu [Gikuyu];
Kinyarwanda;
Kirghiz [??????];
Konkani [??????];
Korean [???];
Koro [kfo];
Koyra Chiini [Koyra ciini];
Koyraboro Senni;
Kpelle [kpe];
Kurdish (Arabic) [?????? (??????)?];
Kurdish (Latin) [?kurdî (?????)?];
Langi [K?laangi];
Lao [???];
Latvian [latviešu];
Lingala [lingála];
Lithuanian [lietuviu];
Low German [Plattdüütsch];
Luo [Dholuo];
Luyia [Luluhia];
Macedonian [??????????];
Machame [Kimachame];
Makonde [Chimakonde];
Malagasy;
Malay [Bahasa Melayu];
Malayalam [??????];
Maltese [Malti];
Manx [Gaelg];
Maori [mi];
Marathi [?????];
Masai [Maa];
Meru [Kimiru];
Mongolian (Cyrillic) [?????? (Cyrl)];
Mongolian (Mongolian) [?????? (Mong)];
Morisyen [kreol morisien];
Nama [Khoekhoegowab];
Nepali [??????];
North Ndebele [isiNdebele];
Northern Sami [davvisámegiella];
Northern Sotho [Sesotho sa Leboa];
Norwegian [norsk];
Norwegian Bokmål [norsk bokmål];
Norwegian Nynorsk [nynorsk];
Nyanja [ny];
Nyankole [Runyankore];
Occitan;
Oriya [?????];
Oromo [Oromoo];
Pashto [??????];
Persian [???????];
Polish [polski];
Portuguese [português];
Punjabi (Arabic) [?????? (???????)?];
Punjabi (Gurmukhi) [?????? (???????)];
Romanian [româna];
Romansh [rumantsch];
Rombo [Kihorombo];
Russian [???????];
Rwa [Kiruwa];
Saho [ssy];
Samburu [Kisampur];
Sango [Sängö];
Sanskrit [??????? ????];
Sena;
Serbian (Cyrillic) [?????? (????????)];
Serbian (Latin) [Srpski (Latinica)];
Shambala [Kishambaa];
Shona [chiShona];
Sichuan Yi [???];
Sidamo [Sidaamu Afo];
Simplified Chinese [??(??)];
Sinhala [?????];
Slovak [slovencina];
Slovenian [slovenšcina];
Soga [Olusoga];
Somali [Soomaali];
South Ndebele [isiNdebele];
Southern Sotho [Sesotho];
Spanish [español];
Swahili [Kenya];
Swati [Siswati];
Swedish [svenska];
Swiss German [Schwiizertüütsch];
Syriac [????????];
Tachelhit (Latin) [tamazight (Latn)];
Tachelhit (Tifinagh) [???????? (Tfng)];
Tagalog;
Taita [Kitaita];
Tajik (Cyrillic) [tg (Cyrl)];
Tamil [?????];
Taroko [trv];
Tatar [?????];
Telugu [??????];
Teso [Kiteso];
Thai [???];
Tibetan [????????];
Tigre [???];
Tigrinya [????];
Tonga [lea fakatonga];
Traditional Chinese [????];
Tsonga [Xitsonga];
Tswana [Setswana];
Turkish [Türkçe];
Tyap [kcg];
Uighur (Arabic) [ug (Arab)];
Ukrainian [??????????];
Urdu [??????];
Uzbek (Arabic) [??????? (????)?];
Uzbek (Cyrillic) [????? (?????)];
Uzbek (Latin) [o'zbekcha (Lotin)];
Venda [Tshiven?a];
Vietnamese [Ti?ng Vi?t];
Vunjo [Kyivunjo];
Walamo [?????];
Welsh [Cymraeg];
Wolof (Latin) [wo (Latn)];
Xhosa [isiXhosa];
Yoruba [Èdè Yorùbá];
Zulu [isiZulu]

Locale IDs can be found in:

http://www.localeplanet.com/icu/

Steps to follow

Step 1 : Need to find which all Languages supported on Android

Sol - follow my above answer ie in cldr-1-8 Languages.

Step 2 : Since cldr-1-8 Languages does not give u Locale short form which is need to be found for desire language Sol - Once language is available in cldr-1-8 Languages list then check for the shortform in http://www.localeplanet.com/icu/ link

Example :For language Hindi [??????] (1)we need to search its present in cldr-1-8 language then (2)search for Hindi in http://www.localeplanet.com/icu/ for Locale id its comes out to be http://www.localeplanet.com/icu/hi/index.html this link and see Locale id from it .

How to scroll UITableView to specific position

it should work using - (void)scrollToRowAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated using it this way:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[yourTableView scrollToRowAtIndexPath:indexPath 
                     atScrollPosition:UITableViewScrollPositionTop 
                             animated:YES];

atScrollPosition could take any of these values:

typedef enum {
UITableViewScrollPositionNone,
UITableViewScrollPositionTop,
UITableViewScrollPositionMiddle,
UITableViewScrollPositionBottom
} UITableViewScrollPosition;

I hope this helps you

Cheers

How to convert object array to string array in Java

For your idea, actually you are approaching the success, but if you do like this should be fine:

for (int i=0;i<String_Array.length;i++) String_Array[i]=(String)Object_Array[i];

BTW, using the Arrays utility method is quite good and make the code elegant.

Clear dropdown using jQuery Select2

This works for me:

 $remote.select2('data', {id: null, text: null})

It also works with jQuery validate when you clear it that way.

-- edit 2013-04-09

At the time of writing this response, it was the only way. With recent patches, a proper and better way is now available.

$remote.select2('data', null)

li:before{ content: "¦"; } How to Encode this Special Character as a Bullit in an Email Stationery?

Lea's converter is no longer available. I just used this converter

Steps:

  1. Enter the Unicode decimal version such as 8226 in the tool's green input field.
  2. Press Dec code points
  3. See the result in the box Unicode U+hex notation (eg U+2022)
  4. Use it in your CSS. Eg content: '\2022'

ps. I have no connection with the web site.

adding 1 day to a DATETIME format value

Using server request time to Add days. Working as expected.

25/08/19 => 27/09/19

$timestamp = $_SERVER['REQUEST_TIME'];
$dateNow = date('d/m/y', $timestamp);
$newDate = date('d/m/y', strtotime('+2 day', $timestamp));

Here '+2 days' to add any number of days.

Get date from input form within PHP

    <?php
if (isset($_POST['birthdate'])) {
    $timestamp = strtotime($_POST['birthdate']); 
    $date=date('d',$timestamp);
    $month=date('m',$timestamp);
    $year=date('Y',$timestamp);
}
?>  

How to use sessions in an ASP.NET MVC 4 application?

Try

//adding data to session
//assuming the method below will return list of Products

var products=Db.GetProducts();

//Store the products to a session

Session["products"]=products;

//To get what you have stored to a session

var products=Session["products"] as List<Product>;

//to clear the session value

Session["products"]=null;

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

Excel shows 24:03 as 3 minutes when you format it as time, because 24:03 is the same as 12:03 AM (in military time).

Use General Format to Add Times

Instead of trying to format as Time, use the General Format and the following formula:

=number of minutes + (number of seconds / 60)

Ex: for 24 minutes and 3 seconds:

=24+3/60

This will give you a value of 24.05.

Do this for each time period. Let's say you enter this formula in cells A1 and A2. Then, to get the total sum of elapsed time, use this formula in cell A3:

=INT(A1+A2)+MOD(A1+A2,1)

Convert back to minutes and seconds

If you put =24+3/60 into each cell, you will have a value of 48.1 in cell A3.

Now you need to convert this back to minutes and seconds. Use the following formula in cell A4:

=MOD(A3,1)*60

This takes the decimal portion and multiples it by 60. Remember, we divided by 60 in the beginning, so to convert it back to seconds we need to multiply.

You could have also done this separately, i.e. in cell A3 use this formula:

=INT(A1+A2)

and this formula in cell A4:

=MOD(A1+A2,1)*60

Here's a screenshot showing the final formulas:

adding times

Remove last character of a StringBuilder?

As of Java 8, the String class has a static method join. The first argument is a string that you want between each pair of strings, and the second is an Iterable<CharSequence> (which are both interfaces, so something like List<String> works. So you can just do this:

String.join(",", serverIds);

Also in Java 8, you could use the new StringJoiner class, for scenarios where you want to start constructing the string before you have the full list of elements to put in it.

Hex-encoded String to Byte Array

I think what the questioner is after is converting the string representation of a hexadecimal value to a byte array representing that hexadecimal value.

The apache commons-codec has a class for that, Hex.

String s = "9B7D2C34A366BF890C730641E6CECF6F";    
byte[] bytes = Hex.decodeHex(s.toCharArray());

Excel error HRESULT: 0x800A03EC while trying to get range with cell's name

I found a possible solution here: http://www.made4dotnet.com/Default.aspx?tabid=141&aid=15

Edit:

If you automate Microsoft Excel with Microsoft Visual Basic .NET, Microsoft Visual C# .NET, or Microsoft Visual C++, you may receive the following errors when calling certain methods because the machine has the locale set to something other than US English (locale ID or LCID 1033):

Exception from HRESULT: 0x800A03EC

and/or

Old format or invalid type library

SOLUTION 1:


To get around this error you can set CurrentCulture to en-US when executing code related to Excel and reset back to your originale by using these 2 functions.

//declare a variable to hold the CurrentCulture
System.Globalization.CultureInfo oldCI;
//get the old CurrenCulture and set the new, en-US
void SetNewCurrentCulture()
{
  oldCI = System.Threading.Thread.CurrentThread.CurrentCulture;
  System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
}
//reset Current Culture back to the originale
void ResetCurrentCulture()
{
  System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
}

SOLUTION 2:


Another solution that could work, create a 1033 directory under Microsoft Office\Office11 (or your corresponding office-version), copy excel.exe to the 1033 directory, and rename it to xllex.dll.

Although you might solve the problem using one off these solutions, when you call the Excel object model in locales other than US English, the Excel object model can act differently and your code can fail in ways you may not have thought of. For example, you might have code that sets the value of a range to a date:

yourRange.Value2 = "10/10/09"

Depending on the locale this code can act differently resulting in Excel putting into the range any of the following values:

October 10, 2009 September 10, 2009 October 9, 2010

Programmatically shut down Spring Boot application

Closing a SpringApplication basically means closing the underlying ApplicationContext. The SpringApplication#run(String...) method gives you that ApplicationContext as a ConfigurableApplicationContext. You can then close() it yourself.

For example,

@SpringBootApplication
public class Example {
    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(Example.class, args);
        // ...determine it's time to shut down...
        ctx.close();
    }
}

Alternatively, you can use the static SpringApplication.exit(ApplicationContext, ExitCodeGenerator...) helper method to do it for you. For example,

@SpringBootApplication
public class Example {
    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(Example.class, args);
        // ...determine it's time to stop...
        int exitCode = SpringApplication.exit(ctx, new ExitCodeGenerator() {
            @Override
            public int getExitCode() {
                // no errors
                return 0;
            }
        });

        // or shortened to
        // int exitCode = SpringApplication.exit(ctx, () -> 0);

        System.exit(exitCode);
    }
}

RuntimeError on windows trying python multiprocessing

As @Ofer said, when you are using another libraries or modules, you should import all of them inside the if __name__ == '__main__':

So, in my case, ended like this:

if __name__ == '__main__':       
    import librosa
    import os
    import pandas as pd
    run_my_program()

CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

Access-Control-Allow-Origin:*

or

Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

Header set Access-Control-Allow-Origin "*"

In nodejs,the code is like this:

res.setHeader('Access-Control-Allow-Origin','*');

Save each sheet in a workbook to separate CSV files

And here's my solution should work with Excel > 2000, but tested only on 2007:

Private Sub SaveAllSheetsAsCSV()
On Error GoTo Heaven

' each sheet reference
Dim Sheet As Worksheet
' path to output to
Dim OutputPath As String
' name of each csv
Dim OutputFile As String

Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False

' ask the user where to save
OutputPath = InputBox("Enter a directory to save to", "Save to directory", Path)

If OutputPath <> "" Then

    ' save for each sheet
    For Each Sheet In Sheets

        OutputFile = OutputPath & "\" & Sheet.Name & ".csv"

        ' make a copy to create a new book with this sheet
        ' otherwise you will always only get the first sheet
        Sheet.Copy
        ' this copy will now become active
        ActiveWorkbook.SaveAs FileName:=OutputFile, FileFormat:=xlCSV, CreateBackup:=False
        ActiveWorkbook.Close
    Next

End If

Finally:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True

Exit Sub

Heaven:
MsgBox "Couldn't save all sheets to CSV." & vbCrLf & _
        "Source: " & Err.Source & " " & vbCrLf & _
        "Number: " & Err.Number & " " & vbCrLf & _
        "Description: " & Err.Description & " " & vbCrLf

GoTo Finally
End Sub

(OT: I wonder if SO will replace some of my minor blogging)

ParseError: not well-formed (invalid token) using cElementTree

I was having the same error (with ElementTree). In my case it was because of encodings, and I was able to solve it without having to use an external library. Hope this helps other people finding this question based on the title. (reference)

import xml.etree.ElementTree as ET
parser = ET.XMLParser(encoding="utf-8")
tree = ET.fromstring(xmlstring, parser=parser)

EDIT: Based on comments, this answer might be outdated. But this did work back when it was answered...

Is there an upper bound to BigInteger?

The first maximum you would hit is the length of a String which is 231-1 digits. It's much smaller than the maximum of a BigInteger but IMHO it loses much of its value if it can't be printed.

C# listView, how do I add items to columns 2, 3 and 4 etc?

There are several ways to do it, but here is one solution (for 4 columns).

string[] row1 = { "s1", "s2", "s3" };
listView1.Items.Add("Column1Text").SubItems.AddRange(row1);

And a more verbose way is here:

ListViewItem item1 = new ListViewItem("Something");
item1.SubItems.Add("SubItem1a");
item1.SubItems.Add("SubItem1b");
item1.SubItems.Add("SubItem1c");

ListViewItem item2 = new ListViewItem("Something2");
item2.SubItems.Add("SubItem2a");
item2.SubItems.Add("SubItem2b");
item2.SubItems.Add("SubItem2c");

ListViewItem item3 = new ListViewItem("Something3");
item3.SubItems.Add("SubItem3a");
item3.SubItems.Add("SubItem3b");
item3.SubItems.Add("SubItem3c");

ListView1.Items.AddRange(new ListViewItem[] {item1,item2,item3});

Passing a local variable from one function to another

You can very easily use this to re-use the value of the variable in another function.

// Use this in source window.var1= oEvent.getSource().getBindingContext();

// Get value of var1 in destination var var2= window.var1;

Image convert to Base64

Function convert image to base64 using jquery (you can convert to vanila js). Hope it help to you!

Usage: input is your nameId input has file image

<input type="file" id="asd"/>
<button onclick="proccessData()">Submit</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>

async function converImageToBase64(inputId) {
  let image = $('#'+inputId)[0]['files']

  if (image && image[0]) {
    const reader = new FileReader();

    return new Promise(resolve => {
      reader.onload = ev => {
        resolve(ev.target.result)
      }
      reader.readAsDataURL(image[0])
    })
  }
}

async function proccessData() {
  const image = await converImageToBase64('asd')
  console.log(image)
}

</script>

Example: converImageToBase64('yourFileInputId')

https://codepen.io/mariohandsome/pen/yLadmVb

Java Minimum and Maximum values in Array

Sum, Maximum and Minimum value of an Array in One Line

 public static void getMinMaxByArraysMethods(int[] givenArray){

       //Sum of Array in One Line 
       long sumofArray =  Arrays.stream(givenArray).sum();

       //get Minimum Value in an array in One Line
        int minimumValue = Arrays.stream(givenArray).min().getAsInt();

        //Get Maximum Value of an Array in One Line
        int MaxmumValue =  Arrays.stream(givenArray).max().getAsInt();

    }

Loop over html table and get checked checkboxes (JQuery)

use .filter(':has(:checkbox:checked)' ie:

$('#mytable tr').filter(':has(:checkbox:checked)').each(function() {
 $('#out').append(this.id);
});

How do I redirect to another webpage?

In JavaScript and jQuery we use this following code to redirect the page:

window.location.href="http://google.com";
window.location.replace("page1.html");

But you can make a function in jQuery to redirect the page:

jQuery.fn.redirect=function(url)
{
    window.location.href=url;
}

And call this function:

jQuery(window).redirect("http://stackoverflow.com/")

Jquery submit form

If you have only 1 form in you page, use this. You do not need to know id or name of the form. I just used this code - working:

document.forms[0].submit();

Question mark and colon in statement. What does it mean?

It is the ternary conditional operator.

If the condition in the parenthesis before the ? is true, it returns the value to the left of the :, otherwise the value to the right.

What is Hash and Range Primary Key?

"Hash and Range Primary Key" means that a single row in DynamoDB has a unique primary key made up of both the hash and the range key. For example with a hash key of X and range key of Y, your primary key is effectively XY. You can also have multiple range keys for the same hash key but the combination must be unique, like XZ and XA. Let's use their examples for each type of table:

Hash Primary Key – The primary key is made of one attribute, a hash attribute. For example, a ProductCatalog table can have ProductID as its primary key. DynamoDB builds an unordered hash index on this primary key attribute.

This means that every row is keyed off of this value. Every row in DynamoDB will have a required, unique value for this attribute. Unordered hash index means what is says - the data is not ordered and you are not given any guarantees into how the data is stored. You won't be able to make queries on an unordered index such as Get me all rows that have a ProductID greater than X. You write and fetch items based on the hash key. For example, Get me the row from that table that has ProductID X. You are making a query against an unordered index so your gets against it are basically key-value lookups, are very fast, and use very little throughput.


Hash and Range Primary Key – The primary key is made of two attributes. The first attribute is the hash attribute and the second attribute is the range attribute. For example, the forum Thread table can have ForumName and Subject as its primary key, where ForumName is the hash attribute and Subject is the range attribute. DynamoDB builds an unordered hash index on the hash attribute and a sorted range index on the range attribute.

This means that every row's primary key is the combination of the hash and range key. You can make direct gets on single rows if you have both the hash and range key, or you can make a query against the sorted range index. For example, get Get me all rows from the table with Hash key X that have range keys greater than Y, or other queries to that affect. They have better performance and less capacity usage compared to Scans and Queries against fields that are not indexed. From their documentation:

Query results are always sorted by the range key. If the data type of the range key is Number, the results are returned in numeric order; otherwise, the results are returned in order of ASCII character code values. By default, the sort order is ascending. To reverse the order, set the ScanIndexForward parameter to false

I probably missed some things as I typed this out and I only scratched the surface. There are a lot more aspects to take into consideration when working with DynamoDB tables (throughput, consistency, capacity, other indices, key distribution, etc.). You should take a look at the sample tables and data page for examples.

Send JSON via POST in C# and Receive the JSON returned?

Using the JSON.NET NuGet package and anonymous types, you can simplify what the other posters are suggesting:

// ...

string payload = JsonConvert.SerializeObject(new
{
    agent = new
    {
        name    = "Agent Name",
        version = 1,
    },

    username = "username",
    password = "password",
    token    = "xxxxx",
});

var client = new HttpClient();
var content = new StringContent(payload, Encoding.UTF8, "application/json");

HttpResponseMessage response = await client.PostAsync(uri, content);

// ...

Check variable equality against a list of values

Using the answers provided, I ended up with the following:

Object.prototype.in = function() {
    for(var i=0; i<arguments.length; i++)
       if(arguments[i] == this) return true;
    return false;
}

It can be called like:

if(foo.in(1, 3, 12)) {
    // ...
}

Edit: I came across this 'trick' lately which is useful if the values are strings and do not contain special characters. For special characters is becomes ugly due to escaping and is also more error-prone due to that.

/foo|bar|something/.test(str);

To be more precise, this will check the exact string, but then again is more complicated for a simple equality test:

/^(foo|bar|something)$/.test(str);

What is the difference between a URI, a URL and a URN?

URIs came about from the need to identify resources on the Web, and other Internet resources such as electronic mailboxes in a uniform and coherent way. So, one can introduce a new type of widget: URIs to identify widget resources or use tel: URIs to have web links cause telephone calls to be made when invoked.

Some URIs provide information to locate a resource (such as a DNS host name and a path on that machine), while some are used as pure resource names. The URL is reserved for identifiers that are resource locators, including 'http' URLs such as http://stackoverflow.com, which identifies the web page at the given path on the host. Another example is 'mailto' URLs, such as mailto:[email protected], which identifies the mailbox at the given address.

URNs are URIs that are used as pure resource names rather than locators. For example, the URI: mid:[email protected] is a URN that identifies the email message containing it in its 'Message-Id' field. The URI serves to distinguish that message from any other email message. But it does not itself provide the message's address in any store.

Can I exclude some concrete urls from <url-pattern> inside <filter-mapping>?

This approach works when you want to prevent a certain filter and all the following ones. It should work well if you eg. want to serve some content as static resources within your servlet container instead of letting your application logic (through a filter like GuiceFilter):

Map the folder with your static resource files to the default servlet. Create a servlet filter and put it before the GuiceFilter in your web.xml. In your created filter, you can separate between forwarding some requests to the GuiceFilter and others directly to the dispatcher. Example follows...

web.xml

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/static/*</url-pattern>
</servlet-mapping>

<filter>
    <filter-name>StaticResourceFilter</filter-name>
    <filter-class>com.project.filter.StaticResourceFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>StaticResourceFilter</filter-name>
    <url-pattern>/static/*</url-pattern>
</filter-mapping>

<filter>
    <filter-name>guiceFilter</filter-name>
    <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>guiceFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

StaticResourceFilter.class

public class StaticResourceFilter implements Filter {

    private final static Logger LOGGER = LoggerFactory.getLogger(StaticResourceFilter.class);

    private static final String RESOURCE_PATH = "/static/";
    @Override
    public void init(final FilterConfig filterConfig) throws ServletException {
        LOGGER.info("StaticResourceFilter initialized");
    }

    @Override
    public void doFilter(final ServletRequest request, final ServletResponse response,
                         final FilterChain chain) throws IOException, ServletException {

        String path = ((HttpServletRequest) request).getServletPath();
        if (path.toLowerCase().startsWith(RESOURCE_PATH)) {
            request.getRequestDispatcher(path).forward(request, response);
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
        LOGGER.info("StaticResourceFilter destroyed");
    }
}

Unfortunately if you just want to skip a single step in the filter chain while keeping those that follows, this will not work.

Using LIMIT within GROUP BY to get N results per group?

for those like me that had queries time out. I made the below to use limits and anything else by a specific group.

DELIMITER $$
CREATE PROCEDURE count_limit200()
BEGIN
    DECLARE a INT Default 0;
    DECLARE stop_loop INT Default 0;
    DECLARE domain_val VARCHAR(250);
    DECLARE domain_list CURSOR FOR SELECT DISTINCT domain FROM db.one;

    OPEN domain_list;

    SELECT COUNT(DISTINCT(domain)) INTO stop_loop 
    FROM db.one;
    -- BEGIN LOOP
    loop_thru_domains: LOOP
        FETCH domain_list INTO domain_val;
        SET a=a+1;

        INSERT INTO db.two(book,artist,title,title_count,last_updated) 
        SELECT * FROM 
        (
            SELECT book,artist,title,COUNT(ObjectKey) AS titleCount, NOW() 
            FROM db.one 
            WHERE book = domain_val
            GROUP BY artist,title
            ORDER BY book,titleCount DESC
            LIMIT 200
        ) a ON DUPLICATE KEY UPDATE title_count = titleCount, last_updated = NOW();

        IF a = stop_loop THEN
            LEAVE loop_thru_domain;
        END IF;
    END LOOP loop_thru_domain;
END $$

it loops through a list of domains and then inserts only a limit of 200 each

Get element of JS object with an index

If you want a specific order, then you must use an array, not an object. Objects do not have a defined order.

For example, using an array, you could do this:

var myobj = [{"A":["B"]}, {"B": ["C"]}];
var firstItem = myobj[0];

Then, you can use myobj[0] to get the first object in the array.

Or, depending upon what you're trying to do:

var myobj = [{key: "A", val:["B"]}, {key: "B",  val:["C"]}];
var firstKey = myobj[0].key;   // "A"
var firstValue = myobj[0].val; // "["B"]

What is the difference between Integrated Security = True and Integrated Security = SSPI?

Integrated Security = False : User ID and Password are specified in the connection. Integrated Security = true : the current Windows account credentials are used for authentication.

Integrated Security = SSPI : this is equivalant to true.

We can avoid the username and password attributes from the connection string and use the Integrated Security

Get Windows version in a batch file

Actually, that one liner doesn't work for windows xp since the ver contains xp in the string. Instead of 5.1 which you want, you would get [Version.5 because of the added token.

I modified the command to look like this: for /f "tokens=4-6 delims=[. " %%i in ('ver') do set VERSION=%%i.%%j

This will output Version.5 for xp systems which you can use to indentify said system inside a batch file. Sadly, this means the command cannot differentiate between 32bit and 64bit build since it doesn't read the .2 from 5.2 that denotes 64bit XP.

You could make it assign %%k that token but doing so would make this script not detect windows vista, 7, or 8 properly as they have one token less in their ver string. Hope this helps!

What is console.log?

console.log has nothing to do with jQuery.

It logs a message to a debugging console, such as Firebug.

Difference between [routerLink] and routerLink

Assume that you have

const appRoutes: Routes = [
  {path: 'recipes', component: RecipesComponent }
];

<a routerLink ="recipes">Recipes</a>

It means that clicking Recipes hyperlink will jump to http://localhost:4200/recipes

Assume that the parameter is 1

<a [routerLink] = "['/recipes', parameter]"></a>

It means that passing dynamic parameter, 1 to the link, then you navigate to http://localhost:4200/recipes/1

PHP Change Array Keys

I think that he want:

$a = array(1=>'first_name', 2=>'last_name');
$a = array_flip($a);

$a['first_name'] = 3;
$a = array_flip($a);

print_r($a);

Change fill color on vector asset in Android Studio

Add this library to the Gradle to enable color vector drawable in old android Devices.

compile 'com.android.support:palette-v7:26.0.0-alpha1'

and re sync gradle. I think it will solve the problem.

Create an Array of Arraylists

You can create like this ArrayList<Individual>[] group = (ArrayList<Individual>[])new ArrayList[4];

You have to create array of non generic type and then cast it into generic one.

The definitive guide to form-based website authentication

I'd like to add one suggestion I've used, based on defense in depth. You don't need to have the same auth&auth system for admins as regular users. You can have a separate login form on a separate url executing separate code for requests that will grant high privileges. This one can make choices that would be a total pain to regular users. One such that I've used is to actually scramble the login URL for admin access and email the admin the new URL. Stops any brute force attack right away as your new URL can be arbitrarily difficult (very long random string) but your admin user's only inconvenience is following a link in their email. The attacker no longer knows where to even POST to.

anaconda - graphviz - can't import after installation

I have followed the following steps and it worked fine for me.

1 . Download and install graphviz-2.38.msi from https://graphviz.gitlab.io/_pages/Download/Download_windows.html

2 . Set the path variable

(a) Control Panel > System and Security > System > Advanced System Settings >  Environment Variables > Path > Edit

(b) add 'C:\Program Files (x86)\Graphviz2.38\bin'

jquery $(this).id return Undefined

Hiya demo http://jsfiddle.net/LYTbc/

this is a reference to the DOM element, so you can wrap it directly.

attr api: http://api.jquery.com/attr/

The .attr() method gets the attribute value for only the first element in the matched set.

have a nice one, cheers!

code

$(document).ready(function () {
    $(".inputs").click(function () {
         alert(this.id);

        alert(" or " + $(this).attr("id"));

    });

});?

Hide the browse button on a input type=file

Oddly enough, this works for me (when I place inside a button tag).

.button {
    position: relative;

    input[type=file] {
            color: transparent;
            background-color: transparent;
            position: absolute;
            left: 0;
            width: 100%;
            height: 100%;
            top: 0;
            opacity: 0;
            z-index: 100;
        }
}

Only tested in Chrome (macOS Sierra).

"Repository does not have a release file" error

In my case the cause was Ubuntu version no longer supported by Canonical. I was able to upgrade to still supported LTS with 2 steps:

1) Manually update repo links from "in.ubuntu" to "old-releases.ubuntu". 1.1) Installed all outstanding updates 2) do-release-upgrade was able to take from this point and do actual upgrade

IMHO, this is safer method then just updating repositories to next supported ubuntu, since do-release-upgrade have chance to prevent upgrade that could fail, and may be able to diagnose a problem for you.

Stop a youtube video with jquery?

if you have autoplay property in the iframe src it wont help to reload the src attr/prop so you have to replace the autoplay=1 to autoplay=0

  var stopVideo = function(player) {
    var vidSrc = player.prop('src').replace('autoplay=1','autoplay=0');
    player.prop('src', vidSrc);
  };

  stopVideo($('#video'));

Difference between int and double

int and double have different semantics. Consider division. 1/2 is 0, 1.0/2.0 is 0.5. In any given situation, one of those answers will be right and the other wrong.

That said, there are programming languages, such as JavaScript, in which 64-bit float is the only numeric data type. You have to explicitly truncate some division results to get the same semantics as Java int. Languages such as Java that support integer types make truncation automatic for integer variables.

In addition to having different semantics from double, int arithmetic is generally faster, and the smaller size (32 bits vs. 64 bits) leads to more efficient use of caches and data transfer bandwidth.

How can I check if a View exists in a Database?

You can check the availability of the view in various ways

FOR SQL SERVER

use sys.objects

IF EXISTS(
   SELECT 1
   FROM   sys.objects
   WHERE  OBJECT_ID = OBJECT_ID('[schemaName].[ViewName]')
          AND Type_Desc = 'VIEW'
)
BEGIN
    PRINT 'View Exists'
END

use sysobjects

IF NOT EXISTS (
   SELECT 1
   FROM   sysobjects
   WHERE  NAME = '[schemaName].[ViewName]'
          AND xtype = 'V'
)
BEGIN
    PRINT 'View Exists'
END

use sys.views

IF EXISTS (
   SELECT 1
   FROM sys.views
   WHERE OBJECT_ID = OBJECT_ID(N'[schemaName].[ViewName]')
)
BEGIN
    PRINT 'View Exists'
END

use INFORMATION_SCHEMA.VIEWS

IF EXISTS (
   SELECT 1
   FROM   INFORMATION_SCHEMA.VIEWS
   WHERE  table_name = 'ViewName'
          AND table_schema = 'schemaName'
)
BEGIN
    PRINT 'View Exists'
END

use OBJECT_ID

IF EXISTS(
   SELECT OBJECT_ID('ViewName', 'V')
)
BEGIN
    PRINT 'View Exists'
END

use sys.sql_modules

IF EXISTS (
   SELECT 1
   FROM   sys.sql_modules
   WHERE  OBJECT_ID = OBJECT_ID('[schemaName].[ViewName]')
)
BEGIN
   PRINT 'View Exists'
END

Illegal mix of collations MySQL Error

You should set both your table encoding and connection encoding to UTF-8:

ALTER TABLE keywords CHARACTER SET UTF8; -- run once

and

SET NAMES 'UTF8';
SET CHARACTER SET 'UTF8';

How to write a:hover in inline CSS?

You could do it at some point in the past. But now (according to the latest revision of the same standard, which is Candidate Recommendation) you can't .

How do I directly modify a Google Chrome Extension File? (.CRX)

I searched it in Google and I found this:

The Google Chrome Extension file type is CRX. It is essentially a compression format. So if you want to see what is behind an extension, the scripts and the code, just change the file-type from “CRX” to “ZIP” .

Unzip the file and you will get all the info you need. This way you can see the guts, learn how to write an extension yourself, or modify it for your own needs.

Then you can pack it back up with Chrome’s internal tools which automatically create the file back into CRX. Installing it just requires a click.

Bootstrap Responsive Text Size

Simplest way is to use dimensions in % or em. Just change the base font size everything will change.

Less

@media (max-width: @screen-xs) {
    body{font-size: 10px;}
}

@media (max-width: @screen-sm) {
    body{font-size: 14px;}
}


h5{
    font-size: 1.4rem;
}       

Look at all the ways at https://stackoverflow.com/a/21981859/406659

You could use viewport units (vh,vw...) but they dont work on Android < 4.4

Sort Dictionary by keys

This is an elegant alternative to sorting the dictionary itself:

As of Swift 4 & 5

let sortedKeys = myDict.keys.sorted()

for key in sortedKeys {
   // Ordered iteration over the dictionary
   let val = myDict[key]
}

ActiveModel::ForbiddenAttributesError when creating new user

For those using CanCanCan:

You will get this error if CanCanCan cannot find the correct params method.

For the :create action, CanCan will try to initialize a new instance with sanitized input by seeing if your controller will respond to the following methods (in order):

  1. create_params
  2. <model_name>_params such as article_params (this is the default convention in rails for naming your param method)
  3. resource_params (a generically named method you could specify in each controller)

Additionally, load_and_authorize_resource can now take a param_method option to specify a custom method in the controller to run to sanitize input.

You can associate the param_method option with a symbol corresponding to the name of a method that will get called:

class ArticlesController < ApplicationController
  load_and_authorize_resource param_method: :my_sanitizer

  def create
    if @article.save
      # hurray
    else
      render :new
    end
  end

  private

  def my_sanitizer
    params.require(:article).permit(:name)
  end
end

source: https://github.com/CanCanCommunity/cancancan#33-strong-parameters

Could not create SSL/TLS secure channel, despite setting ServerCertificateValidationCallback

I came across this thread because I also had the error Could not create SSL/TLS secure channel. In my case, I was attempting to access a Siebel configuration REST API from PowerShell using Invoke-RestMethod, and none of the suggestions above helped.

Eventually I stumbled across the cause of my problem: the server I was contacting required client certificate authentication.

To make the calls work, I had to provide the client certificate (including the private key) with the -Certificate parameter:

$Pwd = 'certificatepassword'
$Pfx = New-Object -TypeName 'System.Security.Cryptography.X509Certificates.X509Certificate2'
$Pfx.Import('clientcert.p12', $Pwd, 'Exportable,PersistKeySet')
Invoke-RestMethod -Uri 'https://your.rest.host/api/' -Certificate $Pfx -OtherParam ...

Hopefully my experience might help someone else who has my particular flavour of this problem.

Sleep function in Windows, using C

Use:

#include <windows.h>

Sleep(sometime_in_millisecs); // Note uppercase S

And here's a small example that compiles with MinGW and does what it says on the tin:

#include <windows.h>
#include <stdio.h>

int main() {
    printf( "starting to sleep...\n" );
    Sleep(3000); // Sleep three seconds
    printf("sleep ended\n");
}

How to execute a JavaScript function when I have its name as a string

The answer to this other question shows you how to do that: Javascript equivalent of Python's locals()?

Basically, you can say

window["foo"](arg1, arg2);

or as many others have suggested, you can just use eval:

eval(fname)(arg1, arg2);

although this is extremely unsafe unless you're absolutely sure about what you're eval-ing.

Putting HTML inside Html.ActionLink(), plus No Link Text?

This has always worked well for me. It's not messy and very clean.

<a href="@Url.Action("Index", "Home")"><span>Text</span></a>

How to stop creating .DS_Store on Mac?

Its is possible by using mach_inject. Take a look at Death to .DS_Store

I found that overriding HFSPlusPropertyStore::FlushChanges() with a function that simply did nothing, successfully prevented the creation of .DS_Store files on both Snow Leopard and Lion.

DeathToDSStore source code

NOTE: On 10.11 you can not inject code into system apps.

How can I perform a str_replace in JavaScript, replacing text in JavaScript?

hm.. Did you check replace() ?

Your code will look like this

var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
document.write(new_text);

Undo a Git merge that hasn't been pushed yet

If your merge and the corresponding commits were not pushed yet, you can always switch to another branch, delete the original one and re-create it.

For example, I accidentally merged a develop branch into master and wanted to undo that. Using the following steps:

git checkout develop
git branch -D master
git branch -t master origin/master

Voila! Master is at the same stage as origin, and your mis-merged state is erased.

Maximum number of rows in an MS Access database engine table?

We're not necessarily talking theoretical limits here, we're talking about real world limits of the 2GB max file size AND database schema.

  • Is your db a single table or multiple?
  • How many columns does each table have?
  • What are the datatypes?

The schema is on even footing with the row count in determining how many rows you can have.

We have used Access MDBs to store exports of MS-SQL data for statistical analysis by some of our corporate users. In those cases we've exported our core table structure, typically four tables with 20 to 150 columns varying from a hundred bytes per row to upwards of 8000 bytes per row. In these cases, we would bump up against a few hundred thousand rows of data were permissible PER MDB that we would ship them.

So, I just don't think that this question has an answer in absence of your schema.

Order by in Inner Join

Add an ORDER BY ONE.ID ASC at the end of your first query.

By default there is no ordering.

Why I can't access remote Jupyter Notebook server?

Is that your private IP address? If so you'll need to use your public one. Go to ipchicken to find out what it is. I know you are in the same LAN, but try this to see if it resolves any issues.

Calculating days between two dates with Java

Java date libraries are notoriously broken. I would advise to use Joda Time. It will take care of leap year, time zone and so on for you.

Minimal working example:

import java.util.Scanner;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class DateTestCase {

    public static void main(String[] args) {

        System.out.print("Insert first date: ");
        Scanner s = new Scanner(System.in);
        String firstdate = s.nextLine();
        System.out.print("Insert second date: ");
        String seconddate = s.nextLine();

        // Formatter
        DateTimeFormatter dateStringFormat = DateTimeFormat
                .forPattern("dd MM yyyy");
        DateTime firstTime = dateStringFormat.parseDateTime(firstdate);
        DateTime secondTime = dateStringFormat.parseDateTime(seconddate);
        int days = Days.daysBetween(new LocalDate(firstTime),
                                    new LocalDate(secondTime)).getDays();
        System.out.println("Days between the two dates " + days);
    }
}

Read Numeric Data from a Text File in C++

Repeat >> reads in loop.

#include <iostream>
#include <fstream>
int main(int argc, char * argv[])
{
    std::fstream myfile("D:\\data.txt", std::ios_base::in);

    float a;
    while (myfile >> a)
    {
        printf("%f ", a);
    }

    getchar();

    return 0;
}

Result:

45.779999 67.900002 87.000000 34.889999 346.000000 0.980000

If you know exactly, how many elements there are in a file, you can chain >> operator:

int main(int argc, char * argv[])
{
    std::fstream myfile("D:\\data.txt", std::ios_base::in);

    float a, b, c, d, e, f;

    myfile >> a >> b >> c >> d >> e >> f;

    printf("%f\t%f\t%f\t%f\t%f\t%f\n", a, b, c, d, e, f);

    getchar();

    return 0;
}

Edit: In response to your comments in main question.

You have two options.

  • You can run previous code in a loop (or two loops) and throw away a defined number of values - for example, if you need the value at point (97, 60), you have to skip 5996 (= 60 * 100 + 96) values and use the last one. This will work if you're interested only in specified value.
  • You can load the data into an array - as Jerry Coffin sugested. He already gave you quite nice class, which will solve the problem. Alternatively, you can use simple array to store the data.

Edit: How to skip values in file

To choose the 1234th value, use the following code:

int skipped = 1233;
for (int i = 0; i < skipped; i++)
{
    float tmp;
    myfile >> tmp;
}
myfile >> value;

Determine on iPhone if user has enabled push notifications

Below you'll find a complete example that covers both iOS8 and iOS7 (and lower versions). Please note that prior to iOS8 you can't distinguish between "remote notifications disabled" and "only View in lockscreen enabled".

BOOL remoteNotificationsEnabled = false, noneEnabled,alertsEnabled, badgesEnabled, soundsEnabled;

if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
    // iOS8+
    remoteNotificationsEnabled = [UIApplication sharedApplication].isRegisteredForRemoteNotifications;

    UIUserNotificationSettings *userNotificationSettings = [UIApplication sharedApplication].currentUserNotificationSettings;

    noneEnabled = userNotificationSettings.types == UIUserNotificationTypeNone;
    alertsEnabled = userNotificationSettings.types & UIUserNotificationTypeAlert;
    badgesEnabled = userNotificationSettings.types & UIUserNotificationTypeBadge;
    soundsEnabled = userNotificationSettings.types & UIUserNotificationTypeSound;

} else {
    // iOS7 and below
    UIRemoteNotificationType enabledRemoteNotificationTypes = [UIApplication sharedApplication].enabledRemoteNotificationTypes;

    noneEnabled = enabledRemoteNotificationTypes == UIRemoteNotificationTypeNone;
    alertsEnabled = enabledRemoteNotificationTypes & UIRemoteNotificationTypeAlert;
    badgesEnabled = enabledRemoteNotificationTypes & UIRemoteNotificationTypeBadge;
    soundsEnabled = enabledRemoteNotificationTypes & UIRemoteNotificationTypeSound;
}

if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
    NSLog(@"Remote notifications enabled: %@", remoteNotificationsEnabled ? @"YES" : @"NO");
}

NSLog(@"Notification type status:");
NSLog(@"  None: %@", noneEnabled ? @"enabled" : @"disabled");
NSLog(@"  Alerts: %@", alertsEnabled ? @"enabled" : @"disabled");
NSLog(@"  Badges: %@", badgesEnabled ? @"enabled" : @"disabled");
NSLog(@"  Sounds: %@", soundsEnabled ? @"enabled" : @"disabled");

How can I assign an ID to a view programmatically?

Android id overview

An Android id is an integer commonly used to identify views; this id can be assigned via XML (when possible) and via code (programmatically.) The id is most useful for getting references for XML-defined Views generated by an Inflater (such as by using setContentView.)

Assign id via XML

  • Add an attribute of android:id="@+id/somename" to your view.
  • When your application is built, the android:id will be assigned a unique int for use in code.
  • Reference your android:id's int value in code using "R.id.somename" (effectively a constant.)
  • this int can change from build to build so never copy an id from gen/package.name/R.java, just use "R.id.somename".
  • (Also, an id assigned to a Preference in XML is not used when the Preference generates its View.)

Assign id via code (programmatically)

  • Manually set ids using someView.setId(int);
  • The int must be positive, but is otherwise arbitrary- it can be whatever you want (keep reading if this is frightful.)
  • For example, if creating and numbering several views representing items, you could use their item number.

Uniqueness of ids

  • XML-assigned ids will be unique.
  • Code-assigned ids do not have to be unique
  • Code-assigned ids can (theoretically) conflict with XML-assigned ids.
  • These conflicting ids won't matter if queried correctly (keep reading).

When (and why) conflicting ids don't matter

  • findViewById(int) will iterate depth-first recursively through the view hierarchy from the View you specify and return the first View it finds with a matching id.
  • As long as there are no code-assigned ids assigned before an XML-defined id in the hierarchy, findViewById(R.id.somename) will always return the XML-defined View so id'd.

Dynamically Creating Views and Assigning IDs

  • In layout XML, define an empty ViewGroup with id.
  • Such as a LinearLayout with android:id="@+id/placeholder".
  • Use code to populate the placeholder ViewGroup with Views.
  • If you need or want, assign any ids that are convenient to each view.
  • Query these child views using placeholder.findViewById(convenientInt);

  • API 17 introduced View.generateViewId() which allows you to generate a unique ID.

If you choose to keep references to your views around, be sure to instantiate them with getApplicationContext() and be sure to set each reference to null in onDestroy. Apparently leaking the Activity (hanging onto it after is is destroyed) is wasteful.. :)

Reserve an XML android:id for use in code

API 17 introduced View.generateViewId() which generates a unique ID. (Thanks to take-chances-make-changes for pointing this out.)*

If your ViewGroup cannot be defined via XML (or you don't want it to be) you can reserve the id via XML to ensure it remains unique:

Here, values/ids.xml defines a custom id:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="reservedNamedId" type="id"/>
</resources>

Then once the ViewGroup or View has been created, you can attach the custom id

myViewGroup.setId(R.id.reservedNamedId);

Conflicting id example

For clarity by way of obfuscating example, lets examine what happens when there is an id conflict behind the scenes.

layout/mylayout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <LinearLayout
        android:id="@+id/placeholder"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
</LinearLayout>

To simulate a conflict, lets say our latest build assigned R.id.placeholder(@+id/placeholder) an int value of 12..

Next, MyActivity.java defines some adds views programmatically (via code):

int placeholderId = R.id.placeholder; // placeholderId==12
// returns *placeholder* which has id==12:
ViewGroup placeholder = (ViewGroup)this.findViewById(placeholderId);
for (int i=0; i<20; i++){
    TextView tv = new TextView(this.getApplicationContext());
    // One new TextView will also be assigned an id==12:
    tv.setId(i);
    placeholder.addView(tv);
}

So placeholder and one of our new TextViews both have an id of 12! But this isn't really a problem if we query placeholder's child views:

// Will return a generated TextView:
 placeholder.findViewById(12);

// Whereas this will return the ViewGroup *placeholder*;
// as long as its R.id remains 12: 
Activity.this.findViewById(12);

*Not so bad

Raising a number to a power in Java

we can use

Math.pow(2, 4);

this mean 2 to the power 4 (2^4)

answer = 16

How do I tell what type of value is in a Perl variable?

$x is always a scalar. The hint is the sigil $: any variable (or dereferencing of some other type) starting with $ is a scalar. (See perldoc perldata for more about data types.)

A reference is just a particular type of scalar. The built-in function ref will tell you what kind of reference it is. On the other hand, if you have a blessed reference, ref will only tell you the package name the reference was blessed into, not the actual core type of the data (blessed references can be hashrefs, arrayrefs or other things). You can use Scalar::Util 's reftype will tell you what type of reference it is:

use Scalar::Util qw(reftype);

my $x = bless {}, 'My::Foo';
my $y = { };

print "type of x: " . ref($x) . "\n";
print "type of y: " . ref($y) . "\n";
print "base type of x: " . reftype($x) . "\n";
print "base type of y: " . reftype($y) . "\n";

...produces the output:

type of x: My::Foo
type of y: HASH
base type of x: HASH
base type of y: HASH

For more information about the other types of references (e.g. coderef, arrayref etc), see this question: How can I get Perl's ref() function to return REF, IO, and LVALUE? and perldoc perlref.

Note: You should not use ref to implement code branches with a blessed object (e.g. $ref($a) eq "My::Foo" ? say "is a Foo object" : say "foo not defined";) -- if you need to make any decisions based on the type of a variable, use isa (i.e if ($a->isa("My::Foo") { ... or if ($a->can("foo") { ...). Also see polymorphism.

Virtual network interface in Mac OS X

In regards to @bmasterswizzle's BRILLIANT answer - more specifically - to @DanRamos' question about how to force the new interface's link-state to "up".. I use this script, of whose origin I cannot recall, but which works fabulously (in coordination with @bmasterswizzles "Mona Lisa" of answers)...

#!/bin/zsh

[[ "$UID" -ne "0" ]] && echo "You must be root. Goodbye..." && exit 1
echo "starting"
exec 4<>/dev/tap0
ifconfig tap0 10.10.10.1 10.10.10.255
ifconfig tap0 up
ping -c1 10.10.10.1
echo "ending"
export PS1="tap interface>"
dd of=/dev/null <&4 & # continuously reads from buffer and dumps to null

I am NOT quite sure I understand the alteration to the prompt at the end, or...

dd of=/dev/null <&4 & # continuously reads from buffer and dumps to null

but WHATEVER. it works. link light: green?. loves it.

enter image description here

Check if cookies are enabled

Here is a very useful and lightweight javascript plugin to accomplish this: js-cookie

Cookies.set('cookieName', 'Value');
      setTimeout(function(){
        var cookieValue =  Cookies.get('cookieName');
        if(cookieValue){
           console.log("Test Cookie is set!");
        } else {
           document.write('<p>Sorry, but cookies must be enabled</p>');
        }
        Cookies.remove('cookieName');
      }, 1000);

Works in all browsers, accepts any character.

Simple way to transpose columns and rows in SQL?

Adding to @Paco Zarate's terrific answer above, if you want to transpose a table which has multiple types of columns, then add this to the end of line 39, so it only transposes int columns:

and C.system_type_id = 56   --56 = type int

Here is the full query that is being changed:

select @colsUnpivot = stuff((select ','+quotename(C.name)
from sys.columns as C
where C.object_id = object_id(@tableToPivot) and
      C.name <> @columnToPivot and C.system_type_id = 56    --56 = type int
for xml path('')), 1, 1, '')

To find other system_type_id's, run this:

select name, system_type_id from sys.types order by name

React - Preventing Form Submission

function onTestClick(evt) {
  evt.stopPropagation();
}

Oracle SQL Developer - tables cannot be seen

SQL Developer 3.1 fixes this issue. Its an early adopter release at the moment though.

How to correctly close a feature branch in Mercurial?

It is strange, that no one yet has suggested the most robust way of closing a feature branches... You can just combine merge commit with --close-branch flag (i.e. commit modified files and close the branch simultaneously):

hg up feature-x
hg merge default
hg ci -m "Merge feature-x and close branch" --close-branch
hg branch default -f

So, that is all. No one extra head on revgraph. No extra commit.

How can I change the remote/target repository URL on Windows?

One more way to do this is:

git config remote.origin.url https://github.com/abc/abc.git

To see the existing URL just do:

git config remote.origin.url

Yes or No confirm box using jQuery

You can reuse your confirm:

    function doConfirm(body, $_nombrefuncion)
    {   var param = undefined;
        var $confirm = $("<div id='confirm' class='hide'></div>").dialog({
            autoOpen: false,
            buttons: {
                Yes: function() {
                param = true;
                $_nombrefuncion(param);
                $(this).dialog('close');
            },
                No: function() {
                param = false;
                $_nombrefuncion(param);
                $(this).dialog('close');
            }
                                    }
        });
        $confirm.html("<h3>"+body+"<h3>");
        $confirm.dialog('open');                                     
    };

// for this form just u must change or create a new function for to reuse the confirm
    function resultadoconfirmresetVTyBFD(param){
        $fecha = $("#asigfecha").val();
        if(param ==true){
              // DO THE CONFIRM
        }
    }

//Now just u must call the function doConfirm
    doConfirm('body message',resultadoconfirmresetVTyBFD);

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class

Just restarting the server with command npm start did the trick. Thanks all for the suggestions.

Is Safari on iOS 6 caching $.ajax results?

Things that DID NOT WORK for me with an iPad 4/iOS 6:

My request containing: Cache-Control:no-cache

//asp.net's:
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache)

Adding cache: false to my jQuery ajax call

 $.ajax(
        {
            url: postUrl,
            type: "POST",
            cache: false,
            ...

Only this did the trick:

var currentTime = new Date();
var n = currentTime.getTime();
postUrl = "http://www.example.com/test.php?nocache="+n;
$.post(postUrl, callbackFunction);

Validate phone number using angular js

Use ng-pattern, in this example you can validate a simple patern with 10 numbers, when the patern is not matched ,the message is show and the button is disabled.

 <form  name="phoneNumber">

        <label for="numCell" class="text-strong">Phone number</label>

        <input id="numCell" type="text" name="inputCelular"  ng-model="phoneNumber" 
            class="form-control" required  ng-pattern="/^[0-9]{10,10}$/"></input>
        <div class="alert-warning" ng-show="phoneNumber.inputCelular.$error.pattern">
            <p> write a phone number</p>
        </div>

    <button id="button"  class="btn btn-success" click-once ng-disabled="!phoneNumber.$valid" ng-click="callDigitaliza()">Buscar</button>

Also you can use another complex patern like

^+?\d{1,3}?[- .]?(?(?:\d{2,3}))?[- .]?\d\d\d[- .]?\d\d\d\d$

, for more complex phone numbers

How to set or change the default Java (JDK) version on OS X?

I have done it for the local terminal with

export JAVA_8_HOME=(/Library/Java/JavaVirtualMachines/jdk1.8.0_221.jdk/Contents/Home/)
export JAVA_13_HOME=(/Library/Java/JavaVirtualMachines/jdk-13.0.1.jdk/Contents/Home/)

alias java8='export JAVA_HOME=$JAVA_8_HOME; alias java="$JAVA_8_HOME/bin/java"; $JAVA_8_HOME/bin/java -version'
alias java13='export JAVA_HOME=$JAVA_13_HOME; alias java="$JAVA_13_HOME/bin/java"; $JAVA_13_HOME/bin/java -version'

export JAVA_HOME=$JAVA_13_HOME

AngularJS access parent scope from child controller

You can also circumvent scope inheritance and store things in the "global" scope.

If you have a main controller in your application which wraps all other controllers, you can install a "hook" to the global scope:

function RootCtrl($scope) {
    $scope.root = $scope;
}

Then in any child controller, you can access the "global" scope with $scope.root. Anything you set here will be globally visible.

Example:

_x000D_
_x000D_
function RootCtrl($scope) {_x000D_
  $scope.root = $scope;_x000D_
}_x000D_
_x000D_
function ChildCtrl($scope) {_x000D_
  $scope.setValue = function() {_x000D_
    $scope.root.someGlobalVar = 'someVal';_x000D_
  }_x000D_
}_x000D_
_x000D_
function OtherChildCtrl($scope) {_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app ng-controller="RootCtrl">_x000D_
  _x000D_
  <p ng-controller="ChildCtrl">_x000D_
    <button ng-click="setValue()">Set someGlobalVar</button>_x000D_
  </p>_x000D_
  _x000D_
  <p ng-controller="OtherChildCtrl">_x000D_
    someGlobalVar value: {{someGlobalVar}}_x000D_
  </p>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I have two fixed width columns with one flexible column in the center?

Compatibility with older browsers can be a drag, so be adviced.

If that is not a problem then go ahead. Run the snippet. Go to full page view and resize. Center will resize itself with no changes to the left or right divs.

Change left and right values to meet your requirement.

Thank you.

Hope this helps.

_x000D_
_x000D_
#container {_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.column.left {_x000D_
  width: 100px;_x000D_
  flex: 0 0 100px;_x000D_
}_x000D_
_x000D_
.column.right {_x000D_
  width: 100px;_x000D_
  flex: 0 0 100px;_x000D_
}_x000D_
_x000D_
.column.center {_x000D_
  flex: 1;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.column.left,_x000D_
.column.right {_x000D_
  background: orange;_x000D_
  text-align: center;_x000D_
}
_x000D_
<div id="container">_x000D_
  <div class="column left">this is left</div>_x000D_
  <div class="column center">this is center</div>_x000D_
  <div class="column right">this is right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I set up a private Git repository on GitHub? Is it even possible?

Since January 7th, 2019, it is possible: unlimited free private repositories on GitHub!
... But for up to three collaborators per private repository.

Nat Friedman just announced it by twitter:

Today(!) we’re thrilled to announce unlimited free private repos for all GitHub users, and a new simplified Enterprise offering:

"New year, new GitHub: Announcing unlimited free private repos and unified Enterprise offering"

For the first time, developers can use GitHub for their private projects with up to three collaborators per repository for free.

Many developers want to use private repos to apply for a job, work on a side project, or try something out in private before releasing it publicly.
Starting today, those scenarios, and many more, are possible on GitHub at no cost.

Public repositories are still free (of course—no changes there) and include unlimited collaborators.

Android emulator: How to monitor network traffic?

For OS X you can use Charles, it's simple and easy to use.

For more information, please have a look at Android Emulator and Charles Proxy blog post.

Disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation)

We are doing the same thing. To support only TLS 1.2 and no SSL protocols, you can do this:

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

SecurityProtocolType.Tls is only TLS 1.0, not all TLS versions.

As a side: If you want to check that your site does not allow SSL connections, you can do so here (I don't think this will be affected by the above setting, we had to edit the registry to force IIS to use TLS for incoming connections): https://www.ssllabs.com/ssltest/index.html

To disable SSL 2.0 and 3.0 in IIS, see this page: https://www.sslshopper.com/article-how-to-disable-ssl-2.0-in-iis-7.html

Best way to call a JSON WebService from a .NET Console

Although the existing answers are valid approaches , they are antiquated . HttpClient is a modern interface for working with RESTful web services . Check the examples section of the page in the link , it has a very straightforward use case for an asynchronous HTTP GET .

using (var client = new System.Net.Http.HttpClient())
{
    return await client.GetStringAsync("https://reqres.in/api/users/3"); //uri
}

CharSequence VS String in Java?

CharSequence = interface
String = concrete implementation

You said:

converting from one to another

There is no converting from String.

  • Every String object is a CharSequence.
  • Every CharSequence can produce a String. Call CharSequence::toString. If the CharSequence happens to be a String, then the method returns a reference to its own object.

In other words, every String is a CharSequence, but not every CharSequence is a String.

Programming to an interface

Programming in Android, most of the text values are expected in CharSequence.

Why is that? What is the benefit, and what are the main impacts of using CharSequence over String?

Generally, programming to an interface is better than programming to concrete classes. This yields flexibility, so we can switch between concrete implementations of a particular interface without breaking other code.

When developing an API to be used by various programmers in various situations, write your code to give and take the most general interfaces possible. This gives the calling programmer the freedom to use various implementations of that interface, whichever implementation is best for their particular context.

For example, look at the Java Collections Framework. If your API gives or takes an ordered collection of objects, declare your methods as using List rather than ArrayList, LinkedList, or any other 3rd-party implementation of List.

When writing a quick-and-dirty little method to be used only by your code in one specific place, as opposed to writing an API to be used in multiple places, you need not bother with using the more general interface rather than a specific concrete class. But even then, it does to hurt to use the most general interface you can.

What are the main differences, and what issues are expected, while using them,

  • With a String you know you have a single piece of text, entirely in memory, and is immutable.
  • With a CharSequence, you do not know what the particular features of the concrete implementation might be.

The CharSequence object might represent an enormous chunk of text, and therefore has memory implications. Or may be many chunks of text tracked separately that will need to be stitched together when you call toString, and therefore has performance issues. The implementation may even be retrieving text from a remote service, and therefore has latency implications.

and converting from one to another?

You generally won't be converting back and forth. A String is a CharSequence. If your method declares that it takes a CharSequence, the calling programmer may pass a String object, or may pass something else such as a StringBuffer or StringBuilder. Your method's code will simply use whatever is passed, calling any of the CharSequence methods.

The closest you would get to converting is if your code receives a CharSequence and you know you need a String. Perhaps your are interfacing with old code written to String class rather than written to the CharSequence interface. Or perhaps your code will work intensively with the text, such as looping repeatedly or otherwise analyzing. In that case, you want to take any possible performance hit only once, so you call toString up front. Then proceed with your work using what you know to be a single piece of text entirely in memory.

Twisted history

Note the comments made on the accepted Answer. The CharSequence interface was retrofitted onto existing class structures, so there are some important subtleties (equals() & hashCode()). Notice the various versions of Java (1, 2, 4 & 5) tagged on the classes/interfaces—quite a bit of churn over the years. Ideally CharSequence would have been in place from the beginning, but such is life.

My class diagram below may help you see the big picture of string types in Java 7/8. I'm not sure if all of these are present in Android, but the overall context may still prove useful to you.

diagram of various string-related classes and interfaces

What is the difference between npm install and npm run build?

  • npm install installs the depedendencies in your package.json config.
  • npm run build runs the script "build" and created a script which runs your application - let's say server.js
  • npm start runs the "start" script which will then be "node server.js"

It's difficult to tell exactly what the issue was but basically if you look at your scripts configuration, I would guess that "build" uses some kind of build tool to create your application while "start" assumes the build has been done but then fails if the file is not there.

You are probably using bower or grunt - I seem to remember that a typical grunt application will have defined those scripts as well as a "clean" script to delete the last build.

Build tools tend to create a file in a bin/, dist/, or build/ folder which the start script then calls - e.g. "node build/server.js". When your npm start fails, it is probably because you called npm clean or similar to delete the latest build so your application file is not present causing npm start to fail.

npm build's source code - to touch on the discussion in this question - is in github for you to have a look at if you like. If you run npm build directly and you have a "build" script defined, it will exit with an error asking you to call your build script as npm run-script build so it's not the same as npm run script.

I'm not quite sure what npm build does, but it seems to be related to postinstall and packaging scripts in dependencies. I assume that this might be making sure that any CLI build scripts's or native libraries required by dependencies are built for the specific environment after downloading the package. This will be why link and install call this script.

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

I searched for the solution online and found this solution but wasn't too keen on the registry change.

I found a better way: right-click on the solution name right at the top of the Solution Explorer and select the Go Online option. Clicking this allowed me to select the files that had been changed when I was offline and make the solution online again.

After finding the solution, I found the following msdn forum thread which confirmed the above.

Making an image act like a button

It sounds like you want an image button:

<input type="image" src="logg.png" name="saveForm" class="btTxt submit" id="saveForm" />

Alternatively, you can use CSS to make the existing submit button use your image as its background.

In any case, you don't want a separate <img /> element on the page.

Java: Rotating Images

Sorry, but all the answers are difficult to understand for me as a beginner in graphics...

After some fiddling, this is working for me and it is easy to reason about.

@Override
public void draw(Graphics2D g) {
    AffineTransform tr = new AffineTransform();
    // X and Y are the coordinates of the image
    tr.translate((int)getX(), (int)getY());
    tr.rotate(
            Math.toRadians(this.rotationAngle),
            img.getWidth() / 2,
            img.getHeight() / 2
    );

    // img is a BufferedImage instance
    g.drawImage(img, tr, null);
}

I suppose that if you want to rotate a rectangular image this method wont work and will cut the image, but I thing you should create square png images and rotate that.

How to format JSON in notepad++

Try with JSToolNpp and follow the snap like this then Plugins | JSTool | JSFormat.

enter image description here

Get Absolute URL from Relative path (refactored method)

With ASP.NET, you need to consider the reference point for a "relative URL" - is it relative to the page request, a user control, or if it is "relative" simply by virtue of using "~/"?

The Uri class contains a simple way to convert a relative URL to an absolute URL (given an absolute URL as the reference point for the relative URL):

var uri = new Uri(absoluteUrl, relativeUrl);

If relativeUrl is in fact an abolute URL, then the absoluteUrl is ignored.

The only question then remains what the reference point is, and whether "~/" URLs are allowed (the Uri constructor does not translate these).

Check if a file exists locally using JavaScript only

If you want to check if file exists using javascript then no, as far as I know, javascript has no access to file system due to security reasons.. But as for me it is not clear enough what are you trying to do..

What do I use on linux to make a python program executable

Another way to do it could be by creating an alias. For example in terminal write:

alias printhello='python /home/hello_world.py'

Writing printhello will run hello_world.py, but this is only temporary. To make aliases permanent, you have to add them to bashrc, you can edit it by writing this in the terminal:

gedit ~/.bashrc

print highest value in dict with key

The clue is to work with the dict's items (i.e. key-value pair tuples). Then by using the second element of the item as the max key (as opposed to the dict key) you can easily extract the highest value and its associated key.

 mydict = {'A':4,'B':10,'C':0,'D':87}
>>> max(mydict.items(), key=lambda k: k[1])
('D', 87)
>>> min(mydict.items(), key=lambda k: k[1])
('C', 0)

java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory

aforementioned solutions did not help me, I could solve it by re-installing the Tomcat server which took few seconds.

How to center horizontal table-cell

Just add this class in your css

.column p{
   text-align:center;
}

Advantages of std::for_each over for loop

There are a lot of good reasons in other answers but all seem to forget that for_each allows you to use reverse or pretty much any custom iterator when for loop always starts with begin() iterator.

Example with reverse iterator:

std::list<int> l {1,2,3};
std::for_each(l.rbegin(), l.rend(), [](auto o){std::cout<<o;});

Example with some custom tree iterator:

SomeCustomTree<int> a{1,2,3,4,5,6,7};
auto node = a.find(4);
std::for_each(node.breadthFirstBegin(), node.breadthFirstEnd(), [](auto o){std::cout<<o;});

Is there a common Java utility to break a list into batches?

Check out Lists.partition(java.util.List, int) from Google Guava:

Returns consecutive sublists of a list, each of the same size (the final list may be smaller). For example, partitioning a list containing [a, b, c, d, e] with a partition size of 3 yields [[a, b, c], [d, e]] -- an outer list containing two inner lists of three and two elements, all in the original order.

Input and output numpy arrays to h5py

A cleaner way to handle file open/close and avoid memory leaks:

Prep:

import numpy as np
import h5py

data_to_write = np.random.random(size=(100,20)) # or some such

Write:

with h5py.File('name-of-file.h5', 'w') as hf:
    hf.create_dataset("name-of-dataset",  data=data_to_write)

Read:

with h5py.File('name-of-file.h5', 'r') as hf:
    data = hf['name-of-dataset'][:]

Javascript Equivalent to C# LINQ Select

Take a peek at underscore.js which provides many linq like functions. In the example you give you would use the map function.