Programs & Examples On #Fms3

Stands for Adobe Flash Media Server version 3, a video streaming server.

T-SQL to list all the user mappings with database roles/permissions for a Login

I wrote a little query to find permission of a user on a specific database.

    SELECT * FROM   
    (
    SELECT 
    perm.permission_name AS 'PERMISSION'
    ,perm.state_desc AS 'RIGHT'
    ,perm.class_desc AS 'RIGHT_ON'
    ,p.NAME AS 'GRANTEE'
    ,m.NAME AS 'USERNAME'
    ,s.name AS 'SCHEMA'
    ,o.name AS 'OBJECT'
    ,IIF(perm.class = 0, db_name(), NULL) AS 'DATABASE'
    FROM
    sys.database_permissions perm
    INNER JOIN sys.database_principals p ON p.principal_id = perm.grantee_principal_id
    LEFT JOIN sys.database_role_members rm ON rm.role_principal_id = p.principal_id
    LEFT JOIN sys.database_principals m ON rm.member_principal_id = m.principal_id
    LEFT JOIN sys.schemas s ON perm.class = 3 AND perm.major_id = s.schema_id
    LEFT JOIN sys.objects AS o ON perm.class = 1 AND perm.major_id = o.object_id
    UNION ALL
    SELECT 
    perm.permission_name AS 'PERMISSION'
    ,perm.state_desc AS 'RIGHT'
    ,perm.class_desc AS 'RIGHT_ON'
    ,'SELF-GRANTED' AS 'GRANTEE'
    ,p.NAME AS 'USERNAME'
    ,s.name AS 'SCHEMA'
    ,o.name AS 'OBJECT'
    ,IIF(perm.class = 0, db_name(), NULL) AS 'DATABASE'
    FROM
    sys.database_permissions perm
    INNER JOIN sys.database_principals p ON p.principal_id = perm.grantee_principal_id
    LEFT JOIN sys.schemas s ON perm.class = 3 AND perm.major_id = s.schema_id
    LEFT JOIN sys.objects AS o ON perm.class = 1 AND perm.major_id = o.object_id
    ) AS [union]
    WHERE [union].USERNAME = 'Username' -- Username you will search for
    ORDER BY [union].RIGHT_ON, [union].PERMISSION, [union].GRANTEE

The permissions of fixed database roles do not appear in sys.database_permissions. Therefore, database principals may have additional permissions not listed here.

I does not prefer

    EXECUTE AS USER = 'userName';
    SELECT * FROM fn_my_permissions(NULL, 'DATABASE') 

Because it's just retrieving which permissions the user has not where they come from!

Maybe i find out how to join the fixed database roles permission granted for the user one day...

Pls enjoy Life and hate the Users :D

How can a web application send push notifications to iOS devices?

No, there is no way for an webapp to receive push notification. What you could do is to wrap your webapp into a native app which has push notifications.

How to convert SecureString to System.String?

// using so that Marshal doesn't have to be qualified
using System.Runtime.InteropServices;    
//using for SecureString
using System.Security;
public string DecodeSecureString (SecureString Convert) 
{
    //convert to IntPtr using Marshal
    IntPtr cvttmpst = Marshal.SecureStringToBSTR(Convert);
    //convert to string using Marshal
    string cvtPlainPassword = Marshal.PtrToStringAuto(cvttmpst);
    //return the now plain string
    return cvtPlainPassword;
}

Redirecting to a new page after successful login

Javascript redirection generated with php code:

 if($match > 0){
     $msg = 'Login Complete! Thanks';
     echo "<script> window.location.assign('index.php'); </script>";
 }
 else{
     $msg = 'Login Failed!<br /> Please make sure that you enter the correct  details and that you have activated your account.';
 }

Php redirection only:

<?php
    header("Location: index.php"); 
    exit;
?>

Find the min/max element of an array in JavaScript

To prevent "max" and "min" to be listed in a "for ... in" loop:

Object.defineProperty(Array.prototype, "max", {
    enumerable: false,
    configurable: false,
    writable: false,    
    value: function() {
        return Math.max.apply(null, this);
    }
});
Object.defineProperty(Array.prototype, "min", {
    enumerable: false,
    configurable: false,
    writable: false,    
    value: function() {
        return Math.min.apply(null, this);
    }
});

Usage:

var x = [10,23,44,21,5];
x.max(); //44
x.min(); //5

How to get difference between two dates in Year/Month/Week/Day?

Use the Subtract method of the DateTime object which returns a TimeSpan...

DateTime dt1 = new DateTime(2009, 3, 14);
DateTime dt2 = new DateTime(2008, 3, 15);

TimeSpan ts = dt1.Subtract(dt2);

Double days = ts.TotalDays;
Double hours = ts.TotalHours;
Double years = ts.TotalDays / 365;

Getting the HTTP Referrer in ASP.NET

Sometime you must to give all the link like this

System.Web.HttpContext.Current.Request.UrlReferrer.ToString();

(in option when "Current" not founded)

Change all files and folders permissions of a directory to 644/755

The shortest one I could come up with is:

chmod -R a=r,u+w,a+X /foo

which works on GNU/Linux, and I believe on Posix in general (from my reading of: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/chmod.html).

What this does is:

  1. Set file/directory to r__r__r__ (0444)
  2. Add w for owner, to get rw_r__r__ (0644)
  3. Set execute for all if a directory (0755 for dir, 0644 for file).

Importantly, the step 1 permission clears all execute bits, so step 3 only adds back execute bits for directories (never files). In addition, all three steps happen before a directory is recursed into (so this is not equivalent to e.g.

chmod -R a=r /foo
chmod -R u+w /foo
chmod -R a+X /foo

since the a=r removes x from directories, so then chmod can't recurse into them.)

Mysql select distinct

You can use DISTINCT like that

mysql_query("SELECT DISTINCT(ticket_id), column1, column2, column3 
FROM temp_tickets 
ORDER BY ticket_id");

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

This was asked on the www-style list, and Tab Atkins (spec editor) provided an answer explaining why. I'll elaborate on that a bit here.

To start out, let's initially assume our flex container is single-line (flex-wrap: nowrap). In this case, there's clearly an alignment difference between the main axis and the cross axis -- there are multiple items stacked in the main axis, but only one item stacked in the cross axis. So it makes sense to have a customizeable-per-item "align-self" in the cross axis (since each item is aligned separately, on its own), whereas it doesn't make sense in the main axis (since there, the items are aligned collectively).

For multi-line flexbox, the same logic applies to each "flex line". In a given line, items are aligned individually in the cross axis (since there's only one item per line, in the cross axis), vs. collectively in the main axis.


Here's another way of phrasing it: so, all of the *-self and *-content properties are about how to distribute extra space around things. But the key difference is that the *-self versions are for cases where there's only a single thing in that axis, and the *-content versions are for when there are potentially many things in that axis. The one-thing vs. many-things scenarios are different types of problems, and so they have different types of options available -- for example, the space-around / space-between values make sense for *-content, but not for *-self.

SO: In a flexbox's main axis, there are many things to distribute space around. So a *-content property makes sense there, but not a *-self property.

In contrast, in the cross axis, we have both a *-self and a *-content property. One determines how we'll distribute space around the many flex lines (align-content), whereas the other (align-self) determines how to distribute space around individual flex items in the cross axis, within a given flex line.

(I'm ignoring *-items properties here, since they simply establish defaults for *-self.)

Zabbix server is not running: the information displayed may not be current

I was in the same trouble. For my case, that was a conflict between /etc/zabbix/zabbix_agentd.conf and zabbix_server.conf parameters. I adjusted

"DBHost=localhost", 
"DBName=zabbix",
"DBUser=zabbix",
"DBPassword=******", 
"DebugLevel=3"
"ListenPort".

If you run the default installation, you should keep ListenPort=10051 for the server and 10050 for the agent.

Cheers!

Android RelativeLayout programmatically Set "centerInParent"

Completely untested, but this should work:

View positiveButton = findViewById(R.id.positiveButton);
RelativeLayout.LayoutParams layoutParams = 
    (RelativeLayout.LayoutParams)positiveButton.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
positiveButton.setLayoutParams(layoutParams);

add android:configChanges="orientation|screenSize" inside your activity in your manifest

How to use npm with ASP.NET Core

Please excuse the length of this post.

This is a working example using ASP.NET Core version 2.5.

Something of note is that the project.json is obsolete (see here) in favor of .csproj. An issue with .csproj. file is the large amount of features and the fact there is no central location for its documentation (see here).

One more thing, this example is running ASP.NET core in a Docker Linux (alpine 3.9) container; so the paths will reflect that. It also uses gulp ^4.0. However, with some modification, it should work with older versions of ASP.NET Core, Gulp, NodeJS, and also without Docker.

But here's an answer:

gulpfile.js see the real working exmple here

// ROOT and OUT_DIR are defined in the file above. The OUT_DIR value comes from .NET Core when ASP.net us built.
const paths = {
    styles: {
        src: `${ROOT}/scss/**/*.scss`,
        dest: `${OUT_DIR}/css`
    },
    bootstrap: {
        src: [
            `${ROOT}/node_modules/bootstrap/dist/css/bootstrap.min.css`,
            `${ROOT}/node_modules/startbootstrap-creative/css/creative.min.css`
        ],
        dest: `${OUT_DIR}/css`
    },
    fonts: {// enter correct paths for font-awsome here.
        src: [
            `${ROOT}/node_modules/fontawesome/...`,
        ],
        dest: `${OUT_DIR}/fonts`
    },
    js: {
        src: `${ROOT}/js/**/*.js`,
        dest: `${OUT_DIR}/js`
    },
    vendorJs: {
        src: [
            `${ROOT}/node_modules/jquery/dist/jquery.min.js`
            `${ROOT}/node_modules/bootstrap/dist/js/bootstrap.min.js`
        ],
        dest: `${OUT_DIR}/js`
    }
};

// Copy files from node_modules folder to the OUT_DIR.
let fonts = () => {
    return gulp
        .src(paths.styles.src)
        .pipe(gulp.dest(paths.styles.dest));
};

// This compiles all the vendor JS files into one, jsut remove the concat to keep them seperate.
let vendorJs = () => {
    return gulp
        .src(paths.vendorJs.src)
        .pipe(concat('vendor.js'))
        .pipe(gulp.dest(paths.vendorJs.dest));
}

// Build vendorJs before my other files, then build all other files in parallel to save time.
let build = gulp.series(vendorJs, gulp.parallel(js, styles, bootstrap));

module.exports = {// Only add what we intend to use externally.
    default: build,
    watch
};

Add a Target in .csproj file. Notice we also added a Watch to watch and exclude if we take advantage of dotnet run watch command.

app.csprod

  <ItemGroup>
    <Watch Include="gulpfile.js;js/**/*.js;scss/**/*.scss" Exclude="node_modules/**/*;bin/**/*;obj/**/*" />
  </ItemGroup>

  <Target Name="BuildFrontend" BeforeTargets="Build">
    <Exec Command="yarn install" />
    <Exec Command="yarn run build -o $(OutputPath)" />
  </Target>

Now when dotnet run build is run it will also install and build node modules.

Remove Style on Element

Just use like this

 $("#sample_id").css("width", "");
 $("#sample_id").css("height", "");

Returning a value even if no result

As you are looking for 1 record, (LIMIT 1) then this will work.

(SELECT field1 FROM table WHERE id = 123) 
UNION 
(SELECT 'default_value_if_no_record')
LIMIT 1;

Can be a handy way to display default values, or indicate no results found. I use it for reports.

See also http://blogs.uoregon.edu/developments/2011/03/31/add-a-header-row-to-mysql-query-results/ for a way to use this to create headers in reports.

Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist

When download mysql zip version, if run mysqld directly, you'll get this error: 2016-02-18T07:23:48.318481Z 0 [ERROR] Fatal error: Can't open and lock privilege tables: Table 'mysql.user' doesn't exist 2016-02-18T07:23:48.319482Z 0 [ERROR] Aborting

You have to run below command first: mysqld --initialize

Make sure your data folder is empty before this command.

Using TortoiseSVN via the command line

There is a confusion that is causing a lot of TortoiseSVN users to use the wrong command line tools when they actually were looking for svn.exe command line client.

What should I do or can't TortoiseSVN be used from the command line?

svn.exe

If you want to run Subversion commands from the command prompt, you should run the svn.exe command line client. TortoiseSVN 1.6.x and older versions did not include SVN command-line tools, but modern versions do.

If you want to get SVN command line tools without having to install TortoiseSVN, check the SVN binary distributions page or simply download the latest version from VisualSVN downloads page.

If you have SVN command line tools installed on your system, but still get the error 'svn' is not recognized as an internal or external command, you should check %PATH% environment variable. %PATH% must include the path to SVN tools directory e.g. C:\Program Files (x86)\VisualSVN\bin.

TortoiseProc.exe

Apart from svn.exe, TortoiseSVN comes with TortoiseProc.exe that can be called from command prompt. In most cases, you do not need to use this tool, because it should be only used for GUI automation. TortoiseProc.exe is not a replacement for SVN command-line client.

How to extract multiple JSON objects from one file?

Use a json array, in the format:

[
{"ID":"12345","Timestamp":"20140101", "Usefulness":"Yes",
  "Code":[{"event1":"A","result":"1"},…]},
{"ID":"1A35B","Timestamp":"20140102", "Usefulness":"No",
  "Code":[{"event1":"B","result":"1"},…]},
{"ID":"AA356","Timestamp":"20140103", "Usefulness":"No",
  "Code":[{"event1":"B","result":"0"},…]},
...
]

Then import it into your python code

import json

with open('file.json') as json_file:

    data = json.load(json_file)

Now the content of data is an array with dictionaries representing each of the elements.

You can access it easily, i.e:

data[0]["ID"]

Why does Eclipse complain about @Override on interface methods?

You could change the compiler settings to accept Java 6 syntax but generate Java 5 output (as I remember). And set the "Generated class files compatibility" a bit lower if needed by your runtime. Update: I checked Eclipse, but it complains if I set source compatibility to 1.6 and class compatibility to 1.5. If 1.6 is not allowed I usually manually comment out the offending @Override annotations in the source (which doesn't help your case).

Update2: If you do only manual build, you could write a small program which copies the original project into a new one, strips @Override annotations from the java sources and you just hit Clean project in Eclipse.

Vue is not defined

try to fix type="JavaScript" to type="text/javascript" in you vue.js srcipt tag, or just remove it. Modern browsers will take script tag as javascript as default.

Reloading .env variables without restarting server (Laravel 5, shared hosting)

I know this is old, but for local dev, this is what got things back to a production .env file:

rm bootstrap/cache/config.php

then

php artisan config:cache
php artisan config:clear
php artisan cache:clear

Accessing JSON elements

import json
weather = urllib2.urlopen('url')
wjson = weather.read()
wjdata = json.loads(wjson)
print wjdata['data']['current_condition'][0]['temp_C']

What you get from the url is a json string. And your can't parse it with index directly. You should convert it to a dict by json.loads and then you can parse it with index.

Instead of using .read() to intermediately save it to memory and then read it to json, allow json to load it directly from the file:

wjdata = json.load(urllib2.urlopen('url'))

How to save public key from a certificate in .pem format

if it is a RSA key

openssl rsa  -pubout -in my_rsa_key.pem

if you need it in a format for openssh , please see Use RSA private key to generate public key?

Note that public key is generated from the private key and ssh uses the identity file (private key file) to generate and send public key to server and un-encrypt the encrypted token from the server via the private key in identity file.

Get selected text from a drop-down list (select box) using jQuery

For those who are using SharePoint lists and don't want to use the long generated id, this will work:

var e = $('select[title="IntenalFieldName"] option:selected').text();

Get last dirname/filename in a file path argument in Bash

Bash can get the last part of a path without having to call the external basename:

subdir="/path/to/whatever/${1##*/}"

Cannot edit in read-only editor VS Code

The easiest way to fix this was to press (CTRL) and (,) in VS Code to open Settings.

After that, on the search bar search for code runner, then scroll down and search for Run In Terminal and check that box as highlighted in the below image:

django templates: include and extends

Edit 10th Dec 2015: As pointed out in the comments, ssi is deprecated since version 1.8. According to the documentation:

This tag has been deprecated and will be removed in Django 1.10. Use the include tag instead.


In my opinion, the right (best) answer to this question is the one from podshumok, as it explains why the behaviour of include when used along with inheritance.

However, I was somewhat surprised that nobody mentioned the ssi tag provided by the Django templating system, which is specifically designed for inline including an external piece of text. Here, inline means the external text will not be interpreted, parsed or interpolated, but simply "copied" inside the calling template.

Please, refer to the documentation for further details (be sure to check your appropriate version of Django in the selector at the lower right part of the page).

https://docs.djangoproject.com/en/dev/ref/templates/builtins/#ssi

From the documentation:

ssi
Outputs the contents of a given file into the page.
Like a simple include tag, {% ssi %} includes the contents of another file
– which must be specified using an absolute path – in the current page

Beware also of the security implications of this technique and also of the required ALLOWED_INCLUDE_ROOTS define, which must be added to your settings files.

What is a good alternative to using an image map generator?

This one is in my opinion the best one for online (offline however dreamweaver is best): http://www.maschek.hu/imagemap/imgmap

What is the point of the diamond operator (<>) in Java 7?

This line causes the [unchecked] warning:

List<String> list = new LinkedList();

So, the question transforms: why [unchecked] warning is not suppressed automatically only for the case when new collection is created?

I think, it would be much more difficult task then adding <> feature.

UPD: I also think that there would be a mess if it were legally to use raw types 'just for a few things'.

Add image to layout in ruby on rails

In a Ruby on Rails project by default the root of the HTML source for the server is the public directory. So your link would be:

<img src="images/rss.jpg" alt="rss feed" />

But it is best practice in a Rails project to use the built in helper:

<%= image_tag("rss.jpg", :alt => "rss feed") %>

That will create the correct image link plus if you ever add assert servers, etc it will work with those.

Turn a string into a valid filename?

>>> import string
>>> safechars = bytearray(('_-.()' + string.digits + string.ascii_letters).encode())
>>> allchars = bytearray(range(0x100))
>>> deletechars = bytearray(set(allchars) - set(safechars))
>>> filename = u'#ab\xa0c.$%.txt'
>>> safe_filename = filename.encode('ascii', 'ignore').translate(None, deletechars).decode()
>>> safe_filename
'abc..txt'

It doesn't handle empty strings, special filenames ('nul', 'con', etc).

Pad a string with leading zeros so it's 3 characters long in SQL Server 2008

Use this function which suits every situation.

CREATE FUNCTION dbo.fnNumPadLeft (@input INT, @pad tinyint)
RETURNS VARCHAR(250)
AS BEGIN
    DECLARE @NumStr VARCHAR(250)

    SET @NumStr = LTRIM(@input)

    IF(@pad > LEN(@NumStr))
        SET @NumStr = REPLICATE('0', @Pad - LEN(@NumStr)) + @NumStr;

    RETURN @NumStr;
END

Sample output

SELECT [dbo].[fnNumPadLeft] (2016,10) -- returns 0000002016
SELECT [dbo].[fnNumPadLeft] (2016,5) -- returns 02016
SELECT [dbo].[fnNumPadLeft] (2016,2) -- returns 2016
SELECT [dbo].[fnNumPadLeft] (2016,0) -- returns 2016 

Safe navigation operator (?.) or (!.) and null property paths

Since TypeScript 3.7 was released you can use optional chaining now.

Property example:

let x = foo?.bar.baz();

This is equvalent to:

let x = (foo === null || foo === undefined) ?
    undefined :
    foo.bar.baz();

Moreover you can call:

Optional Call

function(otherFn: (par: string) => void) {
   otherFn?.("some value");
}

otherFn will be called only if otherFn won't be equal to null or undefined

Usage optional chaining in IF statement

This:

if (someObj && someObj.someProperty) {
    // ...
}

can be replaced now with this

if (someObj?.someProperty) {
    // ...
}

Ref. https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html

Regular expression to search multiple strings (Textpad)

I suggest much better solution. Task in my case: add http://google.com/ path before each record and import multiple fields.

CSV single field value (all images just have filenames, separate by |):
"123.jpg|345.jpg|567.jpg"

Tamper 1st plugin: find and replace by REGEXP: pattern: /([a-zA-Z0-9]*)./ replacement: http://google.com/$1

Tamper 2nd plugin: explode setting: explode by |

In this case you don't need any additinal fields mappings and can use 1 field in CSV

Select from where field not equal to Mysql Php

The key is the sql query, which you will set up as a string:

$sqlquery = "SELECT field1, field2 FROM table WHERE NOT columnA = 'x' AND NOT columbB = 'y'";

Note that there are a lot of ways to specify NOT. Another one that works just as well is:

$sqlquery = "SELECT field1, field2 FROM table WHERE columnA != 'x' AND columbB != 'y'";

Here is a full example of how to use it:

$link = mysql_connect($dbHost,$dbUser,$dbPass) or die("Unable to connect to database");
mysql_select_db("$dbName") or die("Unable to select database $dbName");
$sqlquery = "SELECT field1, field2 FROM table WHERE NOT columnA = 'x' AND NOT columbB = 'y'";
$result=mysql_query($sqlquery);

while ($row = mysql_fetch_assoc($result) {
//do stuff
}

You can do whatever you would like within the above while loop. Access each field of the table as an element of the $row array which means that $row['field1'] will give you the value for field1 on the current row, and $row['field2'] will give you the value for field2.

Note that if the column(s) could have NULL values, those will not be found using either of the above syntaxes. You will need to add clauses to include NULL values:

$sqlquery = "SELECT field1, field2 FROM table WHERE (NOT columnA = 'x' OR columnA IS NULL) AND (NOT columbB = 'y' OR columnB IS NULL)";

How do I make a self extract and running installer

It's simple with open source 7zip SFX-Packager - easy way to just "Drag & drop" folders onto it, and it creates a portable/self-extracting package.

How to extend available properties of User.Identity

I was looking for the same solution and Pawel gave me 99% of the answer. The only thing that was missing that I needed for the Extension to display was adding the following Razor Code into the cshtml(view) page:

@using programname.Models.Extensions

I was looking for the FirstName, to display in the top right of my NavBar after the user logged in.

I thought I would post this incase it helps someone else, So here is my code:

I created a new folder called Extensions(Under my Models Folder) and created the new class as Pawel specified above: IdentityExtensions.cs

using System.Security.Claims;
using System.Security.Principal;

namespace ProgramName.Models.Extensions
{
    public static class IdentityExtensions
    {
        public static string GetUserFirstname(this IIdentity identity)
        {
            var claim = ((ClaimsIdentity)identity).FindFirst("FirstName");
            // Test for null to avoid issues during local testing
            return (claim != null) ? claim.Value : string.Empty;
        }
    }
}

IdentityModels.cs :

public class ApplicationUser : IdentityUser
{

    //Extended Properties
    public string FirstName { get; internal set; }
    public string Surname { get; internal set; }
    public bool isAuthorized { get; set; }
    public bool isActive { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        userIdentity.AddClaim(new Claim("FirstName", this.FirstName));

        return userIdentity;
    }
}

Then in my _LoginPartial.cshtml(Under Views/Shared Folders) I added @using.ProgramName.Models.Extensions

I then added the change to the folling line of code that was going to use the Users First name after Logging in :

@Html.ActionLink("Hello " + User.Identity.GetUserFirstname() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })

Perhaps this helps someone else down the line.

Excel VBA - select a dynamic cell range

I like to used this method the most, it will auto select the first column to the last column being used. However, if the last cell in the first row or the last cell in the first column are empty, this code will not calculate properly. Check the link for other methods to dynamically select cell range.

Sub DynamicRange()
'Best used when first column has value on last row and first row has a value in the last column

Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range

Set sht = Worksheets("Sheet1")
Set StartCell = Range("A1")

'Find Last Row and Column
  LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
  LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column

'Select Range
  sht.Range(StartCell, sht.Cells(LastRow, LastColumn)).Select

End Sub

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

Official Kotlin Way:

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

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

Format string to a 3 digit number

It's called Padding:

myString.PadLeft(3, '0')

Package opencv was not found in the pkg-config search path

Hi first of all i would like you to use 'Synaptic Package Manager'. You just need to goto the ubuntu software center and search for synaptic package manager.. The beauty of this is that all the packages you need are easily available here. Second it will automatically configures all your paths. Now install this then search for opencv packages over there if you found the package with the green box then its installed but else the package is not in the right place so you need to reinstall it but from package manager this time. If installed then you can do this only, you just need to fill the OpenCV_DIR variable with the path of opencv (containing the OpenCVConfig.cmake file)

    export OpenCV_DIR=<path_of_opencv>

Uploading images using Node.js, Express, and Mongoose

You can also use the following to set a path where it saves the file.

req.form.uploadDir = "<path>";

The difference between the Runnable and Callable interfaces in Java

I found this in another blog that can explain it a little bit more these differences:

Though both the interfaces are implemented by the classes who wish to execute in a different thread of execution, but there are few differences between the two interface which are:

  • A Callable<V> instance returns a result of type V, whereas a Runnable instance doesn't.
  • A Callable<V> instance may throw checked exceptions, whereas a Runnable instance can't

The designers of Java felt a need of extending the capabilities of the Runnable interface, but they didn't want to affect the uses of the Runnable interface and probably that was the reason why they went for having a separate interface named Callable in Java 1.5 than changing the already existing Runnable.

How can I kill all sessions connecting to my oracle database?

To answer the question asked, here is the most accurate SQL to accomplish the job, you can combine it with PL/SQL loop to actually run kill statements:

select ses.USERNAME,
    substr(MACHINE,1,10) as MACHINE, 
    substr(module,1,25) as module,
    status, 
    'alter system kill session '''||SID||','||ses.SERIAL#||''';' as kill
from v$session ses LEFT OUTER JOIN v$process p ON (ses.paddr=p.addr)
where schemaname <> 'SYS'
    and not exists
    (select 1 
        from DBA_ROLE_PRIVS 
        where GRANTED_ROLE='DBA' 
            and schemaname=grantee)
    and machine!='yourlocalhostname' 
order by LAST_CALL_ET desc;

Is it possible to format an HTML tooltip (title attribute)?

No. But there are other options out there like Overlib, and jQuery that allow you this freedom.

Personally, I would suggest jQuery as the route to take. It's typically very unobtrusive, and requires no additional setup in the markup of your site (with the exception of adding the jquery script tag in your <head>).

Build .NET Core console application to output an EXE

If a .bat file is acceptable, you can create a bat file with the same name as the DLL file (and place it in the same folder), then paste in the following content:

dotnet %~n0.dll %*

Obviously, this assumes that the machine has .NET Core installed and globally available.

c:\> "path\to\batch\file" -args blah

(This answer is derived from Chet's comment.)

Add primary key to existing table

drop constraint and recreate it

alter table Persion drop CONSTRAINT <constraint_name>

alter table Persion add primary key (persionId,Pname,PMID)

edit:

you can find the constraint name by using the query below:

select OBJECT_NAME(OBJECT_ID) AS NameofConstraint
FROM sys.objects
where OBJECT_NAME(parent_object_id)='Persion'
and type_desc LIKE '%CONSTRAINT'

How to fix/convert space indentation in Sublime Text?

I found, in my mind, a simpler solution than Magne:

On mac:

"cmd+f" => "  "(two spaces) => "alt+enter" => "arrow right" => "  "(two more spaces) => set tab width to 4(this can be done before or after.

On windows or other platforms change cmd+f and alt+enter with whatever your find and select all hotkeys are.

Note: this method is prone to "errors" if you have more than one space within your code. It is thus less safe than Magne's method, but it is faster (for me at least).

How to convert QString to int?

Use .toInt() for int .toFloat() for float and .toDouble() for double

toInt();

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 disable action bar permanently

Another interesting solution where you want to retain the ViewPager while removing the action bar is to have a style as show

<style name="AppTheme" parent="AppBaseTheme">
    <item name="android:windowActionBarOverlay">true</item>
    <item name="android:actionBarStyle">@style/NoActionBarStyle</item>
    <item name="android:windowContentOverlay">@null</item>
</style>
<style name="NoActionBarStyle" parent="android:Widget.Holo.ActionBar">
    <item name="android:backgroundSplit">@null</item>
    <item name="android:displayOptions"></item>
</style>

This is the way most of the Dialer applications in android is showing the ViewPager without the action bar.

Ref: https://github.com/CyanogenMod/android_packages_apps_Dialer

Detect if HTML5 Video element is playing

a bit example when playing video

  let v = document.getElementById('video-plan');
  v.onplay = function() {
      console.log('Start video')
  };

List and kill at jobs on UNIX

You should be able to find your command with a ps variant like:

ps -ef
ps -fubob # if your job's user ID is bob.

Then, once located, it should be a simple matter to use kill to kill the process (permissions permitting).

If you're talking about getting rid of jobs in the at queue (that aren't running yet), you can use atq to list them and atrm to get rid of them.

How to plot all the columns of a data frame in R

This link helped me a lot for the same problem:

p = ggplot() + 
  geom_line(data = df_plot, aes(x = idx, y = col1), color = "blue") +
  geom_line(data = df_plot, aes(x = idx, y = col2), color = "red") 

print(p)

https://rpubs.com/euclid/343644

How to change facet labels?

Adding another solution similar to @domi's with parsing mathematical symbols, superscript, subscript, parenthesis/bracket, .etc.

library(tidyverse)
theme_set(theme_bw(base_size = 18))

### create separate name vectors
# run `demo(plotmath)` for more examples of mathematical annotation in R
am_names <- c(
  `0` = "delta^{15}*N-NO[3]^-{}",
  `1` = "sqrt(x,y)"
)

# use `scriptstyle` to reduce the size of the parentheses &
# `bgroup` to make adding `)` possible 
cyl_names <- c(
  `4` = 'scriptstyle(bgroup("", a, ")"))~T~-~5*"%"',
  `6` = 'scriptstyle(bgroup("", b, ")"))~T~+~10~degree*C',
  `8` = 'scriptstyle(bgroup("", c, ")"))~T~+~30*"%"'
)

ggplot(mtcars, aes(wt, mpg)) + 
  geom_jitter() +
  facet_grid(am ~ cyl,
             labeller = labeller(am  = as_labeller(am_names,  label_parsed),
                                 cyl = as_labeller(cyl_names, label_parsed))
             ) +
  geom_text(x = 4, y = 25, size = 4, nudge_y = 1,
            parse = TRUE, check_overlap = TRUE,
            label = as.character(expression(paste("Log"["10"], bgroup("(", frac("x", "y"), ")")))))

### OR create new variables then assign labels directly
# reverse facet orders just for fun
mtcars <- mtcars %>% 
  mutate(am2  = factor(am,  labels = am_names),
         cyl2 = factor(cyl, labels = rev(cyl_names), levels = rev(attr(cyl_names, "names")))
  )

ggplot(mtcars, aes(wt, mpg)) + 
  geom_jitter() +
  facet_grid(am2 ~ cyl2,
             labeller = label_parsed) +
  annotate("text", x = 4, y = 30, size = 5,
           parse = TRUE, 
           label = as.character(expression(paste("speed [", m * s^{-1}, "]"))))

Created on 2019-03-30 by the reprex package (v0.2.1.9000)

Run parallel multiple commands at once in the same terminal

I am suggesting a much simpler utility I just wrote. It's currently called par, but will be renamed soon to either parl or pll, haven't decided yet.

https://github.com/k-bx/par

API is as simple as:

par "script1.sh" "script2.sh" "script3.sh"

Prefixing commands can be done via:

par "PARPREFIX=[script1] script1.sh" "script2.sh" "script3.sh"

Force “landscape” orientation mode

I had the same problem, it was a missing manifest.json file, if not found the browser decide with orientation is best fit, if you don't specify the file or use a wrong path.

I fixed just calling the manifest.json correctly on html headers.

My html headers:

<meta name="application-name" content="App Name">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link rel="manifest" href="manifest.json">
<meta name="msapplication-starturl" content="/">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#">
<meta name="msapplication-TileColor" content="#">
<meta name="msapplication-config" content="browserconfig.xml">
<link rel="icon" type="image/png" sizes="192x192" href="android-chrome-192x192.png">
<link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon.png">
<link rel="mask-icon" href="safari-pinned-tab.svg" color="#ffffff">
<link rel="shortcut icon" href="favicon.ico">

And the manifest.json file content:

{
  "display": "standalone",
  "orientation": "portrait",
  "start_url": "/",
  "theme_color": "#000000",
  "background_color": "#ffffff",
  "icons": [
  {
    "src": "android-chrome-192x192.png",
    "sizes": "192x192",
    "type": "image/png"
  }
}

To generate your favicons and icons use this webtool: https://realfavicongenerator.net/

To generate your manifest file use: https://tomitm.github.io/appmanifest/

My PWA Works great, hope it helps!

No numeric types to aggregate - change in groupby() behaviour?

I got this error generating a data frame consisting of timestamps and data:

df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp))

Adding the suggested solution works for me:

df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp), dtype=float))

Thanks Chang She!

Example:

                     data
2005-01-01 00:10:00  7.53
2005-01-01 00:20:00  7.54
2005-01-01 00:30:00  7.62
2005-01-01 00:40:00  7.68
2005-01-01 00:50:00  7.81
2005-01-01 01:00:00  7.95
2005-01-01 01:10:00  7.96
2005-01-01 01:20:00  7.95
2005-01-01 01:30:00  7.98
2005-01-01 01:40:00  8.06
2005-01-01 01:50:00  8.04
2005-01-01 02:00:00  8.06
2005-01-01 02:10:00  8.12
2005-01-01 02:20:00  8.12
2005-01-01 02:30:00  8.25
2005-01-01 02:40:00  8.27
2005-01-01 02:50:00  8.17
2005-01-01 03:00:00  8.21
2005-01-01 03:10:00  8.29
2005-01-01 03:20:00  8.31
2005-01-01 03:30:00  8.25
2005-01-01 03:40:00  8.19
2005-01-01 03:50:00  8.17
2005-01-01 04:00:00  8.18
                     data
2005-01-01 00:00:00  7.636000
2005-01-01 01:00:00  7.990000
2005-01-01 02:00:00  8.165000
2005-01-01 03:00:00  8.236667
2005-01-01 04:00:00  8.180000

Paste Excel range in Outlook

Often this question is asked in the context of Ron de Bruin's RangeToHTML function, which creates an HTML PublishObject from an Excel.Range, extracts that via FSO, and inserts the resulting stream HTML in to the email's HTMLBody. In doing so, this removes the default signature (the RangeToHTML function has a helper function GetBoiler which attempts to insert the default signature).

Unfortunately, the poorly-documented Application.CommandBars method is not available via Outlook:

wdDoc.Application.CommandBars.ExecuteMso "PasteExcelTableSourceFormatting"

It will raise a runtime 6158:

enter image description here

But we can still leverage the Word.Document which is accessible via the MailItem.GetInspector method, we can do something like this to copy & paste the selection from Excel to the Outlook email body, preserving your default signature (if there is one).

Dim rng as Range
Set rng = Range("A1:F10") 'Modify as needed

With OutMail
    .To = "[email protected]"
    .BCC = ""
    .Subject = "Subject"
    .Display
    Dim wdDoc As Object     '## Word.Document
    Dim wdRange As Object   '## Word.Range
    Set wdDoc = OutMail.GetInspector.WordEditor
    Set wdRange = wdDoc.Range(0, 0)
    wdRange.InsertAfter vbCrLf & vbCrLf
    'Copy the range in-place
    rng.Copy
    wdRange.Paste
End With

Note that in some cases this may not perfectly preserve the column widths or in some instances the row heights, and while it will also copy shapes and other objects in the Excel range, this may also cause some funky alignment issues, but for simple tables and Excel ranges, it is very good:

enter image description here

C++ Returning reference to local variable

A good thing to remember are these simple rules, and they apply to both parameters and return types...

  • Value - makes a copy of the item in question.
  • Pointer - refers to the address of the item in question.
  • Reference - is literally the item in question.

There is a time and place for each, so make sure you get to know them. Local variables, as you've shown here, are just that, limited to the time they are locally alive in the function scope. In your example having a return type of int* and returning &i would have been equally incorrect. You would be better off in that case doing this...

void func1(int& oValue)
{
    oValue = 1;
}

Doing so would directly change the value of your passed in parameter. Whereas this code...

void func1(int oValue)
{
    oValue = 1;
}

would not. It would just change the value of oValue local to the function call. The reason for this is because you'd actually be changing just a "local" copy of oValue, and not oValue itself.

How to change xampp localhost to another folder ( outside xampp folder)?

It can be done in two steps for Ubuntu 14.04 with Xampp 1.8.3-5

Step 1:- Change DocumentRoot and Directory path in /opt/lampp/etc/httpd.conf from

DocumentRoot "/opt/lampp/htdocs" and Directory "/opt/lampp/htdocs"

to DocumentRoot "/home/user/Desktop/js" and Directory "/home/user/Desktop/js"

Step 2:- Change the rights of folder (in path and its parent folders to 777) eg via

sudo chmod -R 777 /home/user/Desktop/js

One line if/else condition in linux shell scripting

You can use like bellow:

(( var0 = var1<98?9:21 ))

the same as

if [ "$var1" -lt 98 ]; then
   var0=9
else
   var0=21
fi

extends

condition?result-if-true:result-if-false

I found the interested thing on the book "Advanced Bash-Scripting Guide"

vertical divider between two columns in bootstrap

_x000D_
_x000D_
.row.vertical-divider {_x000D_
  overflow: hidden;_x000D_
}_x000D_
.row.vertical-divider > div[class^="col-"] {_x000D_
  text-align: center;_x000D_
  padding-bottom: 100px;_x000D_
  margin-bottom: -100px;_x000D_
  border-left: 3px solid #F2F7F9;_x000D_
  border-right: 3px solid #F2F7F9;_x000D_
}_x000D_
.row.vertical-divider div[class^="col-"]:first-child {_x000D_
  border-left: none;_x000D_
}_x000D_
.row.vertical-divider div[class^="col-"]:last-child {_x000D_
  border-right: none;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="row vertical-divider" style="margin-top: 30px">_x000D_
  <div class="col-xs-6">Hi there</div>_x000D_
  <div class="col-xs-6">Hi world<br/>hi world</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to clear text area with a button in html using javascript?

<input type="button" value="Clear" onclick="javascript: functionName();" >

you just need to set the onclick event, call your desired function on this onclick event.

function functionName()
{
    $("#output").val("");
}

Above function will set the value of text area to empty string.

How to encode the filename parameter of Content-Disposition header in HTTP?

There is discussion of this, including links to browser testing and backwards compatibility, in the proposed RFC 5987, "Character Set and Language Encoding for Hypertext Transfer Protocol (HTTP) Header Field Parameters."

RFC 2183 indicates that such headers should be encoded according to RFC 2184, which was obsoleted by RFC 2231, covered by the draft RFC above.

How to initialize a static array?

Nope, no difference. It's just syntactic sugar. Arrays.asList(..) creates an additional list.

How do I hide a menu item in the actionbar?

Get a MenuItem pointing to such item, call setVisible on it to adjust its visibility and then call invalidateOptionsMenu() on your activity so the ActionBar menu is adjusted accordingly.

Update: A MenuItem is not a regular view that's part of your layout. Its something special, completely different. Your code returns null for item and that's causing the crash. What you need instead is to do:

MenuItem item = menu.findItem(R.id.addAction);

Here is the sequence in which you should call: first call invalidateOptionsMenu() and then inside onCreateOptionsMenu(Menu) obtain a reference to the MenuItem (by calling menu.findItem()) and call setVisible() on it

Left padding a String with Zeros

This will pad left any string to a total width of 10 without worrying about parse errors:

String unpadded = "12345"; 
String padded = "##########".substring(unpadded.length()) + unpadded;

//unpadded is "12345"
//padded   is "#####12345"

If you want to pad right:

String unpadded = "12345"; 
String padded = unpadded + "##########".substring(unpadded.length());

//unpadded is "12345"
//padded   is "12345#####"  

You can replace the "#" characters with whatever character you would like to pad with, repeated the amount of times that you want the total width of the string to be. E.g. if you want to add zeros to the left so that the whole string is 15 characters long:

String unpadded = "12345"; 
String padded = "000000000000000".substring(unpadded.length()) + unpadded;

//unpadded is "12345"
//padded   is "000000000012345"  

The benefit of this over khachik's answer is that this does not use Integer.parseInt, which can throw an Exception (for example, if the number you want to pad is too large like 12147483647). The disadvantage is that if what you're padding is already an int, then you'll have to convert it to a String and back, which is undesirable.

So, if you know for sure that it's an int, khachik's answer works great. If not, then this is a possible strategy.

How to fix height of TR?

Your table width is 90% which is relative to it's container.

If you squeeze the page, you are probably squeezing the table width as well. The width of the cells reduce too and the browser compensate by increasing the height.

To have the height untouched, you have to make sure the widths of the cells can hold the intented content. Fixing the table width is probably something you want to try. Or perhaps play around with the min-width of the table.

The service cannot be started, either because it is disabled or because it has no enabled devices associated with it

Try to open Services Window, by writing services.msc into Start->Run and hit Enter.

When window appears, then find SQL Browser service, right click and choose Properties, and then in dropdown list choose Automatic, or Manual, whatever you want, and click OK. Eventually, if not started immediately, you can again press right click on this service and click Start.

Android studio: emulator is running but not showing up in Run App "choose a running device"

  1. start device from genymotion button (have to install genymotion before and setup genymotion folder location on settings)
  2. run application
  3. choose genymotion running device

How to run SUDO command in WinSCP to transfer files from Windows to linux

There is an option in WinSCP that does exactly what you are looking for:

enter image description here

enter image description here

Node.js: How to send headers with form data using request module?

I've finally managed to do it. Answer in code snippet below:

var querystring = require('querystring');
var request = require('request');

var form = {
    username: 'usr',
    password: 'pwd',
    opaque: 'opaque',
    logintype: '1'
};

var formData = querystring.stringify(form);
var contentLength = formData.length;

request({
    headers: {
      'Content-Length': contentLength,
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    uri: 'http://myUrl',
    body: formData,
    method: 'POST'
  }, function (err, res, body) {
    //it works!
  });

Java replace all square brackets in a string

_x000D_
_x000D_
   Use this line:) String result = strCurBal.replaceAll("[(" what ever u need to remove ")]", "");_x000D_
_x000D_
    String strCurBal = "(+)3428";_x000D_
    Log.e("Agilanbu before omit ", strCurBal);_x000D_
    String result = strCurBal.replaceAll("[()]", ""); // () removing special characters from string_x000D_
    Log.e("Agilanbu after omit ", result);_x000D_
   _x000D_
    o/p :_x000D_
    Agilanbu before omit : (+)3428_x000D_
    Agilanbu after omit :  +3428_x000D_
_x000D_
    String finalVal = result.replaceAll("[+]", ""); // + removing special characters from string_x000D_
    Log.e("Agilanbu finalVal  ", finalVal);_x000D_
    o/p_x000D_
    Agilanbu finalVal : 3428_x000D_
            _x000D_
    String finalVal1 = result.replaceAll("[+]", "-"); // insert | append | replace the special characters from string_x000D_
    Log.e("Agilanbu finalVal  ", finalVal1);_x000D_
    o/p_x000D_
    Agilanbu finalVal : -3428  // replacing the + symbol to -
_x000D_
_x000D_
_x000D_

Distinct by property of class with LINQ

You can use grouping, and get the first car from each group:

List<Car> distinct =
  cars
  .GroupBy(car => car.CarCode)
  .Select(g => g.First())
  .ToList();

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply?

Given a column of numbers:

lst = []
cols = ['A']
for a in range(100, 105):
    lst.append([a])
df = pd.DataFrame(lst, columns=cols, index=range(5))
df

    A
0   100
1   101
2   102
3   103
4   104

You can reference the previous row with shift:

df['Change'] = df.A - df.A.shift(1)
df

    A   Change
0   100 NaN
1   101 1.0
2   102 1.0
3   103 1.0
4   104 1.0

SQL Client for Mac OS X that works with MS SQL Server

It may not be the best solution if you don't already have it, but FileMaker 11 with the Actual SQL Server ODBC driver (http://www.actualtech.com/product_sqlserver.php) worked nicely for a client of mine today. The ODBC driver is only $29, but FileMaker is $299, which is why you might only consider it if you already have it.

nvm is not compatible with the npm config "prefix" option:

I just have a idea. Use the symbolic link to solve the error and you can still use your prefix for globally installed packages. ln -s [your prefix path] [path in the '~/.nvm'] then you will have a symbolic folder in the ~/.nvm folder, but in fact, your global packages are still installed in [your prefix path]. Then the error will not show again and you can use nvm use ** normally. ps: it's worked for me on mac. pps: do not forget to set $PATH to your npm bin folder to use the globally installed packages.

Codeigniter how to create PDF

Please click on this link it should work ..

http://www.php-guru.in/2013/html-to-pdf-conversion-in-codeigniter/

Or you can see below

There are number of PHP libraries on the web to convert HTML page to PDF file. They are easy to implement and deploy when you are working on any web application in core PHP. But when we try to integrate this libraries with any framework or template, then it becomes very tedious work if the framework which we are using does not have its own library to integrate it with any PDF library. The same situation came in front of me when there was one requirement to convert HTML page to PDF file and the framework I was using was codeigniter.

I searched on web and got number of PHP libraries to convert HTML page to PDF file. After lot of research and googling I decided to go with TCPDF PHP library to convert HTML page to PDF file for my requirement. I found TCPDf PHP library quite easy to integrate with codeigniter and stated working on it. After successfully completing my integration of codeigniter and TCPDF, I thought of sharing this script on web.

Now, let’s start with implimentation of the code.

Download the TCPDF library code, you can download it from TCPDF website http://www.tcpdf.org/.

Now create “tcpdf” folder in “application/helpers/” directory of your web application which is developed in codeigniter. Copy all TCPDF library files and paste it in “application/helpers/tcpdf/” directory. Update the configuration file “tcpdf_config.php” of TCPDF, which is located in “application/helpers/tcpdf/config” directory, do changes according to your applicatoin requirements. We can set logo, font, font size, with, height, header etc in the cofing file. Give read, write permissions to “cache” folder which is there in tcpdf folder. After defining your directory structure, updating configuration file and assigning permissions, here starts your actual coding part.

Create one PHP helper file in “application/helpers/” directory of codeigniter, say “pdf_helper.php”, then copy below given code and paste it in helper file

Helper: application/helpers/pdf_helper.php

function tcpdf()
{
    require_once('tcpdf/config/lang/eng.php');
    require_once('tcpdf/tcpdf.php');
}

Then in controller file call the above helper, suppose our controller file is “createpdf.php” and it has method as pdf(), so the method pdf() will load the “pdf_helper” helper and will also have any other code.

Controller: application/controllers/createpdf.php

function pdf()
{
    $this->load->helper('pdf_helper');
    /*
        ---- ---- ---- ----
        your code here
        ---- ---- ---- ----
    */
    $this->load->view('pdfreport', $data);
}

Now create one view file, say “pdfreport.php” in “application/views/” directory, which is also loaded in pdf() method in controller. So in view file we can directly call the tcpdf() function which we have defined in “pdf_helper” helper, which will load all required TCPDF classes, functions, variable etc. Then we can directly use the TCPDF example codes as it is in our current controller or view. Now in out current view “pdfreport” copy the given code below:

View: application/views/pdfreport.php

tcpdf();
$obj_pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$obj_pdf->SetCreator(PDF_CREATOR);
$title = "PDF Report";
$obj_pdf->SetTitle($title);
$obj_pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, $title, PDF_HEADER_STRING);
$obj_pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$obj_pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
$obj_pdf->SetDefaultMonospacedFont('helvetica');
$obj_pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$obj_pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
$obj_pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$obj_pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$obj_pdf->SetFont('helvetica', '', 9);
$obj_pdf->setFontSubsetting(false);
$obj_pdf->AddPage();
ob_start();
    // we can have any view part here like HTML, PHP etc
    $content = ob_get_contents();
ob_end_clean();
$obj_pdf->writeHTML($content, true, false, true, false, '');
$obj_pdf->Output('output.pdf', 'I');

Thus our HTML page will be converted to PDF using TCPDF in CodeIgniter. We can also embed images,css,modifications in PDF file by using TCPDF library.

source command not found in sh shell

$ls -l `which sh`
/bin/sh -> dash

$sudo dpkg-reconfigure dash #Select "no" when you're asked
[...]

$ls -l `which sh`
/bin/sh -> bash

Then it will be OK

How can I check whether a option already exist in select by JQuery

I had a similar issue. Rather than run the search through the dom every time though the loop for the select control I saved the jquery select element in a variable and did this:

function isValueInSelect($select, data_value){
    return $($select).children('option').map(function(index, opt){
        return opt.value;
    }).get().includes(data_value);
}

Where does Internet Explorer store saved passwords?

Short answer: in the Vault. Since Windows 7, a Vault was created for storing any sensitive data among it the credentials of Internet Explorer. The Vault is in fact a LocalSystem service - vaultsvc.dll.

Long answer: Internet Explorer allows two methods of credentials storage: web sites credentials (for example: your Facebook user and password) and autocomplete data. Since version 10, instead of using the Registry a new term was introduced: Windows Vault. Windows Vault is the default storage vault for the credential manager information.

You need to check which OS is running. If its Windows 8 or greater, you call VaultGetItemW8. If its isn't, you call VaultGetItemW7.

To use the "Vault", you load a DLL named "vaultcli.dll" and access its functions as needed.

A typical C++ code will be:

hVaultLib = LoadLibrary(L"vaultcli.dll");

if (hVaultLib != NULL) 
{
    pVaultEnumerateItems = (VaultEnumerateItems)GetProcAddress(hVaultLib, "VaultEnumerateItems");
    pVaultEnumerateVaults = (VaultEnumerateVaults)GetProcAddress(hVaultLib, "VaultEnumerateVaults");
    pVaultFree = (VaultFree)GetProcAddress(hVaultLib, "VaultFree");
    pVaultGetItemW7 = (VaultGetItemW7)GetProcAddress(hVaultLib, "VaultGetItem");
    pVaultGetItemW8 = (VaultGetItemW8)GetProcAddress(hVaultLib, "VaultGetItem");
    pVaultOpenVault = (VaultOpenVault)GetProcAddress(hVaultLib, "VaultOpenVault");
    pVaultCloseVault = (VaultCloseVault)GetProcAddress(hVaultLib, "VaultCloseVault");

    bStatus = (pVaultEnumerateVaults != NULL)
        && (pVaultFree != NULL)
        && (pVaultGetItemW7 != NULL)
        && (pVaultGetItemW8 != NULL)
        && (pVaultOpenVault != NULL)
        && (pVaultCloseVault != NULL)
        && (pVaultEnumerateItems != NULL);
}

Then you enumerate all stored credentials by calling

VaultEnumerateVaults

Then you go over the results.

Export table from database to csv file

Some ideas:

From SQL Server Management Studio

 1. Run a SELECT statement to filter your data
 2. Click on the top-left corner to select all rows
 3. Right-click to copy all the selected
 4. Paste the copied content on Microsoft Excel
 5. Save as CSV

Using SQLCMD (Command Prompt)

Example:

From the command prompt, you can run the query and export it to a file:

sqlcmd -S . -d DatabaseName -E -s, -W -Q "SELECT * FROM TableName" > C:\Test.csv

Do not quote separator use just -s, and not quotes -s',' unless you want to set quote as separator.

More information here: ExcelSQLServer

Notes:

  • This approach will have the "Rows affected" information in the bottom of the file, but you can get rid of this by using the "SET NOCOUNT ON" in the query itself.

  • You may run a stored procedure instead of the actual query (e.g. "EXEC Database.dbo.StoredProcedure")

  • You can use any programming language or even a batch file to automate this

Using BCP (Command Prompt)

Example:

bcp "SELECT * FROM Database.dbo.Table" queryout C:\Test.csv -c -t',' -T -S .\SQLEXPRESS

It is important to quote the comma separator as -t',' vs just -t,

More information here: bcp Utility

Notes:

  • As per when using SQLCMD, you can run stored procedures instead of the actual queries
  • You can use any programming language or a batch file to automate this

Hope this helps.

How can I convert this one line of ActionScript to C#?

There is collection of Func<...> classes - Func that is probably what you are looking for:

 void MyMethod(Func<int> param1 = null) 

This defines method that have parameter param1 with default value null (similar to AS), and a function that returns int. Unlike AS in C# you need to specify type of the function's arguments.

So if you AS usage was

MyMethod(function(intArg, stringArg) { return true; }) 

Than in C# it would require param1 to be of type Func<int, siring, bool> and usage like

MyMethod( (intArg, stringArg) => { return true;} ); 

Aggregate multiple columns at once

You could try:

agg <- aggregate(list(x$val1, x$val2, x$val3, x$val4), by = list(x$id1, x$id2), mean)

Best way to work with dates in Android SQLite

The best way is to store the dates as a number, received by using the Calendar command.

//Building the table includes:
StringBuilder query=new StringBuilder();
query.append("CREATE TABLE "+TABLE_NAME+ " (");
query.append(COLUMN_ID+"int primary key autoincrement,");
query.append(COLUMN_DATETIME+" int)");

//And inserting the data includes this:
values.put(COLUMN_DATETIME, System.currentTimeMillis()); 

Why do this? First of all, getting values from a date range is easy. Just convert your date into milliseconds, and then query appropriately. Sorting by date is similarly easy. The calls to convert among various formats are also likewise easy, as I included. Bottom line is, with this method, you can do anything you need to do, no problems. It will be slightly difficult to read a raw value, but it more than makes up that slight disadvantage with being easily machine readable and usable. And in fact, it is relatively easy to build a reader (And I know there are some out there) that will automatically convert the time tag to date as such for easy of reading.

It's worth mentioning that the values that come out of this should be long, not int. Integer in sqlite can mean many things, anything from 1-8 bytes, but for almost all dates 64 bits, or a long, is what works.

EDIT: As has been pointed out in the comments, you have to use the cursor.getLong() to properly get the timestamp if you do this.

How to get diff between all files inside 2 folders that are on the web?

Once you have the source trees, e.g.

diff -ENwbur repos1/ repos2/ 

Even better

diff -ENwbur repos1/ repos2/  | kompare -o -

and have a crack at it in a good gui tool :)

  • -Ewb ignore the bulk of whitespace changes
  • -N detect new files
  • -u unified
  • -r recurse

Get first and last date of current month with JavaScript or jQuery

Very simple, no library required:

var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);

or you might prefer:

var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);

EDIT

Some browsers will treat two digit years as being in the 20th century, so that:

new Date(14, 0, 1);

gives 1 January, 1914. To avoid that, create a Date then set its values using setFullYear:

var date = new Date();
date.setFullYear(14, 0, 1); // 1 January, 14

I cannot start SQL Server browser

I'm trying to setup rf online game to be played offline using MS SQL server 2019 and ended up with the same problem. The SQL Browser service won't start. Almost all answers in this post have been tried but the outcome is disappointing. I've got a weird idea to try start the SQL browser service manually and then change it to automatic after it runs. Luckily it works. So, just simply right click on SQL Server Browser ==> Properties ==>Service==>Start Mode==>Manual. After apply the changes right click on the SQL Server Browser again and start the service. After the service run change the start mode to automatic. Make sure the information provided on log on as: are correct.

How do I send a JSON string in a POST request in Go

you can just use post to post your json.

values := map[string]string{"username": username, "password": password}

jsonValue, _ := json.Marshal(values)

resp, err := http.Post(authAuthenticatorUrl, "application/json", bytes.NewBuffer(jsonValue))

How to use andWhere and orWhere in Doctrine?

$q->where("a = 1")
  ->andWhere("b = 1 OR b = 2")
  ->andWhere("c = 2 OR c = 2")
  ;

operator << must take exactly one argument

The problem is that you define it inside the class, which

a) means the second argument is implicit (this) and

b) it will not do what you want it do, namely extend std::ostream.

You have to define it as a free function:

class A { /* ... */ };
std::ostream& operator<<(std::ostream&, const A& a);

How to create an empty matrix in R?

To get rid of the first column of NAs, you can do it with negative indexing (which removes indices from the R data set). For example:

output = matrix(1:6, 2, 3) # gives you a 2 x 3 matrix filled with the numbers 1 to 6

# output = 
#           [,1] [,2] [,3]
#     [1,]    1    3    5
#     [2,]    2    4    6

output = output[,-1] # this removes column 1 for all rows

# output = 
#           [,1] [,2]
#     [1,]    3    5
#     [2,]    4    6

So you can just add output = output[,-1]after the for loop in your original code.

How to solve error message: "Failed to map the path '/'."

~I've gone to the Internet Information Services Manager

~Click the sites

~Right click on your website

~Click Manage Website > Advance Settings

~Change the application pool to DefaultAppPool

And it works fine to me.

JQuery - Set Attribute value

Some things before the actual code..

the hash (#) you use as the selector is for IDs and not for names of elements. also the disabled attribute is not a true false scenario .. if it has disabled attribute it means that it is true .. you need to remove the attribute and not set it to false. Also there are the form selectors that identify specific types of items in a form ..

so the code would be

$("input:checkbox[name='chk0']").removeAttr('disabled');

Bringing the answer up-to-date

You should use the .prop() method (added since v1.6)

$("input:checkbox[name='chk0']").prop('disabled', false); // to enable the checkbox

and

$("input:checkbox[name='chk0']").prop('disabled', true); // to disable the checkbox

How can I map "insert='false' update='false'" on a composite-id key-property which is also used in a one-to-many FK?

"Dino TW" has provided the link to the comment Hibernate Mapping Exception : Repeated column in mapping for entity which has the vital information.

The link hints to provide "inverse=true" in the set mapping, I tried it and it actually works. It is such a rare situation wherein a Set and Composite key come together. Make inverse=true, we leave the insert & update of the table with Composite key to be taken care by itself.

Below can be the required mapping,

<class name="com.example.CompanyEntity" table="COMPANY">
    <id name="id" column="COMPANY_ID"/>
    <set name="names" inverse="true" table="COMPANY_NAME" cascade="all-delete-orphan" fetch="join" batch-size="1" lazy="false">
        <key column="COMPANY_ID" not-null="true"/>
        <one-to-many entity-name="vendorName"/>
    </set>
</class>

Adding integers to an int array

Arrays are different than ArrayLists, on which you could call add. You'll need an index first. Declare i before the for loop. Then you can use an array access expression to assign the element to the array.

num[i] = s;
i++;

JQuery - Call the jquery button click event based on name property

$('element[name="element_name"]').click(function(){
    //do stuff
});

in your case:

$('input[name="btnName"]').click(function(){
    //do stuff
});

How to detect a route change in Angular?

I would write something like this:

ngOnInit() {
this.routed = this.router.events.map( event => event instanceof NavigationStart )
  .subscribe(() => {
  } );
}

ngOnDestroy() {
this.routed.unsubscribe();
}

How to print table using Javascript?

Here is your code in a jsfiddle example. I have tested it and it looks fine.

http://jsfiddle.net/dimshik/9DbEP/4/

I used a simple table, maybe you are missing some CSS on your new page that was created with JavaScript.

<table border="1" cellpadding="3" id="printTable">
    <tbody><tr>
        <th>First Name</th>
        <th>Last Name</th>      
        <th>Points</th>
    </tr>
    <tr>
        <td>Jill</td>
        <td>Smith</td>      
        <td>50</td>
    </tr>
    <tr>
        <td>Eve</td>
        <td>Jackson</td>        
        <td>94</td>
    </tr>
    <tr>
        <td>John</td>
        <td>Doe</td>        
        <td>80</td>
    </tr>
    <tr>
        <td>Adam</td>
        <td>Johnson</td>        
        <td>67</td>
    </tr>
</tbody></table>

Retrieving the first digit of a number

int number = 534;
int firstDigit = number/100; 

( / ) operator in java divide the numbers without considering the reminder so when we divide 534 by 100 , it gives us (5) .

but if you want to get the last number , you can use (%) operator

    int lastDigit = number%10; 

which gives us the reminder of the division , so 534%10 , will yield the number 4 .

A valid provisioning profile for this executable was not found... (again)

+1 to banging my head against the wall for a day or two...

Also check this setting:

Build Settings -> Code Signing -> Provisioning Profile

After following the above steps, "Automatic" setting worked for me. ~kjm~

Escape Character in SQL Server

You can escape quotation like this:

select 'it''s escaped'

result will be

it's escaped

Can you get a Windows (AD) username in PHP?

No. But what you can do is have your Active Directory admin enable LDAP so that users can maintain one set of credentials

http://us2.php.net/ldap

Force an Android activity to always use landscape mode

Doing it in code is is IMO wrong and even more so if you put it into the onCreate. Do it in the manifest and the "system" knows the orientation from the startup of the app. And this type of meta or top level "guidance" SHOULD be in the manifest. If you want to prove it to yourself set a break in the Activity's onCreate. If you do it in code there it will be called twice : it starts up in Portrait mode then is switched to Landscape. This does not happen if you do it in the manifest.

How to initialize an array of objects in Java

Player[] players = Stream.iterate(0, x-> x+1 ).limit(PlayerCount).map(i -> new Player(i)).toArray(Player[]::new);

SQL Server ON DELETE Trigger

CREATE TRIGGER sampleTrigger
    ON database1.dbo.table1
    FOR DELETE
AS
    DELETE FROM database2.dbo.table2
    WHERE bar = 4 AND ID IN(SELECT deleted.id FROM deleted)
GO

using c# .net libraries to check for IMAP messages from gmail servers

Cross posted from the other similar question. See what happens when they get so similar?

I've been searching for an IMAP solution for a while now, and after trying quite a few, I'm going with AE.Net.Mail.

There is no documentation, which I consider a downside, but I was able to whip this up by looking at the source code (yay for open source!) and using Intellisense. The below code connects specifically to Gmail's IMAP server:

// Connect to the IMAP server. The 'true' parameter specifies to use SSL
// which is important (for Gmail at least)
ImapClient ic = new ImapClient("imap.gmail.com", "[email protected]", "pass",
                ImapClient.AuthMethods.Login, 993, true);
// Select a mailbox. Case-insensitive
ic.SelectMailbox("INBOX");
Console.WriteLine(ic.GetMessageCount());
// Get the first *11* messages. 0 is the first message;
// and it also includes the 10th message, which is really the eleventh ;)
// MailMessage represents, well, a message in your mailbox
MailMessage[] mm = ic.GetMessages(0, 10);
foreach (MailMessage m in mm)
{
    Console.WriteLine(m.Subject);
}
// Probably wiser to use a using statement
ic.Dispose();

I'm not affiliated with this library or anything, but I've found it very fast and stable.

Using IF ELSE statement based on Count to execute different Insert statements

Simply use the following:

IF((SELECT count(*) FROM table)=0)
BEGIN

....

END

Count number of rows per group and add result to original data frame

Using sqldf package:

library(sqldf)

sqldf("select a.*, b.cnt
       from df a,
           (select name, type, count(1) as cnt
            from df
            group by name, type) b
      where a.name = b.name and
            a.type = b.type")

#    name  type num cnt
# 1 black chair   4   2
# 2 black chair   5   2
# 3 black  sofa  12   1
# 4   red  sofa   4   1
# 5   red plate   3   1

Java Minimum and Maximum values in Array

Here you haven't print the max and min values. Print the max and min values in the getMaxVal and getMin val methods or after the call. This is the output.

Enter the numbers now.
5
Max: 5
Min: 0
3
Max: 5
Min: 0
7
Max: 7
Min: 0
3
Max: 7
Min: 0
90
Max: 90
Min: 0
43
Max: 90
Min: 0
100
Max: 100
Min: 0
45
Max: 100
Min: 0
23
Max: 100
Min: 0
22
Max: 100
Min: 3
These are the numbers you have entered.
5 3 7 3 90 43 100 45 23 22

Also when you are declaring an array, it has all 0s initially.

How can I convert a string to upper- or lower-case with XSLT?

.NET XSLT implementation allows to write custom managed functions in the stylesheet. For lower-case() it can be:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:utils="urn:myExtension" exclude-result-prefixes="msxsl">

  <xsl:output method="xml" indent="yes"/>

  <msxsl:script implements-prefix="utils" language="C#">
    <![CDATA[
      public string ToLower(string stringValue)
      {
        string result = String.Empty;

        if(!String.IsNullOrEmpty(stringValue))
        {
          result = stringValue.ToLower(); 
        }

        return result;
      }
    ]]>
  </msxsl:script>

  <!-- using of our custom function -->
  <lowercaseValue>
    <xsl:value-of select="utils:ToLower($myParam)"/>
  </lowercaseValue>

Assume, that can be slow, but still acceptable.

Do not forget to enable embedded scripts support for transform:

// Create the XsltSettings object with script enabled.
XsltSettings xsltSettings = new XsltSettings(false, true);

XslCompiledTransform xslt = new XslCompiledTransform();

// Load stylesheet
xslt.Load(xsltPath, xsltSettings, new XmlUrlResolver());

MySQL ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES)

You probably have an anonymous user ''@'localhost' or ''@'127.0.0.1'.

As per the manual:

When multiple matches are possible, the server must determine which of them to use. It resolves this issue as follows: (...)

  • When a client attempts to connect, the server looks through the rows [of table mysql.user] in sorted order.
  • The server uses the first row that matches the client host name and user name.

(...) The server uses sorting rules that order rows with the most-specific Host values first. Literal host names [such as 'localhost'] and IP addresses are the most specific.

Hence, such an anonymous user would "mask" any other user like '[any_username]'@'%' when connecting from localhost.

'bill'@'localhost' does match 'bill'@'%', but would match (e.g.) ''@'localhost' beforehands.

The recommended solution is to drop this anonymous user (this is usually a good thing to do anyways).


Below edits are mostly irrelevant to the main question. These are only meant to answer some questions raised in other comments within this thread.

Edit 1

Authenticating as 'bill'@'%' through a socket.


    root@myhost:/home/mysql-5.5.16-linux2.6-x86_64# ./mysql -ubill -ppass --socket=/tmp/mysql-5.5.sock
    Welcome to the MySQL monitor (...)

    mysql> SELECT user, host FROM mysql.user;
    +------+-----------+
    | user | host      |
    +------+-----------+
    | bill | %         |
    | root | 127.0.0.1 |
    | root | ::1       |
    | root | localhost |
    +------+-----------+
    4 rows in set (0.00 sec)

    mysql> SELECT USER(), CURRENT_USER();
    +----------------+----------------+
    | USER()         | CURRENT_USER() |
    +----------------+----------------+
    | bill@localhost | bill@%         |
    +----------------+----------------+
    1 row in set (0.02 sec)

    mysql> SHOW VARIABLES LIKE 'skip_networking';
    +-----------------+-------+
    | Variable_name   | Value |
    +-----------------+-------+
    | skip_networking | ON    |
    +-----------------+-------+
    1 row in set (0.00 sec)

Edit 2

Exact same setup, except I re-activated networking, and I now create an anonymous user ''@'localhost'.


    root@myhost:/home/mysql-5.5.16-linux2.6-x86_64# ./mysql
    Welcome to the MySQL monitor (...)

    mysql> CREATE USER ''@'localhost' IDENTIFIED BY 'anotherpass';
    Query OK, 0 rows affected (0.00 sec)

    mysql> Bye

    root@myhost:/home/mysql-5.5.16-linux2.6-x86_64# ./mysql -ubill -ppass \
        --socket=/tmp/mysql-5.5.sock
    ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES)
    root@myhost:/home/mysql-5.5.16-linux2.6-x86_64# ./mysql -ubill -ppass \
        -h127.0.0.1 --protocol=TCP
    ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES)
    root@myhost:/home/mysql-5.5.16-linux2.6-x86_64# ./mysql -ubill -ppass \
        -hlocalhost --protocol=TCP
    ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES)

Edit 3

Same situation as in edit 2, now providing the anonymous user's password.


    root@myhost:/home/mysql-5.5.16-linux2.6-x86_64# ./mysql -ubill -panotherpass -hlocalhost
    Welcome to the MySQL monitor (...)

    mysql> SELECT USER(), CURRENT_USER();
    +----------------+----------------+
    | USER()         | CURRENT_USER() |
    +----------------+----------------+
    | bill@localhost | @localhost     |
    +----------------+----------------+
    1 row in set (0.01 sec)

Conclusion 1, from edit 1: One can authenticate as 'bill'@'%'through a socket.

Conclusion 2, from edit 2: Whether one connects through TCP or through a socket has no impact on the authentication process (except one cannot connect as anyone else but 'something'@'localhost' through a socket, obviously).

Conclusion 3, from edit 3: Although I specified -ubill, I have been granted access as an anonymous user. This is because of the "sorting rules" advised above. Notice that in most default installations, a no-password, anonymous user exists (and should be secured/removed).

How to use HTTP GET in PowerShell?

In PowerShell v3, have a look at the Invoke-WebRequest and Invoke-RestMethod e.g.:

$msg = Read-Host -Prompt "Enter message"
$encmsg = [System.Web.HttpUtility]::UrlEncode($msg)
Invoke-WebRequest -Uri "http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$encmsg&encoding=windows-1255"

Add "Appendix" before "A" in thesis TOC

You can easily achieve what you want using the appendix package. Here's a sample file that shows you how. The key is the titletoc option when calling the package. It takes whatever value you've defined in \appendixname and the default value is Appendix.

\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents

\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
  \chapter{Consectetur adipiscing elit}
  \chapter{Mauris euismod}
\end{appendices}
\end{document}

The output looks like

enter image description here

Laravel: Using try...catch with DB::transaction()

You could wrapping the transaction over try..catch or even reverse them, here my example code I used to in laravel 5,, if you look deep inside DB:transaction() in Illuminate\Database\Connection that the same like you write manual transaction.

Laravel Transaction

public function transaction(Closure $callback)
    {
        $this->beginTransaction();

        try {
            $result = $callback($this);

            $this->commit();
        }

        catch (Exception $e) {
            $this->rollBack();

            throw $e;
        } catch (Throwable $e) {
            $this->rollBack();

            throw $e;
        }

        return $result;
    }

so you could write your code like this, and handle your exception like throw message back into your form via flash or redirect to another page. REMEMBER return inside closure is returned in transaction() so if you return redirect()->back() it won't redirect immediately, because the it returned at variable which handle the transaction.

Wrap Transaction

$result = DB::transaction(function () use ($request, $message) {
   try{

      // execute query 1
      // execute query 2
      // ..

      return redirect(route('account.article'));

   } catch (\Exception $e) {
       return redirect()->back()->withErrors(['error' => $e->getMessage()]);
    }
 });

// redirect the page
return $result;

then the alternative is throw boolean variable and handle redirect outside transaction function or if your need to retrieve why transaction failed you can get it from $e->getMessage() inside catch(Exception $e){...}

Save and retrieve image (binary) from SQL Server using Entity Framework 6

Convert the image to a byte[] and store that in the database.


Add this column to your model:

public byte[] Content { get; set; }

Then convert your image to a byte array and store that like you would any other data:

public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
    using(var ms = new MemoryStream())
    {
        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);

        return ms.ToArray();
    }
}

public Image ByteArrayToImage(byte[] byteArrayIn)
{
     using(var ms = new MemoryStream(byteArrayIn))
     {
         var returnImage = Image.FromStream(ms);

         return returnImage;
     }
}

Source: Fastest way to convert Image to Byte array

var image = new ImageEntity()
{
   Content = ImageToByteArray(image)
};

_context.Images.Add(image);
_context.SaveChanges();

When you want to get the image back, get the byte array from the database and use the ByteArrayToImage and do what you wish with the Image

This stops working when the byte[] gets to big. It will work for files under 100Mb

Nested classes' scope?

class Outer(object):
    outer_var = 1

    class Inner(object):
        @property
        def inner_var(self):
            return Outer.outer_var

This isn't quite the same as similar things work in other languages, and uses global lookup instead of scoping the access to outer_var. (If you change what object the name Outer is bound to, then this code will use that object the next time it is executed.)

If you instead want all Inner objects to have a reference to an Outer because outer_var is really an instance attribute:

class Outer(object):
    def __init__(self):
        self.outer_var = 1

    def get_inner(self):
        return self.Inner(self)
        # "self.Inner" is because Inner is a class attribute of this class
        # "Outer.Inner" would also work, or move Inner to global scope
        # and then just use "Inner"

    class Inner(object):
        def __init__(self, outer):
            self.outer = outer

        @property
        def inner_var(self):
            return self.outer.outer_var

Note that nesting classes is somewhat uncommon in Python, and doesn't automatically imply any sort of special relationship between the classes. You're better off not nesting. (You can still set a class attribute on Outer to Inner, if you want.)

PPT to PNG with transparent background

Import To Google Slides

Select desired slide and set background to solid transparent

the click "File->Download as PNG"

PowerShell - Start-Process and Cmdline Switches

I've found using cmd works well as an alternative, especially when you need to pipe the output from the called application (espeically when it doesn't have built in logging, unlike msbuild)

cmd /C "$msbuild $args" >> $outputfile

Create a Cumulative Sum Column in MySQL

UPDATE t
SET cumulative_sum = (
 SELECT SUM(x.count)
 FROM t x
 WHERE x.id <= t.id
)

How can I quantify difference between two images?

I think you could simply compute the euclidean distance (i.e. sqrt(sum of squares of differences, pixel by pixel)) between the luminance of the two images, and consider them equal if this falls under some empirical threshold. And you would better do it wrapping a C function.

Newline in JLabel

You can try and do this:

myLabel.setText("<html>" + myString.replaceAll("<","&lt;").replaceAll(">", "&gt;").replaceAll("\n", "<br/>") + "</html>")

The advantages of doing this are:

  • It replaces all newlines with <br/>, without fail.
  • It automatically replaces eventual < and > with &lt; and &gt; respectively, preventing some render havoc.

What it does is:

  • "<html>" + adds an opening html tag at the beginning
  • .replaceAll("<", "&lt;").replaceAll(">", "&gt;") escapes < and > for convenience
  • .replaceAll("\n", "<br/>") replaces all newlines by br (HTML line break) tags for what you wanted
  • ... and + "</html>" closes our html tag at the end.

P.S.: I'm very sorry to wake up such an old post, but whatever, you have a reliable snippet for your Java!

What's in an Eclipse .classpath/.project file?

This eclipse documentation has details on the markups in .project file: The project description file

It describes the .project file as:

When a project is created in the workspace, a project description file is automatically generated that describes the project. The purpose of this file is to make the project self-describing, so that a project that is zipped up or released to a server can be correctly recreated in another workspace. This file is always called ".project"

Uploading multiple files using formData()

I found this work for me!

var fd = new FormData();
$.each($('.modal-banner [type=file]'), function(index, file) {
  fd.append('item[]', $('input[type=file]')[index].files[0]);
});

$.ajax({
  type: 'POST',
  url: 'your/path/', 
  data: fd,
  dataType: 'json',
  contentType: false,
  processData: false,
  cache: false,
  success: function (response) {
    console.log(response);
  },
  error: function(err){
    console.log(err);
  }
}).done(function() {
  // do something....
});
return false;

Select 2 columns in one and combine them

Yes, you can combine columns easily enough such as concatenating character data:

select col1 | col 2 as bothcols from tbl ...

or adding (for example) numeric data:

select col1 + col2 as bothcols from tbl ...

In both those cases, you end up with a single column bothcols, which contains the combined data. You may have to coerce the data type if the columns are not compatible.

How can I exit from a javascript function?

You should use return as in:

function refreshGrid(entity) {
  var store = window.localStorage;
  var partitionKey;
  if (exit) {
    return;
  }

substring index range

Like you I didn't find it came naturally. I normally still have to remind myself that

  • the length of the returned string is

    lastIndex - firstIndex

  • that you can use the length of the string as the lastIndex even though there is no character there and trying to reference it would throw an Exception

so

"University".substring(6, 10)

returns the 4-character string "sity" even though there is no character at position 10.

Best way to test for a variable's existence in PHP; isset() is clearly broken

I'm going to add a quick two cents to this. One reason this issue is confusing is because this scenario seems to return the same result with error reporting not on full:

$a = null;
var_dump($a); // NULL
var_dump($b); // NULL

You could assume from this result that the difference between $a = null and not defining $b at all is nothing.

Crank error reporting up:

NULL

Notice: Undefined variable: b in xxx on line n
NULL

Note: it threw an undefined variable error, but the output value of var_dump is still NULL.

PHP obviously does have an internal ability to distinguish between a null variable and an undefined variable. It seems to me that there should be a built in function to check for this.

I think the accepted answer is good for the most part, but if I was going to implement it I would write a wrapper for it. As previously mentioned in this answer, I have to agree that I haven't actually encountered a situation where this has been a problem. I seem to almost always end up in a scenario where my variables are either set and defined, or they aren't (undefined, unset, null, blank, etc). Not to say that a situation like this won't occur in future, but as it seems to be quite a unique issue I'm not surprised that the PHP devs haven't bothered to put this in.

How to select all and copy in vim?

In normal mode:

gg"+yG

In ex mode:

:%y+

How can I make the contents of a fixed element scrollable only when it exceeds the height of the viewport?

Try this on your position:fixed element.

overflow-y: scroll;
max-height: 100%;

Plugin is too old, please update to a more recent version, or set ANDROID_DAILY_OVERRIDE environment variable to

You can always check the latest gradle plugin version here: https://bintray.com/android/android-tools/com.android.tools.build.gradle

So as of today you should use:

classpath 'com.android.tools.build:gradle:2.2.2'

accordingly.

Getting attribute using XPath

You can try below xPath pattern,

  XPathExpression expr = xPath.compile("/bookstore/book/title[@lang='eng']")

JavaScript Nested function

Functions are another type of variable in JavaScript (with some nuances of course). Creating a function within another function changes the scope of the function in the same way it would change the scope of a variable. This is especially important for use with closures to reduce total global namespace pollution.

The functions defined within another function won't be accessible outside the function unless they have been attached to an object that is accessible outside the function:

function foo(doBar)
{
  function bar()
  {
    console.log( 'bar' );
  }

  function baz()
  {
    console.log( 'baz' );
  }

  window.baz = baz;
  if ( doBar ) bar();
}

In this example, the baz function will be available for use after the foo function has been run, as it's overridden window.baz. The bar function will not be available to any context other than scopes contained within the foo function.

as a different example:

function Fizz(qux)
{
  this.buzz = function(){
    console.log( qux );
  };
}

The Fizz function is designed as a constructor so that, when run, it assigns a buzz function to the newly created object.

Extract time from date String

Use SimpleDateFormat to convert between a date string and a real Date object. with a Date as starting point, you can easily apply formatting based on various patterns as definied in the javadoc of the SimpleDateFormat (click the blue code link for the Javadoc).

Here's a kickoff example:

String originalString = "2010-07-14 09:00:02";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(originalString);
String newString = new SimpleDateFormat("H:mm").format(date); // 9:00

How to use a wildcard in the classpath to add multiple jars?

Basename wild cards were introduced in Java 6; i.e. "foo/*" means all ".jar" files in the "foo" directory.

In earlier versions of Java that do not support wildcard classpaths, I have resorted to using a shell wrapper script to assemble a Classpath by 'globbing' a pattern and mangling the results to insert ':' characters at the appropriate points. This would be hard to do in a BAT file ...

Graph visualization library in JavaScript

JsVIS was pretty nice, but slow with larger graphs, and has been abandoned since 2007.

prefuse is a set of software tools for creating rich interactive data visualizations in Java. flare is an ActionScript library for creating visualizations that run in the Adobe Flash Player, abandoned since 2012.

JDBC ResultSet: I need a getDateTime, but there is only getDate and getTimeStamp

The solution I opted for was to format the date with the mysql query :

String l_mysqlQuery = "SELECT DATE_FORMAT(time, '%Y-%m-%d %H:%i:%s') FROM uld_departure;"
l_importedTable = fStatement.executeQuery( l_mysqlQuery );
System.out.println(l_importedTable.getString( timeIndex));

I had the exact same issue. Even though my mysql table contains dates formatted as such : 2017-01-01 21:02:50

String l_mysqlQuery = "SELECT time FROM uld_departure;"
l_importedTable = fStatement.executeQuery( l_mysqlQuery );
System.out.println(l_importedTable.getString( timeIndex));

was returning a date formatted as such : 2017-01-01 21:02:50.0

How to pass a file path which is in assets folder to File(String path)?

AFAIK, you can't create a File from an assets file because these are stored in the apk, that means there is no path to an assets folder.

But, you can try to create that File using a buffer and the AssetManager (it provides access to an application's raw asset files).

Try to do something like:

AssetManager am = getAssets();
InputStream inputStream = am.open("myfoldername/myfilename");
File file = createFileFromInputStream(inputStream);

private File createFileFromInputStream(InputStream inputStream) {

   try{
      File f = new File(my_file_name);
      OutputStream outputStream = new FileOutputStream(f);
      byte buffer[] = new byte[1024];
      int length = 0;

      while((length=inputStream.read(buffer)) > 0) {
        outputStream.write(buffer,0,length);
      }

      outputStream.close();
      inputStream.close();

      return f;
   }catch (IOException e) {
         //Logging exception
   }

   return null;
}

Let me know about your progress.

Android Notification Sound

You can make a function:

public void playNotificationSound() 
{
    try
    {

        Uri alarmSound = `Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + MyApplication.getInstance().getApplicationContext().getPackageName() + "/raw/notification");`
        Ringtone r = RingtoneManager.getRingtone(MyApplication.getInstance().getApplicationContext(), alarmSound);
        r.play();
    }
    catch (Exception e) 
    {
        e.printStackTrace();
    }
}

Call this function when you receive notification.

Here raw is the folder in res and the notification is the sound file in raw folder.

How to copy a java.util.List into another java.util.List

You should use the addAll method. It appends all of the elements in the specified collection to the end of the copy list. It will be a copy of your list.

List<String> myList = new ArrayList<>();
myList.add("a");
myList.add("b");
List<String> copyList = new ArrayList<>();
copyList.addAll(myList);

Streaming video from Android camera to server

I am able to send the live camera video from mobile to my server.using this link see the link

Refer the above link.there is a sample application in that link. Just you need to set your service url in RecordActivity.class.

Example as: ffmpeg_link="rtmp://yourserveripaddress:1935/live/venkat";

we can able to send H263 and H264 type videos using that link.

How to convert const char* to char* in C?

First of all you should do such things only if it is really necessary - e.g. to use some old-style API with char* arguments which are not modified. If an API function modifies the string which was const originally, then this is unspecified behaviour, very likely crash.

Use cast:

(char*)const_char_ptr

ZIP Code (US Postal Code) validation

Here's one from jQuery Validate plugin's additional-methods.js file...

jQuery.validator.addMethod("zipUS", function(value, element) {
    return /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(value);
}, "Please specify a valid US zip code.");

EDIT: Since the above code is part of the jQuery Validate plugin, it depends on the .addMethod() method.

Remove dependency on plugins and make it more generic....

function checkZip(value) {
    return (/(^\d{5}$)|(^\d{5}-\d{4}$)/).test(value);
};

Example Usage: http://jsfiddle.net/5PNcJ/

Replacing .NET WebBrowser control with a better browser, like Chrome?

You can use registry to set IE version for webbrowser control. Go to: HKLM\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION and add "yourApplicationName.exe" with value of browser_emulation To see value of browser_emulation, refer link: http://msdn.microsoft.com/en-us/library/ee330730%28VS.85%29.aspx#browser_emulation

How can I format DateTime to web UTC format?

You want to use DateTimeOffset class.

var date = new DateTimeOffset(2009, 9, 1, 0, 0, 0, 0, new TimeSpan(0L));
var stringDate = date.ToString("u");

sorry I missed your original formatting with the miliseconds

var stringDate = date.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");

Python memory usage of numpy arrays

In python notebooks I often want to filter out 'dangling' numpy.ndarray's, in particular the ones that are stored in _1, _2, etc that were never really meant to stay alive.

I use this code to get a listing of all of them and their size.

Not sure if locals() or globals() is better here.

import sys
import numpy
from humanize import naturalsize

for size, name in sorted(
    (value.nbytes, name)
    for name, value in locals().items()
    if isinstance(value, numpy.ndarray)):
  print("{:>30}: {:>8}".format(name, naturalsize(size)))

Why is my asynchronous function returning Promise { <pending> } instead of a value?

I know this question was asked 2 years ago, but I run into the same issue and the answer for the problem is since ES2017, that you can simply await the functions return value (as of now, only works in async functions), like:

let AuthUser = function(data) {
  return google.login(data.username, data.password).then(token => { return token } )
}

let userToken = await AuthUser(data)
console.log(userToken) // your data

SELECT CASE WHEN THEN (SELECT)

You should avoid using nested selects and I would go as far to say you should never use them in the actual select part of your statement. You will be running that select for each row that is returned. This is a really expensive operation. Rather use joins. It is much more readable and the performance is much better.

In your case the query below should help. Note the cases statement is still there, but now it is a simple compare operation.

select
    p.product_id,
    p.type_id,
    p.product_name,
    p.type,
    case p.type_id when 10 then (CONCAT_WS(' ' , first_name, middle_name, last_name )) else (null) end artistC
from
    Product p

    inner join Product_Type pt on
        pt.type_id = p.type_id

    left join Product_ArtistAuthor paa on
        paa.artist_id = p.artist_id
where
    p.product_id = $pid

I used a left join since I don't know the business logic.

Fast way to get the min/max values among properties of object

Here's a solution that allows you to return the key as well and only does one loop. It sorts the Object's entries (by val) and then returns the first and last one.

Additionally, it returns the sorted Object which can replace the existing Object so that future sorts will be faster because it will already be semi-sorted = better than O(n). It's important to note that Objects retain their order in ES6.

_x000D_
_x000D_
const maxMinVal = (obj) => {_x000D_
  const sortedEntriesByVal = Object.entries(obj).sort(([, v1], [, v2]) => v1 - v2);_x000D_
_x000D_
  return {_x000D_
    min: sortedEntriesByVal[0],_x000D_
    max: sortedEntriesByVal[sortedEntriesByVal.length - 1],_x000D_
    sortedObjByVal: sortedEntriesByVal.reduce((r, [k, v]) => ({ ...r, [k]: v }), {}),_x000D_
  };_x000D_
};_x000D_
_x000D_
const obj = {_x000D_
  a: 4, b: 0.5, c: 0.35, d: 5_x000D_
};_x000D_
_x000D_
console.log(maxMinVal(obj));
_x000D_
_x000D_
_x000D_

Java system properties and environment variables

I think the difference between the two boils down to access. Environment variables are accessible by any process and Java system properties are only accessible by the process they are added to.

Also as Bohemian stated, env variables are set in the OS (however they 'can' be set through Java) and system properties are passed as command line options or set via setProperty().

Count work days between two dates

All Credit to Bogdan Maxim & Peter Mortensen. This is their post, I just added holidays to the function (This assumes you have a table "tblHolidays" with a datetime field "HolDate".

--Changing current database to the Master database allows function to be shared by everyone.
USE MASTER
GO
--If the function already exists, drop it.
IF EXISTS
(
    SELECT *
    FROM dbo.SYSOBJECTS
    WHERE ID = OBJECT_ID(N'[dbo].[fn_WorkDays]')
    AND XType IN (N'FN', N'IF', N'TF')
)

DROP FUNCTION [dbo].[fn_WorkDays]
GO
 CREATE FUNCTION dbo.fn_WorkDays
--Presets
--Define the input parameters (OK if reversed by mistake).
(
    @StartDate DATETIME,
    @EndDate   DATETIME = NULL --@EndDate replaced by @StartDate when DEFAULTed
)

--Define the output data type.
RETURNS INT

AS
--Calculate the RETURN of the function.
BEGIN
    --Declare local variables
    --Temporarily holds @EndDate during date reversal.
    DECLARE @Swap DATETIME

    --If the Start Date is null, return a NULL and exit.
    IF @StartDate IS NULL
        RETURN NULL

    --If the End Date is null, populate with Start Date value so will have two dates (required by DATEDIFF below).
    IF @EndDate IS NULL
        SELECT @EndDate = @StartDate

    --Strip the time element from both dates (just to be safe) by converting to whole days and back to a date.
    --Usually faster than CONVERT.
    --0 is a date (01/01/1900 00:00:00.000)
    SELECT @StartDate = DATEADD(dd,DATEDIFF(dd,0,@StartDate), 0),
            @EndDate   = DATEADD(dd,DATEDIFF(dd,0,@EndDate)  , 0)

    --If the inputs are in the wrong order, reverse them.
    IF @StartDate > @EndDate
        SELECT @Swap      = @EndDate,
               @EndDate   = @StartDate,
               @StartDate = @Swap

    --Calculate and return the number of workdays using the input parameters.
    --This is the meat of the function.
    --This is really just one formula with a couple of parts that are listed on separate lines for documentation purposes.
    RETURN (
        SELECT
        --Start with total number of days including weekends
        (DATEDIFF(dd,@StartDate, @EndDate)+1)
        --Subtact 2 days for each full weekend
        -(DATEDIFF(wk,@StartDate, @EndDate)*2)
        --If StartDate is a Sunday, Subtract 1
        -(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday'
            THEN 1
            ELSE 0
        END)
        --If EndDate is a Saturday, Subtract 1
        -(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday'
            THEN 1
            ELSE 0
        END)
        --Subtract all holidays
        -(Select Count(*) from [DB04\DB04].[Gateway].[dbo].[tblHolidays]
          where  [HolDate] between @StartDate and @EndDate )
        )
    END  
GO
-- Test Script
/*
declare @EndDate datetime= dateadd(m,2,getdate())
print @EndDate
select  [Master].[dbo].[fn_WorkDays] (getdate(), @EndDate)
*/

How to remove a key from HashMap while iterating over it?

To remove specific key and element from hashmap use

hashmap.remove(key)

full source code is like

import java.util.HashMap;
public class RemoveMapping {
     public static void main(String a[]){
        HashMap hashMap = new HashMap();
        hashMap.put(1, "One");
        hashMap.put(2, "Two");
        hashMap.put(3, "Three");
        System.out.println("Original HashMap : "+hashMap);
        hashMap.remove(3);   
        System.out.println("Changed HashMap : "+hashMap);        
    }
}

Source : http://www.tutorialdata.com/examples/java/collection-framework/hashmap/remove-mapping-of-specified--key-from-hashmap

Is there an exponent operator in C#?

For what it's worth I do miss the ^ operator when raising a power of 2 to define a binary constant. Can't use Math.Pow() there, but shifting an unsigned int of 1 to the left by the exponent's value works. When I needed to define a constant of (2^24)-1:

public static int Phase_count = 24;
public static uint PatternDecimal_Max = ((uint)1 << Phase_count) - 1;

Remember the types must be (uint) << (int).

Setting DataContext in XAML in WPF

There are several issues here.

  1. You can't assign DataContext as DataContext="{Binding Employee}" because it's a complex object which can't be assigned as string. So you have to use <Window.DataContext></Window.DataContext> syntax.
  2. You assign the class that represents the data context object to the view, not an individual property so {Binding Employee} is invalid here, you just have to specify an object.
  3. Now when you assign data context using valid syntax like below
   <Window.DataContext>
      <local:Employee/>
   </Window.DataContext>

know that you are creating a new instance of the Employee class and assigning it as the data context object. You may well have nothing in default constructor so nothing will show up. But then how do you manage it in code behind file? You have typecast the DataContext.

    private void my_button_Click(object sender, RoutedEventArgs e)
    {
        Employee e = (Employee) DataContext;
    }
  1. A second way is to assign the data context in the code behind file itself. The advantage then is your code behind file already knows it and can work with it.

    public partial class MainWindow : Window
    {
       Employee employee = new Employee();
    
       public MainWindow()
       {
           InitializeComponent();
    
           DataContext = employee;
       }
    }
    

How to check Network port access and display useful message?

If you are using older versions of Powershell where Test-NetConnection isn't available, here is a one-liner for hostname "my.hostname" and port "123":

$t = New-Object System.Net.Sockets.TcpClient 'my.hostname', 123; if($t.Connected) {"OK"}

Returns OK, or an error message.

Detecting which UIButton was pressed in a UITableView

func buttonAction(sender:UIButton!)
    {
        var position: CGPoint = sender.convertPoint(CGPointZero, toView: self.tablevw)
        let indexPath = self.tablevw.indexPathForRowAtPoint(position)
        let cell: TableViewCell = tablevw.cellForRowAtIndexPath(indexPath!) as TableViewCell
        println(indexPath?.row)
        println("Button tapped")
    }

How to get UTC+0 date in Java 8?

tl;dr

Instant.now()

java.time

The troublesome old date-time classes bundled with the earliest versions of Java have been supplanted by the java.time classes built into Java 8 and later. See Oracle Tutorial. Much of the functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

Instant

An Instant represents a moment on the timeline in UTC with a resolution of up to nanoseconds.

Instant instant = Instant.now();

The toString method generates a String object with text representing the date-time value using one of the standard ISO 8601 formats.

String output = instant.toString();  

2016-06-27T19:15:25.864Z

The Instant class is a basic building-block class in java.time. This should be your go-to class when handling date-time as generally the best practice is to track, store, and exchange date-time values in UTC.

OffsetDateTime

But Instant has limitations such as no formatting options for generating strings in alternate formats. For more flexibility, convert from Instant to OffsetDateTime. Specify an offset-from-UTC. In java.time that means a ZoneOffset object. Here we want to stick with UTC (+00) so we can use the convenient constant ZoneOffset.UTC.

OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );

2016-06-27T19:15:25.864Z

Or skip the Instant class.

OffsetDateTime.now( ZoneOffset.UTC )

Now with an OffsetDateTime object in hand, you can use DateTimeFormatter to create String objects with text in alternate formats. Search Stack Overflow for many examples of using DateTimeFormatter.

ZonedDateTime

When you want to display wall-clock time for some particular time zone, apply a ZoneId to get a ZonedDateTime.

In this example we apply Montréal time zone. In the summer, under Daylight Saving Time (DST) nonsense, the zone has an offset of -04:00. So note how the time-of-day is four hours earlier in the output, 15 instead of 19 hours. Instant and the ZonedDateTime both represent the very same simultaneous moment, just viewed through two different lenses.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

2016-06-27T15:15:25.864-04:00[America/Montreal]

Converting

While you should avoid the old date-time classes, if you must you can convert using new methods added to the old classes. Here we use java.util.Date.from( Instant ) and java.util.Date::toInstant.

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

And going the other direction.

Instant instant= utilDate.toInstant();

Similarly, look for new methods added to GregorianCalendar (subclass of Calendar) to convert to and from java.time.ZonedDateTime.

Table of types of date-time classes in modern java.time versus legacy.

About java.time

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

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

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

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

Play a Sound with Python

For Windows, you can use winsound. It's built in

import winsound

winsound.PlaySound('sound.wav', winsound.SND_FILENAME)

You should be able to use ossaudiodev for linux:

from wave import open as waveOpen
from ossaudiodev import open as ossOpen
s = waveOpen('tada.wav','rb')
(nc,sw,fr,nf,comptype, compname) = s.getparams( )
dsp = ossOpen('/dev/dsp','w')
try:
  from ossaudiodev import AFMT_S16_NE
except ImportError:
  from sys import byteorder
  if byteorder == "little":
    AFMT_S16_NE = ossaudiodev.AFMT_S16_LE
  else:
    AFMT_S16_NE = ossaudiodev.AFMT_S16_BE
dsp.setparameters(AFMT_S16_NE, nc, fr)
data = s.readframes(nf)
s.close()
dsp.write(data)
dsp.close()

(Credit for ossaudiodev: Bill Dandreta http://mail.python.org/pipermail/python-list/2004-October/288905.html)

fatal: 'origin' does not appear to be a git repository

I had the same error on git pull origin branchname when setting the remote origin as path fs and not ssh in .git/config:

fatal: '/path/to/repo.git' does not appear to be a git repository 
fatal: The remote end hung up unexpectedly

It was like so (this only works for users on same server of git that have access to git):

url = file:///path/to/repo.git/

Fixed it like so (this works on all users that have access to git user (ssh authorizes_keys or password)):

url = [email protected]:path/to/repo.git

the reason I had it as a directory path was because the git files are on the same server.

How to get the Android Emulator's IP address?

Within the code of my app I can get the running device IP andress easily like beolow:

WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());

HTML tag <a> want to add both href and onclick working

Use ng-click in place of onclick. and its as simple as that:

<a href="www.mysite.com" ng-click="return theFunction();">Item</a>

<script type="text/javascript">
function theFunction () {
    // return true or false, depending on whether you want to allow 
    // the`href` property to follow through or not
 }
</script>

How can I specify a [DllImport] path at runtime?

DllImport will work fine without the complete path specified as long as the dll is located somewhere on the system path. You may be able to temporarily add the user's folder to the path.

How do you test to see if a double is equal to NaN?

The below code snippet will help evaluate primitive type holding NaN.

double dbl = Double.NaN; Double.valueOf(dbl).isNaN() ? true : false;

Why does JSHint throw a warning if I am using const?

In your package.json you can tell Jshint to use es6 like this

"jshintConfig":{
    "esversion": 6 
}

Spark: subtract two DataFrames

In pyspark DOCS it would be subtract

df1.subtract(df2)

PHP - Session destroy after closing browser

There are different ways to do this, but the server can't detect when de browser gets closed so destroying it then is hard.

  • timeout session.

Either create a new session with the current time or add a time variable to the current session. and then check it when you start up or perform an action to see if the session has to be removed.

session_start();
$_SESSION["timeout"] = time();
//if 100 seconds have passed since creating session delete it.
if(time() - $_SESSION["timeout"] > 100){ 
    unset($_SESSION["timeout"];
}
  • ajax

Make javascript perform an ajax call that will delete the session, with onbeforeunload() a javascript function that calls a final action when the user leaves the page. For some reason this doesnt always work though.

  • delete it on startup.

If you always want the user to see the login page on startup after the page has been closed you can just delete the session on startup.

<? php
session_start();
unset($_SESSION["session"]);

and there probably are some more.

ASP.NET MVC Custom Error Handling Application_Error Global.asax?

Use Following code for redirecting on route page. Use exception.Message instide of exception. Coz exception query string gives error if it extends the querystring length.

routeData.Values.Add("error", exception.Message);
// clear error on server
Server.ClearError();
Response.RedirectToRoute(routeData.Values);

What's the most efficient way to test two integer ranges for overlap?

Subtracting the Minimum of the ends of the ranges from the Maximum of the beginning seems to do the trick. If the result is less than or equal to zero, we have an overlap. This visualizes it well:

enter image description here

Output an Image in PHP

$file = '../image.jpg';

if (file_exists($file))
{
    $size = getimagesize($file);

    $fp = fopen($file, 'rb');

    if ($size and $fp)
    {
        // Optional never cache
    //  header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
    //  header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    //  header('Pragma: no-cache');

        // Optional cache if not changed
    //  header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($file)).' GMT');

        // Optional send not modified
    //  if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) and 
    //      filemtime($file) == strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']))
    //  {
    //      header('HTTP/1.1 304 Not Modified');
    //  }

        header('Content-Type: '.$size['mime']);
        header('Content-Length: '.filesize($file));

        fpassthru($fp);

        exit;
    }
}

http://php.net/manual/en/function.fpassthru.php

How do I jump out of a foreach loop in C#?

Use break; and this will exit the foreach loop

Creating multiple log files of different content with log4j

This should get you started:

log4j.rootLogger=QuietAppender, LoudAppender, TRACE
# setup A1
log4j.appender.QuietAppender=org.apache.log4j.RollingFileAppender
log4j.appender.QuietAppender.Threshold=INFO
log4j.appender.QuietAppender.File=quiet.log
...


# setup A2
log4j.appender.LoudAppender=org.apache.log4j.RollingFileAppender
log4j.appender.LoudAppender.Threshold=DEBUG
log4j.appender.LoudAppender.File=loud.log
...

log4j.logger.com.yourpackage.yourclazz=TRACE

What precisely does 'Run as administrator' do?

A little clearer... A software program that has kernel mode access has total access to all of the computer's data and its hardware.

Since Windows Vista Microsoft has stopped any and all I/O processes from accessing the kernel (ring 0) directly ever again. The closest we get is a folder created as a virtual kernel access partition, but technically no access to kernel itself; the kernel meets halfway.

This is because the software itself dictates which token to use, so if it asks for an administrator access token, instead of just allowing communications with the kernel like on Windows XP you are prompted to allow access to the kernel, each and every time. Changing UAC could reduce prompts, but never the kernel prompts.

Even when you login as an Administrator, you are running processes as a standard user until prompted to elevate the rights you have. I believe logged in as the administrator saves you from entering the credentials. But it also writes to the administrator users folder structure.

Kernel access is similar to root access in Linux. When you elevate your permissions you are isolating yourself from the root of C:\ and whatever lovely environment variables are contained within.

If you remember BSODs this was the OS shutting down when it believed a bad I/O reached the kernel.

How to print out all the elements of a List in Java?

I wrote a dump function, which basicly prints out the public members of an object if it has not overriden toString(). One could easily expand it to call getters. Javadoc:

Dumps an given Object to System.out, using the following rules:

  • If the Object is Iterable, all of its components are dumped.
  • If the Object or one of its superclasses overrides toString(), the "toString" is dumped
  • Else the method is called recursively for all public members of the Object

/**
 * Dumps an given Object to System.out, using the following rules:<br>
 * <ul>
 * <li> If the Object is {@link Iterable}, all of its components are dumped.</li>
 * <li> If the Object or one of its superclasses overrides {@link #toString()}, the "toString" is dumped</li>
 * <li> Else the method is called recursively for all public members of the Object </li>
 * </ul>
 * @param input
 * @throws Exception
 */
public static void dump(Object input) throws Exception{
    dump(input, 0);
}

private static void dump(Object input, int depth) throws Exception{
    if(input==null){
        System.out.print("null\n"+indent(depth));
        return;
    }

    Class<? extends Object> clazz = input.getClass();
    System.out.print(clazz.getSimpleName()+" ");
    if(input instanceof Iterable<?>){
        for(Object o: ((Iterable<?>)input)){
            System.out.print("\n"+indent(depth+1));
            dump(o, depth+1);
        }
    }else if(clazz.getMethod("toString").getDeclaringClass().equals(Object.class)){
        Field[] fields = clazz.getFields();
        if(fields.length == 0){
            System.out.print(input+"\n"+indent(depth));
        }
        System.out.print("\n"+indent(depth+1));
        for(Field field: fields){
            Object o = field.get(input);
            String s = "|- "+field.getName()+": ";
            System.out.print(s);
            dump(o, depth+1);
        }
    }else{

        System.out.print(input+"\n"+indent(depth));
    }
}

private static String indent(int depth) {
    StringBuilder sb = new StringBuilder();
    for(int i=0; i<depth; i++)
        sb.append("  ");
    return sb.toString();
}

How to validate GUID is a GUID

See if these helps :-

  1. Guid.Parse - Docs
Guid guidResult = Guid.Parse(inputString)
  1. Guid.TryParse - Docs
bool isValid = Guid.TryParse(inputString, out guidOutput)

C++ [Error] no matching function for call to

to add to John's answer:

what you want to pass to the shuffle function is a deck of cards from the class deckOfCards that you've declared in main; however, the deck of cards or vector<Card> deck that you've declared in your class is private, so not accessible from outside the class. this means you'd want a getter function, something like this:

class deckOfCards
{
    private:
        vector<Card> deck;

    public:
        deckOfCards();
        static int count;
        static int next;
        void shuffle(vector<Card>& deck);
        Card dealCard();
        bool moreCards();
        vector<Card>& getDeck() {   //GETTER
            return deck;
        }
};

this will in turn allow you to call your shuffle function from main like this:

deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck.getDeck()); // shuffle the cards in the deck

however, you have more problems, specifically when calling cout. first, you're calling the dealCard function wrongly; as dealCard is a memeber function of a class, you should be calling it like this cardDeck.dealCard(); instead of this dealCard(cardDeck);.

now, we come to your second problem - print to standard output. you're trying to print your deal card, which is an object of type Card by using the following instruction:

cout << cardDeck.dealCard();// deal the cards in the deck

yet, the cout doesn't know how to print it, as it's not a standard type. this means you should overload your << operator to print whatever you want it to print when calling with a Card type.

Python str vs unicode types

Your terminal happens to be configured to UTF-8.

The fact that printing a works is a coincidence; you are writing raw UTF-8 bytes to the terminal. a is a value of length two, containing two bytes, hex values C3 and A1, while ua is a unicode value of length one, containing a codepoint U+00E1.

This difference in length is one major reason to use Unicode values; you cannot easily measure the number of text characters in a byte string; the len() of a byte string tells you how many bytes were used, not how many characters were encoded.

You can see the difference when you encode the unicode value to different output encodings:

>>> a = 'á'
>>> ua = u'á'
>>> ua.encode('utf8')
'\xc3\xa1'
>>> ua.encode('latin1')
'\xe1'
>>> a
'\xc3\xa1'

Note that the first 256 codepoints of the Unicode standard match the Latin 1 standard, so the U+00E1 codepoint is encoded to Latin 1 as a byte with hex value E1.

Furthermore, Python uses escape codes in representations of unicode and byte strings alike, and low code points that are not printable ASCII are represented using \x.. escape values as well. This is why a Unicode string with a code point between 128 and 255 looks just like the Latin 1 encoding. If you have a unicode string with codepoints beyond U+00FF a different escape sequence, \u.... is used instead, with a four-digit hex value.

It looks like you don't yet fully understand what the difference is between Unicode and an encoding. Please do read the following articles before you continue:

return query based on date

You probably want to make a range query, for example, all items created after a given date:

db.gpsdatas.find({"createdAt" : { $gte : new ISODate("2012-01-12T20:15:31Z") }});

I'm using $gte (greater than or equals), because this is often used for date-only queries, where the time component is 00:00:00.

If you really want to find a date that equals another date, the syntax would be

db.gpsdatas.find({"createdAt" : new ISODate("2012-01-12T20:15:31Z") });

Python: Find a substring in a string and returning the index of the substring

Here is a simple approach:

my_string = 'abcdefg'
print(text.find('def'))

Output:

3

I the substring is not there, you will get -1. For example:

my_string = 'abcdefg'
print(text.find('xyz'))

Output:

-1

Sometimes, you might want to throw exception if substring is not there:

my_string = 'abcdefg'
print(text.index('xyz')) # It returns an index only if it's present

Output:

Traceback (most recent call last):

File "test.py", line 6, in print(text.index('xyz'))

ValueError: substring not found

How to Get True Size of MySQL Database?

None of the answers include the overhead size and the metadata sizes of tables.

Here is a more accurate estimation of the "disk space" allocated by a database.

SELECT ROUND((SUM(data_length+index_length+data_free) + (COUNT(*) * 300 * 1024))/1048576+150, 2) AS MegaBytes FROM information_schema.TABLES WHERE table_schema = 'DATABASE-NAME'

Table overflowing outside of div

I tried almost all of above but did not work for me ... The following did

word-break: break-all;

This to be added on the parent div (container of the table .)

Secure hash and salt for PHP passwords

A much shorter and safer answer - don't write your own password mechanism at all, use a tried and tested mechanism.

  • PHP 5.5 or higher: password_hash() is good quality and part of PHP core.
  • PHP 4.x (obsolete): OpenWall's phpass library is much better than most custom code - used in WordPress, Drupal, etc.

Most programmers just don't have the expertise to write crypto related code safely without introducing vulnerabilities.

Quick self-test: what is password stretching and how many iterations should you use? If you don't know the answer, you should use password_hash(), as password stretching is now a critical feature of password mechanisms due to much faster CPUs and the use of GPUs and FPGAs to crack passwords at rates of billions of guesses per second (with GPUs).

For example, you can crack all 8-character Windows passwords in 6 hours using 25 GPUs installed in 5 desktop PCs. This is brute-forcing i.e. enumerating and checking every 8-character Windows password, including special characters, and is not a dictionary attack. That was in 2012, as of 2018 you could use fewer GPUs, or crack faster with 25 GPUs.

There are also many rainbow table attacks on Windows passwords that run on ordinary CPUs and are very fast. All this is because Windows still doesn't salt or stretch its passwords, even in Windows 10 - don't make the same mistake as Microsoft did!

See also:

  • excellent answer with more about why password_hash() or phpass are the best way to go.
  • good blog article giving recommmended 'work factors' (number of iterations) for main algorithms including bcrypt, scrypt and PBKDF2.

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

I have to say that my situation might not be what you are looking for, but it may provide an alternative to your thinking.

I have tried both the set() and any() method but still have problems with speed. So I remembered Raymond Hettinger said everything in python is a dictionary and use dict whenever you can. So that's what I tried.

I used a defaultdict with int to indicate negative results and used the item in the first list as the key for the second list (converted to defaultdict). Because you have instant lookup with dict, you know immediately whether that item exist in the defaultdict. I know you don't always get to change data structure for your second list, but if you are able to from the start, then it's much faster. You may have to convert list2 (larger list) to a defaultdict, where key is the potential value you want to check from small list, and value is either 1 (hit) or 0 (no hit, default).

from collections import defaultdict
already_indexed = defaultdict(int)

def check_exist(small_list, default_list):
    for item in small_list:
        if default_list[item] == 1:
            return True
    return False

if check_exist(small_list, already_indexed):
    continue
else:
    for x in small_list:
        already_indexed[x] = 1

What does "var" mean in C#?

It means the data type is derived (implied) from the context.

From http://msdn.microsoft.com/en-us/library/bb383973.aspx

Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i are functionally equivalent:

var i = 10; // implicitly typed
int i = 10; //explicitly typed

var is useful for eliminating keyboard typing and visual noise, e.g.,

MyReallyReallyLongClassName x = new MyReallyReallyLongClassName();

becomes

var x = new MyReallyReallyLongClassName();

but can be overused to the point where readability is sacrificed.

Split string based on a regular expression

By using (,), you are capturing the group, if you simply remove them you will not have this problem.

>>> str1 = "a    b     c      d"
>>> re.split(" +", str1)
['a', 'b', 'c', 'd']

However there is no need for regex, str.split without any delimiter specified will split this by whitespace for you. This would be the best way in this case.

>>> str1.split()
['a', 'b', 'c', 'd']

If you really wanted regex you can use this ('\s' represents whitespace and it's clearer):

>>> re.split("\s+", str1)
['a', 'b', 'c', 'd']

or you can find all non-whitespace characters

>>> re.findall(r'\S+',str1)
['a', 'b', 'c', 'd']

Using VBA to get extended file attributes

Lucky discovery

if objFolderItem is Nothing when you call

objFolder.GetDetailsOf(objFolderItem, i)

the string returned is the name of the property, rather than its (undefined) value e.g. when i=3 it returns "Date modified"

Doing it for all 288 values of I makes it clear why most cause it to return blank for most filetypes e.g i=175 is "Horizontal resolution"

Change/Get check state of CheckBox

This will be useful

$("input[type=checkbox]").change((e)=>{ 
  console.log(e.target.checked);
});

Android Studio - No JVM Installation found

Had the same problem after upgrading my machine from 7 to 10 had to reinstall the JDK all overgain and took me only a few seconds. Here are the steps I followed.

Go to this link http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

Agree to oracle contact agreement.Then pick your windows version in my case is 64 bit after that its ..Next..Next,,once compete you can relaunch your Android studio without any problem. Hope this helps

The model item passed into the dictionary is of type .. but this dictionary requires a model item of type

Consider the partial map.cshtml at Partials/Map.cshtml. This can be called from the Page where the partial is to be rendered, simply by using the <partial> tag:

<partial name="Partials/Map" model="new Pages.Partials.MapModel()" />

This is one of the easiest methods I encountered (although I am using razor pages, I am sure same is for MVC too)

iPhone/iPad browser simulator?

EDIT 2020: Most of these are basically just to test resolution stuff, some of them even outdated, sadly, mobile browser development went sideways with desktop (especially in Apple), therefore one can't really "emulate" a real phone with these as mentioned with comment.

To emulate real phones, often the best choice is to download a desktop app which, for Windows, is usually paid/freemium, on Mac just use the Xcode one (but I doubt Mac people are looking for this Q/A).

Freemium online easy to use that I found recently is Appetize.io it seems to really render the screen according to network, but honestly I didn't really dig into whether it also has identical features and indentically missing features as real iOS.

Online simulators / emulators I use

1) recombu

Fine simulator which - unlike resizing browser window to mobile phone dimensions - acts same as a smart phone. Don't be confused that you can't edit address bar in safari - just open deveolper tools (usually F12) and rewrite iframe's source URL to yours.
Link: http://recombu.com/mobile/interactive/ios7-demo/

2) responsimulator

Seems to work like recombu, but you can open url directly by text input and you can zoom in/out.
Link: http://www.responsimulator.com/

3) transmog

This one seems to process the webpage, but it emulates old iPhone - still handy sometimes.
Link: http://transmog.net/iphone-simulator/mobile-web-browser-emulator.php

X) google it / internet search for it

Always use google (or other internet searchers) to check for other simulators/emulators and new versions.
Link with example google search for this one:
https://www.google.cz/search?q=online+iphone+emulator

Browser device mode

If you open your browser's developer's tools (in Chrome F12), there will probably be an option to toggle device mode (in Chrome it is the little smartphone icon at top-left).
chrome device mode icon

After choosing this option GUI will change and will provide option to select device to simulate (in Chrome it is at the top - select option "Device"), after selecting device, refreshing the page is often adviced to ensure simulator's accuracy.
chrome device mode - device select option

No Main class found in NetBeans

  1. Right click on your Project in the project explorer
  2. Click on properties
  3. Click on Run
  4. Make sure your Main Class is the one you want to be the entry point. (Make sure to use the fully qualified name i.e. mypackage.MyClass)
  5. Click OK.
  6. Run Project :)

If you just want to run the file, right click on the class from the package explorer, and click Run File, or (Alt + R, F), or (Shift + F6)

Where do I find some good examples for DDD?

ddd-cqrs-sample is also a good resource. Written with Java, Spring and JPA.

Updated link: https://github.com/BottegaIT/ddd-leaven-v2

Correct way to use StringBuilder in SQL

The aim of using StringBuilder, i.e reducing memory. Is it achieved?

No, not at all. That code is not using StringBuilder correctly. (I think you've misquoted it, though; surely there aren't quotes around id2 and table?)

Note that the aim (usually) is to reduce memory churn rather than total memory used, to make life a bit easier on the garbage collector.

Will that take memory equal to using String like below?

No, it'll cause more memory churn than just the straight concat you quoted. (Until/unless the JVM optimizer sees that the explicit StringBuilder in the code is unnecessary and optimizes it out, if it can.)

If the author of that code wants to use StringBuilder (there are arguments for, but also against; see note at the end of this answer), better to do it properly (here I'm assuming there aren't actually quotes around id2 and table):

StringBuilder sb = new StringBuilder(some_appropriate_size);
sb.append("select id1, ");
sb.append(id2);
sb.append(" from ");
sb.append(table);
return sb.toString();

Note that I've listed some_appropriate_size in the StringBuilder constructor, so that it starts out with enough capacity for the full content we're going to append. The default size used if you don't specify one is 16 characters, which is usually too small and results in the StringBuilder having to do reallocations to make itself bigger (IIRC, in the Sun/Oracle JDK, it doubles itself [or more, if it knows it needs more to satisfy a specific append] each time it runs out of room).

You may have heard that string concatenation will use a StringBuilder under the covers if compiled with the Sun/Oracle compiler. This is true, it will use one StringBuilder for the overall expression. But it will use the default constructor, which means in the majority of cases, it will have to do a reallocation. It's easier to read, though. Note that this is not true of a series of concatenations. So for instance, this uses one StringBuilder:

return "prefix " + variable1 + " middle " + variable2 + " end";

It roughly translates to:

StringBuilder tmp = new StringBuilder(); // Using default 16 character size
tmp.append("prefix ");
tmp.append(variable1);
tmp.append(" middle ");
tmp.append(variable2);
tmp.append(" end");
return tmp.toString();

So that's okay, although the default constructor and subsequent reallocation(s) isn't ideal, the odds are it's good enough — and the concatenation is a lot more readable.

But that's only for a single expression. Multiple StringBuilders are used for this:

String s;
s = "prefix ";
s += variable1;
s += " middle ";
s += variable2;
s += " end";
return s;

That ends up becoming something like this:

String s;
StringBuilder tmp;
s = "prefix ";
tmp = new StringBuilder();
tmp.append(s);
tmp.append(variable1);
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(" middle ");
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(variable2);
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(" end");
s = tmp.toString();
return s;

...which is pretty ugly.

It's important to remember, though, that in all but a very few cases it doesn't matter and going with readability (which enhances maintainability) is preferred barring a specific performance issue.

How do I use floating-point division in bash?

There are scenarios in wich you cannot use bc becouse it might simply not be present, like in some cut down versions of busybox or embedded systems. In any case limiting outer dependencies is always a good thing to do so you can always add zeroes to the number being divided by (numerator), that is the same as multiplying by a power of 10 (you should choose a power of 10 according to the precision you need), that will make the division output an integer number. Once you have that integer treat it as a string and position the decimal point (moving it from right to left) a number of times equal to the power of ten you multiplied the numerator by. This is a simple way of obtaining float results by using only integer numbers.

Search input with an icon Bootstrap 4

Update 2019

Why not use an input-group?

<div class="input-group col-md-4">
      <input class="form-control py-2" type="search" value="search" id="example-search-input">
      <span class="input-group-append">
        <button class="btn btn-outline-secondary" type="button">
            <i class="fa fa-search"></i>
        </button>
      </span>
</div>

And, you can make it appear inside the input using the border utils...

        <div class="input-group col-md-4">
            <input class="form-control py-2 border-right-0 border" type="search" value="search" id="example-search-input">
            <span class="input-group-append">
              <button class="btn btn-outline-secondary border-left-0 border" type="button">
                    <i class="fa fa-search"></i>
              </button>
            </span>
        </div>

Or, using a input-group-text w/o the gray background so the icon appears inside the input...

        <div class="input-group">
            <input class="form-control py-2 border-right-0 border" type="search" value="search" id="example-search-input">
            <span class="input-group-append">
                <div class="input-group-text bg-transparent"><i class="fa fa-search"></i></div>
            </span>
        </div>

Alternately, you can use the grid (row>col-) with no gutter spacing:

<div class="row no-gutters">
     <div class="col">
          <input class="form-control border-secondary border-right-0 rounded-0" type="search" value="search" id="example-search-input4">
     </div>
     <div class="col-auto">
          <button class="btn btn-outline-secondary border-left-0 rounded-0 rounded-right" type="button">
             <i class="fa fa-search"></i>
          </button>
     </div>
</div>

Or, prepend the icon like this...

<div class="input-group">
  <span class="input-group-prepend">
    <div class="input-group-text bg-transparent border-right-0">
      <i class="fa fa-search"></i>
    </div>
  </span>
  <input class="form-control py-2 border-left-0 border" type="search" value="..." id="example-search-input" />
  <span class="input-group-append">
    <button class="btn btn-outline-secondary border-left-0 border" type="button">
     Search
    </button>
  </span>
</div>

Demo of all Bootstrap 4 icon input options


enter image description here


Example with validation icons

/bin/sh: apt-get: not found

The image you're using is Alpine based, so you can't use apt-get because it's Ubuntu's package manager.

To fix this just use:

apk update and apk add

Why can't I center with margin: 0 auto?

We can set the width for ul tag then it will align center.

#header ul {
    display: block;
    margin: 0 auto;
    width: 420px;
    max-width: 100%;
}

Angular 2 declaring an array of objects

Datatype: array_name:datatype[]=[]; Example string: users:string[]=[];

For array of objects:

Objecttype: object_name:objecttype[]=[{}]; Example user: Users:user[]=[{}];

And if in some cases it's coming undefined in binding, make sure to initialize it on Oninit().

How to move certain commits to be based on another branch in git?

This is a classic case of rebase --onto:

 # let's go to current master (X, where quickfix2 should begin)
 git checkout master

 # replay every commit *after* quickfix1 up to quickfix2 HEAD.
 git rebase --onto master quickfix1 quickfix2 

So you should go from

o-o-X (master HEAD)
     \ 
      q1a--q1b (quickfix1 HEAD)
              \
               q2a--q2b (quickfix2 HEAD)

to:

      q2a'--q2b' (new quickfix2 HEAD)
     /
o-o-X (master HEAD)
     \ 
      q1a--q1b (quickfix1 HEAD)

This is best done on a clean working tree.
See git config --global rebase.autostash true, especially after Git 2.10.