Programs & Examples On #Ftp4j

The ftp4j library implements a Java full-features FTP client. With ftp4j embedded in your application you can: transfer files (upload and download), browse the remote FTP site (directory listing included), create, delete, rename and move remote directories and files. Source: http://www.sauronsoftware.it/projects/ftp4j/index.php

Windows shell command to get the full path to the current directory?

Quote the Windows help for the set command (set /?):

If Command Extensions are enabled, then there are several dynamic
environment variables that can be expanded but which don't show up in
the list of variables displayed by SET.  These variable values are
computed dynamically each time the value of the variable is expanded.
If the user explicitly defines a variable with one of these names, then
that definition will override the dynamic one described below:

%CD% - expands to the current directory string.

%DATE% - expands to current date using same format as DATE command.

%TIME% - expands to current time using same format as TIME command.

%RANDOM% - expands to a random decimal number between 0 and 32767.

%ERRORLEVEL% - expands to the current ERRORLEVEL value

%CMDEXTVERSION% - expands to the current Command Processor Extensions
    version number.

%CMDCMDLINE% - expands to the original command line that invoked the
    Command Processor.

Note the %CD% - expands to the current directory string. part.

How to give environmental variable path for file appender in configuration file in log4j

This syntax is documented only in log4j 2.X so make sure you are using the correct version.

    <Appenders>
    <File name="file" fileName="${env:LOG_PATH}">
        <PatternLayout>
            <Pattern>%d %p %c{1.} [%t] %m %ex%n</Pattern>
        </PatternLayout>
    </File>
</Appenders>

http://logging.apache.org/log4j/2.x/manual/lookups.html#EnvironmentLookup

jQuery: How can I create a simple overlay?

If you're already using jquery, I don't see why you wouldn't also be able to use a lightweight overlay plugin. Other people have already written some nice ones in jquery, so why re-invent the wheel?

How to connect from windows command prompt to mysql command line

The cd in your question is invalid (quoting it here because you've removed it once, and it was there when this answer was posted):

cd CD:\MYSQL\bin\

You can't cd to CD:\ anything, because CD:\ isn't a valid directory in Windows. CD: would indicate a drive, except that drives are restricted to a single letter between A and Z.

If your \MYSQL\BIN is on drive C:, then your commands need to be:

C:\>cd \MYSQL\Bin
C:\MYSQL\Bin>mysql -u root -p admin

If you're not already on C: (which you'll know by looking at the prompt in the cmd window), or your MySQL folder is on another drive (for instance, D:), change to that drive too:

C:\> cd /d D:\MYSQL\Bin
D:\MYSQL\Bin>mysql -u root -p admin

The .exe after mysql is optional, since .exe is an executable extension on Windows. If you type mysql, Windows will automatically look for an executable file with that name and run it if it finds it.

Note that in both my examples of running mysql, there are no = signs. You should just use -p with no password, and wait to be prompted for it instead.

Use Async/Await with Axios in React.js

Two issues jump out:

  1. Your getData never returns anything, so its promise (async functions always return a promise) will resolve with undefined when it resolves

  2. The error message clearly shows you're trying to directly render the promise getData returns, rather than waiting for it to resolve and then rendering the resolution

Addressing #1: getData should return the result of calling json:

async getData(){
   const res = await axios('/data');
   return await res.json();
}

Addressig #2: We'd have to see more of your code, but fundamentally, you can't do

<SomeElement>{getData()}</SomeElement>

...because that doesn't wait for the resolution. You'd need instead to use getData to set state:

this.getData().then(data => this.setState({data}))
              .catch(err => { /*...handle the error...*/});

...and use that state when rendering:

<SomeElement>{this.state.data}</SomeElement>

Update: Now that you've shown us your code, you'd need to do something like this:

class App extends React.Component{
    async getData() {
        const res = await axios('/data');
        return await res.json(); // (Or whatever)
    }
    constructor(...args) {
        super(...args);
        this.state = {data: null};
    }
    componentDidMount() {
        if (!this.state.data) {
            this.getData().then(data => this.setState({data}))
                          .catch(err => { /*...handle the error...*/});
        }
    }
    render() {
        return (
            <div>
                {this.state.data ? <em>Loading...</em> : this.state.data}
            </div>
        );
    }
}

Futher update: You've indicated a preference for using await in componentDidMount rather than then and catch. You'd do that by nesting an async IIFE function within it and ensuring that function can't throw. (componentDidMount itself can't be async, nothing will consume that promise.) E.g.:

class App extends React.Component{
    async getData() {
        const res = await axios('/data');
        return await res.json(); // (Or whatever)
    }
    constructor(...args) {
        super(...args);
        this.state = {data: null};
    }
    componentDidMount() {
        if (!this.state.data) {
            (async () => {
                try {
                    this.setState({data: await this.getData()});
                } catch (e) {
                    //...handle the error...
                }
            })();
        }
    }
    render() {
        return (
            <div>
                {this.state.data ? <em>Loading...</em> : this.state.data}
            </div>
        );
    }
}

How to present a modal atop the current view in Swift

The only way I able to get this to work was by doing this on the presenting view controller:

    func didTapButton() {
    self.definesPresentationContext = true
    self.modalTransitionStyle = .crossDissolve
    let yourVC = self.storyboard?.instantiateViewController(withIdentifier: "YourViewController") as! YourViewController
    let navController = UINavigationController(rootViewController: yourVC)
    navController.modalPresentationStyle = .overCurrentContext
    navController.modalTransitionStyle = .crossDissolve
    self.present(navController, animated: true, completion: nil)
}

Concatenate strings from several rows using Pandas groupby

You can groupby the 'name' and 'month' columns, then call transform which will return data aligned to the original df and apply a lambda where we join the text entries:

In [119]:

df['text'] = df[['name','text','month']].groupby(['name','month'])['text'].transform(lambda x: ','.join(x))
df[['name','text','month']].drop_duplicates()
Out[119]:
    name         text  month
0  name1       hej,du     11
2  name1        aj,oj     12
4  name2     fin,katt     11
6  name2  mycket,lite     12

I sub the original df by passing a list of the columns of interest df[['name','text','month']] here and then call drop_duplicates

EDIT actually I can just call apply and then reset_index:

In [124]:

df.groupby(['name','month'])['text'].apply(lambda x: ','.join(x)).reset_index()

Out[124]:
    name  month         text
0  name1     11       hej,du
1  name1     12        aj,oj
2  name2     11     fin,katt
3  name2     12  mycket,lite

update

the lambda is unnecessary here:

In[38]:
df.groupby(['name','month'])['text'].apply(','.join).reset_index()

Out[38]: 
    name  month         text
0  name1     11           du
1  name1     12        aj,oj
2  name2     11     fin,katt
3  name2     12  mycket,lite

How to SELECT the last 10 rows of an SQL table which has no ID field?

If you know how many rows to expect, I would create a separate temporary table in your database of the expected structure, append into that, then check the count... Once you are good with that, then you can massage that data before appending it into your final production table.

jQuery $.cookie is not a function

You should add first jquery.cookie.js then add your js or jQuery where you are using that function.

When browser loads the webpage first it loads this jquery.cookie.js and after then you js or jQuery and now that function is available for use

Hash and salt passwords in C#

In answer to this part of the original question "Is there any other C# method for hashing passwords" You can achieve this using ASP.NET Identity v3.0 https://www.nuget.org/packages/Microsoft.AspNet.Identity.EntityFramework/3.0.0-rc1-final

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using System.Security.Principal;

namespace HashTest{


    class Program
    {
        static void Main(string[] args)
        {

            WindowsIdentity wi = WindowsIdentity.GetCurrent();

            var ph = new PasswordHasher<WindowsIdentity>();

            Console.WriteLine(ph.HashPassword(wi,"test"));

            Console.WriteLine(ph.VerifyHashedPassword(wi,"AQAAAAEAACcQAAAAEA5S5X7dmbx/NzTk6ixCX+bi8zbKqBUjBhID3Dg1teh+TRZMkAy3CZC5yIfbLqwk2A==","test"));

        }
    }


}

Why is `input` in Python 3 throwing NameError: name... is not defined

If we setaside the syntax error of print, then the way to use input in multiple scenarios are -

If using python 2.x :

then for evaluated input use "input"
example: number = input("enter a number")

and for string use "raw_input"
example: name = raw_input("enter your name")

If using python 3.x :

then for evaluated result use "eval" and "input"
example: number = eval(input("enter a number"))

for string use "input"
example: name = input("enter your name")

Find the files that have been changed in last 24 hours

For others who land here in the future (including myself), add a -name option to find specific file types, for instance: find /var -name "*.php" -mtime -1 -ls

Eclipse - debugger doesn't stop at breakpoint

Also verify if breakpoints on other lines DO work, it may be a bug in the debugger. I have had a problem with the Eclipse debugger where putting a breakpoint on a boolean assignment whose code was on the next line didn't work I reported this here, but putting it on the previous or next line did.

How to remove item from a JavaScript object

_x000D_
_x000D_
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
_x000D_
_x000D_

this deletes test.blue

batch script - read line by line

This has worked for me in the past and it will even expand environment variables in the file if it can.

for /F "delims=" %%a in (LogName.txt) do (
     echo %%a>>MyDestination.txt
)

How to disable right-click context-menu in JavaScript

You can't rely on context menus because the user can deactivate it. Most websites want to use the feature to annoy the visitor.

HTML5 Canvas Resize (Downscale) Image High Quality?

DEMO: Resizing images with JS and HTML Canvas Demo fiddler.

You may find 3 different methods to do this resize, that will help you understand how the code is working and why.

https://jsfiddle.net/1b68eLdr/93089/

Full code of both demo, and TypeScript method that you may want to use in your code, can be found in the GitHub project.

https://github.com/eyalc4/ts-image-resizer

This is the final code:

export class ImageTools {
base64ResizedImage: string = null;

constructor() {
}

ResizeImage(base64image: string, width: number = 1080, height: number = 1080) {
    let img = new Image();
    img.src = base64image;

    img.onload = () => {

        // Check if the image require resize at all
        if(img.height <= height && img.width <= width) {
            this.base64ResizedImage = base64image;

            // TODO: Call method to do something with the resize image
        }
        else {
            // Make sure the width and height preserve the original aspect ratio and adjust if needed
            if(img.height > img.width) {
                width = Math.floor(height * (img.width / img.height));
            }
            else {
                height = Math.floor(width * (img.height / img.width));
            }

            let resizingCanvas: HTMLCanvasElement = document.createElement('canvas');
            let resizingCanvasContext = resizingCanvas.getContext("2d");

            // Start with original image size
            resizingCanvas.width = img.width;
            resizingCanvas.height = img.height;


            // Draw the original image on the (temp) resizing canvas
            resizingCanvasContext.drawImage(img, 0, 0, resizingCanvas.width, resizingCanvas.height);

            let curImageDimensions = {
                width: Math.floor(img.width),
                height: Math.floor(img.height)
            };

            let halfImageDimensions = {
                width: null,
                height: null
            };

            // Quickly reduce the size by 50% each time in few iterations until the size is less then
            // 2x time the target size - the motivation for it, is to reduce the aliasing that would have been
            // created with direct reduction of very big image to small image
            while (curImageDimensions.width * 0.5 > width) {
                // Reduce the resizing canvas by half and refresh the image
                halfImageDimensions.width = Math.floor(curImageDimensions.width * 0.5);
                halfImageDimensions.height = Math.floor(curImageDimensions.height * 0.5);

                resizingCanvasContext.drawImage(resizingCanvas, 0, 0, curImageDimensions.width, curImageDimensions.height,
                    0, 0, halfImageDimensions.width, halfImageDimensions.height);

                curImageDimensions.width = halfImageDimensions.width;
                curImageDimensions.height = halfImageDimensions.height;
            }

            // Now do final resize for the resizingCanvas to meet the dimension requirments
            // directly to the output canvas, that will output the final image
            let outputCanvas: HTMLCanvasElement = document.createElement('canvas');
            let outputCanvasContext = outputCanvas.getContext("2d");

            outputCanvas.width = width;
            outputCanvas.height = height;

            outputCanvasContext.drawImage(resizingCanvas, 0, 0, curImageDimensions.width, curImageDimensions.height,
                0, 0, width, height);

            // output the canvas pixels as an image. params: format, quality
            this.base64ResizedImage = outputCanvas.toDataURL('image/jpeg', 0.85);

            // TODO: Call method to do something with the resize image
        }
    };
}}

Select values of checkbox group with jQuery

You could use the checked selector to grab only the selected ones (negating the need to know the count or to iterate over them all yourself):

$("input[name='user_group[]']:checked")

With those checked items, you can either create a collection of those values or do something to the collection:

var values = new Array();
$.each($("input[name='user_group[]']:checked"), function() {
  values.push($(this).val());
  // or you can do something to the actual checked checkboxes by working directly with  'this'
  // something like $(this).hide() (only something useful, probably) :P
});

Hide horizontal scrollbar on an iframe?

I'd suggest doing this with a combination of

  1. CSS overflow-y: hidden;
  2. scrolling="no" (for HTML4)
  3. and seamless="seamless" (for HTML5)*

* The seamless attribute has been removed from the standard, and no browsers support it.


_x000D_
_x000D_
.foo {_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  overflow-y: hidden;_x000D_
}
_x000D_
<iframe src="https://bing.com" _x000D_
        class="foo" _x000D_
        scrolling="no" >_x000D_
</iframe>
_x000D_
_x000D_
_x000D_

WordPress is giving me 404 page not found for all pages except the homepage

If your WordPress installation is in a subfolder (ex. https://www.example.com/subfolder) change this line in your WordPress .htaccess

RewriteRule . /index.php [L]

to

RewriteRule . /subfolder/index.php [L]

By doing so, you are telling the server to look for WordPress index.php in the WordPress folder (ex. https://www.example.com/subfolder) rather than in the public folder (ex. https://www.example.com).

jQuery add text to span within a div

You can use append or prepend

The .append() method inserts the specified content as the last child of each element in the jQuery collection (To insert it as the first child, use .prepend()).

$("#tagscloud span").append(second);
$("#tagscloud span").append(third);
$("#tagscloud span").prepend(first);

What's the best way to send a signal to all members of a process group?

In sh the jobs command will list the background processes. In some cases it might be better to kill the newest process first, e.g. the older one created a shared socket. In those cases sort the PIDs in reverse order. Sometimes you want to wait moment for the jobs to write something on disk or stuff like that before they stop.

And don't kill if you don't have to!

for SIGNAL in TERM KILL; do
  for CHILD in $(jobs -s|sort -r); do
    kill -s $SIGNAL $CHILD
    sleep $MOMENT
  done
done

Twitter Bootstrap hide css class and jQuery

I agree with dfsq if all you want to do is show the button. If you want to switch between hiding and showing the button however, it is easier to use:

$("#buttonEditComment").toggleClass("hide");

oracle sql: update if exists else insert

The way I always do it (assuming the data is never to be deleted, only inserted) is to

  • Firstly do an insert, if this fails with a unique constraint violation then you know the row is there,
  • Then do an update

Unfortunately many frameworks such as Hibernate treat all database errors (e.g. unique constraint violation) as unrecoverable conditions, so it isn't always easy. (In Hibernate the solution is to open a new session/transaction just to execute this one insert command.)

You can't just do a select count(*) .. where .. as even if that returns zero, and therefore you choose to do an insert, between the time you do the select and the insert someone else might have inserted the row and therefore your insert will fail.

Mockito: InvalidUseOfMatchersException

Do not use Mockito.anyXXXX(). Directly pass the value to the method parameter of same type. Example:

A expected = new A(10);

String firstId = "10w";
String secondId = "20s";
String product = "Test";
String type = "type2";
Mockito.when(service.getTestData(firstId, secondId, product,type)).thenReturn(expected);

public class A{
   int a ;
   public A(int a) {
      this.a = a;
   }
}

Program "make" not found in PATH

I had the same problem. Initially I had setup Eclipse CDT with Cygwing & was working smoothly. One day there happened a problem due to which I had to reset windows. After that when I opened Eclipse I started facing the issue described above. This is how I solved it.

First I searched that in the error the PATH variable value is same as the PATH variable of windows ( just by manual comparison of both two values ). I found that to be same. Now I realized that it is a PATH problem.

Then started looking for Cygwin whether it is there or not? It was there. I located & found that it exists in

C:\cygwin64\bin>
C:\cygwin64\bin>dir ma*
 Volume in drive C is Windows8_OS
 Volume Serial Number is 042E-11B5

 Directory of C:\cygwin64\bin

16-05-2015  18:34            10,259 mag.exe
13-08-2013  04:57               384 mailmail
11-04-2015  02:56             4,252 make-emacs-shortcut
15-02-2015  23:25           194,579 make.exe
04-05-2015  21:36            40,979 makeconv.exe
29-07-2013  11:57            29,203 makedepend.exe
16-05-2015  18:34            79,891 makeindex.exe
16-05-2015  18:34            34,323 makejvf.exe
07-05-2015  03:04               310 mako-render
18-04-2015  02:07            92,179 man.exe
18-04-2015  02:07           113,683 mandb.exe
13-08-2013  04:57               286 manhole
18-04-2015  02:07            29,203 manpath.exe
24-10-2014  13:31           274,461 mate-terminal.exe
24-10-2014  13:31             1,366 mate-terminal.wrapper
              15 File(s)        905,358 bytes
               0 Dir(s)  373,012,271,104 bytes free

C:\cygwin64\bin>

Then I simply went ahead & updated the PATH variable to include this path & restarted eclipse.

The code compiles & debugging (GDB ) is working nicely.

Hope this helps.

Standard concise way to copy a file in Java?

Note that all of these mechanisms only copy the contents of the file, not the metadata such as permissions. So if you were to copy or move an executable .sh file on linux the new file would not be executable.

In order to truly a copy or move a file, ie to get the same result as copying from a command line, you actually need to use a native tool. Either a shell script or JNI.

Apparently, this might be fixed in java 7 - http://today.java.net/pub/a/today/2008/07/03/jsr-203-new-file-apis.html. Fingers crossed!

How to wait for a number of threads to complete?

Depending on your needs, you may also want to check out the classes CountDownLatch and CyclicBarrier in the java.util.concurrent package. They can be useful if you want your threads to wait for each other, or if you want more fine-grained control over the way your threads execute (e.g., waiting in their internal execution for another thread to set some state). You could also use a CountDownLatch to signal all of your threads to start at the same time, instead of starting them one by one as you iterate through your loop. The standard API docs have an example of this, plus using another CountDownLatch to wait for all threads to complete their execution.

Check if int is between two numbers

The inconvenience of typing 10 < x && x < 20 is minimal compared to the increase in language complexity if one would allow 10 < x < 20, so the designers of the Java language decided against supporting it.

CSS to keep element at "fixed" position on screen

position: sticky;

The sticky element sticks on top of the page (top: 0) when you reach its scroll position.

See example: https://www.w3schools.com/css/tryit.asp?filename=trycss_position_sticky

How can I make Java print quotes, like "Hello"?

char ch='"';

System.out.println(ch + "String" + ch);

Or

System.out.println('"' + "ASHISH" + '"');

COALESCE with Hive SQL

From [Hive Language Manual][1]:

COALESCE (T v1, T v2, ...)

Will return the first value that is not NULL, or NULL if all values's are NULL

https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-ConditionalFunctions

installing apache: no VCRUNTIME140.dll

Also, please make sure you installed the correct version of apache on your computer. For example, not install a x86 on a 64bit system. Vice versa.

What's the difference between a 302 and a 307 redirect?

A good example of the 307 Internal Redirect in action is when Google Chrome encounters a HTTP call to a domain it knows as requiring Strict Transport Security.

The browser redirects seamlessly, using the same method as the original call.

HTST 307 Internal Redirect

How do you push a tag to a remote repository using Git?

To expand on Trevor's answer, you can push a single tag or all of your tags at once.

Push a Single Tag

git push <remote> <tag>

This is a summary of the relevant documentation that explains this (some command options omitted for brevity):

git push [[<repository> [<refspec>…]]

<refspec>...

The format of a <refspec> parameter is…the source ref <src>, followed by a colon :, followed by the destination ref <dst>

The <dst> tells which ref on the remote side is updated with this push…If :<dst> is omitted, the same ref as <src> will be updated…

tag <tag> means the same as refs/tags/<tag>:refs/tags/<tag>.

Push All of Your Tags at Once

git push --tags <remote>
# Or
git push <remote> --tags

Here is a summary of the relevant documentation (some command options omitted for brevity):

git push [--all | --mirror | --tags] [<repository> [<refspec>…]]

--tags

All refs under refs/tags are pushed, in addition to refspecs explicitly listed on the command line.

How to get file's last modified date on Windows command line?

Useful reference to get file properties using a batch file, included is the last modified time:

FOR %%? IN ("C:\somefile\path\file.txt") DO (
    ECHO File Name Only       : %%~n?
    ECHO File Extension       : %%~x?
    ECHO Name in 8.3 notation : %%~sn?
    ECHO File Attributes      : %%~a?
    ECHO Located on Drive     : %%~d?
    ECHO File Size            : %%~z?
    ECHO Last-Modified Date   : %%~t?
    ECHO Drive and Path       : %%~dp?
    ECHO Drive                : %%~d?
    ECHO Fully Qualified Path : %%~f?
    ECHO FQP in 8.3 notation  : %%~sf?
    ECHO Location in the PATH : %%~dp$PATH:?
)

Specifying colClasses in the read.csv

Assuming your 'time' column has at least one observation with a non-numeric character and all your other columns only have numbers, then 'read.csv's default will be to read in 'time' as a 'factor' and all the rest of the columns as 'numeric'. Therefore setting 'stringsAsFactors=F' will have the same result as setting the 'colClasses' manually i.e.,

data <- read.csv('test.csv', stringsAsFactors=F)

How to loop over directories in Linux?

All answers so far use find, so here's one with just the shell. No need for external tools in your case:

for dir in /tmp/*/     # list directories in the form "/tmp/dirname/"
do
    dir=${dir%*/}      # remove the trailing "/"
    echo "${dir##*/}"    # print everything after the final "/"
done

Date format Mapping to JSON Jackson

Since Jackson v2.0, you can use @JsonFormat annotation directly on Object members;

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm a z")
private Date date;

How do you get the currently selected <option> in a <select> via JavaScript?

This will do it for you:

var yourSelect = document.getElementById( "your-select-id" );
alert( yourSelect.options[ yourSelect.selectedIndex ].value )

How do I determine scrollHeight?

scrollHeight is a regular javascript property so you don't need jQuery.

var test = document.getElementById("foo").scrollHeight;

How to open a WPF Popup when another control is clicked, using XAML markup only?

I did something simple, but it works.

I used a typical ToggleButton, which I restyled as a textblock by changing its control template. Then I just bound the IsChecked property on the ToggleButton to the IsOpen property on the popup. Popup has some properties like StaysOpen that let you modify the closing behavior.

The following works in XamlPad.

 <StackPanel>
  <ToggleButton Name="button"> 
    <ToggleButton.Template>
      <ControlTemplate TargetType="ToggleButton">
        <TextBlock>Click Me Here!!</TextBlock>
      </ControlTemplate>      
    </ToggleButton.Template>
  </ToggleButton>
  <Popup IsOpen="{Binding IsChecked, ElementName=button}" StaysOpen="False">
    <Border Background="LightYellow">
      <TextBlock>I'm the popup</TextBlock>
    </Border>
  </Popup> 
 </StackPanel>

Linker Error C++ "undefined reference "

This error tells you everything:

undefined reference toHash::insert(int, char)

You're not linking with the implementations of functions defined in Hash.h. Don't you have a Hash.cpp to also compile and link?

Copy/duplicate database without using mysqldump

You can duplicate a table without data by running:

CREATE TABLE x LIKE y;

(See the MySQL CREATE TABLE Docs)

You could write a script that takes the output from SHOW TABLES from one database and copies the schema to another. You should be able to reference schema+table names like:

CREATE TABLE x LIKE other_db.y;

As far as the data goes, you can also do it in MySQL, but it's not necessarily fast. After you've created the references, you can run the following to copy the data:

INSERT INTO x SELECT * FROM other_db.y;

If you're using MyISAM, you're better off to copy the table files; it'll be much faster. You should be able to do the same if you're using INNODB with per table table spaces.

If you do end up doing an INSERT INTO SELECT, be sure to temporarily turn off indexes with ALTER TABLE x DISABLE KEYS!

EDIT Maatkit also has some scripts that may be helpful for syncing data. It may not be faster, but you could probably run their syncing scripts on live data without much locking.

How can I auto increment the C# assembly version via our CI platform (Hudson)?

Here's what I did, for stamping the AssemblyFileVersion attribute.

Removed the AssemblyFileVersion from AssemblyInfo.cs

Add a new, empty, file called AssemblyFileInfo.cs to the project.

Install the MSBuild community tasks toolset on the hudson build machine or as a NuGet dependency in your project.

Edit the project (csproj) file , it's just an msbuild file, and add the following.

Somewhere there'll be a <PropertyGroup> stating the version. Change that so it reads e.g.

 <Major>1</Major>
 <Minor>0</Minor>
 <!--Hudson sets BUILD_NUMBER and SVN_REVISION -->
 <Build>$(BUILD_NUMBER)</Build>
 <Revision>$(SVN_REVISION)</Revision>

Hudson provides those env variables you see there when the project is built on hudson (assuming it's fetched from subversion).

At the bottom of the project file, add

 <Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets" Condition="Exists('$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets')" />
  <Target Name="BeforeBuild" Condition="Exists('$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets')">
    <Message Text="Version: $(Major).$(Minor).$(Build).$(Revision)" />
    <AssemblyInfo CodeLanguage="CS" OutputFile="AssemblyFileInfo.cs" AssemblyFileVersion="$(Major).$(Minor).$(Build).$(Revision)" AssemblyConfiguration="$(Configuration)" Condition="$(Revision) != '' " />
  </Target>

This uses the MSBuildCommunityTasks to generate the AssemblyFileVersion.cs to include an AssemblyFileVersion attribute before the project is built. You could do this for any/all of the version attributes if you want.

The result is, whenever you issue a hudson build, the resulting assembly gets an AssemblyFileVersion of 1.0.HUDSON_BUILD_NR.SVN_REVISION e.g. 1.0.6.2632 , which means the 6'th build # in hudson, buit from the subversion revision 2632.

How I can delete in VIM all text from current line to end of file?

dG will delete from the current line to the end of file

dCtrl+End will delete from the cursor to the end of the file

But if this file is as large as you say, you may be better off reading the first few lines with head rather than editing and saving the file.

head hugefile > firstlines

(If you are on Windows you can use the Win32 port of head)

How to set image in circle in swift

This way is the least expensive way and always keeps your image view rounded:

class RoundedImageView: UIImageView {

    override init(frame: CGRect) {
        super.init(frame: frame)

        clipsToBounds = true
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        clipsToBounds = true
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        assert(bounds.height == bounds.width, "The aspect ratio isn't 1/1. You can never round this image view!")

        layer.cornerRadius = bounds.height / 2
    }
}

The other answers are telling you to make views rounded based on frame calculations set in a UIViewControllers viewDidLoad() method. This isn't correct, since it isn't sure what the final frame will be.

no overload for matches delegate 'system.eventhandler'

You need to wrap button click handler to match the pattern

public void klik(object sender, EventArgs e)

.autocomplete is not a function Error

Note that if you're not using the full jquery UI library, this can be triggered if you're missing Widget, Menu, Position, or Core. There might be different dependencies depending on your version of jQuery UI

Using std::max_element on a vector<double>

As others have said, std::max_element() and std::min_element() return iterators, which need to be dereferenced to obtain the value.

The advantage of returning an iterator (rather than just the value) is that it allows you to determine the position of the (first) element in the container with the maximum (or minimum) value.

For example (using C++11 for brevity):

#include <vector>
#include <algorithm>
#include <iostream>

int main()
{
    std::vector<double> v {1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0, 5.0};

    auto biggest = std::max_element(std::begin(v), std::end(v));
    std::cout << "Max element is " << *biggest
        << " at position " << std::distance(std::begin(v), biggest) << std::endl;

    auto smallest = std::min_element(std::begin(v), std::end(v));
    std::cout << "min element is " << *smallest
        << " at position " << std::distance(std::begin(v), smallest) << std::endl;
}

This yields:

Max element is 5 at position 4
min element is 1 at position 0

Note:

Using std::minmax_element() as suggested in the comments above may be faster for large data sets, but may give slightly different results. The values for my example above would be the same, but the position of the "max" element would be 9 since...

If several elements are equivalent to the largest element, the iterator to the last such element is returned.

TypeError: no implicit conversion of Symbol into Integer

You probably meant this:

require 'active_support/core_ext' # for titleize

myHash = {company_name:"MyCompany", street:"Mainstreet", postcode:"1234", city:"MyCity", free_seats:"3"}

def cleanup string
  string.titleize
end

def format(hash)
  output = {}
  output[:company_name] = cleanup(hash[:company_name])
  output[:street] = cleanup(hash[:street])
  output
end

format(myHash) # => {:company_name=>"My Company", :street=>"Mainstreet"}

Please read documentation on Hash#each

What are named pipes?

Compare

echo "test" | wc

to

mkdnod apipe p
wc apipe

wc will block until

echo "test" > apipe

executes

Convert an integer to an array of digits

Use:

public static void main(String[] args)
{
    int num = 1234567;
    int[] digits = Integer.toString(num).chars().map(c -> c-'0').toArray();
    for(int d : digits)
        System.out.print(d);
}

The main idea is

  1. Convert the int to its String value

    Integer.toString(num);
    
  2. Get a stream of int that represents the ASCII value of each char(~digit) composing the String version of our integer

    Integer.toString(num).chars();
    
  3. Convert the ASCII value of each character to its value. To get the actual int value of a character, we have to subtract the ASCII code value of the character '0' from the ASCII code of the actual character. To get all the digits of our number, this operation has to be applied on each character (corresponding to the digit) composing the string equivalent of our number which is done by applying the map function below to our IntStream.

    Integer.toString(num).chars().map(c -> c-'0');
    
  4. Convert the stream of int to an array of int using toArray()

     Integer.toString(num).chars().map(c -> c-'0').toArray();
    

Detect browser or tab closing

I found a way, that works on all of my browsers.

Tested on following versions: Firefox 57, Internet Explorer 11, Edge 41, one of the latested Chrome (it won't show my version)

Note: onbeforeunload fires if you leave the page in any way possible (refresh, close browser, redirect, link, submit..). If you only want it to happen on browser close, simply bind the event handlers.

  $(document).ready(function(){         

        var validNavigation = false;

        // Attach the event keypress to exclude the F5 refresh (includes normal refresh)
        $(document).bind('keypress', function(e) {
            if (e.keyCode == 116){
                validNavigation = true;
            }
        });

        // Attach the event click for all links in the page
        $("a").bind("click", function() {
            validNavigation = true;
        });

        // Attach the event submit for all forms in the page
        $("form").bind("submit", function() {
          validNavigation = true;
        });

        // Attach the event click for all inputs in the page
        $("input[type=submit]").bind("click", function() {
          validNavigation = true;
        }); 

        window.onbeforeunload = function() {                
            if (!validNavigation) {     
                // ------->  code comes here
            }
        };

  });

bash string compare to multiple correct values

Instead of saying:

if [ "$cms" != "wordpress" && "$cms" != "meganto" && "$cms" != "typo3" ]; then

say:

if [[ "$cms" != "wordpress" && "$cms" != "meganto" && "$cms" != "typo3" ]]; then

You might also want to refer to Conditional Constructs.

Which versions of SSL/TLS does System.Net.WebRequest support?

When using System.Net.WebRequest your application will negotiate with the server to determine the highest TLS version that both your application and the server support, and use this. You can see more details on how this works here:

http://en.wikipedia.org/wiki/Transport_Layer_Security#TLS_handshake

If the server doesn't support TLS it will fallback to SSL, therefore it could potentially fallback to SSL3. You can see all of the versions that .NET 4.5 supports here:

http://msdn.microsoft.com/en-us/library/system.security.authentication.sslprotocols(v=vs.110).aspx

In order to prevent your application being vulnerable to POODLE, you can disable SSL3 on the machine that your application is running on by following this explanation:

https://serverfault.com/questions/637207/on-iis-how-do-i-patch-the-ssl-3-0-poodle-vulnerability-cve-2014-3566

Call Activity method from adapter

One more way is::

Write a method in your adapter lets say public void callBack(){}.

Now while creating an object for adapter in activity override this method. Override method will be called when you call the method in adapter.

Myadapter adapter = new Myadapter() {
  @Override
  public void callBack() {
    // dosomething
  }
};

Java Minimum and Maximum values in Array

import java.util.*;
class Maxmin
{
    public static void main(String args[])
    {
        int[] arr = new int[10];
        Scanner in = new Scanner(System.in);
        int i, min=0, max=0;
        for(i=0; i<=arr.length; i++)
        {
            System.out.print("Enter any number: ");
            arr[i] = in.nextInt();          
        }
        min = arr[0];
        for(i=0; i<=9; i++)
        {
            if(arr[i] > max)
            {
                max = arr[i];
            }
            if(arr[i] < min)
            {
                min = arr[i];
            }
        }
        System.out.println("Maximum is: " + max);
        System.out.println("Minimum is: " + min);
    }
}

Gray out image with CSS?

Considering filter:expression is a Microsoft extension to CSS, so it will only work in Internet Explorer. If you want to grey it out, I would recommend that you set it's opacity to 50% using a bit of javascript.

http://lyxus.net/mv would be a good place to start, because it discusses an opacity script that works with Firefox, Safari, KHTML, Internet Explorer and CSS3 capable browsers.

You might also want to give it a grey border.

Calling startActivity() from outside of an Activity?

if your android version is below Android - 6 then you need to add this line otherwise it will work above Android - 6.

...
Intent i = new Intent(this, Wakeup.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
...

Post multipart request with Android SDK

For posterity, I didn't see okhttp mentioned. Related post.

Basically you build up the body using a MultipartBody.Builder, and then post this in a request.

Example in kotlin:

    val body = MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart(
                "file", 
                file.getName(),
                RequestBody.create(MediaType.parse("image/png"), file)
            )
            .addFormDataPart("timestamp", Date().time.toString())
            .build()

    val request = Request.Builder()
            .url(url)
            .post(body)
            .build()

    httpClient.newCall(request).enqueue(object : okhttp3.Callback {
        override fun onFailure(call: Call?, e: IOException?) {
            ...
        }

        override fun onResponse(call: Call?, response: Response?) {
            ...
        }
    })

document.getelementbyId will return null if element is not defined?

Yes it will return null if it's not present you can try this below in the demo. Both will return true. The first elements exists the second doesn't.

Demo

Html

<div id="xx"></div>

Javascript:

   if (document.getElementById('xx') !=null) 
     console.log('it exists!');

   if (document.getElementById('xxThisisNotAnElementOnThePage') ==null) 
     console.log('does not exist!');

java.lang.OutOfMemoryError: bitmap size exceeds VM budget - Android

The BitmapFactory.decode* methods, discussed in the Load Large Bitmaps Efficiently lesson, should not be executed on the main UI thread if the source data is read from disk or a network location (or really any source other than memory). The time this data takes to load is unpredictable and depends on a variety of factors (speed of reading from disk or network, size of image, power of CPU, etc.). If one of these tasks blocks the UI thread, the system flags your application as non-responsive and the user has the option of closing it (see Designing for Responsiveness for more information).

Check if element at position [x] exists in the list

if(list.ElementAtOrDefault(2) != null)
{
   // logic
}

ElementAtOrDefault() is part of the System.Linq namespace.

Although you have a List, so you can use list.Count > 2.

Altering a column to be nullable

This depends on what SQL Engine you are using, in Sybase your command works fine:

ALTER TABLE Merchant_Pending_Functions 
Modify NumberOfLocations NULL;

Converting an array to a function arguments list

@bryc - yes, you could do it like this:

Element.prototype.setAttribute.apply(document.body,["foo","bar"])

But that seems like a lot of work and obfuscation compared to:

document.body.setAttribute("foo","bar")

Mysql Compare two datetime fields

Do you want to order it?

Select * From temp where mydate > '2009-06-29 04:00:44' ORDER BY mydate;

How do I add Git version control (Bitbucket) to an existing source code folder?

The commands are given in your Bitbucket account. When you open the repository in Bitbucket, it gives you the entire list of commands you need to execute in the order. What is missing is where exactly you need to execute those commands (Git CLI, SourceTree terminal).

I struggled with these commands as I was writing these in Git CLI, but we need to execute the commands in the SourceTree terminal window and the repository will be added to Bitbucket.

VBA shorthand for x=x+1?

If you want to call the incremented number directly in a function, this solution works bettter:

Function inc(ByRef data As Integer)
    data = data + 1
    inc = data
End Function

for example:

Wb.Worksheets(mySheet).Cells(myRow, inc(myCol))

If the function inc() returns no value, the above line will generate an error.

How can I open a link in a new window?

I just found an interesting solution to this issue. I was creating spans which contain information based on the return from a web service. I thought about trying to put a link around the span so that if I clicked on it, the "a" would capture the click.

But I was trying to capture the click with the span... so I thought why not do this when I created the span.

var span = $('<span id="something" data-href="'+url+'" />');

I then bound a click handler to the span which created a link based on the 'data-href' attribute:

span.click(function(e) {
    e.stopPropagation();
    var href = $(this).attr('data-href');
    var link = $('<a href="http://' + href + '" />');
    link.attr('target', '_blank');
    window.open(link.attr('href'));
});

This successfully allowed me to click on a span and open a new window with a proper url.

ERROR Source option 1.5 is no longer supported. Use 1.6 or later

This error might be also for plugin versions. You can fix it in the .POM file like the followings:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.1</version>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
            </configuration>
        </plugin>
    </plugins>
</build>

How can a file be copied?

You can use one of the copy functions from the shutil package:

??????????????????????????????????????????????????????????????????????????????
Function              preserves     supports          accepts     copies other
                      permissions   directory dest.   file obj    metadata  
------------------------------------------------------------------------------
shutil.copy              ?             ?                 ?           ?
shutil.copy2             ?             ?                 ?           ?
shutil.copyfile          ?             ?                 ?           ?
shutil.copyfileobj       ?             ?                 ?           ?
??????????????????????????????????????????????????????????????????????????????

Example:

import shutil
shutil.copy('/etc/hostname', '/var/tmp/testhostname')

ES6 export default with multiple functions referring to each other

tl;dr: baz() { this.foo(); this.bar() }

In ES2015 this construct:

var obj = {
    foo() { console.log('foo') }
}

is equal to this ES5 code:

var obj = {
    foo : function foo() { console.log('foo') }
}

exports.default = {} is like creating an object, your default export translates to ES5 code like this:

exports['default'] = {
    foo: function foo() {
        console.log('foo');
    },
    bar: function bar() {
        console.log('bar');
    },
    baz: function baz() {
        foo();bar();
    }
};

now it's kind of obvious (I hope) that baz tries to call foo and bar defined somewhere in the outer scope, which are undefined. But this.foo and this.bar will resolve to the keys defined in exports['default'] object. So the default export referencing its own methods shold look like this:

export default {
    foo() { console.log('foo') }, 
    bar() { console.log('bar') },
    baz() { this.foo(); this.bar() }
}

See babel repl transpiled code.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". in a Maven Project

I am assuming you are using Eclipse as your developing environment.

Eclipse Juno, Indigo and Kepler when using the bundled maven version(m2e), are not suppressing the message SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". This behaviour is present from the m2e version 1.1.0.20120530-0009 and onwards.

Although, this is indicated as an error your logs will be saved normally. The highlighted error will still be present until there is a fix of this bug. More about this in the m2e support site.

The current available solution is to use an external maven version rather than the bundled version of Eclipse. You can find about this solution and more details regarding this bug in the question below which i believe describes the same problem you are facing.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

Compare two Lists for differences

I hope that I am understing your question correctly, but you can do this very quickly with Linq. I'm assuming that universally you will always have an Id property. Just create an interface to ensure this.

If how you identify an object to be the same changes from class to class, I would recommend passing in a delegate that returns true if the two objects have the same persistent id.

Here is how to do it in Linq:

List<Employee> listA = new List<Employee>();
        List<Employee> listB = new List<Employee>();

        listA.Add(new Employee() { Id = 1, Name = "Bill" });
        listA.Add(new Employee() { Id = 2, Name = "Ted" });

        listB.Add(new Employee() { Id = 1, Name = "Bill Sr." });
        listB.Add(new Employee() { Id = 3, Name = "Jim" });

        var identicalQuery = from employeeA in listA
                             join employeeB in listB on employeeA.Id equals employeeB.Id
                             select new { EmployeeA = employeeA, EmployeeB = employeeB };

        foreach (var queryResult in identicalQuery)
        {
            Console.WriteLine(queryResult.EmployeeA.Name);
            Console.WriteLine(queryResult.EmployeeB.Name);
        }

HTML5 record audio to file

The code shown below is copyrighted to Matt Diamond and available for use under MIT license. The original files are here:

Save this files and use

_x000D_
_x000D_
(function(window){_x000D_
_x000D_
      var WORKER_PATH = 'recorderWorker.js';_x000D_
      var Recorder = function(source, cfg){_x000D_
        var config = cfg || {};_x000D_
        var bufferLen = config.bufferLen || 4096;_x000D_
        this.context = source.context;_x000D_
        this.node = this.context.createScriptProcessor(bufferLen, 2, 2);_x000D_
        var worker = new Worker(config.workerPath || WORKER_PATH);_x000D_
        worker.postMessage({_x000D_
          command: 'init',_x000D_
          config: {_x000D_
            sampleRate: this.context.sampleRate_x000D_
          }_x000D_
        });_x000D_
        var recording = false,_x000D_
          currCallback;_x000D_
_x000D_
        this.node.onaudioprocess = function(e){_x000D_
          if (!recording) return;_x000D_
          worker.postMessage({_x000D_
            command: 'record',_x000D_
            buffer: [_x000D_
              e.inputBuffer.getChannelData(0),_x000D_
              e.inputBuffer.getChannelData(1)_x000D_
            ]_x000D_
          });_x000D_
        }_x000D_
_x000D_
        this.configure = function(cfg){_x000D_
          for (var prop in cfg){_x000D_
            if (cfg.hasOwnProperty(prop)){_x000D_
              config[prop] = cfg[prop];_x000D_
            }_x000D_
          }_x000D_
        }_x000D_
_x000D_
        this.record = function(){_x000D_
       _x000D_
          recording = true;_x000D_
        }_x000D_
_x000D_
        this.stop = function(){_x000D_
        _x000D_
          recording = false;_x000D_
        }_x000D_
_x000D_
        this.clear = function(){_x000D_
          worker.postMessage({ command: 'clear' });_x000D_
        }_x000D_
_x000D_
        this.getBuffer = function(cb) {_x000D_
          currCallback = cb || config.callback;_x000D_
          worker.postMessage({ command: 'getBuffer' })_x000D_
        }_x000D_
_x000D_
        this.exportWAV = function(cb, type){_x000D_
          currCallback = cb || config.callback;_x000D_
          type = type || config.type || 'audio/wav';_x000D_
          if (!currCallback) throw new Error('Callback not set');_x000D_
          worker.postMessage({_x000D_
            command: 'exportWAV',_x000D_
            type: type_x000D_
          });_x000D_
        }_x000D_
_x000D_
        worker.onmessage = function(e){_x000D_
          var blob = e.data;_x000D_
          currCallback(blob);_x000D_
        }_x000D_
_x000D_
        source.connect(this.node);_x000D_
        this.node.connect(this.context.destination);    //this should not be necessary_x000D_
      };_x000D_
_x000D_
      Recorder.forceDownload = function(blob, filename){_x000D_
        var url = (window.URL || window.webkitURL).createObjectURL(blob);_x000D_
        var link = window.document.createElement('a');_x000D_
        link.href = url;_x000D_
        link.download = filename || 'output.wav';_x000D_
        var click = document.createEvent("Event");_x000D_
        click.initEvent("click", true, true);_x000D_
        link.dispatchEvent(click);_x000D_
      }_x000D_
_x000D_
      window.Recorder = Recorder;_x000D_
_x000D_
    })(window);_x000D_
_x000D_
    //ADDITIONAL JS recorderWorker.js_x000D_
    var recLength = 0,_x000D_
      recBuffersL = [],_x000D_
      recBuffersR = [],_x000D_
      sampleRate;_x000D_
    this.onmessage = function(e){_x000D_
      switch(e.data.command){_x000D_
        case 'init':_x000D_
          init(e.data.config);_x000D_
          break;_x000D_
        case 'record':_x000D_
          record(e.data.buffer);_x000D_
          break;_x000D_
        case 'exportWAV':_x000D_
          exportWAV(e.data.type);_x000D_
          break;_x000D_
        case 'getBuffer':_x000D_
          getBuffer();_x000D_
          break;_x000D_
        case 'clear':_x000D_
          clear();_x000D_
          break;_x000D_
      }_x000D_
    };_x000D_
_x000D_
    function init(config){_x000D_
      sampleRate = config.sampleRate;_x000D_
    }_x000D_
_x000D_
    function record(inputBuffer){_x000D_
_x000D_
      recBuffersL.push(inputBuffer[0]);_x000D_
      recBuffersR.push(inputBuffer[1]);_x000D_
      recLength += inputBuffer[0].length;_x000D_
    }_x000D_
_x000D_
    function exportWAV(type){_x000D_
      var bufferL = mergeBuffers(recBuffersL, recLength);_x000D_
      var bufferR = mergeBuffers(recBuffersR, recLength);_x000D_
      var interleaved = interleave(bufferL, bufferR);_x000D_
      var dataview = encodeWAV(interleaved);_x000D_
      var audioBlob = new Blob([dataview], { type: type });_x000D_
_x000D_
      this.postMessage(audioBlob);_x000D_
    }_x000D_
_x000D_
    function getBuffer() {_x000D_
      var buffers = [];_x000D_
      buffers.push( mergeBuffers(recBuffersL, recLength) );_x000D_
      buffers.push( mergeBuffers(recBuffersR, recLength) );_x000D_
      this.postMessage(buffers);_x000D_
    }_x000D_
_x000D_
    function clear(){_x000D_
      recLength = 0;_x000D_
      recBuffersL = [];_x000D_
      recBuffersR = [];_x000D_
    }_x000D_
_x000D_
    function mergeBuffers(recBuffers, recLength){_x000D_
      var result = new Float32Array(recLength);_x000D_
      var offset = 0;_x000D_
      for (var i = 0; i < recBuffers.length; i++){_x000D_
        result.set(recBuffers[i], offset);_x000D_
        offset += recBuffers[i].length;_x000D_
      }_x000D_
      return result;_x000D_
    }_x000D_
_x000D_
    function interleave(inputL, inputR){_x000D_
      var length = inputL.length + inputR.length;_x000D_
      var result = new Float32Array(length);_x000D_
_x000D_
      var index = 0,_x000D_
        inputIndex = 0;_x000D_
_x000D_
      while (index < length){_x000D_
        result[index++] = inputL[inputIndex];_x000D_
        result[index++] = inputR[inputIndex];_x000D_
        inputIndex++;_x000D_
      }_x000D_
      return result;_x000D_
    }_x000D_
_x000D_
    function floatTo16BitPCM(output, offset, input){_x000D_
      for (var i = 0; i < input.length; i++, offset+=2){_x000D_
        var s = Math.max(-1, Math.min(1, input[i]));_x000D_
        output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true);_x000D_
      }_x000D_
    }_x000D_
_x000D_
    function writeString(view, offset, string){_x000D_
      for (var i = 0; i < string.length; i++){_x000D_
        view.setUint8(offset + i, string.charCodeAt(i));_x000D_
      }_x000D_
    }_x000D_
_x000D_
    function encodeWAV(samples){_x000D_
      var buffer = new ArrayBuffer(44 + samples.length * 2);_x000D_
      var view = new DataView(buffer);_x000D_
_x000D_
      /* RIFF identifier */_x000D_
      writeString(view, 0, 'RIFF');_x000D_
      /* file length */_x000D_
      view.setUint32(4, 32 + samples.length * 2, true);_x000D_
      /* RIFF type */_x000D_
      writeString(view, 8, 'WAVE');_x000D_
      /* format chunk identifier */_x000D_
      writeString(view, 12, 'fmt ');_x000D_
      /* format chunk length */_x000D_
      view.setUint32(16, 16, true);_x000D_
      /* sample format (raw) */_x000D_
      view.setUint16(20, 1, true);_x000D_
      /* channel count */_x000D_
      view.setUint16(22, 2, true);_x000D_
      /* sample rate */_x000D_
      view.setUint32(24, sampleRate, true);_x000D_
      /* byte rate (sample rate * block align) */_x000D_
      view.setUint32(28, sampleRate * 4, true);_x000D_
      /* block align (channel count * bytes per sample) */_x000D_
      view.setUint16(32, 4, true);_x000D_
      /* bits per sample */_x000D_
      view.setUint16(34, 16, true);_x000D_
      /* data chunk identifier */_x000D_
      writeString(view, 36, 'data');_x000D_
      /* data chunk length */_x000D_
      view.setUint32(40, samples.length * 2, true);_x000D_
_x000D_
      floatTo16BitPCM(view, 44, samples);_x000D_
_x000D_
      return view;_x000D_
    }
_x000D_
<html>_x000D_
     <body>_x000D_
      <audio controls autoplay></audio>_x000D_
      <script type="text/javascript" src="recorder.js"> </script>_x000D_
                    <fieldset><legend>RECORD AUDIO</legend>_x000D_
      <input onclick="startRecording()" type="button" value="start recording" />_x000D_
      <input onclick="stopRecording()" type="button" value="stop recording and play" />_x000D_
                    </fieldset>_x000D_
      <script>_x000D_
       var onFail = function(e) {_x000D_
        console.log('Rejected!', e);_x000D_
       };_x000D_
_x000D_
       var onSuccess = function(s) {_x000D_
        var context = new webkitAudioContext();_x000D_
        var mediaStreamSource = context.createMediaStreamSource(s);_x000D_
        recorder = new Recorder(mediaStreamSource);_x000D_
        recorder.record();_x000D_
_x000D_
        // audio loopback_x000D_
        // mediaStreamSource.connect(context.destination);_x000D_
       }_x000D_
_x000D_
       window.URL = window.URL || window.webkitURL;_x000D_
       navigator.getUserMedia  = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;_x000D_
_x000D_
       var recorder;_x000D_
       var audio = document.querySelector('audio');_x000D_
_x000D_
       function startRecording() {_x000D_
        if (navigator.getUserMedia) {_x000D_
         navigator.getUserMedia({audio: true}, onSuccess, onFail);_x000D_
        } else {_x000D_
         console.log('navigator.getUserMedia not present');_x000D_
        }_x000D_
       }_x000D_
_x000D_
       function stopRecording() {_x000D_
        recorder.stop();_x000D_
        recorder.exportWAV(function(s) {_x000D_
                                _x000D_
                                  audio.src = window.URL.createObjectURL(s);_x000D_
        });_x000D_
       }_x000D_
      </script>_x000D_
     </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

Django CSRF check failing with an Ajax POST request

Add this line to your jQuery code:

$.ajaxSetup({
  data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
});

and done.

Remove URL parameters without refreshing page

To clear out all the parameters, without doing a page refresh, AND if you are using HTML5, then you can do this:

history.pushState({}, '', 'index.html' ); //replace 'index.html' with whatever your page name is

This will add an entry in the browser history. You could also consider replaceState if you don't wan't to add a new entry and just want to replace the old entry.

How can I listen for a click-and-hold in jQuery?

I wrote some code to make it easy

_x000D_
_x000D_
//Add custom event listener_x000D_
$(':root').on('mousedown', '*', function() {_x000D_
    var el = $(this),_x000D_
        events = $._data(this, 'events');_x000D_
    if (events && events.clickHold) {_x000D_
        el.data(_x000D_
            'clickHoldTimer',_x000D_
            setTimeout(_x000D_
                function() {_x000D_
                    el.trigger('clickHold')_x000D_
                },_x000D_
                el.data('clickHoldTimeout')_x000D_
            )_x000D_
        );_x000D_
    }_x000D_
}).on('mouseup mouseleave mousemove', '*', function() {_x000D_
    clearTimeout($(this).data('clickHoldTimer'));_x000D_
});_x000D_
_x000D_
//Attach it to the element_x000D_
$('#HoldListener').data('clickHoldTimeout', 2000); //Time to hold_x000D_
$('#HoldListener').on('clickHold', function() {_x000D_
    console.log('Worked!');_x000D_
});
_x000D_
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>_x000D_
<img src="http://lorempixel.com/400/200/" id="HoldListener">
_x000D_
_x000D_
_x000D_

See on JSFiddle

Now you need just to set the time of holding and add clickHold event on your element

Verilog generate/genvar in an always block

You don't need a generate bock if you want all the bits of temp assigned in the same always block.

parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
always @(posedge sysclk) begin
    for (integer c=0; c<ROWBITS; c=c+1) begin: test
        temp[c] <= 1'b0;
    end
end

Alternatively, if your simulator supports IEEE 1800 (SytemVerilog), then

parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
always @(posedge sysclk) begin
        temp <= '0; // fill with 0
    end
end

MySQL config file location - redhat linux server

Default options are read from the following files in the given order:

/etc/mysql/my.cnf 
/etc/my.cnf 
~/.my.cnf 

How to delete all files and folders in a directory?

 new System.IO.DirectoryInfo(@"C:\Temp").Delete(true);

 //Or

 System.IO.Directory.Delete(@"C:\Temp", true);

How to round each item in a list of floats to 2 decimal places?

If you really want an iterator-free solution, you can use numpy and its array round function.

import numpy as np
myList = list(np.around(np.array(myList),2))

Validation for 10 digit mobile number and focus input field on invalid

I used $form.submit() as it keeps html input validation.

Also I used input type tel as it supported by mobile browsers, only display numeric keypad.

<input type="tel" minlength="10" maxlength="10" id="mobile" name="mobile" title="10 digit mobile number" required>


$('#mob_frm').submit(function(e) {
            e.preventDefault();
            if(!$('#mobile').val().match('[0-9]{10}'))  {
                alert("Please put 10 digit mobile number");
                return;
            }  

        });

Ignoring a class property in Entity Framework 4.1 Code First

You can use the NotMapped attribute data annotation to instruct Code-First to exclude a particular property

public class Customer
{
    public int CustomerID { set; get; }
    public string FirstName { set; get; } 
    public string LastName{ set; get; } 
    [NotMapped]
    public int Age { set; get; }
}

[NotMapped] attribute is included in the System.ComponentModel.DataAnnotations namespace.

You can alternatively do this with Fluent API overriding OnModelCreating function in your DBContext class:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Entity<Customer>().Ignore(t => t.LastName);
   base.OnModelCreating(modelBuilder);
}

http://msdn.microsoft.com/en-us/library/hh295847(v=vs.103).aspx

The version I checked is EF 4.3, which is the latest stable version available when you use NuGet.


Edit : SEP 2017

Asp.NET Core(2.0)

Data annotation

If you are using asp.net core (2.0 at the time of this writing), The [NotMapped] attribute can be used on the property level.

public class Customer
{
    public int Id { set; get; }
    public string FirstName { set; get; } 
    public string LastName { set; get; } 
    [NotMapped]
    public int FullName { set; get; }
}

Fluent API

public class SchoolContext : DbContext
{
    public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
    {
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>().Ignore(t => t.FullName);
        base.OnModelCreating(modelBuilder);
    }
    public DbSet<Customer> Customers { get; set; }
}

JavaScript before leaving the page

Normally you want to show this message, when the user has made changes in a form, but they are not saved.

Take this approach to show a message, only when the user has changed something

var form = $('#your-form'),
  original = form.serialize()

form.submit(function(){
  window.onbeforeunload = null
})

window.onbeforeunload = function(){
  if (form.serialize() != original)
    return 'Are you sure you want to leave?'
}

How to convert a column of DataTable to a List

1.Very Simple Code to iterate datatable and get columns in list.

2.code ==>>>

 foreach (DataColumn dataColumn in dataTable.Columns)
 {
    var list = dataTable.Rows.OfType<DataRow>()
     .Select(dataRow => dataRow.Field<string> 
       (dataColumn.ToString())).ToList();
 }

How to get the size of the current screen in WPF?

As far as I know there is no native WPF function to get dimensions of the current monitor. Instead you could PInvoke native multiple display monitors functions, wrap them in managed class and expose all properties you need to consume them from XAML.

How to open a new tab using Selenium WebDriver

 Actions at=new Actions(wd);
 at.moveToElement(we);
 at.contextClick(we).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();

GC overhead limit exceeded

From Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning

the following

Excessive GC Time and OutOfMemoryError

The concurrent collector will throw an OutOfMemoryError if too much time is being spent in garbage collection: if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, an OutOfMemoryError will be thrown. This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small. If necessary, this feature can be disabled by adding the option -XX:-UseGCOverheadLimit to the command line.

The policy is the same as that in the parallel collector, except that time spent performing concurrent collections is not counted toward the 98% time limit. In other words, only collections performed while the application is stopped count toward excessive GC time. Such collections are typically due to a concurrent mode failure or an explicit collection request (e.g., a call to System.gc()).

in conjunction with a passage further down

One of the most commonly encountered uses of explicit garbage collection occurs with RMIs distributed garbage collection (DGC). Applications using RMI refer to objects in other virtual machines. Garbage cannot be collected in these distributed applications without occasionally collection the local heap, so RMI forces full collections periodically. The frequency of these collections can be controlled with properties. For example,

java -Dsun.rmi.dgc.client.gcInterval=3600000

-Dsun.rmi.dgc.server.gcInterval=3600000 specifies explicit collection once per hour instead of the default rate of once per minute. However, this may also cause some objects to take much longer to be reclaimed. These properties can be set as high as Long.MAX_VALUE to make the time between explicit collections effectively infinite, if there is no desire for an upper bound on the timeliness of DGC activity.

Seems to imply that the evaluation period for determining the 98% is one minute long, but it might be configurable on Sun's JVM with the correct define.

Of course, other interpretations are possible.

How to list files and folder in a dir (PHP)

You may use Directory Functions: http://php.net/manual/en/book.dir.php

Simple example from opendir() function description:

<?php
$dir_path = "/path/to/your/dir";

if (is_dir($dir_path)) {
    if ($dir_handler = opendir($dir_path)) {
        while (($file = readdir($dir_handler)) !== false) {
            echo "filename: $file : filetype: " . filetype($dir_path . $file) . "\n";
        }
        closedir($dir_handler);
    }
}
?>

How to set up file permissions for Laravel?

I found an even better solution to this. Its caused because php is running as another user by default.

so to fix this do

sudo nano /etc/php/7.0/fpm/pool.d/www.conf

then edit the user = "put user that owns the directories" group = "put user that owns the directories"

then:

sudo systemctl reload php7.0-fpm

AWS EFS vs EBS vs S3 (differences & when to use?)

AWS EFS, EBS and S3. From Functional Standpoint, here is the difference

EFS:

  1. Network filesystem :can be shared across several Servers; even between regions. The same is not available for EBS case. This can be used esp for storing the ETL programs without the risk of security

  2. Highly available, scalable service.

  3. Running any application that has a high workload, requires scalable storage, and must produce output quickly.

  4. It can provide higher throughput. It match sudden file system growth, even for workloads up to 500,000 IOPS or 10 GB per second.

  5. Lift-and-shift application support: EFS is elastic, available, and scalable, and enables you to move enterprise applications easily and quickly without needing to re-architect them.

  6. Analytics for big data: It has the ability to run big data applications, which demand significant node throughput, low-latency file access, and read-after-write operations.

EBS:

  1. for NoSQL databases, EBS offers NoSQL databases the low-latency performance and dependability they need for peak performance.

S3:

Robust performance, scalability, and availability: Amazon S3 scales storage resources free from resource procurement cycles or investments upfront.

2)Data lake and big data analytics: Create a data lake to hold raw data in its native format, then using machine learning tools, analytics to draw insights.

  1. Backup and restoration: Secure, robust backup and restoration solutions
  2. Data archiving
  3. S3 is an object store good at storing vast numbers of backups or user files. Unlike EBS or EFS, S3 is not limited to EC2. Files stored within an S3 bucket can be accessed programmatically or directly from services such as AWS CloudFront. Many websites use it to hold their content and media files, which may be served efficiently via AWS CloudFront.

Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

This will work:

The problem may happen when you're trying to read a list with a single element as a JsonArray rather than a JsonNode or vice versa.

Since you can't know for sure if the returned list contains a single element (so the json looks like this {...}) or multiple elements (and the json looks like this [{...},{...}]) - you'll have to check in runtime the type of the element.

It should look like this:

(Note: in this code sample I'm using com.fasterxml.jackson)

String jsonStr = response.readEntity(String.class);
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(jsonStr);

// Start by checking if this is a list -> the order is important here:                      
if (rootNode instanceof ArrayNode) {
    // Read the json as a list:
    myObjClass[] objects = mapper.readValue(rootNode.toString(), myObjClass[].class);
    ...
} else if (rootNode instanceof JsonNode) {
    // Read the json as a single object:
    myObjClass object = mapper.readValue(rootNode.toString(), myObjClass.class);
    ...
} else {
    ...
}

How to move the layout up when the soft keyboard is shown android

Set windowSoftInputMode property to adjustPan and adjustResize

<activity android:windowSoftInputMode="adjustPan|adjustResize"> </activity>

How to set Python's default version to 3.x on OS X?

This worked for me. I added alias and restarted my terminal:

alias python=/usr/local/bin/python3

Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type

Check the "tsconfig.json" file for compilation options "include" and "exclude". If it does not exist, just add them by informing your root directory.

// tsconfig.json
{
  "compilerOptions": {
  ...
  "include": [
    "src", 
  ],
  "exclude": [
    "node_modules", 
  ]
}

I solved my silly problem just by removing the extension statement "*.spec.ts" from the "exclude", because when including the "import" in these files, there were always problems.

REST API Best practice: How to accept list of parameter values as input

First:

I think you can do it 2 ways

http://our.api.com/Product/<id> : if you just want one record

http://our.api.com/Product : if you want all records

http://our.api.com/Product/<id1>,<id2> :as James suggested can be an option since what comes after the Product tag is a parameter

Or the one I like most is:

You can use the the Hypermedia as the engine of application state (HATEOAS) property of a RestFul WS and do a call http://our.api.com/Product that should return the equivalent urls of http://our.api.com/Product/<id> and call them after this.

Second

When you have to do queries on the url calls. I would suggest using HATEOAS again.

1) Do a get call to http://our.api.com/term/pumas/productType/clothing/color/black

2) Do a get call to http://our.api.com/term/pumas/productType/clothing,bags/color/black,red

3) (Using HATEOAS) Do a get call to `http://our.api.com/term/pumas/productType/ -> receive the urls all clothing possible urls -> call the ones you want (clothing and bags) -> receive the possible color urls -> call the ones you want

How to replace blank (null ) values with 0 for all records?

I would change the SQL statement above to be more generic. Using wildcards is never a bad idea when it comes to mass population to avoid nulls.

Try this:

Update Table Set * = 0 Where * Is Null; 

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

I find using a Mongo url handy. I store the URL in an environment variable and use that to configure servers whilst the development version uses a default url with no password.

The URL has the form:

export MONGODB_DATABASE_URL=mongodb://USERNAME:PASSWORD@DBHOST:DBPORT/DBNAME

Code to connect this way:

var DATABASE_URL = process.env.MONGODB_DATABASE_URL || mongodb.DEFAULT_URL;

mongo_connect(DATABASE_URL, mongodb_server_options, 
      function(err, db) { 

          if(db && !err) {
          console.log("connected to mongodb" + " " + lobby_db);
          }
          else if(err) {
          console.log("NOT connected to mongodb " + err + " " + lobby_db);
          }
      });    

phpmyadmin "no data received to import" error, how to fix?

It’s a common error and it can be easily fixed. This error message is an indication of that the file you are trying to import is larger than your web host allows

No data was received to import. Either no file name was submitted, or the file size exceeded the maximum size permitted by your PHP configuration. See FAQ 1.16.

Solution:

A solution is easy, Need to increase file size upload limit as per your requirement.

First of all, stop the XAMPP/Wamp and then find the php.ini in the following locations. Windows: C:\xampp\php\php.ini

Open the php.ini file. Find these lines in the php.ini file and replace it following numbers

upload_max_filesize = 64M

And then restart your XAMPP/Wamp


NOTE: For Windows, you can find the file in the C:\xampp\php\php.ini-Folder (Windows) or in the etc-Folder (within the xampp-Folder)

What does <T> (angle brackets) mean in Java?

Generic classes are a type of class that takes in a data type as a parameter when it's created. This type parameter is specified using angle brackets and the type can change each time a new instance of the class is instantiated. For instance, let's create an ArrayList for Employee objects and another for Company objects

ArrayList<Employee> employees = new ArrayList<Employee>();
ArrayList<Company> companies = new ArrayList<Company>();

You'll notice that we're using the same ArrayList class to create both lists and we pass in the Employee or Company type using angle brackets. Having one generic class be able to handle multiple types of data cuts down on having a lot of classes that perform similar tasks. Generics also help to cut down on bugs by giving everything a strong type which helps the compiler point out errors. By specifying a type for ArrayList, the compiler will throw an error if you try to add an Employee to the Company list or vice versa.

I can't find my git.exe file in my Github folder

I found my git.exe here

C:\Program Files\Git\bin\git.exe

while installing git, it asks for the location. copy it and use it.

How can I enable or disable the GPS programmatically on Android?

the GPS can be toggled by exploiting a bug in the power manager widget. see this xda thread for discussion.

here's some example code i use

private void turnGPSOn(){
    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

    if(!provider.contains("gps")){ //if gps is disabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        sendBroadcast(poke);
    }
}

private void turnGPSOff(){
    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

    if(provider.contains("gps")){ //if gps is enabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        sendBroadcast(poke);
    }
}

use the following to test if the existing version of the power control widget is one which will allow you to toggle the gps.

private boolean canToggleGPS() {
    PackageManager pacman = getPackageManager();
    PackageInfo pacInfo = null;

    try {
        pacInfo = pacman.getPackageInfo("com.android.settings", PackageManager.GET_RECEIVERS);
    } catch (NameNotFoundException e) {
        return false; //package not found
    }

    if(pacInfo != null){
        for(ActivityInfo actInfo : pacInfo.receivers){
            //test if recevier is exported. if so, we can toggle GPS.
            if(actInfo.name.equals("com.android.settings.widget.SettingsAppWidgetProvider") && actInfo.exported){
                return true;
            }
        }
    }

    return false; //default
}

Pass form data to another page with php

The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

index.php

<html>
<body>

<form action="site2.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>

</body>
</html> 

site2.php

 <html>
 <body>

 Hello <?php echo $_POST["name"]; ?>!<br>
 Your mail is <?php echo $_POST["mail"]; ?>.

 </body>
 </html> 

output

Hello "name" !

Your email is "[email protected]" .

adb shell command to make Android package uninstall dialog appear

In my case, I do an adb shell pm list packages to see first what are the packages/apps installed in my Android device or emulator, then upon locating the desired package/app, I do an adb shell pm uninstall -k com.package.name.

Why in C++ do we use DWORD rather than unsigned int?

When MS-DOS and Windows 3.1 operated in 16-bit mode, an Intel 8086 word was 16 bits, a Microsoft WORD was 16 bits, a Microsoft DWORD was 32 bits, and a typical compiler's unsigned int was 16 bits.

When Windows NT operated in 32-bit mode, an Intel 80386 word was 32 bits, a Microsoft WORD was 16 bits, a Microsoft DWORD was 32 bits, and a typical compiler's unsigned int was 32 bits. The names WORD and DWORD were no longer self-descriptive but they preserved the functionality of Microsoft programs.

When Windows operates in 64-bit mode, an Intel word is 64 bits, a Microsoft WORD is 16 bits, a Microsoft DWORD is 32 bits, and a typical compiler's unsigned int is 32 bits. The names WORD and DWORD are no longer self-descriptive, AND an unsigned int no longer conforms to the principle of least surprises, but they preserve the functionality of lots of programs.

I don't think WORD or DWORD will ever change.

Cannot make Project Lombok work on Eclipse

Did you add

-vmargs
...
-javaagent:lombok.jar
-Xbootclasspath/a:lombok.jar

to your eclipse.ini?

Because if you have (and if you have added the lombok.jar to the libraries used by your project), it works just fine with Eclipse Helios:

alt text


Ian Tegebo mentions in the comments that:

a simple "restart" was not sufficient to pick up the changed vmargs:
I needed to explicitly exit and then start again.


chrisjleu mentions in the comments:

If you happen to be running a customized Eclipse Helios (3.6+) distribution then you may have to use the full path to lombok.jar in both the vm arguments.
See commit b47e87f for more details.

boolean fullPathRequired = IdeFinder.getOS() == EclipseFinder.OS.UNIX || System.getProperty("lombok.installer.fullpath") != null;

How to download all dependencies and packages to directory

The marked answer has the problem that the available packages on the machine that is doing the downloads might be different from the target machine, and thus the package set might be incomplete.

To avoid this and get all dependencies, use the following:

apt-get download $(apt-rdepends <package>|grep -v "^ ")

Some packages returned from apt-rdepends don't exist with the exact name for apt-get download to download (for example, libc-dev). In those cases, filter out those exact names (be sure to use ^<NAME>$ so that other related names, for example libc-dev-bin, that do exist are not skipped).

apt-get download $(apt-rdepends <package>|grep -v "^ " |grep -v "^libc-dev$")

Once downloaded, you can move the .deb files to a machine without Internet and install them:

sudo dpkg -i *.deb

SQL Server 2005 Setting a variable to the result of a select query

You could also just put the first SELECT in a subquery. Since most optimizers will fold it into a constant anyway, there should not be a performance hit on this.

Incidentally, since you are using a predicate like this:

CONVERT(...) = CONVERT(...)

that predicate expression cannot be optimized properly or use indexes on the columns reference by the CONVERT() function.

Here is one way to make the original query somewhat better:

DECLARE @ooDate datetime
SELECT @ooDate = OO.Date FROM OLAP.OutageHours AS OO where OO.OutageID = 1

SELECT 
  COUNT(FF.HALID)
FROM
  Outages.FaultsInOutages AS OFIO 
  INNER JOIN Faults.Faults as FF ON 
    FF.HALID = OFIO.HALID 
WHERE
  FF.FaultDate >= @ooDate AND
  FF.FaultDate < DATEADD(day, 1, @ooDate) AND
  OFIO.OutageID = 1

This version could leverage in index that involved FaultDate, and achieves the same goal.

Here it is, rewritten to use a subquery to avoid the variable declaration and subsequent SELECT.

SELECT 
  COUNT(FF.HALID)
FROM
  Outages.FaultsInOutages AS OFIO 
  INNER JOIN Faults.Faults as FF ON 
    FF.HALID = OFIO.HALID 
WHERE
  CONVERT(varchar(10), FF.FaultDate, 126) = (SELECT CONVERT(varchar(10), OO.Date, 126) FROM OLAP.OutageHours AS OO where OO.OutageID = 1) AND
  OFIO.OutageID = 1

Note that this approach has the same index usage issue as the original, because of the use of CONVERT() on FF.FaultDate. This could be remedied by adding the subquery twice, but you would be better served with the variable approach in this case. This last version is only for demonstration.

Regards.

Dealing with "java.lang.OutOfMemoryError: PermGen space" error

Use the command line parameter -XX:MaxPermSize=128m for a Sun JVM (obviously substituting 128 for whatever size you need).

Listing all extras of an Intent

Bundle extras = getIntent().getExtras();
Set<String> ks = extras.keySet();
Iterator<String> iterator = ks.iterator();
while (iterator.hasNext()) {
    Log.d("KEY", iterator.next());
}

iOS Launching Settings -> Restrictions URL Scheme

Update:

prefs: will NOT work since iOS 10.

Select all DIV text with single mouse click

Niko Lay: How about this simple solution? :)

`<input style="background-color:white; border:1px white solid;" onclick="this.select();" id="selectable" value="http://example.com/page.htm">`

.....

Code before:

<textarea rows="20" class="codearea" style="padding:5px;" readonly="readonly">

Code after:

<textarea rows="20" class="codearea" style="padding:5px;" readonly="readonly" onclick="this.select();" id="selectable">

Just this part onclick="this.select();" id="selectable" in my code worked fine. Selects all in my code box with one mouse click.

Thanks for help Niko Lay!

How would you do a "not in" query with LINQ?

I don't know if this will help you but..

NorthwindDataContext dc = new NorthwindDataContext();    
dc.Log = Console.Out;

var query =    
    from c in dc.Customers    
    where !(from o in dc.Orders    
            select o.CustomerID)    
           .Contains(c.CustomerID)    
    select c;

foreach (var c in query) Console.WriteLine( c );

from The NOT IN clause in LINQ to SQL by Marco Russo

Easiest way to detect Internet connection on iOS?

EDIT: This will not work for network URLs (see comments)

As of iOS 5, there is a new NSURL instance method:

- (BOOL)checkResourceIsReachableAndReturnError:(NSError **)error

Point it to the website you care about or point it to apple.com; I think it is the new one-line call to see if the internet is working on your device.

TypeScript enum to object array

There is a simple solution, So when you run Object.keys(Enum) that gonna give you a Array of Values and Keys, in first slice Values and in the second one keys, so why we don't just return the second slice, this code below works for me.

enum Enum {
   ONE,
   TWO,
   THREE,
   FOUR,
   FIVE,
   SIX,
   SEVEN
}
const keys = Object.keys(Enum); 
console.log(keys.slice(keys.length / 2));

Why is the console window closing immediately once displayed my output?

Here is a way to do it without involving Console:

var endlessTask = new TaskCompletionSource<bool>().Task;
endlessTask.Wait();

MySQL SELECT last few days?

You can use this in your MySQL WHERE clause to return records that were created within the last 7 days/week:

created >= DATE_SUB(CURDATE(),INTERVAL 7 day)

Also use NOW() in the subtraction to give hh:mm:ss resolution. So to return records created exactly (to the second) within the last 24hrs, you could do:

created >= DATE_SUB(NOW(),INTERVAL 1 day)

What's the pythonic way to use getters and setters?

You can use accessors/mutators (i.e. @attr.setter and @property) or not, but the most important thing is to be consistent!

If you're using @property to simply access an attribute, e.g.

class myClass:
    def __init__(a):
        self._a = a

    @property
    def a(self):
        return self._a

use it to access every* attribute! It would be a bad practice to access some attributes using @property and leave some other properties public (i.e. name without an underscore) without an accessor, e.g. do not do

class myClass:
    def __init__(a, b):
        self.a = a
        self.b = b

    @property
    def a(self):
        return self.a

Note that self.b does not have an explicit accessor here even though it's public.

Similarly with setters (or mutators), feel free to use @attribute.setter but be consistent! When you do e.g.

class myClass:
    def __init__(a, b):
        self.a = a
        self.b = b 

    @a.setter
    def a(self, value):
        return self.a = value

It's hard for me to guess your intention. On one hand you're saying that both a and b are public (no leading underscore in their names) so I should theoretically be allowed to access/mutate (get/set) both. But then you specify an explicit mutator only for a, which tells me that maybe I should not be able to set b. Since you've provided an explicit mutator I am not sure if the lack of explicit accessor (@property) means I should not be able to access either of those variables or you were simply being frugal in using @property.

*The exception is when you explicitly want to make some variables accessible or mutable but not both or you want to perform some additional logic when accessing or mutating an attribute. This is when I am personally using @property and @attribute.setter (otherwise no explicit acessors/mutators for public attributes).

Lastly, PEP8 and Google Style Guide suggestions:

PEP8, Designing for Inheritance says:

For simple public data attributes, it is best to expose just the attribute name, without complicated accessor/mutator methods. Keep in mind that Python provides an easy path to future enhancement, should you find that a simple data attribute needs to grow functional behavior. In that case, use properties to hide functional implementation behind simple data attribute access syntax.

On the other hand, according to Google Style Guide Python Language Rules/Properties the recommendation is to:

Use properties in new code to access or set data where you would normally have used simple, lightweight accessor or setter methods. Properties should be created with the @property decorator.

The pros of this approach:

Readability is increased by eliminating explicit get and set method calls for simple attribute access. Allows calculations to be lazy. Considered the Pythonic way to maintain the interface of a class. In terms of performance, allowing properties bypasses needing trivial accessor methods when a direct variable access is reasonable. This also allows accessor methods to be added in the future without breaking the interface.

and cons:

Must inherit from object in Python 2. Can hide side-effects much like operator overloading. Can be confusing for subclasses.

Windows 7 environment variable not working in path

I had the same problem, I fixed it by removing PATHEXT from user variable. It must only exist in System variable with .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC

Also remove the variable from user to system and only include that path on user variable

SQL variable to hold list of integers

In the end i came to the conclusion that without modifying how the query works i could not store the values in variables. I used SQL profiler to catch the values and then hard coded them into the query to see how it worked. There were 18 of these integer arrays and some had over 30 elements in them.

I think that there is a need for MS/SQL to introduce some aditional datatypes into the language. Arrays are quite common and i don't see why you couldn't use them in a stored proc.

AngularJS : ng-click not working

It just happend to me. I solved the problem by tracing backward from the point ng-click is coded. Found out that an extra

</div> 

was placed in the html to prematurely close the div block that contains the ng-click.

Removed the extra

</div> 

then everything is working fine.

Is it a bad practice to use break in a for loop?

I disagree!

Why would you ignore the built-in functionality of a for loop to make your own? You do not need to reinvent the wheel.

I think it makes more sense to have your checks at the top of your for loop like so

for(int i = 0; i < myCollection.Length && myCollection[i].SomeValue != "Break Condition"; i++)
{
//loop body
}

or if you need to process the row first

for(int i = 0; i < myCollection.Length && (i == 0 ? true : myCollection[i-1].SomeValue != "Break Condition"); i++)
{
//loop body
}

This way you can write a function to perform everything and make much cleaner code.

for(int i = 0; i < myCollection.Length && (i == 0 ? true : myCollection[i-1].SomeValue != "Break Condition"); i++)
{
    DoAllThatCrazyStuff(myCollection[i]);
}

Or if your condition is complicated you can move that code out too!

for(int i = 0; i < myCollection.Length && BreakFunctionCheck(i, myCollection); i++)
{
    DoAllThatCrazyStuff(myCollection[i]);
}

"Professional Code" that is riddled with breaks doesn't really sound like professional code to me. It sounds like lazy coding ;)

How do I use a custom deleter with a std::unique_ptr member?

Unless you need to be able to change the deleter at runtime, I would strongly recommend using a custom deleter type. For example, if use a function pointer for your deleter, sizeof(unique_ptr<T, fptr>) == 2 * sizeof(T*). In other words, half of the bytes of the unique_ptr object are wasted.

Writing a custom deleter to wrap every function is a bother, though. Thankfully, we can write a type templated on the function:

Since C++17:

template <auto fn>
using deleter_from_fn = std::integral_constant<decltype(fn), fn>;

template <typename T, auto fn>
using my_unique_ptr = std::unique_ptr<T, deleter_from_fn<fn>>;

// usage:
my_unique_ptr<Bar, destroy> p{create()};

Prior to C++17:

template <typename D, D fn>
using deleter_from_fn = std::integral_constant<D, fn>;

template <typename T, typename D, D fn>
using my_unique_ptr = std::unique_ptr<T, deleter_from_fn<D, fn>>;

// usage:
my_unique_ptr<Bar, decltype(destroy), destroy> p{create()};

How to do associative array/hashing in JavaScript

Since every object in JavaScript behaves like - and is generally implemented as - a hashtable, I just go with that...

var hashSweetHashTable = {};

Int or Number DataType for DataAnnotation validation attribute

ASP.NET Core 3.1

This is my implementation of the feature, it works on server side as well as with jquery validation unobtrusive with a custom error message just like any other attribute:

The attribute:

  [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public class MustBeIntegerAttribute : ValidationAttribute, IClientModelValidator
    {
        public void AddValidation(ClientModelValidationContext context)
        {
            MergeAttribute(context.Attributes, "data-val", "true");
            var errorMsg = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
            MergeAttribute(context.Attributes, "data-val-mustbeinteger", errorMsg);
        }

        public override bool IsValid(object value)
        {
            return int.TryParse(value?.ToString() ?? "", out int newVal);
        }

        private bool MergeAttribute(
              IDictionary<string, string> attributes,
              string key,
              string value)
        {
            if (attributes.ContainsKey(key))
            {
                return false;
            }
            attributes.Add(key, value);
            return true;
        }
    }

Client side logic:

$.validator.addMethod("mustbeinteger",
    function (value, element, parameters) {
        return !isNaN(parseInt(value)) && isFinite(value);
    });

$.validator.unobtrusive.adapters.add("mustbeinteger", [], function (options) {
    options.rules.mustbeinteger = {};
    options.messages["mustbeinteger"] = options.message;
});

And finally the Usage:

 [MustBeInteger(ErrorMessage = "You must provide a valid number")]
 public int SomeNumber { get; set; }

Git in Visual Studio - add existing project?

The easiest way is obviously as described in the MSDN article Share your code with Visual Studio 2017 and VSTS Git.

  1. Create a new local Git repository for your project by selecting Add to Source Control in the status bar in the lower right hand corner of Visual Studio. This will create a new repository in the folder the solution is in and commit your code into that repository.

    Enter image description here

  2. In the Push view in Team Explorer, select the Publish Git Repository button under Push to Visual Studio Team Services.

    Enter image description here

  3. Connect Remote Source Control and enter your repository name and select Publish Repository.

    Enter image description here

C# - Making a Process.Start wait until the process has start-up

public static class WinApi
{

    [DllImport("user32.dll")]
    public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    public static class Windows
    {
        public const int NORMAL = 1;
        public const int HIDE = 0;
        public const int RESTORE = 9;
        public const int SHOW = 5;
        public const int MAXIMIXED = 3;
    }

}

App

String process_name = "notepad"
Process process;
process = Process.Start( process_name );

while (!WinApi.ShowWindow(process.MainWindowHandle, WinApi.Windows.NORMAL))
{
    Thread.Sleep(100);
    process.Refresh();
}

// Done!
// Continue your code here ...

How do I install package.json dependencies in the current directory using npm

Running:

npm install

from inside your app directory (i.e. where package.json is located) will install the dependencies for your app, rather than install it as a module, as described here. These will be placed in ./node_modules relative to your package.json file (it's actually slightly more complex than this, so check the npm docs here).

You are free to move the node_modules dir to the parent dir of your app if you want, because node's 'require' mechanism understands this. However, if you want to update your app's dependencies with install/update, npm will not see the relocated 'node_modules' and will instead create a new dir, again relative to package.json.

To prevent this, just create a symlink to the relocated node_modules from your app dir:

ln -s ../node_modules node_modules

regex error - nothing to repeat

It's not only a Python bug with * actually, it can also happen when you pass a string as a part of your regular expression to be compiled, like ;

import re
input_line = "string from any input source"
processed_line= "text to be edited with {}".format(input_line)
target = "text to be searched"
re.search(processed_line, target)

this will cause an error if processed line contained some "(+)" for example, like you can find in chemical formulae, or such chains of characters. the solution is to escape but when you do it on the fly, it can happen that you fail to do it properly...

SELECT list is not in GROUP BY clause and contains nonaggregated column

country.code is not in your group by statement, and is not an aggregate (wrapped in an aggregate function).

https://www.w3schools.com/sql/sql_ref_sqlserver.asp

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

Resolved the problem using Jackson library. Prints are called out of Main class and all POJO classes are created. Here is the code snippets.

MainClass.java

public class MainClass {
  public static void main(String[] args) throws JsonParseException, 
       JsonMappingException, IOException {

String jsonStr = "{\r\n" + "    \"id\": 2,\r\n" + " \"socket\": \"0c317829-69bf- 
             43d6-b598-7c0c550635bb\",\r\n"
            + " \"type\": \"getDashboard\",\r\n" + "    \"data\": {\r\n"
            + "     \"workstationUuid\": \"ddec1caa-a97f-4922-833f- 
            632da07ffc11\"\r\n" + " },\r\n"
            + " \"reply\": true\r\n" + "}";

    ObjectMapper mapper = new ObjectMapper();

    MyPojo details = mapper.readValue(jsonStr, MyPojo.class);

    System.out.println("Value for getFirstName is: " + details.getId());
    System.out.println("Value for getLastName  is: " + details.getSocket());
    System.out.println("Value for getChildren is: " + 
      details.getData().getWorkstationUuid());
    System.out.println("Value for getChildren is: " + details.getReply());

}

MyPojo.java

public class MyPojo {
    private String id;

    private Data data;

    private String reply;

    private String socket;

    private String type;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Data getData() {
        return data;
    }

    public void setData(Data data) {
        this.data = data;
    }

    public String getReply() {
        return reply;
    }

    public void setReply(String reply) {
        this.reply = reply;
    }

    public String getSocket() {
        return socket;
    }

    public void setSocket(String socket) {
        this.socket = socket;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    } 
}

Data.java

public class Data {
    private String workstationUuid;

    public String getWorkstationUuid() {
        return workstationUuid;
    }

    public void setWorkstationUuid(String workstationUuid) {
        this.workstationUuid = workstationUuid;
    }   
}

RESULTS:

Value for getFirstName is: 2
Value for getLastName  is: 0c317829-69bf-43d6-b598-7c0c550635bb
Value for getChildren is: ddec1caa-a97f-4922-833f-632da07ffc11
Value for getChildren is: true

Can't append <script> element

You don't need jQuery to create a Script DOM Element. It can be done with vanilla ES6 like so:

const script = "console.log('Did it work?')"
new Promise((resolve, reject) => {
  (function(i,s,o,g,r,a,m){
      a=s.createElement(o),m=s.getElementsByTagName(o)[0];
      a.innerText=g;
      a.onload=r;m.parentNode.insertBefore(a,m)}
  )(window,document,'script',script, resolve())
}).then(() => console.log('Sure did!'))

It doesn't need to be wrapped in a Promise, but doing so allows you to resolve the promise when the script loads, helping prevent race conditions for long-running scripts.

Count number of iterations in a foreach loop

There's a few different ways you can tackle this one.

You can set a counter before the foreach() and then just iterate through which is the easiest approach.

$counter = 0;
foreach ($Contents as $item) {
      $counter++;
       $item[number];// if there are 15 $item[number] in this foreach, I want get the value : 15
}

C: Run a System Command and Get Output?

Usually, if the command is an external program, you can use the OS to help you here.

command > file_output.txt

So your C code would be doing something like

exec("command > file_output.txt");

Then you can use the file_output.txt file.

Updating a local repository with changes from a GitHub repository

To pull from the default branch, new repositories should use the command:

git pull origin main

Github changed naming convention of default branch from master to main in 2020. https://github.com/github/renaming

Find the last time table was updated

Find last time of update on a table

SELECT
tbl.name
,ius.last_user_update
,ius.user_updates
,ius.last_user_seek
,ius.last_user_scan
,ius.last_user_lookup
,ius.user_seeks
,ius.user_scans
,ius.user_lookups
FROM
sys.dm_db_index_usage_stats ius INNER JOIN
sys.tables tbl ON (tbl.OBJECT_ID = ius.OBJECT_ID)
WHERE ius.database_id = DB_ID()

http://www.sqlserver-dba.com/2012/10/sql-server-find-last-time-of-update-on-a-table.html

Concept of void pointer in C programming

void abc(void *a, int b) {
  char *format[] = {"%d", "%c", "%f"};
  printf(format[b-1], a);
}

UIView Infinite 360 degree rotation animation?

Nate's answer above is ideal for stop and start animation and gives a better control. I was intrigued why yours didn't work and his does. I wanted to share my findings here and a simpler version of the code that would animate a UIView continuously without stalling.

This is the code I used,

- (void)rotateImageView
{
    [UIView animateWithDuration:1 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        [self.imageView setTransform:CGAffineTransformRotate(self.imageView.transform, M_PI_2)];
    }completion:^(BOOL finished){
        if (finished) {
            [self rotateImageView];
        }
    }];
}

I used 'CGAffineTransformRotate' instead of 'CGAffineTransformMakeRotation' because the former returns the result which is saved as the animation proceeds. This will prevent the jumping or resetting of the view during the animation.

Another thing is not to use 'UIViewAnimationOptionRepeat' because at the end of the animation before it starts repeating, it resets the transform making the view jump back to its original position. Instead of a repeat, you recurse so that the transform is never reset to the original value because the animation block virtually never ends.

And the last thing is, you have to transform the view in steps of 90 degrees (M_PI / 2) instead of 360 or 180 degrees (2*M_PI or M_PI). Because transformation occurs as a matrix multiplication of sine and cosine values.

t' =  [ cos(angle) sin(angle) -sin(angle) cos(angle) 0 0 ] * t

So, say if you use 180-degree transformation, the cosine of 180 yields -1 making the view transform in opposite direction each time (Note-Nate's answer will also have this issue if you change the radian value of transformation to M_PI). A 360-degree transformation is simply asking the view to remain where it was, hence you don't see any rotation at all.

What is the difference between BIT and TINYINT in MySQL?

BIT should only allow 0 and 1 (and NULL, if the field is not defined as NOT NULL). TINYINT(1) allows any value that can be stored in a single byte, -128..127 or 0..255 depending on whether or not it's unsigned (the 1 shows that you intend to only use a single digit, but it does not prevent you from storing a larger value).

For versions older than 5.0.3, BIT is interpreted as TINYINT(1), so there's no difference there.

BIT has a "this is a boolean" semantic, and some apps will consider TINYINT(1) the same way (due to the way MySQL used to treat it), so apps may format the column as a check box if they check the type and decide upon a format based on that.

Get GPS location from the web browser

If you use the Geolocation API, it would be as simple as using the following code.

navigator.geolocation.getCurrentPosition(function(location) {
  console.log(location.coords.latitude);
  console.log(location.coords.longitude);
  console.log(location.coords.accuracy);
});

You may also be able to use Google's Client Location API.

This issue has been discussed in Is it possible to detect a mobile browser's GPS location? and Get position data from mobile browser. You can find more information there.

How to set the value of a hidden field from a controller in mvc

Without a view model you could use a simple HTML hidden input.

<input type="hidden" name="FullName" id="FullName" value="@ViewBag.FullName" />

Regular Expression for password validation

I would check them one-by-one; i.e. look for a number \d+, then if that fails you can tell the user they need to add a digit. This avoids returning an "Invalid" error without hinting to the user whats wrong with it.

MVC Razor Hidden input and passing values

You are doing it wrong since you try to map WebForms in the MVC application.

There are no server side controlls in MVC. Only the View and the Controller on the back-end. You send the data from server to the client by means of initialization of the View with your model.

This is happening on the HTTP GET request to your resource.

[HttpGet]
public ActionResult Home() 
{
  var model = new HomeModel { Greeatings = "Hi" };
  return View(model);
}

You send data from client to server by means of posting data to server. To make that happen, you create a form inside your view and [HttpPost] handler in your controller.

// View

@using (Html.BeginForm()) {
  @Html.TextBoxFor(m => m.Name)
  @Html.TextBoxFor(m => m.Password)
}

// Controller

[HttpPost]
public ActionResult Home(LoginModel model) 
{
  // do auth.. and stuff
  return Redirect();
}

Raising a number to a power in Java

^ in java does not mean to raise to a power. It means XOR.

You can use java's Math.pow()


And you might want to consider using double instead of int—that is:

double height;
double weight;

Note that 199/100 evaluates to 1.

What's a concise way to check that environment variables are set in a Unix shell script?

Parameter Expansion

The obvious answer is to use one of the special forms of parameter expansion:

: ${STATE?"Need to set STATE"}
: ${DEST:?"Need to set DEST non-empty"}

Or, better (see section on 'Position of double quotes' below):

: "${STATE?Need to set STATE}"
: "${DEST:?Need to set DEST non-empty}"

The first variant (using just ?) requires STATE to be set, but STATE="" (an empty string) is OK — not exactly what you want, but the alternative and older notation.

The second variant (using :?) requires DEST to be set and non-empty.

If you supply no message, the shell provides a default message.

The ${var?} construct is portable back to Version 7 UNIX and the Bourne Shell (1978 or thereabouts). The ${var:?} construct is slightly more recent: I think it was in System III UNIX circa 1981, but it may have been in PWB UNIX before that. It is therefore in the Korn Shell, and in the POSIX shells, including specifically Bash.

It is usually documented in the shell's man page in a section called Parameter Expansion. For example, the bash manual says:

${parameter:?word}

Display Error if Null or Unset. If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.

The Colon Command

I should probably add that the colon command simply has its arguments evaluated and then succeeds. It is the original shell comment notation (before '#' to end of line). For a long time, Bourne shell scripts had a colon as the first character. The C Shell would read a script and use the first character to determine whether it was for the C Shell (a '#' hash) or the Bourne shell (a ':' colon). Then the kernel got in on the act and added support for '#!/path/to/program' and the Bourne shell got '#' comments, and the colon convention went by the wayside. But if you come across a script that starts with a colon, now you will know why.


Position of double quotes

blong asked in a comment:

Any thoughts on this discussion? https://github.com/koalaman/shellcheck/issues/380#issuecomment-145872749

The gist of the discussion is:

… However, when I shellcheck it (with version 0.4.1), I get this message:

In script.sh line 13:
: ${FOO:?"The environment variable 'FOO' must be set and non-empty"}
  ^-- SC2086: Double quote to prevent globbing and word splitting.

Any advice on what I should do in this case?

The short answer is "do as shellcheck suggests":

: "${STATE?Need to set STATE}"
: "${DEST:?Need to set DEST non-empty}"

To illustrate why, study the following. Note that the : command doesn't echo its arguments (but the shell does evaluate the arguments). We want to see the arguments, so the code below uses printf "%s\n" in place of :.

$ mkdir junk
$ cd junk
$ > abc
$ > def
$ > ghi
$ 
$ x="*"
$ printf "%s\n" ${x:?You must set x}    # Careless; not recommended
abc
def
ghi
$ unset x
$ printf "%s\n" ${x:?You must set x}    # Careless; not recommended
bash: x: You must set x
$ printf "%s\n" "${x:?You must set x}"  # Careful: should be used
bash: x: You must set x
$ x="*"
$ printf "%s\n" "${x:?You must set x}"  # Careful: should be used
*
$ printf "%s\n" ${x:?"You must set x"}  # Not quite careful enough
abc
def
ghi
$ x=
$ printf "%s\n" ${x:?"You must set x"}  # Not quite careful enough
bash: x: You must set x
$ unset x
$ printf "%s\n" ${x:?"You must set x"}  # Not quite careful enough
bash: x: You must set x
$ 

Note how the value in $x is expanded to first * and then a list of file names when the overall expression is not in double quotes. This is what shellcheck is recommending should be fixed. I have not verified that it doesn't object to the form where the expression is enclosed in double quotes, but it is a reasonable assumption that it would be OK.

Where are static methods and static variables stored in Java?

Prior to Java 8:

The static variables were stored in the permgen space(also called the method area).

PermGen Space is also known as Method Area

PermGen Space used to store 3 things

  1. Class level data (meta-data)
  2. interned strings
  3. static variables

From Java 8 onwards

The static variables are stored in the Heap itself.From Java 8 onwards the PermGen Space have been removed and new space named as MetaSpace is introduced which is not the part of Heap any more unlike the previous Permgen Space. Meta-Space is present on the native memory (memory provided by the OS to a particular Application for its own usage) and it now only stores the class meta-data.

The interned strings and static variables are moved into the heap itself.

For official information refer : JEP 122:Remove the Permanent Gen Space

From ND to 1D arrays

Use np.ravel (for a 1D view) or np.ndarray.flatten (for a 1D copy) or np.ndarray.flat (for an 1D iterator):

In [12]: a = np.array([[1,2,3], [4,5,6]])

In [13]: b = a.ravel()

In [14]: b
Out[14]: array([1, 2, 3, 4, 5, 6])

Note that ravel() returns a view of a when possible. So modifying b also modifies a. ravel() returns a view when the 1D elements are contiguous in memory, but would return a copy if, for example, a were made from slicing another array using a non-unit step size (e.g. a = x[::2]).

If you want a copy rather than a view, use

In [15]: c = a.flatten()

If you just want an iterator, use np.ndarray.flat:

In [20]: d = a.flat

In [21]: d
Out[21]: <numpy.flatiter object at 0x8ec2068>

In [22]: list(d)
Out[22]: [1, 2, 3, 4, 5, 6]

how to access the command line for xampp on windows

Run PHP file from command Promp.

Please set Environment Variable as per below mention steps.

  1. Right Click on MY Computer Icon and Click on Properties or Go to "Control Panel\System and Security\System".
  2. Select "Advanced System Settings" and select "Advance" Tab
  3. Now Select "Environment Variable" option and select "Path" from "System Variables" and click on "Edit" button
  4. Now set path where php.exe file is available - For example if XAMPP install in to C: drive then Path is "C:\xampp\php"
  5. After set path Click Ok and Apply.

Now open Command prompt where your source file are available and run command "php test.php"

How to check SQL Server version

TL;DR

SQLCMD -S (LOCAL) -E -V 16 -Q "IF(ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS INT),0)<11) RAISERROR('You need SQL 2012 or later!',16,1)"
IF ERRORLEVEL 1 GOTO :ExitFail

This uses SQLCMD (comes with SQL Server) to connect to the local server instance using Windows auth, throw an error if a version check fails and return the @@ERROR as the command line ERRORLEVEL if >= 16 (and the second line goes to the :ExitFail label if the aforementioned ERRORLEVEL is >= 1).

Watchas, Gotchas & More Info

For SQL 2000+ you can use the SERVERPROPERTY to determine a lot of this info.

While SQL 2008+ supports the ProductMajorVersion & ProductMinorVersion properties, ProductVersion has been around since 2000 (remembering that if a property is not supported the function returns NULL).

If you are interested in earlier versions you can use the PARSENAME function to split the ProductVersion (remembering the "parts" are numbered right to left i.e. PARSENAME('a.b.c', 1) returns c).

Also remember that PARSENAME('a.b.c', 4) returns NULL, because SQL 2005 and earlier only used 3 parts in the version number!

So for SQL 2008+ you can simply use:

SELECT
    SERVERPROPERTY('ProductVersion') AS ProductVersion,
    CAST(SERVERPROPERTY('ProductMajorVersion')  AS INT) AS ProductMajorVersion,
    CAST(SERVERPROPERTY ('ProductMinorVersion') AS INT) AS ProductMinorVersion;

For SQL 2000-2005 you can use:

SELECT
    SERVERPROPERTY('ProductVersion') AS ProductVersion,
    CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME), CASE WHEN SERVERPROPERTY('ProductVersion') IS NULL THEN 3 ELSE 4 END) AS INT) AS ProductVersion_Major,
    CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME), CASE WHEN SERVERPROPERTY('ProductVersion') IS NULL THEN 2 ELSE 3 END) AS INT) AS ProductVersion_Minor,
    CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME), CASE WHEN SERVERPROPERTY('ProductVersion') IS NULL THEN 1 ELSE 2 END) AS INT) AS ProductVersion_Revision,
    CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME), CASE WHEN SERVERPROPERTY('ProductVersion') IS NULL THEN 0 ELSE 1 END) AS INT) AS ProductVersion_Build;

(the PARSENAME(...,0) is a hack to improve readability)

So a check for a SQL 2000+ version would be:

IF (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME), CASE WHEN SERVERPROPERTY('ProductVersion') IS NULL THEN 3 ELSE 4 END) AS INT) < 10) -- SQL2008
OR (
    (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME), CASE WHEN SERVERPROPERTY('ProductVersion') IS NULL THEN 3 ELSE 4 END) AS INT) = 10) -- SQL2008
AND (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME), CASE WHEN SERVERPROPERTY('ProductVersion') IS NULL THEN 2 ELSE 1 END) AS INT) < 5)  -- R2 (this may need to be 50)
   )
    RAISERROR('You need SQL 2008R2 or later!', 16, 1);

This is a lot simpler if you're only only interested in SQL 2008+ because SERVERPROPERTY('ProductMajorVersion') returns NULL for earlier versions, so you can use:

IF (ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS INT), 0) < 11) -- SQL2012
    RAISERROR('You need SQL 2012 or later!', 16, 1);

And you can use the ProductLevel and Edition (or EngineEdition) properties to determine RTM / SPn / CTPn and Dev / Std / Ent / etc respectively.

SELECT
    CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME) AS ProductVersion,
    CAST(SERVERPROPERTY('ProductLevel') AS SYSNAME)   AS ProductLevel,
    CAST(SERVERPROPERTY('Edition') AS SYSNAME)        AS Edition,
    CAST(SERVERPROPERTY('EngineEdition') AS INT)      AS EngineEdition;

FYI the major SQL version numbers are:

  • 8 = SQL 2000
  • 9 = SQL 2005
  • 10 = SQL 2008 (and 10.5 = SQL 2008R2)
  • 11 = SQL 2012
  • 12 = SQL 2014
  • 13 = SQL 2016
  • 14 = SQL 2017

And this all works for SQL Azure too!

EDITED: You may also want to check your DB compatibility level since it could be set to a lower compatibility.

IF EXISTS (SELECT * FROM sys.databases WHERE database_id=DB_ID() AND [compatibility_level] < 110)
    RAISERROR('Database compatibility level must be SQL2008R2 or later (110)!', 16, 1)

Select Last Row in the Table

To get the last record details, use the code below:

Model::where('field', 'value')->get()->last()

What is "406-Not Acceptable Response" in HTTP?

You mentioned you're using Ruby on Rails as a backend. You didn't post the code for the relevant method, but my guess is that it looks something like this:

def create
  post = Post.create params[:post]
  respond_to do |format|
    format.json { render :json => post }
  end
end

Change it to:

def create
  post = Post.create params[:post])
  render :json => post
end

And it will solve your problem. It worked for me :)

Get file content from URL?

Use file_get_contents in combination with json_decode and echo.

what's data-reactid attribute in html?

That's the HTML data attribute. See this for more detail: http://html5doctor.com/html5-custom-data-attributes/

Basically it's just a container of your custom data while still making the HTML valid. It's data- plus some unique identifier.

How do I check out a specific version of a submodule using 'git submodule'?

Step 1: Add the submodule

   git submodule add git://some_repository.git some_repository

Step 2: Fix the submodule to a particular commit

By default the new submodule will be tracking HEAD of the master branch, but it will NOT be updated as you update your primary repository. In order to change the submodule to track a particular commit or different branch, change directory to the submodule folder and switch branches just like you would in a normal repository.

   git checkout -b some_branch origin/some_branch

Now the submodule is fixed on the development branch instead of HEAD of master.

From Two Guys Arguing — Tie Git Submodules to a Particular Commit or Branch .

How can I send an HTTP POST request to a server from Excel using VBA?

To complete the response of the other users:

For this I have created an "WinHttp.WinHttpRequest.5.1" object.

Send a post request with some data from Excel using VBA:

Dim LoginRequest As Object
Set LoginRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
LoginRequest.Open "POST", "http://...", False
LoginRequest.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
LoginRequest.send ("key1=value1&key2=value2")

Send a get request with token authentication from Excel using VBA:

Dim TCRequestItem As Object
Set TCRequestItem = CreateObject("WinHttp.WinHttpRequest.5.1")
TCRequestItem.Open "GET", "http://...", False
TCRequestItem.setRequestHeader "Content-Type", "application/xml"
TCRequestItem.setRequestHeader "Accept", "application/xml"
TCRequestItem.setRequestHeader "Authorization", "Bearer " & token
TCRequestItem.send

Is SQL syntax case sensitive?

No. MySQL is not case sensitive, and neither is the SQL standard. It's just common practice to write the commands upper-case.

Now, if you are talking about table/column names, then yes they are, but not the commands themselves.

So

SELECT * FROM foo;

is the same as

select * from foo;

but not the same as

select * from FOO;

How to remove array element in mongodb?

This below code will remove the complete object element from the array, where the phone number is '+1786543589455'

db.collection.update(
  { _id: id },
  { $pull: { 'contact': { number: '+1786543589455' } } }
);

vertical-align with Bootstrap 3

I ran into this same issue. In my case I did not know the height of the outer container, but this is how I fixed it:

First set the height for your html and body elements so that they are 100%. This is important! Without this, the html and body elements will simply inherit the height of their children.

html, body {
   height: 100%;
}

Then I had an outer container class with:

.container {
  display: table;
  width: 100%;
  height: 100%; /* For at least Firefox */
  min-height: 100%;
}

And lastly the inner container with class:

.inner-container {
  display: table-cell;
  vertical-align: middle;
}

HTML is as simple as:

<body>
   <div class="container">
     <div class="inner-container">
        <p>Vertically Aligned</p>
     </div>
   </div>
</body>

This is all you need to vertically align contents. Check it out in fiddle:

Jsfiddle

month name to month number and vice versa in python

form month name to number
d=['JAN','FEB','MAR','April','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC']
N=input()
for i in range(len(d)):
    if d[i] == N:
        month=(i+1)
print(month)

BeautifulSoup getText from between <p>, not picking up subsequent paragraphs

This works well for specific articles where the text is all wrapped in <p> tags. Since the web is an ugly place, it's not always the case.

Often, websites will have text scattered all over, wrapped in different types of tags (e.g. maybe in a <span> or a <div>, or an <li>).

To find all text nodes in the DOM, you can use soup.find_all(text=True).

This is going to return some undesired text, like the contents of <script> and <style> tags. You'll need to filter out the text contents of elements you don't want.

blacklist = [
  'style',
  'script',
  # other elements,
]

text_elements = [t for t in soup.find_all(text=True) if t.parent.name not in blacklist]

If you are working with a known set of tags, you can tag the opposite approach:

whitelist = [
  'p'
]

text_elements = [t for t in soup.find_all(text=True) if t.parent.name in whitelist]

How to quickly check if folder is empty (.NET)?

private static void test()
{
    System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
    sw.Start();

    string [] dirs = System.IO.Directory.GetDirectories("C:\\Test\\");
    string[] files = System.IO.Directory.GetFiles("C:\\Test\\");

    if (dirs.Length == 0 && files.Length == 0)
        Console.WriteLine("Empty");
    else
        Console.WriteLine("Not Empty");

    sw.Stop();
    Console.WriteLine(sw.ElapsedMilliseconds);
}

This quick test came back in 2 milliseconds for the folder when empty and when containing subfolders & files (5 folders with 5 files in each)

if, elif, else statement issues in Bash

Missing space between elif and [ rest your program is correct. you need to correct it an check it out. here is fixed program:

#!/bin/bash

if [ "$seconds" -eq 0 ]; then
   timezone_string="Z"
elif [ "$seconds" -gt 0 ]; then
   timezone_string=$(printf "%02d:%02d" $((seconds/3600)) $(((seconds / 60) % 60)))
else
   echo "Unknown parameter"
fi

useful link related to this bash if else statement

R: Plotting a 3D surface from x, y, z

Maybe is late now but following Spacedman, did you try duplicate="strip" or any other option?

x=runif(1000)
y=runif(1000)
z=rnorm(1000)
s=interp(x,y,z,duplicate="strip")
surface3d(s$x,s$y,s$z,color="blue")
points3d(s)

jQuery select by attribute using AND and OR operators

The and operator in a selector is just an empty string, and the or operator is the comma.

There is however no grouping or priority, so you have to repeat one of the conditions:

a=$('[myc=blue][myid="1"],[myc=blue][myid="3"]');

Custom designing EditText

enter image description here

For EditText in image above, You have to create two xml files in res-->drawable folder. First will be "bg_edittext_focused.xml" paste the lines of code in it

<?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" >
        <solid android:color="#FFFFFF" />
        <stroke
            android:width="2dip"
            android:color="#F6F6F6" />
        <corners android:radius="2dip" />
        <padding
            android:bottom="7dip"
            android:left="7dip"
            android:right="7dip"
            android:top="7dip" />
    </shape>

Second file will be "bg_edittext_normal.xml" paste the lines of code in it

<?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" >
        <solid android:color="#F6F6F6" />
        <stroke
            android:width="2dip"
            android:color="#F6F6F6" />
        <corners android:radius="2dip" />
        <padding
            android:bottom="7dip"
            android:left="7dip"
            android:right="7dip"
            android:top="7dip" />
    </shape>

In res-->drawable folder create another xml file with name "bg_edittext.xml" that will call above mentioned code. paste the following lines of code below in bg_edittext.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/bg_edittext_focused" android:state_focused="true"/>
    <item android:drawable="@drawable/bg_edittext_normal"/>
</selector>

Finally in res-->layout-->example.xml file in your case wherever you created your editText you'll call bg_edittext.xml as background

   <EditText
    :::::
    :::::  
    android:background="@drawable/bg_edittext"
    :::::
    :::::
    />

How can I read command line parameters from an R script?

Since optparse has been mentioned a couple of times in the answers, and it provides a comprehensive kit for command line processing, here's a short simplified example of how you can use it, assuming the input file exists:

script.R:

library(optparse)

option_list <- list(
  make_option(c("-n", "--count_lines"), action="store_true", default=FALSE,
    help="Count the line numbers [default]"),
  make_option(c("-f", "--factor"), type="integer", default=3,
    help="Multiply output by this number [default %default]")
)

parser <- OptionParser(usage="%prog [options] file", option_list=option_list)

args <- parse_args(parser, positional_arguments = 1)
opt <- args$options
file <- args$args

if(opt$count_lines) {
  print(paste(length(readLines(file)) * opt$factor))
}

Given an arbitrary file blah.txt with 23 lines.

On the command line:

Rscript script.R -h outputs

Usage: script.R [options] file


Options:
        -n, --count_lines
                Count the line numbers [default]

        -f FACTOR, --factor=FACTOR
                Multiply output by this number [default 3]

        -h, --help
                Show this help message and exit

Rscript script.R -n blah.txt outputs [1] "69"

Rscript script.R -n -f 5 blah.txt outputs [1] "115"

Structuring online documentation for a REST API

That's a very complex question for a simple answer.

You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.

Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.

At the very top level I think quality REST API docs require at least the following:

  • a list of all your API endpoints (base/relative URLs)
  • corresponding HTTP GET/POST/... method type for each endpoint
  • request/response MIME-type (how to encode params and parse replies)
  • a sample request/response, including HTTP headers
  • type and format specified for all params, including those in the URL, body and headers
  • a brief text description and important notes
  • a short code snippet showing the use of the endpoint in popular web programming languages

Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.

Correct syntax to compare values in JSTL <c:if test="${values.type}=='object'">

The comparison needs to be evaluated fully inside EL ${ ... }, not outside.

<c:if test="${values.type eq 'object'}">

As to the docs, those ${} things are not JSTL, but EL (Expression Language) which is a whole subject at its own. JSTL (as every other JSP taglib) is just utilizing it. You can find some more EL examples here.

<c:if test="#{bean.booleanValue}" />
<c:if test="#{bean.intValue gt 10}" />
<c:if test="#{bean.objectValue eq null}" />
<c:if test="#{bean.stringValue ne 'someValue'}" />
<c:if test="#{not empty bean.collectionValue}" />
<c:if test="#{not bean.booleanValue and bean.intValue ne 0}" />
<c:if test="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />

See also:


By the way, unrelated to the concrete problem, if I guess your intent right, you could also just call Object#getClass() and then Class#getSimpleName() instead of adding a custom getter.

<c:forEach items="${list}" var="value">
    <c:if test="${value['class'].simpleName eq 'Object'}">
        <!-- code here -->
    </c:if>
</c:forEeach>

See also:

How to add a local repo and treat it as a remote repo

I am posting this answer to provide a script with explanations that covers three different scenarios of creating a local repo that has a local remote. You can run the entire script and it will create the test repos in your home folder (tested on windows git bash). The explanations are inside the script for easier saving to your personal notes, its very readable from, e.g. Visual Studio Code.

I would also like to thank Jack for linking to this answer where adelphus has good, detailed, hands on explanations on the topic.

This is my first post here so please advise what should be improved.

## SETUP LOCAL GIT REPO WITH A LOCAL REMOTE
# the main elements:
# - remote repo must be initialized with --bare parameter
# - local repo must be initialized
# - local repo must have at least one commit that properly initializes a branch(root of the commit tree)
# - local repo needs to have a remote
# - local repo branch must have an upstream branch on the remote

{ # the brackets are optional, they allow to copy paste into terminal and run entire thing without interruptions, run without them to see which cmd outputs what

cd ~
rm -rf ~/test_git_local_repo/

## Option A - clean slate - you have nothing yet

mkdir -p ~/test_git_local_repo/option_a ; cd ~/test_git_local_repo/option_a
git init --bare local_remote.git # first setup the local remote
git clone local_remote.git local_repo # creates a local repo in dir local_repo
cd ~/test_git_local_repo/option_a/local_repo
git remote -v show origin # see that git clone has configured the tracking
touch README.md ; git add . ; git commit -m "initial commit on master" # properly init master
git push origin master # now have a fully functional setup, -u not needed, git clone does this for you

# check all is set-up correctly
git pull # check you can pull
git branch -avv # see local branches and their respective remote upstream branches with the initial commit
git remote -v show origin # see all branches are set to pull and push to remote
git log --oneline --graph --decorate --all # see all commits and branches tips point to the same commits for both local and remote

## Option B - you already have a local git repo and you want to connect it to a local remote

mkdir -p ~/test_git_local_repo/option_b ; cd ~/test_git_local_repo/option_b
git init --bare local_remote.git # first setup the local remote

# simulate a pre-existing git local repo you want to connect with the local remote
mkdir local_repo ; cd local_repo
git init # if not yet a git repo
touch README.md ; git add . ; git commit -m "initial commit on master" # properly init master
git checkout -b develop ; touch fileB ; git add . ; git commit -m "add fileB on develop" # create develop and fake change

# connect with local remote
cd ~/test_git_local_repo/option_b/local_repo
git remote add origin ~/test_git_local_repo/option_b/local_remote.git
git remote -v show origin # at this point you can see that there is no the tracking configured (unlike with git clone), so you need to push with -u
git push -u origin master # -u to set upstream
git push -u origin develop # -u to set upstream; need to run this for every other branch you already have in the project

# check all is set-up correctly
git pull # check you can pull
git branch -avv # see local branch(es) and its remote upstream with the initial commit
git remote -v show origin # see all remote branches are set to pull and push to remote
git log --oneline --graph --decorate --all # see all commits and branches tips point to the same commits for both local and remote

## Option C - you already have a directory with some files and you want it to be a git repo with a local remote

mkdir -p ~/test_git_local_repo/option_c ; cd ~/test_git_local_repo/option_c
git init --bare local_remote.git # first setup the local remote

# simulate a pre-existing directory with some files
mkdir local_repo ; cd local_repo ; touch README.md fileB

# make a pre-existing directory a git repo and connect it with local remote
cd ~/test_git_local_repo/option_c/local_repo
git init
git add . ; git commit -m "inital commit on master" # properly init master
git remote add origin ~/test_git_local_repo/option_c/local_remote.git
git remote -v show origin # see there is no the tracking configured (unlike with git clone), so you need to push with -u
git push -u origin master # -u to set upstream

# check all is set-up correctly
git pull # check you can pull
git branch -avv # see local branch and its remote upstream with the initial commit
git remote -v show origin # see all remote branches are set to pull and push to remote
git log --oneline --graph --decorate --all # see all commits and branches tips point to the same commits for both local and remote
}

Print array without brackets and commas

I have used Arrays.toString(array_name).replace("[","").replace("]","").replace(", ",""); as I have seen it from some of the comments above, but also i added an additional space character after the comma (the part .replace(", ","")), because while I was printing out each value in a new line, there was still the space character shifting the words. It solved my problem.

how to compare two elements in jquery

You could compare DOM elements. Remember that jQuery selectors return arrays which will never be equal in the sense of reference equality.

Assuming:

<div id="a" class="a"></div>

this:

$('div.a')[0] == $('div#a')[0]

returns true.

How to split a long array into smaller arrays, with JavaScript

Assuming you don't want to destroy the original array, you can use code like this to break up the long array into smaller arrays which you can then iterate over:

var longArray = [];   // assume this has 100 or more email addresses in it
var shortArrays = [], i, len;

for (i = 0, len = longArray.length; i < len; i += 10) {
    shortArrays.push(longArray.slice(i, i + 10));
}

// now you can iterate over shortArrays which is an 
// array of arrays where each array has 10 or fewer 
// of the original email addresses in it

for (i = 0, len = shortArrays.length; i < len; i++) {
    // shortArrays[i] is an array of email addresss of 10 or less
}

PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers

My case was that i was using RDS (mysql db verion 8) of AWS and was connecting my application through EC2 (my php code 5.6 was in EC2).

Here in this case since it is RDS there is no my.cnf the parameters are maintained by PARAMETER Group of AWS. Refer: https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithParamGroups.html

so what i did was:

  1. Created a new Parameter group and then edited them.

  2. Searched all character-set parameters. These are blank by default. edit them individually and select utf8 from drop down list.

character_set_client, character_set_connection, character_set_database, character_set_server

  1. SAVE

And then most important, Rebooted RDS instance.

This has solved my problem and connection from php5.6 to mysql 8.x was working great.

hope this helps.

Please view this image for better understanding. enter image description here

Get int from String, also containing letters, in Java

Perhaps get the size of the string and loop through each character and call isDigit() on each character. If it is a digit, then add it to a string that only collects the numbers before calling Integer.parseInt().

Something like:

    String something = "423e";
    int length = something.length();
    String result = "";
    for (int i = 0; i < length; i++) {
        Character character = something.charAt(i);
        if (Character.isDigit(character)) {
            result += character;
        }
    }
    System.out.println("result is: " + result);

How to extend a class in python?

class MyParent:

    def sayHi():
        print('Mamma says hi')
from path.to.MyParent import MyParent

class ChildClass(MyParent):
    pass

An instance of ChildClass will then inherit the sayHi() method.

ORA-00932: inconsistent datatypes: expected - got CLOB

You can't put a CLOB in the WHERE clause. From the documentation:

Large objects (LOBs) are not supported in comparison conditions. However, you can use PL/SQL programs for comparisons on CLOB data.

If your values are always less than 4k, you can use:

UPDATE IMS_TEST 
   SET TEST_Category           = 'just testing'  
 WHERE to_char(TEST_SCRIPT)    = 'something'
   AND ID                      = '10000239';

It is strange to search by a CLOB anyways.. could you not just search by the ID column?

Can a unit test project load the target application's app.config file?

If you are using NUnit, take a look at this post. Basically you'll need to have your app.config in the same directory as your .nunit file.

Is there a way to get LaTeX to place figures in the same page as a reference to that figure?

I have some useful comments. Because I had similar problem with location of figures. I used package "wrapfig" that allows to make figures wrapped by text. Something like

...
\usepackage{wrapfig}
\usepackage{graphicx}
...
\begin{wrapfigure}{r}{53pt}
\includegraphics[width=53pt]{cone.pdf}
\end{wrapfigure}

In options {r} means to put figure from right side. {l} can be use for left side.

How do I delete an exported environment variable?

As mentioned in the above answers, unset GNUPLOT_DRIVER_DIR should work if you have used export to set the variable. If you have set it permanently in ~/.bashrc or ~/.zshrc then simply removing it from there will work.

How to get time (hour, minute, second) in Swift 3 using NSDate?

For best useful I create this function:

func dateFormatting() -> String {
    let date = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "EEEE dd MMMM yyyy - HH:mm:ss"//"EE" to get short style
    let mydt = dateFormatter.string(from: date).capitalized

    return "\(mydt)"
}

You simply call it wherever you want like this:

print("Date = \(self.dateFormatting())")

this is the Output:

Date = Monday 15 October 2018 - 17:26:29

if want only the time simply change :

dateFormatter.dateFormat  = "HH:mm:ss"

and this is the output:

Date = 17:27:30

and that's it...

How to get all Errors from ASP.Net MVC modelState?

Using LINQ:

IEnumerable<ModelError> allErrors = ModelState.Values.SelectMany(v => v.Errors);

JavaScript/jQuery - "$ is not defined- $function()" error

Try:

(function($) {
    $(function() {
        $('.update').live('change', function() {
            formObject.run($(this));
        });
    });
})(jQuery);

By using this way you ensure the global variable jQuery will be bound to the "$" inside the closure. Just make sure jQuery is properly loaded into the page by inserting:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>

Replace "http://code.jquery.com/jquery-1.7.1.min.js" to the path where your jQuery source is located within the page context.

Padding In bootstrap

I have not used Bootstrap but I worked on Zurb Foundation. On that I used to add space like this.

<div id="main" class="container" role="main">
    <div class="row">

        <div class="span5 offset1">
            <h2>Welcome</h2>
            <p>Hello and welcome to my website.</p>
        </div>
        <div class="span6">
            Image Here (TODO)
        </div>
    </div>

Visit this link: http://getbootstrap.com/2.3.2/scaffolding.html and read the section: Offsetting columns.

I think I know what you are doing wrong. If you are applying padding to the span6 like this:

<div class="span6" style="padding-left:5px;">
    <h2>Welcome</h2>
    <p>Hello and welcome to my website.</p>
</div>

It is wrong. What you have to do is add padding to the elements inside:

<div class="span6">
    <h2 style="padding-left:5px;">Welcome</h2>
    <p  style="padding-left:5px;">Hello and welcome to my website.</p>
</div>

How can I convert a .jar to an .exe?

JSmooth .exe wrapper

JSmooth is a Java Executable Wrapper. It creates native Windows launchers (standard .exe) for your Java applications. It makes java deployment much smoother and user-friendly, as it is able to find any installed Java VM by itself. When no VM is available, the wrapper can automatically download and install a suitable JVM, or simply display a message or redirect the user to a website.

JSmooth provides a variety of wrappers for your java application, each of them having their own behavior: Choose your flavor!

Download: http://jsmooth.sourceforge.net/

JarToExe 1.8 Jar2Exe is a tool to convert jar files into exe files. Following are the main features as describe on their website:

Can generate “Console”, “Windows GUI”, “Windows Service” three types of .exe files.

Generated .exe files can add program icons and version information. Generated .exe files can encrypt and protect java programs, no temporary files will be generated when the program runs.

Generated .exe files provide system tray icon support. Generated .exe files provide record system event log support. Generated windows service .exe files are able to install/uninstall itself, and support service pause/continue.

Executor

Package your Java application as a jar, and Executor will turn the jar into a Windows .exe file, indistinguishable from a native application. Simply double-clicking the .exe file will invoke the Java Runtime Environment and launch your application.

Dynamically create an array of strings with malloc

Given that your strings are all fixed-length (presumably at compile-time?), you can do the following:

char (*orderedIds)[ID_LEN+1]
    = malloc(variableNumberOfElements * sizeof(*orderedIds));

// Clear-up
free(orderedIds);

A more cumbersome, but more general, solution, is to assign an array of pointers, and psuedo-initialising them to point at elements of a raw backing array:

char *raw = malloc(variableNumberOfElements * (ID_LEN + 1));
char **orderedIds = malloc(sizeof(*orderedIds) * variableNumberOfElements);

// Set each pointer to the start of its corresponding section of the raw buffer.
for (i = 0; i < variableNumberOfElements; i++)
{
    orderedIds[i] = &raw[i * (ID_LEN+1)];
}

...

// Clear-up pointer array
free(orderedIds);
// Clear-up raw array
free(raw);

node.js Error: connect ECONNREFUSED; response from server

I had the same problem on my mac, but in my case, the problem was that I did not run the database (sudo mongod) before; the problem was solved when I first ran the mondo sudod on the console and, once it was done, on another console, the connection to the server ...

Could not load file or assembly 'Microsoft.ReportViewer.WebForms'

Upload the file Microsoft.ReportViewer.WebForms.dll to your bin directory of your web applicaion.

You can find this dll file in the bin directory of your local web application.

Reading a column from CSV file using JAVA

You are not changing the value of line. It should be something like this.

import java.io.BufferedReader;
import java.io.FileReader;

public class InsertValuesIntoTestDb {

  @SuppressWarnings("rawtypes")
  public static void main(String[] args) throws Exception {
      String splitBy = ",";
      BufferedReader br = new BufferedReader(new FileReader("test.csv"));
      while((line = br.readLine()) != null){
           String[] b = line.split(splitBy);
           System.out.println(b[0]);
      }
      br.close();

  }
}

readLine returns each line and only returns null when there is nothing left. The above code sets line and then checks if it is null.

Make DateTimePicker work as TimePicker only in WinForms

The best way to do this is this:

datetimepicker.Format = DatetimePickerFormat.Custom;
datetimepicker.CustomFormat = "HH:mm tt";
datetimepicker.ShowUpDowm = true;

C++ Object Instantiation

The only reason I'd worry about is that Dog is now allocated on the stack, rather than the heap. So if Dog is megabytes in size, you may have a problem,

If you do need to go the new/delete route, be wary of exceptions. And because of this you should use auto_ptr or one of the boost smart pointer types to manage the object lifetime.

How do I get a decimal value when using the division operator in Python?

Here we have two possible cases given below

from __future__ import division

print(4/100)
print(4//100)

How do I correctly clone a JavaScript object?

//
// creates 'clone' method on context object
//
//  var 
//     clon = Object.clone( anyValue );
//
!((function (propertyName, definition) {
    this[propertyName] = definition();
}).call(
    Object,
    "clone",
    function () {
        function isfn(fn) {
            return typeof fn === "function";
        }

        function isobj(o) {
            return o === Object(o);
        }

        function isarray(o) {
            return Object.prototype.toString.call(o) === "[object Array]";
        }

        function fnclon(fn) {
            return function () {
                fn.apply(this, arguments);
            };
        }

        function owns(obj, p) {
            return obj.hasOwnProperty(p);
        }

        function isemptyobj(obj) {
            for (var p in obj) {
                return false;
            }
            return true;
        }

        function isObject(o) {
            return Object.prototype.toString.call(o) === "[object Object]";
        }
        return function (input) {
            if (isfn(input)) {
                return fnclon(input);
            } else if (isobj(input)) {
                var cloned = {};
                for (var p in input) {
                    owns(Object.prototype, p)
                    || (
                        isfn(input[p])
                        && ( cloned[p] = function () { return input[p].apply(input, arguments); } )
                        || ( cloned[p] = input[p] )
                    );
                }
                if (isarray(input)) {
                    cloned.length = input.length;
                    "concat every filter forEach indexOf join lastIndexOf map pop push reduce reduceRight reverse shift slice some sort splice toLocaleString toString unshift"
                    .split(" ")
                    .forEach(
                      function (methodName) {
                        isfn( Array.prototype[methodName] )
                        && (
                            cloned[methodName] =
                            function () {
                                return Array.prototype[methodName].apply(cloned, arguments);
                            }
                        );
                      }
                    );
                }
                return isemptyobj(cloned)
                       ? (
                          isObject(input)
                          ? cloned
                          : input
                        )
                       : cloned;
            } else {
                return input;
            }
        };
    }
));
//

PHP Parse error: syntax error, unexpected '?' in helpers.php 233

I had the same problem with the laravel initiation. The solution was as follows.

1st - I checked the version of my PHP. That it was 5.6 would soon give problem with the laravel.

2nd - I changed the version of my PHP to PHP 7.1.1. ATTENTION, in my case I changed my environment variable that was getting Xampp's PHP version 5.6 I changed to 7.1.1 for laragon.

3rd - I went to the terminal / console and navigated to my folder where my project was and typed the following command: php artisan serves. And it worked! In my case it started at the port: 8000 see example below.

C: \ laragon \ www \ first> php artisan serves Laravel development server started: http://127.0.0.1:8000

I hope I helped someone who has been through the same problem as me.

Indent multiple lines quickly in vi

I don’t know why it's so difficult to find a simple answer like this one...

I myself had to struggle a lot to know this. It's very simple:

  • Edit your .vimrc file under the home directory.
  • Add this line

    set cindent
    

    in your file where you want to indent properly.

  • In normal/command mode type

    10==   (This will indent 10 lines from the current cursor location)
    gg=G   (Complete file will be properly indented)