Programs & Examples On #Application design

File Upload in WebView

this is the only solution that i found that works!

WebView webview;

private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE = 1;

@Override
protected void onActivityResult(int requestCode, int resultCode,
        Intent intent) {
    if (requestCode == FILECHOOSER_RESULTCODE) {
        if (null == mUploadMessage)
            return;
        Uri result = intent == null || resultCode != RESULT_OK ? null
                : intent.getData();
        mUploadMessage.onReceiveValue(result);
        mUploadMessage = null;

    }
}

// Next part 

class MyWebChromeClient extends WebChromeClient {
    // The undocumented magic method override
    // Eclipse will swear at you if you try to put @Override here
    public void openFileChooser(ValueCallback<Uri> uploadMsg) {

        mUploadMessage = uploadMsg;
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        Cv5appActivity.this.startActivityForResult(
                Intent.createChooser(i, "Image Browser"),
                FILECHOOSER_RESULTCODE);
    }
}

Currency formatting in Python

If you are using OSX and have yet to set your locale module setting this first answer will not work you will receive the following error:

Traceback (most recent call last):File "<stdin>", line 1, in <module> File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/locale.py", line 221, in currency
raise ValueError("Currency formatting is not possible using "ValueError: Currency formatting is not possible using the 'C' locale.

To remedy this you will have to do use the following:

locale.setlocale(locale.LC_ALL, 'en_US')

How do I select the parent form based on which submit button is clicked?

i used the following method & it worked fine for me

$('#mybutton').click(function(){
        clearForm($('#mybutton').closest("form"));
    });

$('#mybutton').closest("form") did the trick for me.

Why is the time complexity of both DFS and BFS O( V + E )

I think every edge has been considered twice and every node has been visited once, so the total time complexity should be O(2E+V).

Java Currency Number format

I'm using this one (using StringUtils from commons-lang):

Double qty = 1.01;
String res = String.format(Locale.GERMANY, "%.2f", qty);
String fmt = StringUtils.removeEnd(res, ",00");

You must only take care of the locale and the corresponding String to chop.

Transform hexadecimal information to binary using a Linux command

As @user786653 suggested, use the xxd(1) program:

xxd -r -p input.txt output.bin

How to create Python egg file

You are reading the wrong documentation. You want this: https://setuptools.readthedocs.io/en/latest/setuptools.html#develop-deploy-the-project-source-in-development-mode

  1. Creating setup.py is covered in the distutils documentation in Python's standard library documentation here. The main difference (for python eggs) is you import setup from setuptools, not distutils.

  2. Yep. That should be right.

  3. I don't think so. pyc files can be version and platform dependent. You might be able to open the egg (they should just be zip files) and delete .py files leaving .pyc files, but it wouldn't be recommended.

  4. I'm not sure. That might be “Development Mode”. Or are you looking for some “py2exe” or “py2app” mode?

Difference between xcopy and robocopy

I have written lot of scripts to automate daily backups etc. Previously I used XCopy and then moved to Robocopy. Anyways Robocopy and XCopy both are frequently used in terms of file transfers in Windows. Robocopy stands for Robust File Copy. All type of huge file copying both these commands are used but Robocopy has added options which makes copying easier as well as for debugging purposes.

Having said that lets talk about features between these two.

  • Robocopy becomes handy for mirroring or synchronizing directories. It also checks the files in the destination directory against the files to be copied and doesn't waste time copying unchanged files.

  • Just like myself, if you are into automation to take daily backups etc, "Run Hours - /RH" becomes very useful without any interactions. This is supported by Robocopy. It allows you to set when copies should be done rather than the time of the command as with XCopy. You will see robocopy.exe process in task list since it will run background to monitor clock to execute when time is right to copy.

  • Robocopy supports file and directory monitoring with the "/MON" or "/MOT" commands.

  • Robocopy gives extra support for copying over the "archive" attribute on files, it supports copying over all attributes including timestamps, security, owner, and auditing information.

Hope this helps you.

How do I add a library path in cmake?

might fail working with link_directories, then add each static library like following:

target_link_libraries(foo /path_to_static_library/libbar.a)

Convert integer to class Date

as.character() would be the general way rather than use paste() for its side effect

> v <- 20081101
> date <- as.Date(as.character(v), format = "%Y%m%d")
> date
[1] "2008-11-01"

(I presume this is a simple example and something like this:

v <- "20081101"

isn't possible?)

Starting of Tomcat failed from Netbeans

It affects at least NetBeans versions 7.4 through 8.0.2. It was first reported from version 8.0 and fixed in NetBeans 8.1. It would have had the problem for any tomcat version (confirmed for versions 7.0.56 through 8.0.28).

Specifics are described as Netbeans bug #248182.

This problem is also related to postings mentioning the following error output:

'127.0.0.1*' is not recognized as an internal or external command, operable program or batch file.

For a tomcat installed from the zip file, I fixed it by changing the catalina.bat file in the tomcat bin directory.

Find the bellow configuration in your catalina.bat file.

:noJuliConfig
set "JAVA_OPTS=%JAVA_OPTS% %LOGGING_CONFIG%"

:noJuliManager
set "JAVA_OPTS=%JAVA_OPTS% %LOGGING_MANAGER%"

And change it as in below by removing the double quotes:

:noJuliConfig
set JAVA_OPTS=%JAVA_OPTS% %LOGGING_CONFIG%

:noJuliManager
set JAVA_OPTS=%JAVA_OPTS% %LOGGING_MANAGER%

Now save your changes, and start your tomcat from within NetBeans.

How to update a single pod without touching other dependencies

It's 2015

So because pod update SomePod touches everything in the latest versions of cocoapods, I found a workaround.

Follow the next steps:

  1. Remove SomePod from the Podfile

  2. Run pod install

pods will now remove SomePod from our project and from the Podfile.lock file.

  1. Put back SomePod into the Podfile

  2. Run pod install again

This time the latest version of our pod will be installed and saved in the Podfile.lock.

file_get_contents() Breaks Up UTF-8 Characters

Try this too

 $url = 'http://www.domain.com/';
    $html = file_get_contents($url);

    //Change encoding to UTF-8 from ISO-8859-1
    $html = iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $html);

Single vs Double quotes (' vs ")

Quoting Conventions for Web Developers

The Short Answer

In HTML the use of single quotes (') and double quotes (") are interchangeable, there is no difference.

But consistency is recommended, therefore we must pick a syntax convention and use it regularly.

The Long Answer

Web Development often consists of many programming languages. HTML, JS, CSS, PHP, ASP, RoR, Python, ect. Because of this we have many syntax conventions for different programing languages. Often habbits from one language will follow us to other languages, even if it is not considered "proper" i.e. commenting conventions. Quoting conventions also falls into this category for me.

But I tend to use HTML tightly in conjunction with PHP. And in PHP there is a major difference between single quotes and double quotes. In PHP with double quotes "you can insert variables directly within the text of the string". (scriptingok.com) And when using single quotes "the text appears as it is". (scriptingok.com)

PHP takes longer to process double quoted strings. Since the PHP parser has to read the whole string in advance to detect any variable inside—and concatenate it—it takes longer to process than a single quoted string. (scriptingok.com)

 

Single quotes are easier on the server. Since PHP does not need to read the whole string in advance, the server can work faster and happier. (scriptingok.com)

Other things to consider

  1. Frequency of double quotes within string. I find that I need to use double quotes (") within my strings more often than I need to use single quotes (') within strings. To reduce the number of character escapes needed I favor single quote delimiters.
  2. It's easier to make a single quote. This is fairly self explanatory but to clarify, why press the SHIFT key more times then you have to.

My Convention

With this understanding of PHP I have set the convention (for myself and the rest of my company) that strings are to be represented as single quotes by default for server optimization. Double quotes are used within the string if a quotes are required such as JavaScript within an attribute, for example:

<button onClick='func("param");'>Press Me</button>

Of course if we are in PHP and want the parser to handle PHP variables within the string we should intentionally use double quotes. $a='Awesome'; $b = "Not $a";

Sources

Single quotes vs Double quotes in PHP. (n.d.). Retrieved November 26, 2014, from http://www.scriptingok.com/tutorial/Single-quotes-vs-double-quotes-in-PHP

How can I validate google reCAPTCHA v2 using javascript/jQuery?

I used Palek's solution inside a Bootstrap validator and it works. I'd have added a comment to his but I don'y have the rep;). Simplified version:

        $('#form').validator().on('submit', function (e) {
           var response = grecaptcha.getResponse();
           //recaptcha failed validation
           if(response.length == 0) {
               e.preventDefault();
               $('#recaptcha-error').show();
           }
           //recaptcha passed validation
           else {
               $('#recaptcha-error').hide();
           }
           if (e.isDefaultPrevented()) {
              return false;
           } else {
              return true;
           }
       });

Powershell Error "The term 'Get-SPWeb' is not recognized as the name of a cmdlet, function..."

I think this need to be run from the Management Shell rather than the console, it sounds like the module isn't being imported into the Powershell console. You can add the module by running:

Add-PSSnapin Microsoft.Sharepoint.Powershell

in the Powershell console.

StringBuilder vs String concatenation in toString() in Java

For performance reasons, the use of += (String concatenation) is discouraged. The reason why is: Java String is an immutable, every time a new concatenation is done a new String is created (the new one has a different fingerprint from the older one already in the String pool ). Creating new strings puts pressure on the GC and slows down the program: object creation is expensive.

Below code should make it more practical and clear at the same time.

public static void main(String[] args) 
{
    // warming up
    for(int i = 0; i < 100; i++)
        RandomStringUtils.randomAlphanumeric(1024);
    final StringBuilder appender = new StringBuilder();
    for(int i = 0; i < 100; i++)
        appender.append(RandomStringUtils.randomAlphanumeric(i));

    // testing
    for(int i = 1; i <= 10000; i*=10)
        test(i);
}

public static void test(final int howMany) 
{
    List<String> samples = new ArrayList<>(howMany);
    for(int i = 0; i < howMany; i++)
        samples.add(RandomStringUtils.randomAlphabetic(128));

    final StringBuilder builder = new StringBuilder();
    long start = System.nanoTime();
    for(String sample: samples)
        builder.append(sample);
    builder.toString();
    long elapsed = System.nanoTime() - start;
    System.out.printf("builder - %d - elapsed: %dus\n", howMany, elapsed / 1000);

    String accumulator = "";
    start = System.nanoTime();
    for(String sample: samples)
        accumulator += sample;
    elapsed = System.nanoTime() - start;
    System.out.printf("concatenation - %d - elapsed: %dus\n", howMany, elapsed / (int) 1e3);

    start = System.nanoTime();
    String newOne = null;
    for(String sample: samples)
        newOne = new String(sample);
    elapsed = System.nanoTime() - start;
    System.out.printf("creation - %d - elapsed: %dus\n\n", howMany, elapsed / 1000);
}

Results for a run are reported below.

builder - 1 - elapsed: 132us
concatenation - 1 - elapsed: 4us
creation - 1 - elapsed: 5us

builder - 10 - elapsed: 9us
concatenation - 10 - elapsed: 26us
creation - 10 - elapsed: 5us

builder - 100 - elapsed: 77us
concatenation - 100 - elapsed: 1669us
creation - 100 - elapsed: 43us

builder - 1000 - elapsed: 511us
concatenation - 1000 - elapsed: 111504us
creation - 1000 - elapsed: 282us

builder - 10000 - elapsed: 3364us 
concatenation - 10000 - elapsed: 5709793us
creation - 10000 - elapsed: 972us

Not considering the results for 1 concatenation (JIT was not yet doing its job), even for 10 concatenations the performance penalty is relevant; for thousands of concatenations, the difference is huge.

Lessons learned from this very quick experiment (easily reproducible with the above code): never use the += to concatenate strings together, even in very basic cases where a few concatenations are needed (as said, creating new strings is expensive anyway and puts pressure on the GC).

How to prepare a Unity project for git?

On the Unity Editor open your project and:

  1. Enable External option in Unity ? Preferences ? Packages ? Repository (only if Unity ver < 4.5)
  2. Switch to Visible Meta Files in Edit ? Project Settings ? Editor ? Version Control Mode
  3. Switch to Force Text in Edit ? Project Settings ? Editor ? Asset Serialization Mode
  4. Save Scene and Project from File menu.
  5. Quit Unity and then you can delete the Library and Temp directory in the project directory. You can delete everything but keep the Assets and ProjectSettings directory.

If you already created your empty git repo on-line (eg. github.com) now it's time to upload your code. Open a command prompt and follow the next steps:

cd to/your/unity/project/folder

git init

git add *

git commit -m "First commit"

git remote add origin [email protected]:username/project.git

git push -u origin master

You should now open your Unity project while holding down the Option or the Left Alt key. This will force Unity to recreate the Library directory (this step might not be necessary since I've seen Unity recreating the Library directory even if you don't hold down any key).

Finally have git ignore the Library and Temp directories so that they won’t be pushed to the server. Add them to the .gitignore file and push the ignore to the server. Remember that you'll only commit the Assets and ProjectSettings directories.

And here's my own .gitignore recipe for my Unity projects:

# =============== #
# Unity generated #
# =============== #
Temp/
Obj/
UnityGenerated/
Library/
Assets/AssetStoreTools*

# ===================================== #
# Visual Studio / MonoDevelop generated #
# ===================================== #
ExportedObj/
*.svd
*.userprefs
*.csproj
*.pidb
*.suo
*.sln
*.user
*.unityproj
*.booproj

# ============ #
# OS generated #
# ============ #
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
Icon?
ehthumbs.db
Thumbs.db

Android, How to limit width of TextView (and add three dots at the end of text)?

Apart from

android:ellipsize="end" 
android:maxLines="1"

you should set

android:layout_width="0dp"

also know as "match constraint", because the wrap_content value just expands the box to fit the whole text, and the ellipsize property can't make its effect.

Post an object as data using Jquery Ajax

Is not necessary to pass the data as JSON string, you can pass the object directly, without defining contentType or dataType, like this:

$.ajax({
    type: "POST",
    url: "TelephoneNumbers.aspx/DeleteNumber",
    data: data0,

    success: function(data)
    {
        alert('Done');
    }
});

Server configuration by allow_url_fopen=0 in

Using relative instead of absolute file path solved the problem for me. I had the same issue and setting allow_url_fopen=on did not help. This means for instance :

use $file="folder/file.ext"; instead of $file="https://website.com/folder/file.ext"; in

$f=fopen($file,"r+");

Laravel 5 Carbon format datetime

$suborder['payment_date'] = Carbon::parse($item['created_at'])->format('M d Y');

How does strtok() split the string into tokens in C?

To understand how strtok() works, one first need to know what a static variable is. This link explains it quite well....

The key to the operation of strtok() is preserving the location of the last seperator between seccessive calls (that's why strtok() continues to parse the very original string that is passed to it when it is invoked with a null pointer in successive calls)..

Have a look at my own strtok() implementation, called zStrtok(), which has a sligtly different functionality than the one provided by strtok()

char *zStrtok(char *str, const char *delim) {
    static char *static_str=0;      /* var to store last address */
    int index=0, strlength=0;           /* integers for indexes */
    int found = 0;                  /* check if delim is found */

    /* delimiter cannot be NULL
    * if no more char left, return NULL as well
    */
    if (delim==0 || (str == 0 && static_str == 0))
        return 0;

    if (str == 0)
        str = static_str;

    /* get length of string */
    while(str[strlength])
        strlength++;

    /* find the first occurance of delim */
    for (index=0;index<strlength;index++)
        if (str[index]==delim[0]) {
            found=1;
            break;
        }

    /* if delim is not contained in str, return str */
    if (!found) {
        static_str = 0;
        return str;
    }

    /* check for consecutive delimiters
    *if first char is delim, return delim
    */
    if (str[0]==delim[0]) {
        static_str = (str + 1);
        return (char *)delim;
    }

    /* terminate the string
    * this assignmetn requires char[], so str has to
    * be char[] rather than *char
    */
    str[index] = '\0';

    /* save the rest of the string */
    if ((str + index + 1)!=0)
        static_str = (str + index + 1);
    else
        static_str = 0;

        return str;
}

And here is an example usage

  Example Usage
      char str[] = "A,B,,,C";
      printf("1 %s\n",zStrtok(s,","));
      printf("2 %s\n",zStrtok(NULL,","));
      printf("3 %s\n",zStrtok(NULL,","));
      printf("4 %s\n",zStrtok(NULL,","));
      printf("5 %s\n",zStrtok(NULL,","));
      printf("6 %s\n",zStrtok(NULL,","));

  Example Output
      1 A
      2 B
      3 ,
      4 ,
      5 C
      6 (null)

The code is from a string processing library I maintain on Github, called zString. Have a look at the code, or even contribute :) https://github.com/fnoyanisi/zString

Script to Change Row Color when a cell changes text

user2532030's answer is the correct and most simple answer.

I just want to add, that in the case, where the value of the determining cell is not suitable for a RegEx-match, I found the following syntax to work the same, only with numerical values, relations et.c.:

[Custom formula is]
=$B$2:$B = "Complete"
Range: A2:Z1000

If column 2 of any row (row 2 in script, but the leading $ means, this could be any row) textually equals "Complete", do X for the Range of the entire sheet (excluding header row (i.e. starting from A2 instead of A1)).

But obviously, this method allows also for numerical operations (even though this does not apply for op's question), like:

=$B$2:$B > $C$2:$C

So, do stuff, if the value of col B in any row is higher than col C value.

One last thing: Most likely, this applies only to me, but I was stupid enough to repeatedly forget to choose Custom formula is in the drop-down, leaving it at Text contains. Obviously, this won't float...

How to import Angular Material in project?

Step 1

yarn add @angular/material @angular/cdk @angular/animations

Step 2 - Create a new file( /myApp/src/app/material.module.ts ) that includes all the material UI modules (there is no shortcut, you have to include individual modules one by one)

import { NgModule } from '@angular/core';

    import {
      MatButtonModule,
      MatMenuModule,
      MatToolbarModule,
      MatIconModule,
      MatCardModule
    } from '@angular/material';

    @NgModule({
      imports: [
        MatButtonModule,
        MatMenuModule,
        MatToolbarModule,
        MatIconModule,
        MatCardModule
      ],
      exports: [
        MatButtonModule,
        MatMenuModule,
        MatToolbarModule,
        MatIconModule,
        MatCardModule
      ]
    })
    export class MaterialModule {}

Step 3 - Import and add that newly created module to your app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { MaterialModule } from './material.module'; // material module imported

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    MaterialModule // MAteria module added
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Execute another jar in a Java program

The following works by starting the jar with a batch file, in case the program runs as a stand alone:

public static void startExtJarProgram(){
        String extJar = Paths.get("C:\\absolute\\path\\to\\batchfile.bat").toString();
        ProcessBuilder processBuilder = new ProcessBuilder(extJar);
        processBuilder.redirectError(new File(Paths.get("C:\\path\\to\\JavaProcessOutput\\extJar_out_put.txt").toString()));
        processBuilder.redirectInput();
        try {
           final Process process = processBuilder.start();
            try {
                final int exitStatus = process.waitFor();
                if(exitStatus==0){
                    System.out.println("External Jar Started Successfully.");
                    System.exit(0); //or whatever suits 
                }else{
                    System.out.println("There was an error starting external Jar. Perhaps path issues. Use exit code "+exitStatus+" for details.");
                    System.out.println("Check also C:\\path\\to\\JavaProcessOutput\\extJar_out_put.txt file for additional details.");
                    System.exit(1);//whatever
                }
            } catch (InterruptedException ex) {
                System.out.println("InterruptedException: "+ex.getMessage());
            }
        } catch (IOException ex) {
            System.out.println("IOException. Faild to start process. Reason: "+ex.getMessage());
        }
        System.out.println("Process Terminated.");
        System.exit(0);
    }

In the batchfile.bat then we can say:

@echo off
start /min C:\path\to\jarprogram.jar

How can I use inverse or negative wildcards when pattern matching in a unix/linux shell?

Not in bash (that I know of), but:

cp `ls | grep -v Music` /target_directory

I know this is not exactly what you were looking for, but it will solve your example.

Python - Count elements in list

len() 

it will count the element in the list, tuple and string and dictionary, eg.

>>> mylist = [1,2,3] #list
>>> len(mylist)
3
>>> word = 'hello' # string 
>>> len(word)
5
>>> vals = {'a':1,'b':2} #dictionary
>>> len(vals)
2
>>> tup = (4,5,6) # tuple 
>>> len(tup)
3

To learn Python you can use byte of python , it is best ebook for python beginners.

What are 'get' and 'set' in Swift?

You should look at Computed Properties

In your code sample, perimeter is a property not backed up by a class variable, instead its value is computed using the get method and stored via the set method - usually referred to as getter and setter.

When you use that property like this:

var cp = myClass.perimeter

you are invoking the code contained in the get code block, and when you use it like this:

myClass.perimeter = 5.0

you are invoking the code contained in the set code block, where newValue is automatically filled with the value provided at the right of the assignment operator.

Computed properties can be readwrite if both a getter and a setter are specified, or readonly if the getter only is specified.

How to set the component size with GridLayout? Is there a better way?

In my project I managed to use GridLayout and results are very stable, with no flickering and with a perfectly working vertical scrollbar.

First I created a JPanel for the settings; in my case it is a grid with a row for each parameter and two columns: left column is for labels and right column is for components. I believe your case is similar.

JPanel yourSettingsPanel = new JPanel();
yourSettingsPanel.setLayout(new GridLayout(numberOfParams, 2));

I then populate this panel by iterating on my parameters and alternating between adding a JLabel and adding a component.

for (int i = 0; i < numberOfParams; ++i) {
    yourSettingsPanel.add(labels[i]);
    yourSettingsPanel.add(components[i]);
}

To prevent yourSettingsPanel from extending to the entire container I first wrap it in the north region of a dummy panel, that I called northOnlyPanel.

JPanel northOnlyPanel = new JPanel();
northOnlyPanel.setLayout(new BorderLayout());
northOnlyPanel.add(yourSettingsPanel, BorderLayout.NORTH);

Finally I wrap the northOnlyPanel in a JScrollPane, which should behave nicely pretty much anywhere.

JScrollPane scroll = new JScrollPane(northOnlyPanel,
                                     JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                                     JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

Most likely you want to display this JScrollPane extended inside a JFrame; you can add it to a BorderLayout JFrame, in the CENTER region:

window.add(scroll, BorderLayout.CENTER);

In my case I put it on the left column of a GridLayout(1, 2) panel, and I use the right column to display contextual help for each parameter.

JTextArea help = new JTextArea();
help.setLineWrap(true);
help.setWrapStyleWord(true);
help.setEditable(false);

JPanel split = new JPanel();
split.setLayout(new GridLayout(1, 2));
split.add(scroll);
split.add(help);

How to convert Set to Array?

if no such option exists, then maybe there is a nice idiomatic one-liner for doing that ? like, using for...of, or similar ?

Indeed, there are several ways to convert a Set to an Array:

using Array.from

let array = Array.from(mySet);

Simply spreading the Set out in an array

let array = [...mySet];

The old fashion way, iterating and pushing to a new array (Sets do have forEach)

let array = [];
mySet.forEach(v => array.push(v));

Previously, using the non-standard, and now deprecated array comprehension syntax:

let array = [v for (v of mySet)];

Scrollbar without fixed height/Dynamic height with scrollbar

Flexbox is a modern alternative that lets you do this without fixed heights or JavaScript.

Setting display: flex; flex-direction: column; on the container and flex-shrink: 0; on the header and footer divs does the trick:

HTML:

<div id="body">
    <div id="head">
        <p>Dynamic size without scrollbar</p>
        <p>Dynamic size without scrollbar</p>
        <p>Dynamic size without scrollbar</p>  
    </div>
    <div id="content">
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
    </div>
    <div id="foot">
        <p>Fixed size without scrollbar</p>
        <p>Fixed size without scrollbar</p>
    </div>  
</div>

CSS:

#body {
    position: absolute;
    top: 150px;
    left: 150px;
    height: 300px;
    width: 500px;
    border: black dashed 2px;
    display: flex;
    flex-direction: column;
}

#head {
    border: green solid 1px;
    flex-shrink: 0;
}

#content{
    border: red solid 1px;
    overflow-y: auto;
    /*height: 100%;*/
}

#foot {
    border: blue solid 1px;
    height: 50px;
    flex-shrink: 0;
}

How to create an array of object literals in a loop?

If you want to go even further than @tetra with ES6 you can use the Object spread syntax and do something like this:

let john = {
    firstName: "John",
    lastName: "Doe",
};

let people = new Array(10).fill().map((e, i) => {(...john, id: i});

Double vs. BigDecimal?

If you are dealing with calculation, there are laws on how you should calculate and what precision you should use. If you fail that you will be doing something illegal. The only real reason is that the bit representation of decimal cases are not precise. As Basil simply put, an example is the best explanation. Just to complement his example, here's what happens:

static void theDoubleProblem1() {
    double d1 = 0.3;
    double d2 = 0.2;
    System.out.println("Double:\t 0,3 - 0,2 = " + (d1 - d2));

    float f1 = 0.3f;
    float f2 = 0.2f;
    System.out.println("Float:\t 0,3 - 0,2 = " + (f1 - f2));

    BigDecimal bd1 = new BigDecimal("0.3");
    BigDecimal bd2 = new BigDecimal("0.2");
    System.out.println("BigDec:\t 0,3 - 0,2 = " + (bd1.subtract(bd2)));
}

Output:

Double:  0,3 - 0,2 = 0.09999999999999998
Float:   0,3 - 0,2 = 0.10000001
BigDec:  0,3 - 0,2 = 0.1

Also we have that:

static void theDoubleProblem2() {
    double d1 = 10;
    double d2 = 3;
    System.out.println("Double:\t 10 / 3 = " + (d1 / d2));

    float f1 = 10f;
    float f2 = 3f;
    System.out.println("Float:\t 10 / 3 = " + (f1 / f2));

    // Exception! 
    BigDecimal bd3 = new BigDecimal("10");
    BigDecimal bd4 = new BigDecimal("3");
    System.out.println("BigDec:\t 10 / 3 = " + (bd3.divide(bd4)));
}

Gives us the output:

Double:  10 / 3 = 3.3333333333333335
Float:   10 / 3 = 3.3333333
Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion

But:

static void theDoubleProblem2() {
    BigDecimal bd3 = new BigDecimal("10");
    BigDecimal bd4 = new BigDecimal("3");
    System.out.println("BigDec:\t 10 / 3 = " + (bd3.divide(bd4, 4, BigDecimal.ROUND_HALF_UP)));
}

Has the output:

BigDec:  10 / 3 = 3.3333 

How can I get a value from a map?

Unfortunately std::map::operator[] is a non-const member function, and you have a const reference.

You either need to change the signature of function or do:

MAP::const_iterator pos = map.find("string");
if (pos == map.end()) {
    //handle the error
} else {
    std::string value = pos->second;
    ...
}

operator[] handles the error by adding a default-constructed value to the map and returning a reference to it. This is no use when all you have is a const reference, so you will need to do something different.

You could ignore the possibility and write string value = map.find("string")->second;, if your program logic somehow guarantees that "string" is already a key. The obvious problem is that if you're wrong then you get undefined behavior.

Window.open and pass parameters by post method

I wanted to do this in React using plain Js and the fetch polyfill. OP didn't say he specifically wanted to create a form and invoke the submit method on it, so I have done it by posting the form values as json:

examplePostData = {
    method: 'POST',
    headers: {
       'Content-type' : 'application/json',
       'Accept' : 'text/html'
    },
    body: JSON.stringify({
        someList: [1,2,3,4],
        someProperty: 'something',
        someObject: {some: 'object'}
    })
}

asyncPostPopup = () => {

    //open a new window and set some text until the fetch completes
    let win=window.open('about:blank')
    writeToWindow(win,'Loading...')

    //async load the data into the window
    fetch('../postUrl', this.examplePostData)
    .then((response) => response.text())
    .then((text) => writeToWindow(win,text))
    .catch((error) => console.log(error))
}

writeToWindow = (win,text) => {
    win.document.open()
    win.document.write(text)
    win.document.close()
}

Undoing a git rebase

The easiest way would be to find the head commit of the branch as it was immediately before the rebase started in the reflog...

git reflog

and to reset the current branch to it (with the usual caveats about being absolutely sure before reseting with the --hard option).

Suppose the old commit was HEAD@{5} in the ref log:

git reset --hard HEAD@{5}

In Windows, you may need to quote the reference:

git reset --hard "HEAD@{5}"

You can check the history of the candidate old head by just doing a git log HEAD@{5} (Windows: git log "HEAD@{5}").

If you've not disabled per branch reflogs you should be able to simply do git reflog branchname@{1} as a rebase detaches the branch head before reattaching to the final head. I would double check this, though as I haven't verified this recently.

Per default, all reflogs are activated for non-bare repositories:

[core]
    logAllRefUpdates = true

Check if a input box is empty

Another approach is using regex , as show below , you can use the empty regex pattern and achieve the same using ng-pattern

HTML :

 <body ng-app="app" ng-controller="formController">
 <form name="myform">
 <input name="myfield" ng-model="somefield" ng-minlength="5" ng-pattern="mypattern" required>
 <span ng-show="myform.myfield.$error.pattern">Please enter!</span>
 <span ng-show="!myform.myfield.$error.pattern">great!</span>
</form>

Controller:@formController :

var App = angular.module('app', []);
App.controller('formController', function ($scope) {              
  $scope.mypattern = /^\s*$/g;
});

View array in Visual Studio debugger?

Hover your mouse cursor over the name of the array, then hover over the little (+) icon that appears.

How to run test methods in specific order in JUnit4?

You can use one of these piece of codes: @FixMethodOrder(MethodSorters.JVM) OR @FixMethodOrder(MethodSorters.DEFAULT) OR @FixMethodOrder(MethodSorters.NAME_ASCENDING)

Before your test class like this:

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class BookTest {...}

Export to CSV using MVC, C# and jQuery

Simple excel file create in mvc 4

public ActionResult results() { return File(new System.Text.UTF8Encoding().GetBytes("string data"), "application/csv", "filename.csv"); }

Display array values in PHP

Other option:

$lijst=array(6,4,7,2,1,8,9,5,0,3);
for($i=0;$i<10;$i++){
echo $lijst[$i];
echo "<br>";
}

How can I set the default value for an HTML <select> element?

You can try like this

  <select name="hall" id="hall">
      <option>1</option>
      <option>2</option>
      <option selected="selected">3</option>
      <option>4</option>
      <option>5</option>
    </select>

How do I tell if a regular file does not exist in Bash?

You can negate an expression with "!":

#!/bin/bash
FILE=$1

if [ ! -f "$FILE" ]
then
    echo "File $FILE does not exist"
fi

The relevant man page is man test or, equivalently, man [ -- or help test or help [ for the built-in bash command.

Open a file with Notepad in C#

You are not providing a lot of information, but assuming you want to open just any file on your computer with the application that is specified for the default handler for that filetype, you can use something like this:

var fileToOpen = "SomeFilePathHere";
var process = new Process();
process.StartInfo = new ProcessStartInfo()
{
    UseShellExecute = true,
    FileName = fileToOpen
};

process.Start();
process.WaitForExit();

The UseShellExecute parameter tells Windows to use the default program for the type of file you are opening.

The WaitForExit will cause your application to wait until the application you luanched has been closed.

SQL Server : How to test if a string has only digit characters

I was attempting to find strings with numbers ONLY, no punctuation or anything else. I finally found an answer that would work here.

Using PATINDEX('%[^0-9]%', some_column) = 0 allowed me to filter out everything but actual number strings.

How to reload apache configuration for a site without restarting apache?

If you are using Ubuntu server, you can use systemctl

systemctl reload apache2

Reset select2 value and show placeholder

From select2 website,

$("#mySelect2ControlId").val(null).trigger("change");

Removing padding gutter from grid columns in Bootstrap 4

You can use this css code to get gutterless grid in bootstrap.

.no-gutter.row,
.no-gutter.container,
.no-gutter.container-fluid{
  margin-left: 0;
  margin-right: 0;
}

.no-gutter>[class^="col-"]{
  padding-left: 0;
  padding-right: 0;
}

Using a SELECT statement within a WHERE clause

Subquery is the name.

At times it's required, but good/bad depends on how it's applied.

How to make a custom LinkedIn share button

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

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

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

What is the best way to redirect a page using React Router?

You can also use react router dom library useHistory;

`
import { useHistory } from "react-router-dom";

function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}
`

https://reactrouter.com/web/api/Hooks/usehistory

How to get character array from a string?

How about this?

function stringToArray(string) {
  let length = string.length;
  let array = new Array(length);
  while (length--) {
    array[length] = string[length];
  }
  return array;
}

How to POST using HTTPclient content type = application/x-www-form-urlencoded

Another variant to POST this content type and which does not use a dictionary would be:

StringContent postData = new StringContent(JSON_CONTENT, Encoding.UTF8, "application/x-www-form-urlencoded");
using (HttpResponseMessage result = httpClient.PostAsync(url, postData).Result)
{
    string resultJson = result.Content.ReadAsStringAsync().Result;
}

What are these ^M's that keep showing up in my files in emacs?

^M at the end of line in Emacs is indicating a carriage return (\r) followed by a line feed (\n). You'll often see this if one person edits files on Windows (where end of line is the combination of carriage return and newline characters) and you edit in Unix or Linux (where end of line is only a newline character).

The combination of characters is usually not harmful. If you're using source control, you may be able to configure the text file checkin format so that lines are magically adjusted for you. Alternatively, you may be able to use checkin and checkout triggers that will automatically "fix" the files for you. Or, you might just use a tool like dos2unix to manually adjust things.

TypeScript: Interfaces vs Types

When it comes to compilation speed, composed interfaces perform better than type intersections:

[...] interfaces create a single flat object type that detects property conflicts. This is in contrast with intersection types, where every constituent is checked before checking against the effective type. Type relationships between interfaces are also cached, as opposed to intersection types.

Source: https://github.com/microsoft/TypeScript/wiki/Performance#preferring-interfaces-over-intersections

How do I get extra data from intent on Android?

If used in a FragmentActivity, try this:

The first page extends FragmentActivity

Intent Tabdetail = new Intent(getApplicationContext(), ReceivePage.class);
Tabdetail.putExtra("Marker", marker.getTitle().toString());
startActivity(Tabdetail);

In the fragment, you just need to call getActivity() first,

The second page extends Fragment:

String receive = getActivity().getIntent().getExtras().getString("name");

How to convert array to SimpleXML

IF the array is associative and keyed correctly, it would probably be easier to turn it into xml first. Something like:

  function array2xml ($array_item) {
    $xml = '';
    foreach($array_item as $element => $value)
    {
        if (is_array($value))
        {
            $xml .= "<$element>".array2xml($value)."</$element>";
        }
        elseif($value == '')
        {
            $xml .= "<$element />";
        }
        else
        {
            $xml .= "<$element>".htmlentities($value)."</$element>";
        }
    }
    return $xml;
}

$simple_xml = simplexml_load_string(array2xml($assoc_array));

The other route would be to create your basic xml first, like

$simple_xml = simplexml_load_string("<array></array>");

and then for each part of your array, use something similar to my text creating loop and instead use the simplexml functions "addChild" for each node of the array.

I'll try that out later and update this post with both versions.

Basic HTTP and Bearer Token Authentication

Try this one to push basic authentication at url:

curl -i http://username:[email protected]/api/users -H "Authorization: Bearer mytoken123"
               ^^^^^^^^^^^^^^^^^^

If above one doesn't work, then you have nothing to do with it. So try the following alternates.

You can pass the token under another name. Because you are handling the authorization from your Application. So you can easily use this flexibility for this special purpose.

curl -i http://dev.myapp.com/api/users \
  -H "Authorization: Basic Ym9zY236Ym9zY28=" \
  -H "Application-Authorization: mytoken123"

Notice I have changed the header into Application-Authorization. So from your application catch the token under that header and process what you need to do.

Another thing you can do is, to pass the token through the POST parameters and grab the parameter's value from the Server side. For example passing token with curl post parameter:

-d "auth-token=mytoken123"

Call static method with reflection

As the documentation for MethodInfo.Invoke states, the first argument is ignored for static methods so you can just pass null.

foreach (var tempClass in macroClasses)
{
   // using reflection I will be able to run the method as:
   tempClass.GetMethod("Run").Invoke(null, null);
}

As the comment points out, you may want to ensure the method is static when calling GetMethod:

tempClass.GetMethod("Run", BindingFlags.Public | BindingFlags.Static).Invoke(null, null);

Alter MySQL table to add comments on columns

As per the documentation you can add comments only at the time of creating table. So it is must to have table definition. One way to automate it using the script to read the definition and update your comments.

Reference:

http://cornempire.net/2010/04/15/add-comments-to-column-mysql/

http://bugs.mysql.com/bug.php?id=64439

How to convert date format to DD-MM-YYYY in C#

DateTime s1 = System.Convert.ToDateTime(textbox.Trim());
        DateTime date = (s1);
        String frmdt = date.ToString("dd-MM-yyyy"); 

will work

Importing PNG files into Numpy?

This can also be done with the Image class of the PIL library:

from PIL import Image
import numpy as np

im_frame = Image.open(path_to_file + 'file.png')
np_frame = np.array(im_frame.getdata())

Note: The .getdata() might not be needed - np.array(im_frame) should also work

SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

its not a big issue just change your server name see where to server name change:

enter image description here

how to find server name

  1. open run
  2. write 'cmd'
  3. write in console window "Hostname".

your server name will show you

thank you.

Should a 502 HTTP status code be used if a proxy receives no response at all?

Yes. Empty or incomplete headers or response body typically caused by broken connections or server side crash can cause 502 errors if accessed via a gateway or proxy.

For more information about the network errors

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

Why is division in Ruby returning an integer instead of decimal value?

You can check it with irb:

$ irb
>> 2 / 3
=> 0
>> 2.to_f / 3
=> 0.666666666666667
>> 2 / 3.to_f
=> 0.666666666666667

CronJob not running

To add another point, a file in /etc/cron.d must contain an empty new line at the end. This is likely related to the response by Luciano which specifies that:

The entire command portion of the line, up to a newline or a "%"
character, will be executed

ActiveXObject creation error " Automation server can't create object"

I have the same problem , it solved by registering the dll

at project properties => build => register for COM interop => check it

Find a private field with Reflection?

I use this method personally

if (typeof(Foo).GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Any(c => c.GetCustomAttributes(typeof(SomeAttribute), false).Any()))
{ 
    // do stuff
}

nginx- duplicate default server error

Execute this at the terminal to see conflicting configurations listening to the same port:

grep -R default_server /etc/nginx

How do I combine the first character of a cell with another cell in Excel?

=CONCATENATE(LEFT(A1,1), B1)

Assuming A1 holds 1st names; B1 Last names

IPython Notebook save location

Jupyter under the WinPython environment has a batch file in the scripts folder called:

make_working_directory_be_not_winpython.bat

You need to edit the following line in it:

echo WINPYWORKDIR = %%HOMEDRIVE%%%%HOMEPATH%%\Documents\WinPython%%WINPYVER%%\Notebooks>>"%winpython_ini%"

replacing the Documents\WinPython%%WINPYVER%%\Notebooks part with your folder address.

Notice that the %%HOMEDRIVE%%%%HOMEPATH%%\ part will identify the root and user folders (i.e. C:\Users\your_name\) which will allow you to point different WinPython installations on separate computers to the same cloud storage folder (e.g. OneDrive) where you could store, access, and work with the same files from different machines. I find that very useful.

CSS - how to make image container width fixed and height auto stretched

Try width:inherit to make the image take the width of it's container <div>. It will stretch/shrink it's height to maintain proportion. Don't set the height in the <div>, it will size to fit the image height.

img {
    width:inherit;
}

.item {
    border:1px solid pink;
    width: 120px;
    float: left;
    margin: 3px;
    padding: 3px;
}

JSFiddle example

Choosing the default value of an Enum type without having to change values

You can't, but if you want, you can do some trick. :)

    public struct Orientation
    {
        ...
        public static Orientation None = -1;
        public static Orientation North = 0;
        public static Orientation East = 1;
        public static Orientation South = 2;
        public static Orientation West = 3;
    }

usage of this struct as simple enum.
where you can create p.a == Orientation.East (or any value that you want) by default
to use the trick itself, you need to convert from int by code.
there the implementation:

        #region ConvertingToEnum
        private int val;
        static Dictionary<int, string> dict = null;

        public Orientation(int val)
        {
            this.val = val;
        }

        public static implicit operator Orientation(int value)
        {
            return new Orientation(value - 1);
        }

        public static bool operator ==(Orientation a, Orientation b)
        {
            return a.val == b.val;
        }

        public static bool operator !=(Orientation a, Orientation b)
        {
            return a.val != b.val;
        }

        public override string ToString()
        {
            if (dict == null)
                InitializeDict();
            if (dict.ContainsKey(val))
                return dict[val];
            return val.ToString();
        }

        private void InitializeDict()
        {
            dict = new Dictionary<int, string>();
            foreach (var fields in GetType().GetFields(BindingFlags.Public | BindingFlags.Static))
            {
                dict.Add(((Orientation)fields.GetValue(null)).val, fields.Name);
            }
        } 
        #endregion

SQL Error: ORA-00913: too many values

You should specify column names as below. It's good practice and probably solve your problem

insert into abc.employees (col1,col2) 
select col1,col2 from employees where employee_id=100; 

EDIT:

As you said employees has 112 columns (sic!) try to run below select to compare both tables' columns

select * 
from ALL_TAB_COLUMNS ATC1
left join ALL_TAB_COLUMNS ATC2 on ATC1.COLUMN_NAME = ATC1.COLUMN_NAME 
                               and  ATC1.owner = UPPER('2nd owner')
where ATC1.owner = UPPER('abc')
and ATC2.COLUMN_NAME is null
AND ATC1.TABLE_NAME = 'employees'

and than you should upgrade your tables to have the same structure.

What does the function then() mean in JavaScript?

To my knowledge, there isn't a built-in then() method in javascript (at the time of this writing).

It appears that whatever it is that doSome("task") is returning has a method called then.

If you log the return result of doSome() to the console, you should be able to see the properties of what was returned.

console.log( myObj.doSome("task") ); // Expand the returned object in the
                                     //   console to see its properties.

UPDATE (As of ECMAScript6) :-

The .then() function has been included to pure javascript.

From the Mozilla documentation here,

The then() method returns a Promise. It takes two arguments: callback functions for the success and failure cases of the Promise.

The Promise object, in turn, is defined as

The Promise object is used for deferred and asynchronous computations. A Promise represents an operation that hasn't completed yet, but is expected in the future.

That is, the Promise acts as a placeholder for a value that is not yet computed, but shall be resolved in the future. And the .then() function is used to associate the functions to be invoked on the Promise when it is resolved - either as a success or a failure.

Go to Matching Brace in Visual Studio?

On a Mac use command+shift+\.

Source: a comment on this answer: https://stackoverflow.com/a/37877082/3345085. Tested in Visual Studio Code version 1.10.2.

JavaFX Panel inside Panel auto resizing

No need to cede.

just select pane ,right click then select Fit to parent.

It will automatically resize pane to anchor pane size.

SQL Server Insert if not exists

Try below code

ALTER PROCEDURE [dbo].[EmailsRecebidosInsert]
  (@_DE nvarchar(50),
   @_ASSUNTO nvarchar(50),
   @_DATA nvarchar(30) )
AS
BEGIN
   INSERT INTO EmailsRecebidos (De, Assunto, Data)
   select @_DE, @_ASSUNTO, @_DATA
   EXCEPT
   SELECT De, Assunto, Data from EmailsRecebidos
END

Converting Swagger specification JSON to HTML documentation

There's a small Java program which generates docs (adoc or md) from a yaml file.

Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
        .withMarkupLanguage(MarkupLanguage.ASCIIDOC)
        .withSwaggerMarkupLanguage(MarkupLanguage.ASCIIDOC)
        .withOutputLanguage(Language.DE)
        .build();

Swagger2MarkupConverter builder = Swagger2MarkupConverter.from(yamlFileAsString).withConfig(config).build();
return builder.toFileWithoutExtension(outFile);

Unfortunately it only supports OpenAPI 2.0 but not OpenAPI 3.0.

How to manually install an artifact in Maven 2?

All the posted answers rightfully discuss this from a strictly maven perspective. My issues was in doing this install for maven using Netbeans as my primary IDE. I found the below article helpful.

Credit to the following netbeans forum article: http://forums.netbeans.org/topic22907.html

  1. In Maven project open "Add dependency" dialog
  2. Make up some groupId, artifactId and version and fill them, OK.
  3. Dependency will be added to the pom.xml and will appear under "Libraries" node of maven project
  4. Right-click Lib node and "manually install artifact", fill the path to the jar. Jar should be installed to local Maven repo with coordinates entered in step 2)

Swapping two variable value without using third variable

single line solution for swapping two values in c language.

a=(b=(a=a+b,a-b),a-b);

<strong> vs. font-weight:bold & <em> vs. font-style:italic

The <em> element - from W3C (HTML5 reference)

YES! There is a clear difference.

The <em> element represents stress emphasis of its contents. The level of emphasis that a particular piece of content has is given by its number of ancestor <em> elements.

<strong>  =  important content
<em>      =  stress emphasis of its contents

The placement of emphasis changes the meaning of the sentence. The element thus forms an integral part of the content. The precise way in which emphasis is used in this way depends on the language.

Note!

  1. The <em> element also isnt intended to convey importance; for that purpose, the <strong> element is more appropriate.

  2. The <em> element isn't a generic "italics" element. Sometimes, text is intended to stand out from the rest of the paragraph, as if it was in a different mood or voice. For this, the i element is more appropriate.

Reference (examples): See W3C Reference

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysql.sock' (2)

You may be missing mysql-server. install it using

sudo apt-get install mysql-server

HAProxy redirecting http to https (ssl)

redirect statement is legacy

use http-request redirect instead

acl http      ssl_fc,not
http-request redirect scheme https if http

Locking a file in Python

Coordinating access to a single file at the OS level is fraught with all kinds of issues that you probably don't want to solve.

Your best bet is have a separate process that coordinates read/write access to that file.

How to show a GUI message box from a bash script in linux?

Kdialog and dialog are both good, but I'd recommend Zenity. Quick, easy, and much better looking the xmessage or dialog.

javascript code to check special characters

Directly from the w3schools website:

   var str = "The best things in life are free";
   var patt = new RegExp("e");
   var res = patt.test(str);

To combine their example with a regular expression, you could do the following:

function checkUserName() {
    var username = document.getElementsByName("username").value;
    var pattern = new RegExp(/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/); //unacceptable chars
    if (pattern.test(username)) {
        alert("Please only use standard alphanumerics");
        return false;
    }
    return true; //good user input
}

How to move an element into another element?

I noticed huge memory leak & performance difference between insertAfter & after or insertBefore & before .. If you have tons of DOM elements, or you need to use after() or before() inside a MouseMove event, the browser memory will probably increase and next operations will run really slow.

The solution I've just experienced is to use inserBefore instead before() and insertAfter instead after().

Horizontal scroll on overflow of table

Unless I grossly misunderstood your question, move overflow-x:scroll from .search-table to .search-table-outter.

http://jsfiddle.net/ZXnqM/4/

.search-table-outter {border:2px solid red; overflow-x:scroll;}
.search-table{table-layout: fixed; margin:40px auto 0px auto;   }

As far as I know you can't give scrollbars to tables themselves.

jwt check if token expired

You should use jwt.verify it will check if the token is expired. jwt.decode should not be used if the source is not trusted as it doesn't check if the token is valid.

Generating unique random numbers (integers) between 0 and 'x'

const getRandomNo = (min, max) => {
   min = Math.ceil(min);
   max = Math.floor(max);
   return Math.floor(Math.random() * (max - min + 1)) + min; 
}

This function returns a random integer between the specified values. The value is no lower than min (or the next integer greater than min if min isn't an integer) and is less than (but not equal to) max. Example

console.log(`Random no between 0 and 10 ${getRandomNo(0,10)}`)

In C#, what's the difference between \n and \r\n?

It's about how the operating system recognizes line ends.

  • Windows user \r\n
  • Mac user \r
  • Linux uses \n

Morale: if you are developing for Windows, stick to \r\n. Or even better, use C# string functions to deal with strings which already consider line endings (WriteLine, and such).

How to git reset --hard a subdirectory?

Try changing

git checkout -- a

to

git checkout -- `git ls-files -m -- a`

Since version 1.7.0, Git's ls-files honors the skip-worktree flag.

Running your test script (with some minor tweaks changing git commit... to git commit -q and git status to git status --short) outputs:

Initialized empty Git repository in /home/user/repo/.git/
After read-tree:
a/a/aa
a/b/ab
b/a/ba
After modifying:
b/a/ba
 D a/a/aa
 D a/b/ab
 M b/a/ba
After checkout:
 M b/a/ba
a/a/aa
a/c/ac
a/b/ab
b/a/ba

Running your test script with the proposed checkout change outputs:

Initialized empty Git repository in /home/user/repo/.git/
After read-tree:
a/a/aa
a/b/ab
b/a/ba
After modifying:
b/a/ba
 D a/a/aa
 D a/b/ab
 M b/a/ba
After checkout:
 M b/a/ba
a/a/aa
a/b/ab
b/a/ba

jQuery multiple conditions within if statement

i == 'InvKey' && i == 'PostDate' will never be true, since i can never equal two different things at once.

You're probably trying to write

if (i !== 'InvKey' && i !== 'PostDate')) 

How to display images from a folder using php - PHP

You have two ways to do that:

METHOD 1. The secure way.

Put the images on /www/htdocs/

<?php
    $www_root = 'http://localhost/images';
    $dir = '/var/www/images';
    $file_display = array('jpg', 'jpeg', 'png', 'gif');

    if ( file_exists( $dir ) == false ) {
       echo 'Directory \'', $dir, '\' not found!';
    } else {
       $dir_contents = scandir( $dir );

        foreach ( $dir_contents as $file ) {
           $file_type = strtolower( end( explode('.', $file ) ) );
           if ( ($file !== '.') && ($file !== '..') && (in_array( $file_type, $file_display)) ) {
              echo '<img src="', $www_root, '/', $file, '" alt="', $file, '"/>';
           break;
           }
        }
    }
?>

METHOD 2. Unsecure but more flexible.

Put the images on any directory (apache must have permission to read the file).

<?php
    $dir = '/home/user/Pictures';
    $file_display = array('jpg', 'jpeg', 'png', 'gif');

    if ( file_exists( $dir ) == false ) {
       echo 'Directory \'', $dir, '\' not found!';
    } else {
       $dir_contents = scandir( $dir );

        foreach ( $dir_contents as $file ) {
           $file_type = strtolower( end( explode('.', $file ) ) );
           if ( ($file !== '.') && ($file !== '..') && (in_array( $file_type, $file_display)) ) {
              echo '<img src="file_viewer.php?file=', base64_encode($dir . '/' . $file), '" alt="', $file, '"/>';
           break;
           }
        }
    }
?>

And create another script to read the image file.

<?php
    $filename = base64_decode($_GET['file']);
    // Check the folder location to avoid exploit
    if (dirname($filename) == '/home/user/Pictures')
        echo file_get_contents($filename);
?>

How do I use the new computeIfAbsent function?

Suppose you have the following code:

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class Test {
    public static void main(String[] s) {
        Map<String, Boolean> whoLetDogsOut = new ConcurrentHashMap<>();
        whoLetDogsOut.computeIfAbsent("snoop", k -> f(k));
        whoLetDogsOut.computeIfAbsent("snoop", k -> f(k));
    }
    static boolean f(String s) {
        System.out.println("creating a value for \""+s+'"');
        return s.isEmpty();
    }
}

Then you will see the message creating a value for "snoop" exactly once as on the second invocation of computeIfAbsent there is already a value for that key. The k in the lambda expression k -> f(k) is just a placeolder (parameter) for the key which the map will pass to your lambda for computing the value. So in the example the key is passed to the function invocation.

Alternatively you could write: whoLetDogsOut.computeIfAbsent("snoop", k -> k.isEmpty()); to achieve the same result without a helper method (but you won’t see the debugging output then). And even simpler, as it is a simple delegation to an existing method you could write: whoLetDogsOut.computeIfAbsent("snoop", String::isEmpty); This delegation does not need any parameters to be written.

To be closer to the example in your question, you could write it as whoLetDogsOut.computeIfAbsent("snoop", key -> tryToLetOut(key)); (it doesn’t matter whether you name the parameter k or key). Or write it as whoLetDogsOut.computeIfAbsent("snoop", MyClass::tryToLetOut); if tryToLetOut is static or whoLetDogsOut.computeIfAbsent("snoop", this::tryToLetOut); if tryToLetOut is an instance method.

Selecting a Linux I/O Scheduler

It's possible to use a udev rule to let the system decide on the scheduler based on some characteristics of the hw.
An example udev rule for SSDs and other non-rotational drives might look like

# set noop scheduler for non-rotating disks
ACTION=="add|change", KERNEL=="sd[a-z]", ATTR{queue/rotational}=="0", ATTR{queue/scheduler}="noop"

inside a new udev rules file (e.g., /etc/udev/rules.d/60-ssd-scheduler.rules). This answer is based on the debian wiki

To check whether ssd disks would use the rule, it's possible to check for the trigger attribute in advance:

for f in /sys/block/sd?/queue/rotational; do printf "$f "; cat $f; done

How to install multiple python packages at once using pip

pip install -r requirements.txt

and in the requirements.txt file you put your modules in a list, with one item per line.

  • Django=1.3.1

  • South>=0.7

  • django-debug-toolbar

Group by & count function in sqlalchemy

You can also count on multiple groups and their intersection:

self.session.query(func.count(Table.column1),Table.column1, Table.column2).group_by(Table.column1, Table.column2).all()

The query above will return counts for all possible combinations of values from both columns.

MySQL Error #1133 - Can't find any matching row in the user table

It turns out, the error is very vague indeed!

1) Password was setting while logged on as root, as it was updating the user/password field in the users table under MySql.

2) When logged on as user, password was in fact not changing and even though there was one specified in the users table in MySql, config.inc.php file allowed authentication without password.

Solution:

Change following value to false in the config.inc.php.

$cfg['Servers'][$i]['AllowNoPassword'] = true;

So that it reads

$cfg['Servers'][$i]['AllowNoPassword'] = false;

Change user's host from Any or % to localhost in MySql users table. This could easily be achieved via phpMyAdmin console.

These two changes allowed me to authenticate as user with it's password and disallowed authentication without password.

It also allowed user to change its password while logged on as user.

Seems all permissions and the rest was fixed with these two changes.

What is the purpose of the return statement?

The print() function writes, i.e., "prints", a string in the console. The return statement causes your function to exit and hand back a value to its caller. The point of functions in general is to take in inputs and return something. The return statement is used when a function is ready to return a value to its caller.

For example, here's a function utilizing both print() and return:

def foo():
    print("hello from inside of foo")
    return 1

Now you can run code that calls foo, like so:

if __name__ == '__main__':
    print("going to call foo")
    x = foo()
    print("called foo")
    print("foo returned " + str(x))

If you run this as a script (e.g. a .py file) as opposed to in the Python interpreter, you will get the following output:

going to call foo
hello from inside foo
called foo   
foo returned 1

I hope this makes it clearer. The interpreter writes return values to the console so I can see why somebody could be confused.

Here's another example from the interpreter that demonstrates that:

>>> def foo():
...     print("hello from within foo")
...     return 1
...
>>> foo()
hello from within foo
1
>>> def bar():
...   return 10 * foo()
...
>>> bar()
hello from within foo
10

You can see that when foo() is called from bar(), 1 isn't written to the console. Instead it is used to calculate the value returned from bar().

print() is a function that causes a side effect (it writes a string in the console), but execution resumes with the next statement. return causes the function to stop executing and hand a value back to whatever called it.

Get escaped URL parameter

Based on the 999's answer:

function getURLParameter(name) {
    return decodeURIComponent(
        (location.search.match(RegExp("[?|&]"+name+'=(.+?)(&|$)'))||[,null])[1]
    );  
}

Changes:

  • decodeURI() is replaced with decodeURIComponent()
  • [?|&] is added at the beginning of the regexp

Make a UIButton programmatically in Swift

You should be able to create a customize UI button programmatically by accessing the titleLabel property of UIButton.

Per Class Reference in Swift: Regarding the titleLabel property, it says that "although this property is read-only, its own properties are read/write. Use these properties primarily to configure the text of the button."

In Swift, you can directly modify the properties of titleLabel like such:

let myFirstButton = UIButton()
myFirstButton.titleLabel!.text = "I made a label on the screen #toogood4you"
myFirstButton.titleLabel!.font = UIFont(name: "MarkerFelt-Thin", size: 45)
myFirstButton.titleLabel!.textColor = UIColor.red
myFirstButton.titleLabel!.textAlignment = .center
myFirstButton.titleLabel!.numberOfLines = 5
myFirstButton.titleLabel!.frame = CGRect(x: 15, y: 54, width: 300, height: 500)

Edit

Swift 3.1 Syntax

How to urlencode data for curl command?

I've found the following snippet useful to stick it into a chain of program calls, where URI::Escape might not be installed:

perl -p -e 's/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg'

(source)

React: trigger onChange if input value is changing by state?

The other answers talked about direct binding in render hence I want to add few points regarding that.

You are not recommended to bind the function directly in render or anywhere else in the component except in constructor. Because for every function binding a new function/object will be created in webpack bundle js file hence the bundle size will grow. Your component will re-render for many reasons like when you do setState, new props received, when you do this.forceUpdate() etc. So if you directly bind your function in render it will always create a new function. Instead do function binding always in constructor and call the reference wherever required. In this way it creates new function only once because constructor gets called only once per component.

How you should do is something like below

constructor(props){
  super(props);
  this.state = {
    value: 'random text'
  }
  this.handleChange = this.handleChange.bind(this);
}

handleChange (e) {
  console.log('handle change called');
  this.setState({value: e.target.value});
}

<input value={this.state.value} onChange={this.handleChange}/>

You can also use arrow functions but arrow functions also does create new function every time the component re-renders in certain cases. You should know about when to use arrow function and when are not suppose to. For detailed explation about when to use arrow functions check the accepted answer here

get index of DataTable column with name

Try this:

int index = row.Table.Columns["ColumnName"].Ordinal;

How to get all Windows service names starting with a common word?

sc queryex type= service state= all | find /i "NATION"
  • use /i for case insensitive search
  • the white space after type=is deliberate and required

What's the difference between %s and %d in Python string formatting?

They are format specifiers. They are used when you want to include the value of your Python expressions into strings, with a specific format enforced.

See Dive into Python for a relatively detailed introduction.

Difference between IsNullOrEmpty and IsNullOrWhiteSpace in C#

Short answer:

In common use, space " ", Tab "\t" and newline "\n" are the difference:

string.IsNullOrWhiteSpace("\t"); //true
string.IsNullOrEmpty("\t"); //false

string.IsNullOrWhiteSpace(" "); //true
string.IsNullOrEmpty(" "); //false

string.IsNullOrWhiteSpace("\n"); //true
string.IsNullOrEmpty("\n"); //false

https://dotnetfiddle.net/4hkpKM

also see this answer about: whitespace characters


Long answer:

There are also a few other white space characters, you probably never used before

https://docs.microsoft.com/en-us/dotnet/api/system.char.iswhitespace

Foreign Key to non-primary key

If you really want to create a foreign key to a non-primary key, it MUST be a column that has a unique constraint on it.

From Books Online:

A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.

So in your case if you make AnotherID unique, it will be allowed. If you can't apply a unique constraint you're out of luck, but this really does make sense if you think about it.

Although, as has been mentioned, if you have a perfectly good primary key as a candidate key, why not use that?

Differences between JDK and Java SDK

Taken from the Java EE 6 SDK Installer, shows what SDK 6 contains besides JDK:

What SDK 6 contains, besides JDK

Find a value in DataTable

AFAIK, there is nothing built in for searching all columns. You can use Find only against the primary key. Select needs specified columns. You can perhaps use LINQ, but ultimately this just does the same looping. Perhaps just unroll it yourself? It'll be readable, at least.

How to generate random float number in C

Try:

float x = (float)rand()/(float)(RAND_MAX/a);

To understand how this works consider the following.

N = a random value in [0..RAND_MAX] inclusively.

The above equation (removing the casts for clarity) becomes:

N/(RAND_MAX/a)

But division by a fraction is the equivalent to multiplying by said fraction's reciprocal, so this is equivalent to:

N * (a/RAND_MAX)

which can be rewritten as:

a * (N/RAND_MAX)

Considering N/RAND_MAX is always a floating point value between 0.0 and 1.0, this will generate a value between 0.0 and a.

Alternatively, you can use the following, which effectively does the breakdown I showed above. I actually prefer this simply because it is clearer what is actually going on (to me, anyway):

float x = ((float)rand()/(float)(RAND_MAX)) * a;

Note: the floating point representation of a must be exact or this will never hit your absolute edge case of a (it will get close). See this article for the gritty details about why.

Sample

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

int main(int argc, char *argv[])
{
    srand((unsigned int)time(NULL));

    float a = 5.0;
    for (int i=0;i<20;i++)
        printf("%f\n", ((float)rand()/(float)(RAND_MAX)) * a);
    return 0;
}

Output

1.625741
3.832026
4.853078
0.687247
0.568085
2.810053
3.561830
3.674827
2.814782
3.047727
3.154944
0.141873
4.464814
0.124696
0.766487
2.349450
2.201889
2.148071
2.624953
2.578719

How do I make the first letter of a string uppercase in JavaScript?

Like it:

function capitalize(string,a) {
    var tempstr = string.toLowerCase();
    if (a == false || a == undefined)
        return tempstr.replace(tempstr[0], tempstr[0].toUpperCase());
    else {
        return tempstr.split(" ").map(function (i) { return i[0].toUpperCase() + i.substring(1) }).join(" ");
    }
}


capitalize('stack overflow yeah!',true)); //Stack Overflow Yeah!

capitalize('stack stack stack stack overflow yeah!'));//Stack overflow yeah!

https://jsfiddle.net/dgmLgv7b/

AttributeError: 'str' object has no attribute

The problem is in your playerMovement method. You are creating the string name of your room variables (ID1, ID2, ID3):

letsago = "ID" + str(self.dirDesc.values())

However, what you create is just a str. It is not the variable. Plus, I do not think it is doing what you think its doing:

>>>str({'a':1}.values())
'dict_values([1])'

If you REALLY needed to find the variable this way, you could use the eval function:

>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'

or the globals function:

class Foo(object):
    def __init__(self):
        super(Foo, self).__init__()
    def test(self, name):
        print(globals()[name])

foo = Foo()
bar = 'Hello World!'
foo.text('bar')

However, instead I would strongly recommend you rethink you class(es). Your userInterface class is essentially a Room. It shouldn't handle player movement. This should be within another class, maybe GameManager or something like that.

call javascript function onchange event of dropdown list

jsFunction is not in good closure. change to:

jsFunction = function(value)
{
    alert(value);
}

and don't use global variables and functions, change it into module

How can I permanently enable line numbers in IntelliJ?

On IntelliJ 12 on MAC OSX, I had a hard time finding it. The search wouldn't show me the way for some reason. Go to Preferences and under IDE Settings, Editor, Appearance and select 'Show line numbers'

enter image description here

SQL distinct for 2 fields in a database

If you want distinct values from only two fields, plus return other fields with them, then the other fields must have some kind of aggregation on them (sum, min, max, etc.), and the two columns you want distinct must appear in the group by clause. Otherwise, it's just as Decker says.

Get multiple elements by Id

If you're not religious about keeping your HTML valid then I can see use cases where having the same ID on multiple elements may be useful.

One example is testing. Often we identify elements to test against by finding all elements with a particular class. However, if we find ourselves adding classes purely for testing purposes, then I would contend that that's wrong. Classes are for styling, not identification.

If IDs are for identification, why must it be that only one element can have a particular identifier? Particularly in today's frontend world, with reusable components, if we don't want to use classes for identification, then we need to use IDs. But, if we use multiples of a component, we'll have multiple elements with the same ID.

I'm saying that's OK. If that's anathema to you, that's fine, I understand your view. Let's agree to disagree and move on.

If you want a solution that actually finds all IDs of the same name though, then it's this:

function getElementsById(id) {
    const elementsWithId = []
    const allElements = document.getElementsByTagName('*')
    for(let key in allElements) {
        if(allElements.hasOwnProperty(key)) {
            const element = allElements[key]
            if(element.id === id) {
                elementsWithId.push(element)
            }        
        }
    }
    return elementsWithId
}

EDIT, ES6 FTW:

function getElementsById(id) {
    return [...document.getElementsByTagName('*')].filter(element => element.id === id)
}

Jest spyOn function called

You were almost done without any changes besides how you spyOn. When you use the spy, you have two options: spyOn the App.prototype, or component component.instance().

const spy = jest.spyOn(Class.prototype, "method")

The order of attaching the spy on the class prototype and rendering (shallow rendering) your instance is important.

const spy = jest.spyOn(App.prototype, "myClickFn");
const instance = shallow(<App />);

The App.prototype bit on the first line there are what you needed to make things work. A JavaScript class doesn't have any of its methods until you instantiate it with new MyClass(), or you dip into the MyClass.prototype. For your particular question, you just needed to spy on the App.prototype method myClickFn.

jest.spyOn(component.instance(), "method")

const component = shallow(<App />);
const spy = jest.spyOn(component.instance(), "myClickFn");

This method requires a shallow/render/mount instance of a React.Component to be available. Essentially spyOn is just looking for something to hijack and shove into a jest.fn(). It could be:

A plain object:

const obj = {a: x => (true)};
const spy = jest.spyOn(obj, "a");

A class:

class Foo {
    bar() {}
}

const nope = jest.spyOn(Foo, "bar");
// THROWS ERROR. Foo has no "bar" method.
// Only an instance of Foo has "bar".
const fooSpy = jest.spyOn(Foo.prototype, "bar");
// Any call to "bar" will trigger this spy; prototype or instance

const fooInstance = new Foo();
const fooInstanceSpy = jest.spyOn(fooInstance, "bar");
// Any call fooInstance makes to "bar" will trigger this spy.

Or a React.Component instance:

const component = shallow(<App />);
/*
component.instance()
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(component.instance(), "myClickFn");

Or a React.Component.prototype:

/*
App.prototype
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(App.prototype, "myClickFn");
// Any call to "myClickFn" from any instance of App will trigger this spy.

I've used and seen both methods. When I have a beforeEach() or beforeAll() block, I might go with the first approach. If I just need a quick spy, I'll use the second. Just mind the order of attaching the spy.

EDIT: If you want to check the side effects of your myClickFn you can just invoke it in a separate test.

const app = shallow(<App />);
app.instance().myClickFn()
/*
Now assert your function does what it is supposed to do...
eg.
expect(app.state("foo")).toEqual("bar");
*/

EDIT: Here is an example of using a functional component. Keep in mind that any methods scoped within your functional component are not available for spying. You would be spying on function props passed into your functional component and testing the invocation of those. This example explores the use of jest.fn() as opposed to jest.spyOn, both of which share the mock function API. While it does not answer the original question, it still provides insight on other techniques that could suit cases indirectly related to the question.

function Component({ myClickFn, items }) {
   const handleClick = (id) => {
       return () => myClickFn(id);
   };
   return (<>
       {items.map(({id, name}) => (
           <div key={id} onClick={handleClick(id)}>{name}</div>
       ))}
   </>);
}

const props = { myClickFn: jest.fn(), items: [/*...{id, name}*/] };
const component = render(<Component {...props} />);
// Do stuff to fire a click event
expect(props.myClickFn).toHaveBeenCalledWith(/*whatever*/);

Parse JSON String to JSON Object in C#.NET

use new JavaScriptSerializer().Deserialize<object>(jsonString)

You need System.Web.Extensions dll and import the following namespace.

Namespace: System.Web.Script.Serialization

for more info MSDN

Python equivalent of a given wget command

Here's the code adopted from the torchvision library:

import urllib

def download_url(url, root, filename=None):
    """Download a file from a url and place it in root.
    Args:
        url (str): URL to download file from
        root (str): Directory to place downloaded file in
        filename (str, optional): Name to save the file under. If None, use the basename of the URL
    """

    root = os.path.expanduser(root)
    if not filename:
        filename = os.path.basename(url)
    fpath = os.path.join(root, filename)

    os.makedirs(root, exist_ok=True)

    try:
        print('Downloading ' + url + ' to ' + fpath)
        urllib.request.urlretrieve(url, fpath)
    except (urllib.error.URLError, IOError) as e:
        if url[:5] == 'https':
            url = url.replace('https:', 'http:')
            print('Failed download. Trying https -> http instead.'
                    ' Downloading ' + url + ' to ' + fpath)
            urllib.request.urlretrieve(url, fpath)

If you are ok to take dependency on torchvision library then you also also simply do:

from torchvision.datasets.utils import download_url
download_url('http://something.com/file.zip', '~/my_folder`)

Why doesn't git recognize that my file has been changed, therefore git add not working

I had a similar issue when I created a patch file in server with vi editor. It seems the issue was with spacing. When I pushed the patch from local, deployment was proper.

How to "properly" print a list?

You can delete all unwanted characters from a string using its translate() method with None for the table argument followed by a string containing the character(s) you want removed for its deletechars argument.

lst = ['x', 3, 'b']

print str(lst).translate(None, "'")

# [x, 3, b]

If you're using a version of Python before 2.6, you'll need to use the string module's translate() function instead because the ability to pass None as the table argument wasn't added until Python 2.6. Using it looks like this:

import string

print string.translate(str(lst), None, "'")

Using the string.translate() function will also work in 2.6+, so using it might be preferable.

I want to calculate the distance between two points in Java

You could also you Point2D Java API class:

public static double distance(double x1, double y1, double x2, double y2)

Example:

double distance = Point2D.distance(3.0, 4.0, 5.0, 6.0);
System.out.println("The distance between the points is " + distance);

How to install Ruby 2.1.4 on Ubuntu 14.04

First of all, install the prerequisite libraries:

sudo apt-get update
sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties libffi-dev

Then install rbenv, which is used to install Ruby:

cd
git clone https://github.com/rbenv/rbenv.git ~/.rbenv
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
exec $SHELL

git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build
echo 'export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"' >> ~/.bashrc
exec $SHELL

rbenv install 2.3.1
rbenv global 2.3.1
ruby -v

Then (optional) tell Rubygems to not install local documentation:

echo "gem: --no-ri --no-rdoc" > ~/.gemrc

Credits: https://gorails.com/setup/ubuntu/14.10

Warning!!! There are issues with Gnome-Shell. See comment below.

Min/Max-value validators in asp.net mvc

A complete example of how this could be done. To avoid having to write client-side validation scripts, the existing ValidationType = "range" has been used.

public class MinValueAttribute : ValidationAttribute, IClientValidatable
{
    private readonly double _minValue;

    public MinValueAttribute(double minValue)
    {
        _minValue = minValue;
        ErrorMessage = "Enter a value greater than or equal to " + _minValue;  
    }

    public MinValueAttribute(int minValue)
    {
        _minValue = minValue;
        ErrorMessage = "Enter a value greater than or equal to " + _minValue;
    }

    public override bool IsValid(object value)
    {
        return Convert.ToDouble(value) >= _minValue;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule();
        rule.ErrorMessage = ErrorMessage;
        rule.ValidationParameters.Add("min", _minValue);
        rule.ValidationParameters.Add("max", Double.MaxValue);
        rule.ValidationType = "range";
        yield return rule;
    }

}

Setting Curl's Timeout in PHP

Hmm, it looks to me like CURLOPT_TIMEOUT defines the amount of time that any cURL function is allowed to take to execute. I think you should actually be looking at CURLOPT_CONNECTTIMEOUT instead, since that tells cURL the maximum amount of time to wait for the connection to complete.

In Gradle, is there a better way to get Environment Variables?

In android gradle 0.4.0 you can just do:

println System.env.HOME

classpath com.android.tools.build:gradle-experimental:0.4.0

Is there a "do ... while" loop in Ruby?

From what I gather, Matz does not like the construct

begin
    <multiple_lines_of_code>
end while <cond>

because, it's semantics is different than

<single_line_of_code> while <cond>

in that the first construct executes the code first before checking the condition, and the second construct tests the condition first before it executes the code (if ever). I take it Matz prefers to keep the second construct because it matches one line construct of if statements.

I never liked the second construct even for if statements. In all other cases, the computer executes code left-to-right (eg. || and &&) top-to-bottom. Humans read code left-to-right top-to-bottom.

I suggest the following constructs instead:

if <cond> then <one_line_code>      # matches case-when-then statement

while <cond> then <one_line_code>

<one_line_code> while <cond>

begin <multiple_line_code> end while <cond> # or something similar but left-to-right

I don't know if those suggestions will parse with the rest of the language. But in any case I prefere keeping left-to-right execution as well as language consistency.

How to match hyphens with Regular Expression?

It’s less confusing to always use an escaped hyphen, so that it doesn't have to be positionally dependent. That’s a \- inside the bracketed character class.

But there’s something else to consider. Some of those enumerated characters should possibly be written differently. In some circumstances, they definitely should.

This comparison of regex flavors says that C? can use some of the simpler Unicode properties. If you’re dealing with Unicode, you should probably use the general category \p{L} for all possible letters, and maybe \p{Nd} for decimal numbers. Also, if you want to accomodate all that dash punctuation, not just HYPHEN-MINUS, you should use the \p{Pd} property. You might also want to write that sequence of whitespace characters simply as \s, assuming that’s not too general for you.

All together, that works out to apattern of [\p{L}\p{Nd}\p{Pd}!$*] to match any one character from that set.

I’d likely use that anyway, even if I didn’t plan on dealing with the full Unicode set, because it’s a good habit to get into, and because these things often grow beyond their original parameters. Now when you lift it to use in other code, it will still work correctly. If you hard-code all the characters, it won’t.

How to take keyboard input in JavaScript?

You can do this by registering an event handler on the document or any element you want to observe keystrokes on and examine the key related properties of the event object.

Example that works in FF and Webkit-based browsers:

document.addEventListener('keydown', function(event) {
    if(event.keyCode == 37) {
        alert('Left was pressed');
    }
    else if(event.keyCode == 39) {
        alert('Right was pressed');
    }
});

DEMO

Vim: insert the same characters across multiple lines

I wanted to comment out a lot of lines in some config file on a server that only had vi (no nano), so visual method was cumbersome as well Here's how i did that.

  1. Open file vi file
  2. Display line numbers :set number! or :set number
  3. Then use the line numbers to replace start-of-line with "#", how?

:35,77s/^/#/

Note: the numbers are inclusive, lines from 35 to 77, both included will be modified.

To uncomment/undo that, simply use :35,77s/^#//

If you want to add a text word as a comment after every line of code, you can also use:

:35,77s/$/#test/ (for languages like Python)

:35,77s/;$/;\/\/test/ (for languages like Java)

credits/references:

  1. https://unix.stackexchange.com/questions/84929/uncommenting-multiple-lines-of-code-specified-by-line-numbers-using-vi-or-vim

  2. https://unix.stackexchange.com/questions/120615/how-to-comment-multiple-lines-at-once

DOS: find a string, if found then run another script

@echo off
cls
MD %homedrive%\TEMPBBDVD\
CLS
TIMEOUT /T 1 >NUL
CLS
systeminfo >%homedrive%\TEMPBBDVD\info.txt
cls
timeout /t 3 >nul
cls
find "x64-based PC" %homedrive%\TEMPBBDVD\info.txt >nul
if %errorlevel% equ 1 goto 32bitsok
goto 64bitsok
cls

:commandlineerror
cls
echo error, command failed or you not are using windows OS.
pause >nul
cls
exit

:64bitsok
cls
echo done, system of 64 bits
pause >nul
cls
del /q /f %homedrive%\TEMPBBDVD\info.txt >nul
cls
timeout /t 1 >nul
cls
RD %homedrive%\TEMPBBDVD\ >nul
cls
exit

:32bitsok
cls
echo done, system of 32 bits
pause >nul
cls
del /q /f %homedrive%\TEMPBBDVD\info.txt >nul
cls
timeout /t 1 >nul
cls
RD %homedrive%\TEMPBBDVD\ >nul
cls
exit

jQuery multiple events to trigger the same function

You could define the function that you would like to reuse as below:

var foo = function() {...}

And later you can set however many event listeners you want on your object to trigger that function using on('event') leaving a space in between as shown below:

$('#selector').on('keyup keypress blur change paste cut', foo);

Error handling in C code

I've used both approaches, and they both worked fine for me. Whichever one I use, I always try to apply this principle:

If the only possible errors are programmer errors, don't return an error code, use asserts inside the function.

An assertion that validates the inputs clearly communicates what the function expects, while too much error checking can obscure the program logic. Deciding what to do for all the various error cases can really complicate the design. Why figure out how functionX should handle a null pointer if you can instead insist that the programmer never pass one?

python, sort descending dataframe with pandas

Edit: This is out of date, see @Merlin's answer.

[False], being a nonempty list, is not the same as False. You should write:

test = df.sort('one', ascending=False)

C# Clear Session

Found this article on net, very relevant to this topic. So posting here.

ASP.NET Internals - Clearing ASP.NET Session variables

Synchronous request in Node.js

Another possibility is to set up a callback that tracks completed tasks:

function onApiResults(requestId, response, results) {
    requestsCompleted |= requestId;

    switch(requestId) {
        case REQUEST_API1:
            ...
            [Call API2]
            break;
        case REQUEST_API2:
            ...
            [Call API3]
            break;
        case REQUEST_API3:
            ...
            break;
    }

    if(requestId == requestsNeeded)
        response.end();
}

Then simply assign an ID to each and you can set up your requirements for which tasks must be completed before closing the connection.

const var REQUEST_API1 = 0x01;
const var REQUEST_API2 = 0x02;
const var REQUEST_API3 = 0x03;
const var requestsNeeded = REQUEST_API1 | REQUEST_API2 | REQUEST_API3;

Okay, it's not pretty. It is just another way to make sequential calls. It's unfortunate that NodeJS does not provide the most basic synchronous calls. But I understand what the lure is to asynchronicity.

Bash tool to get nth line from a file

After taking a look at the top answer and the benchmark, I've implemented a tiny helper function:

function nth {
    if (( ${#} < 1 || ${#} > 2 )); then
        echo -e "usage: $0 \e[4mline\e[0m [\e[4mfile\e[0m]"
        return 1
    fi
    if (( ${#} > 1 )); then
        sed "$1q;d" $2
    else
        sed "$1q;d"
    fi
}

Basically you can use it in two fashions:

nth 42 myfile.txt
do_stuff | nth 42

Filter by Dates in SQL

Well you are trying to compare Date with Nvarchar which is wrong. Should be

Where dates between date1 And date2
-- both date1 & date2 should be date/datetime

If date1,date2 strings; server will convert them to date type before filtering.

Rails has_many with alias name

Give this a shot:

has_many :jobs, foreign_key: "user_id", class_name: "Task"

Note, that :as is used for polymorphic associations.

How to run PowerShell in CMD

Try just:

powershell.exe -noexit D:\Work\SQLExecutor.ps1 -gettedServerName "MY-PC"

HTML text input allow only numeric input

This is an improved function:

function validateNumber(evt) {
  var theEvent = evt || window.event;
  var key = theEvent.keyCode || theEvent.which;
  if ((key < 48 || key > 57) && !(key == 8 || key == 9 || key == 13 || key == 37 || key == 39 || key == 46) ){
    theEvent.returnValue = false;
    if (theEvent.preventDefault) theEvent.preventDefault();
  }
}

git pull displays "fatal: Couldn't find remote ref refs/heads/xxxx" and hangs up

There are probably some commands to resolve it, but I would start by looking in your .git/config file for references to that branch, and removing them.

Entity framework code-first null foreign key

I recommend to read Microsoft guide for use Relationships, Navigation Properties and Foreign Keys in EF Code First, like this picture.

enter image description here

Guide link below:

https://docs.microsoft.com/en-gb/ef/ef6/fundamentals/relationships?redirectedfrom=MSDN

iPhone - Get Position of UIView within entire UIWindow

For me this code worked best:

private func getCoordinate(_ view: UIView) -> CGPoint {
    var x = view.frame.origin.x
    var y = view.frame.origin.y
    var oldView = view

    while let superView = oldView.superview {
        x += superView.frame.origin.x
        y += superView.frame.origin.y
        if superView.next is UIViewController {
            break //superView is the rootView of a UIViewController
        }
        oldView = superView
    }

    return CGPoint(x: x, y: y)
}

How to use CSS to surround a number with a circle?

Something like what I've done here could work (for numbers 0 to 99):

CSS:

.circle {
    border: 0.1em solid grey;
    border-radius: 100%;
    height: 2em;
    width: 2em;
    text-align: center;
}

.circle p {
    margin-top: 0.10em;
    font-size: 1.5em;
    font-weight: bold;
    font-family: sans-serif;
    color: grey;
}

HTML:

<body>
    <div class="circle"><p>30</p></div>
</body>

Each for object?

for(var key in object) {
   console.log(object[key]);
}

How can I check if mysql is installed on ubuntu?

# mysqladmin -u root -p status

Output:

Enter password:
Uptime: 4  Threads: 1  Questions: 62  Slow queries: 0  Opens: 51  Flush tables: 1  Open tables: 45  Queries per second avg: 15.500

It means MySQL serer is running

If server is not running then it will dump error as follows

# mysqladmin -u root -p status

Output :

mysqladmin: connect to server at 'localhost' failed
error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)'
Check that mysqld is running and that the socket: '/var/run/mysqld/mysqld.sock' exists!

So Under Debian Linux you can type following command

# /etc/init.d/mysql status

Remove secure warnings (_CRT_SECURE_NO_WARNINGS) from projects by default in Visual Studio

just copy " _CRT_SECURE_NO_WARNINGS " paste it on projects->properties->c/c++->preprocessor->preprocessor definitions click ok.it will work

What does (function($) {})(jQuery); mean?

A little help:

_x000D_
_x000D_
// an anonymous function_x000D_
  _x000D_
(function () { console.log('allo') });_x000D_
_x000D_
// a self invoked anonymous function_x000D_
_x000D_
(function () { console.log('allo') })();_x000D_
  _x000D_
// a self invoked anonymous function with a parameter called "$"_x000D_
  _x000D_
var jQuery = 'I\'m not jQuery.';_x000D_
_x000D_
(function ($) { console.log($) })(jQuery);
_x000D_
_x000D_
_x000D_

TypeLoadException says 'no implementation', but it is implemented

I ran into this and only my local machine was having the problem. No other developers in our group nor my VM had the problem.

In the end it seemed to be related to a "targeting pack" Visual Studio 2017

  • Open the Visual Studio Installer
  • Select Modify
  • Go to the second top tab "Individual Components"
  • See what Frameworks and Targeting packs you have selected.
  • I did not have the two newest targeting packs selected
  • I also noticed I did not have "Advanced ASP.NET features" selected and the other machines did.
  • Selected and installed the new items and it is all good now.

php/mySQL on XAMPP: password for phpMyAdmin and mysql_connect different?

if you open localhost/phpmyadmin you will find a tab called "User accounts". There you can define all your users that can access the mysql database, set their rights and even limit from where they can connect.

powerpoint loop a series of animation

Unfortunately you're probably done with the animation and presentation already. In the hopes this answer can help future questioners, however, this blog post has a walkthrough of steps that can loop a single slide as a sort of sub-presentation.

First, click Slide Show > Set Up Show.

Put a checkmark to Loop continuously until 'Esc'.

Click Ok. Now, Click Slide Show > Custom Shows. Click New.

Select the slide you are looping, click Add. Click Ok and Close.

Click on the slide you are looping. Click Slide Show > Slide Transition. Under Advance slide, put a checkmark to Automatically After. This will allow the slide to loop automatically. Do NOT Apply to all slides.

Right click on the thumbnail of the current slide, select Hide Slide.

Now, you will need to insert a new slide just before the slide you are looping. On the new slide, insert an action button. Set the hyperlink to the custom show you have created. Put a checkmark on "Show and Return"

This has worked for me.

Replace \n with <br />

For some reason using python3 I had to escape the "\"-sign

somestring.replace('\\n', '')

Hope this helps someone else!

Disable sorting on last column when using jQuery DataTables

use this link http://datatables.net/ref#bSortable

$(document).ready( function() {
   $('#example').dataTable( {
      "aoColumnDefs": [{ "bSortable": false, "aTargets": [ 0 ] }]
    } );
} );

Ring Buffer in Java

Consider CircularFifoBuffer from Apache Common.Collections. Unlike Queue you don't have to maintain the limited size of underlying collection and wrap it once you hit the limit.

Buffer buf = new CircularFifoBuffer(4);
buf.add("A");
buf.add("B");
buf.add("C");
buf.add("D"); //ABCD
buf.add("E"); //BCDE

CircularFifoBuffer will do this for you because of the following properties:

  • CircularFifoBuffer is a first in first out buffer with a fixed size that replaces its oldest element if full.
  • The removal order of a CircularFifoBuffer is based on the insertion order; elements are removed in the same order in which they were added. The iteration order is the same as the removal order.
  • The add(Object), BoundedFifoBuffer.remove() and BoundedFifoBuffer.get() operations all perform in constant time. All other operations perform in linear time or worse.

However you should consider it's limitations as well - for example, you can't add missing timeseries to this collection because it doens't allow nulls.

NOTE: When using current Common Collections (4.*), you have to use Queue. Like this:

Queue buf = new CircularFifoQueue(4);

Initialize a byte array to a certain value, other than the default null?

This is a faster version of the code from the post marked as the answer.

All of the benchmarks that I have performed show that a simple for loop that only contains something like an array fill is typically twice as fast if it is decrementing versus if it is incrementing.

Also, the array Length property is already passed as the parameter so it doesn't need to be retrieved from the array properties. It should also be pre-calculated and assigned to a local variable. Loop bounds calculations that involve a property accessor will re-compute the value of the bounds before each iteration of the loop.

public static byte[] CreateSpecialByteArray(int length)
{
    byte[] array = new byte[length];

    int len = length - 1;

    for (int i = len; i >= 0; i--)
    {
        array[i] = 0x20;
    }

    return array;
}

How do you add a Dictionary of items into another Dictionary

There is no need extension or any extra func anymore. You can write like that :

firstDictionary.merge(secondDictionary) { (value1, value2) -> AnyObject in
        return object2 // what you want to return if keys same.
    }

C# Get a control's position on a form

Supergeek, your non recursive function did not producte the correct result, but mine does. I believe yours does one too many additions.

private Point LocationOnClient(Control c)
{
   Point retval = new Point(0, 0);
   for (; c.Parent != null; c = c.Parent)
   { retval.Offset(c.Location); }
   return retval;
}

Find max and second max salary for a employee table MySQL

try this

select max(salary) as first, 
       (select salary from employee order by salary desc limit 1, 1) as second 
from employee limit 1

VBA: Conditional - Is Nothing

Just becuase your class object has no variables does not mean that it is nothing. Declaring and object and creating an object are two different things. Look and see if you are setting/creating the object.

Take for instance the dictionary object - just because it contains no variables does not mean it has not been created.

Sub test()

Dim dict As Object
Set dict = CreateObject("scripting.dictionary")

If Not dict Is Nothing Then
    MsgBox "Dict is something!"  '<--- This shows
Else
    MsgBox "Dict is nothing!"
End If

End Sub

However if you declare an object but never create it, it's nothing.

Sub test()

Dim temp As Object

If Not temp Is Nothing Then
    MsgBox "Temp is something!"
Else
    MsgBox "Temp is nothing!" '<---- This shows
End If

End Sub

How to return multiple values in one column (T-SQL)?

DECLARE @Str varchar(500)

SELECT @Str=COALESCE(@Str,'') + CAST(ID as varchar(10)) + ','
FROM dbo.fcUser

SELECT @Str

jquery change style of a div on click

If I understand correctly you want to change the CSS style of an element by clicking an item in a ul list. Am I right?

HTML:

<div class="results" style="background-color:Red;">
</div>

 <ul class="colors-list">
     <li>Red</li>
     <li>Blue</li>
     <li>#ffee99</li>
 </ul>

jquery

$('.colors-list li').click(function(e){
    var color = $(this).text();
    $('.results').css('background-color',color);
});

Note that jquery can use addClass, removeClass and toggleClass if you want to use classes rather than inline styling. This means that you can do something like that:

$('.results').addClass('selected');

And define the 'selected' styling in the CSS.

Working example: http://jsfiddle.net/uuJmP/

Iterating over each line of ls -l output

As already mentioned, awk is the right tool for this. If you don't want to use awk, instead of parsing output of "ls -l" line by line, you could iterate over all files and do an "ls -l" for each individual file like this:

for x in * ; do echo `ls -ld $x` ; done

How to log PostgreSQL queries?

You also need add these lines in PostgreSQL and restart the server:

log_directory = 'pg_log'                    
log_filename = 'postgresql-dateformat.log'
log_statement = 'all'
logging_collector = on

.htaccess redirect all pages to new domain

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTP_HOST} ^olddomain.com$ [OR]
  RewriteCond %{HTTP_HOST} ^www.olddomain.com$
  RewriteRule (.*)$ http://www.newdomain.com/$1 [R=301,L]
</IfModule>

This worked for me

Passing a Bundle on startActivity()?

You can pass values from one activity to another activity using the Bundle. In your current activity, create a bundle and set the bundle for the particular value and pass that bundle to the intent.

Intent intent = new Intent(this,NewActivity.class);
Bundle bundle = new Bundle();
bundle.putString(key,value);
intent.putExtras(bundle);
startActivity(intent);

Now in your NewActivity, you can get this bundle and retrive your value.

Bundle bundle = getArguments();
String value = bundle.getString(key);

You can also pass data through the intent. In your current activity, set intent like this,

Intent intent = new Intent(this,NewActivity.class);
intent.putExtra(key,value);
startActivity(intent);

Now in your NewActivity, you can get that value from intent like this,

String value = getIntent().getExtras().getString(key);

In git, what is the difference between merge --squash and rebase?

Both git merge --squash and git rebase --interactive can produce a "squashed" commit.
But they serve different purposes.

will produce a squashed commit on the destination branch, without marking any merge relationship.
(Note: it does not produce a commit right away: you need an additional git commit -m "squash branch")
This is useful if you want to throw away the source branch completely, going from (schema taken from SO question):

 git checkout stable

      X                   stable
     /                   
a---b---c---d---e---f---g tmp

to:

git merge --squash tmp
git commit -m "squash tmp"

      X-------------------G stable
     /                   
a---b---c---d---e---f---g tmp

and then deleting tmp branch.


Note: git merge has a --commit option, but it cannot be used with --squash. It was never possible to use --commit and --squash together.
Since Git 2.22.1 (Q3 2019), this incompatibility is made explicit:

See commit 1d14d0c (24 May 2019) by Vishal Verma (reloadbrain).
(Merged by Junio C Hamano -- gitster -- in commit 33f2790, 25 Jul 2019)

merge: refuse --commit with --squash

Previously, when --squash was supplied, 'option_commit' was silently dropped. This could have been surprising to a user who tried to override the no-commit behavior of squash using --commit explicitly.

git/git builtin/merge.c#cmd_merge() now includes:

if (option_commit > 0)
    die(_("You cannot combine --squash with --commit."));

replays some or all of your commits on a new base, allowing you to squash (or more recently "fix up", see this SO question), going directly to:

git checkout tmp
git rebase -i stable

      stable
      X-------------------G tmp
     /                     
a---b

If you choose to squash all commits of tmp (but, contrary to merge --squash, you can choose to replay some, and squashing others).

So the differences are:

  • squash does not touch your source branch (tmp here) and creates a single commit where you want.
  • rebase allows you to go on on the same source branch (still tmp) with:
    • a new base
    • a cleaner history

invalid operands of types int and double to binary 'operator%'

Because % is only defined for integer types. That's the modulus operator.

5.6.2 of the standard:

The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]

As Oli pointed out, you can use fmod(). Don't forget to include math.h.

What is the difference between HTTP and REST?

HTTP is a contract, a communication protocol and REST is a concept, an architectural style which may use HTTP, FTP or other communication protocols but is widely used with HTTP.

REST implies a series of constraints about how Server and Client should interact. HTTP is a communication protocol with a given mechanism for server-client data transfer, it's most commonly used in REST API just because REST was inspired by WWW (world wide web) which largely used HTTP before REST was defined, so it's easier to implement REST API style with HTTP.

There are three major constraints in REST (but there are more):

1. Interaction between server and client should be described via hypertext only.

2. Server and client should be loosely coupled and make no assumptions about each other. Client should only know resource entry point. Interaction data should be provided by the server in the response.

3. Server shouldn't store any information about request context. Requests must be independent and idempotent (means if same request is repeated infinitely, exactly same result is retrieved)

And HTTP is just a communication protocol (a tool) that can help to achieve this.

For more info check these links:

https://martinfowler.com/articles/richardsonMaturityModel.html http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven

Vue Js - Loop via v-for X times (in a range)

The same goes for v-for in range:

<li v-for="n in 20 " :key="n">{{n}}</li>

How to use addTarget method in swift 3

The poster's second comment from September 21st is spot on. For those who may be coming to this thread later with the same problem as the poster, here is a brief explanation. The other answers are good to keep in mind, but do not address the common issue encountered by this code.

In Swift, declarations made with the let keyword are constants. Of course if you were going to add items to an array, the array can't be declared as a constant, but a segmented control should be fine, right?! Not if you reference the completed segmented control in its declaration.

Referencing the object (in this case a UISegmentedControl, but this also happens with UIButton) in its declaration when you say .addTarget and let the target be self, things crash. Why? Because self is in the midst of being defined. But we do want to define behaviour as part of the object... Declare it lazily as a variable with var. The lazy fools the compiler into thinking that self is well defined - it silences your compiler from caring at the time of declaration. Lazily declared variables don't get set until they are first called. So in this situation, lazy lets you use the notion of self without issue while you set up the object, and then when your object gets a .touchUpInside or .valueChanged or whatever your 3rd argument is in your .addTarget(), THEN it calls on the notion of self, which at that point is fully established and totally prepared to be a valid target. So it lets you be lazy in declaring your variable. In cases like these, I think they could give us a keyword like necessary, but it is generally seen as a lazy, sloppy practice and you don't want to use it all over your code, though it may have its place in this sort of situation. What it

There is no lazy let in Swift (no lazy for constants).

Here is the Apple documentation on lazy.

Here is the Apple on variables and constants. There is a little more in their Language Reference under Declarations.

What is the role of the package-lock.json?

package-lock.json is automatically generated for any operations where npm modifies either the node_modules tree, or package.json. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.

It describes a single representation of a dependency tree such that teammates, deployments, and continuous integration are guaranteed to install exactly the same dependencies.It contains the following properties.

{
    "name": "mobileapp",
    "version": "1.0.0",
    "lockfileVersion": 1,
    "requires": true,
    "dependencies": {
    "@angular-devkit/architect": {
      "version": "0.11.4",
      "resolved": "https://registry.npmjs.org/@angular- devkit/architect/-/architect-0.11.4.tgz",
      "integrity": "sha512-2zi6S9tPlk52vyqNFg==",
      "dev": true,
      "requires": {
        "@angular-devkit/core": "7.1.4",
        "rxjs": "6.3.3"
      }
    },
}       

Stack smashing detected

Please look at the following situation:

ab@cd-x:$ cat test_overflow.c 
#include <stdio.h>
#include <string.h>

int check_password(char *password){
    int flag = 0;
    char buffer[20];
    strcpy(buffer, password);

    if(strcmp(buffer, "mypass") == 0){
        flag = 1;
    }
    if(strcmp(buffer, "yourpass") == 0){
        flag = 1;
    }
    return flag;
}

int main(int argc, char *argv[]){
    if(argc >= 2){
        if(check_password(argv[1])){
            printf("%s", "Access granted\n");
        }else{
            printf("%s", "Access denied\n");
        }
    }else{
        printf("%s", "Please enter password!\n");
    }
}
ab@cd-x:$ gcc -g -fno-stack-protector test_overflow.c 
ab@cd-x:$ ./a.out mypass
Access granted
ab@cd-x:$ ./a.out yourpass
Access granted
ab@cd-x:$ ./a.out wepass
Access denied
ab@cd-x:$ ./a.out wepassssssssssssssssss
Access granted

ab@cd-x:$ gcc -g -fstack-protector test_overflow.c 
ab@cd-x:$ ./a.out wepass
Access denied
ab@cd-x:$ ./a.out mypass
Access granted
ab@cd-x:$ ./a.out yourpass
Access granted
ab@cd-x:$ ./a.out wepassssssssssssssssss
*** stack smashing detected ***: ./a.out terminated
======= Backtrace: =========
/lib/tls/i686/cmov/libc.so.6(__fortify_fail+0x48)[0xce0ed8]
/lib/tls/i686/cmov/libc.so.6(__fortify_fail+0x0)[0xce0e90]
./a.out[0x8048524]
./a.out[0x8048545]
/lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe6)[0xc16b56]
./a.out[0x8048411]
======= Memory map: ========
007d9000-007f5000 r-xp 00000000 08:06 5776       /lib/libgcc_s.so.1
007f5000-007f6000 r--p 0001b000 08:06 5776       /lib/libgcc_s.so.1
007f6000-007f7000 rw-p 0001c000 08:06 5776       /lib/libgcc_s.so.1
0090a000-0090b000 r-xp 00000000 00:00 0          [vdso]
00c00000-00d3e000 r-xp 00000000 08:06 1183       /lib/tls/i686/cmov/libc-2.10.1.so
00d3e000-00d3f000 ---p 0013e000 08:06 1183       /lib/tls/i686/cmov/libc-2.10.1.so
00d3f000-00d41000 r--p 0013e000 08:06 1183       /lib/tls/i686/cmov/libc-2.10.1.so
00d41000-00d42000 rw-p 00140000 08:06 1183       /lib/tls/i686/cmov/libc-2.10.1.so
00d42000-00d45000 rw-p 00000000 00:00 0 
00e0c000-00e27000 r-xp 00000000 08:06 4213       /lib/ld-2.10.1.so
00e27000-00e28000 r--p 0001a000 08:06 4213       /lib/ld-2.10.1.so
00e28000-00e29000 rw-p 0001b000 08:06 4213       /lib/ld-2.10.1.so
08048000-08049000 r-xp 00000000 08:05 1056811    /dos/hacking/test/a.out
08049000-0804a000 r--p 00000000 08:05 1056811    /dos/hacking/test/a.out
0804a000-0804b000 rw-p 00001000 08:05 1056811    /dos/hacking/test/a.out
08675000-08696000 rw-p 00000000 00:00 0          [heap]
b76fe000-b76ff000 rw-p 00000000 00:00 0 
b7717000-b7719000 rw-p 00000000 00:00 0 
bfc1c000-bfc31000 rw-p 00000000 00:00 0          [stack]
Aborted
ab@cd-x:$ 

When I disabled the stack smashing protector no errors were detected, which should have happened when I used "./a.out wepassssssssssssssssss"

So to answer your question above, the message "** stack smashing detected : xxx" was displayed because your stack smashing protector was active and found that there is stack overflow in your program.

Just find out where that occurs, and fix it.

Display XML content in HTML page

2017 Update I guess. textarea worked fine for me using Spring, Bootstrap and a bunch of other things. Got the SOAP payload stored in a DB, read by Spring and push via Spring-MVC. xmp didn't work at all.

Which rows are returned when using LIMIT with OFFSET in MySQL?

OFFSET is nothing but a keyword to indicate starting cursor in table

SELECT column FROM table LIMIT 18 OFFSET 8 -- fetch 18 records, begin with record 9 (OFFSET 8)

you would get the same result form

SELECT column FROM table LIMIT 8, 18

visual representation (R is one record in the table in some order)

 OFFSET        LIMIT          rest of the table
 __||__   _______||_______   __||__
/      \ /                \ /
RRRRRRRR RRRRRRRRRRRRRRRRRR RRRR...
         \________________/
                 ||
             your result

mysql query result into php array

I think you wanted to do this:

while( $row = mysql_fetch_assoc( $result)){
    $new_array[] = $row; // Inside while loop
}

Or maybe store id as key too

 $new_array[ $row['id']] = $row;

Using the second ways you would be able to address rows directly by their id, such as: $new_array[ 5].

Responsive font size in CSS

 h1 { font-size: 2.25em; } 
 h2 { font-size: 1.875em; }
 h3 { font-size: 1.5em; }
 h4 { font-size: 1.125em; }
 h5 { font-size: 0.875em; }
 h6 { font-size: 0.75em; }

jQuery - Detecting if a file has been selected in the file input

You should be able to attach an event handler to the onchange event of the input and have that call a function to set the text in your span.

<script type="text/javascript">
  $(function() {
     $("input:file").change(function (){
       var fileName = $(this).val();
       $(".filename").html(fileName);
     });
  });
</script>

You may want to add IDs to your input and span so you can select based on those to be specific to the elements you are concerned with and not other file inputs or spans in the DOM.

How can I enable "URL Rewrite" Module in IIS 8.5 in Server 2012?

Thought I'd give a full answer combining some of the possible intricacies required for completeness.

  1. Check if you have 32-bit or 64-bit IIS installed:
    • Go to IIS Manager ? Application Pools, choose the appropriate app pool then Advanced Settings.
    • Check the setting "Enable 32-bit Applications". If that's true, that means the worker process is forced to run in 32-bit. If the setting is false, then the app pool is running in 64-bit mode.
    • You can also open up Task Manager and check w3wp.exe. If it's showing as w3wp*32.exe then it's 32-bit.
  2. Download the appropriate version here: https://www.iis.net/downloads/microsoft/url-rewrite#additionalDownloads.
  3. Install it.
  4. Close and reopen IIS Manager to ensure the URL Rewrite module appears.

Xcode Objective-C | iOS: delay function / NSTimer help?

Less code is better code.

[NSThread sleepForTimeInterval:0.06];

Swift:

Thread.sleep(forTimeInterval: 0.06)

Colors in JavaScript console

If you want to color your terminal console, then you can use npm package chalk

npm i chalk

enter image description here

How to implement __iter__(self) for a container object (Python)

example for inhert from dict, modify its iter, for example, skip key 2 when in for loop

# method 1
class Dict(dict):
    def __iter__(self):
        keys = self.keys()
        for i in keys:
            if i == 2:
                continue
            yield i

# method 2
class Dict(dict):
    def __iter__(self):
        for i in super(Dict, self).__iter__():
            if i == 2:
                continue
            yield i

Count number of occurences for each unique value

If you have multiple factors (= a multi-dimensional data frame), you can use the dplyr package to count unique values in each combination of factors:

library("dplyr")
data %>% group_by(factor1, factor2) %>% summarize(count=n())

It uses the pipe operator %>% to chain method calls on the data frame data.

How do you get a timestamp in JavaScript?

Here is another solution to generate a timestamp in JavaScript - including a padding method for single numbers - using day, month, year, hour, minute and seconds in its result (working example at jsfiddle):

var pad = function(int) { return int < 10 ? 0 + int : int; };
var timestamp = new Date();

    timestamp.day = [
        pad(timestamp.getDate()),
        pad(timestamp.getMonth() + 1), // getMonth() returns 0 to 11.
        timestamp.getFullYear()
    ];

    timestamp.time = [
        pad(timestamp.getHours()),
        pad(timestamp.getMinutes()),
        pad(timestamp.getSeconds())
    ];

timestamp.now = parseInt(timestamp.day.join("") + timestamp.time.join(""));
alert(timestamp.now);

IOS: verify if a point is inside a rect

It is so simple,you can use following method to do this kind of work:-

-(BOOL)isPoint:(CGPoint)point insideOfRect:(CGRect)rect
{
    if ( CGRectContainsPoint(rect,point))
        return  YES;// inside
    else
        return  NO;// outside
}

In your case,you can pass imagView.center as point and another imagView.frame as rect in about method.

You can also use this method in bellow UITouch Method :

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
}

How to tell if node.js is installed or not

Open the command prompt in Windows or terminal in Linux and Mac.Type

node -v

If node is install it will show its version.For eg.,

v6.9.5

Else download it from nodejs.org

How to use relative paths without including the context root name?

Instead using entire link we can make as below (solution concerns jsp files)

With JSTL we can make it like: To link resource like css, js:

     <link rel="stylesheet" href="${pageContext.request.contextPath}/style/sample.css" />
     <script src="${pageContext.request.contextPath}/js/sample.js"></script>   

To simply make a link:

     <a id=".." class=".." href="${pageContext.request.contextPath}/jsp/sample.jsp">....</a>

It's worth to get familiar with tags

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

There is also jsp method to do it like below, but better way like above:

   <link rel="stylesheet" href="<%=request.getContextPath()%>/style/sample.css" />
   <script type="text/javascript" src="<%=request.getContextPath()%>/js/sample.js"></script>

To simply make a link:

   <a id=".." class=".." href="<%=request.getContextPath()%>/jsp/sample.jsp">....</a>

Find which commit is currently checked out in Git

You have at least 5 different ways to view the commit you currently have checked out into your working copy during a git bisect session (note that options 1-4 will also work when you're not doing a bisect):

  1. git show.
  2. git log -1.
  3. Bash prompt.
  4. git status.
  5. git bisect visualize.

I'll explain each option in detail below.

Option 1: git show

As explained in this answer to the general question of how to determine which commit you currently have checked-out (not just during git bisect), you can use git show with the -s option to suppress patch output:

$ git show --oneline -s
a9874fd Merge branch 'epic-feature'

Option 2: git log -1

You can also simply do git log -1 to find out which commit you're currently on.

$ git log -1 --oneline
c1abcde Add feature-003

Option 3: Bash prompt

In Git version 1.8.3+ (or was it an earlier version?), if you have your Bash prompt configured to show the current branch you have checked out into your working copy, then it will also show you the current commit you have checked out during a bisect session or when you're in a "detached HEAD" state. In the example below, I currently have c1abcde checked out:

# Prompt during a bisect
user ~ (c1abcde...)|BISECTING $

# Prompt at detached HEAD state 
user ~ (c1abcde...) $

Option 4: git status

Also as of Git version 1.8.3+ (and possibly earlier, again not sure), running git status will also show you what commit you have checked out during a bisect and when you're in detached HEAD state:

$ git status
# HEAD detached at c1abcde <== RIGHT HERE

Option 5: git bisect visualize

Finally, while you're doing a git bisect, you can also simply use git bisect visualize or its built-in alias git bisect view to launch gitk, so that you can graphically view which commit you are on, as well as which commits you have marked as bad and good so far. I'm pretty sure this existed well before version 1.8.3, I'm just not sure in which version it was introduced:

git bisect visualize 
git bisect view # shorter, means same thing

enter image description here

Using SVG as background image

Set Background svg with content/cart at center

.login-container {
  justify-content: center;
  align-items: center;
  display: flex;
  height: 100vh; 
  background-image: url(/assets/images/login-bg.svg);
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

How to open a URL in a new Tab using JavaScript or jQuery?

You can easily create a new tab; do like the following:

function newTab() {
     var form = document.createElement("form");
     form.method = "GET";
     form.action = "http://www.example.com";
     form.target = "_blank";
     document.body.appendChild(form);
     form.submit();
}

Only variables should be passed by reference

Just as you can't index the array immediately, you can't call end on it either. Assign it to a variable first, then call end.

$basenameAndExtension = explode('.', $file_name);
$ext = end($basenameAndExtension);

Maven artifact and groupId naming

Your convention seems to be reasonable. If I were searching for your framework in the Maven repo, I would look for awesome-inhouse-framework-x.y.jar in com.mycompany.awesomeinhouseframework group directory. And I would find it there according to your convention.

Two simple rules work for me:

  • reverse-domain-packages for groupId (since such are quite unique) with all the constrains regarding Java packages names
  • project name as artifactId (keeping in mind that it should be jar-name friendly i.e. not contain characters that maybe invalid for a file name or just look weird)