text:
Q: How to safely echo FOR variable %%~p followed by a string literal I have a variable %%p created from for /f command
When i try to use it with some additional references like: %%~dp and then write some text afterwards it accesses a different variable
set var="%%~dpabc.txt"

Code outputs
%%~dpa instead of %%~dp

A: So you must be using FOR /F with multiple tokens, like
for /f "tokens=1-16" %%a in (file) do echo %%~dpabc.txt

Or your code could have nested FOR loops. Something like
for %%a in (something) do (
  for %%p in (somethingelse) do (
    echo %%~dpabc.txt
  )
)

Or even something like
for %%a in (something) do call :sub
exit /b

:sub
for %%p in (somethingelse) do echo %%~dpabc.txt
exit /b

All three code examples above will print out the drive and path of %%~dpa, followed by "bc.txt". As per the documentation, the FOR variables are global, so the DO clause of the subroutine FOR loop has access to both %%a and %%p.
Aschipfl does a good job documenting the rules for how modifiers and variable letters are parsed.
Whenever you use a FOR variable before a string literal, you must be extremely careful that the string literal cannot be interpreted as part of the FOR variable expansion. As can be seen with your example, this can be difficult. Make the literal dynamic, and the problem is even worse.
set /p "myFile=Enter a file name: "
for %%a in (something) do (
  for %%p in (somethingelse) do (
    echo %%~dp%myFile%
  )
)

If the user enters "abc.txt" then we are right back where we started. But looking at the code it is not obvious that you have a potential problem.
As Gerhard and Mofi say, you are safe if you use a character that cannot be interpreted as a modifier. But that is not always easy, especially if you are using FOR /F returning multiple tokens.
There are solutions!
1) Stop the FOR variable parsing with !! and delayed expansion
If you look at the rules for how cmd.exe parses scripts, you will see that FOR variables are expanded in phase 4 before delayed expansion occurs in phase 5. This provides the opportunity to use !! as a hard stop for the FOR expansion, provided that delayed expansion is enabled.
setlocal enableDelayedExpansion
for %%a in (something) do (
  for %%p in (somethingelse) do (
    echo %%~dp!!abc.txt
  )
)

The %%~dp is expanded properly in phase 4, and then in phase 5 !! is expanded to nothing, yielding your desired result of the drive letter followed by "abc.txt".
But this does not solve all situations. It is possible for ! to be used as a FOR variable, but that should be easy to avoid except under extreme situations.
More troubling is the fact that delayed expansion must be enabled. This is not an issue here, but if the FOR variable expands to a string containing ! then that character will be parsed by delayed expansion, and the results will most likely be messed up.
So the !! delayed expansion hack is safe to use only if you know that your FOR variable value does not contain !.
2) Use intermediate environment variables
The only simple foolproof method to avoid problems in all situations is to transfer the value of the FOR variable to an intermediate environment variable, and then toggle delayed expansion and work with the entire desired string.
for %%a in (something) do (
  for %%p in (somethingelse) do (
    set "drive=%%~dp"
    setlocal enableDelayedExpansion
    echo !drive!abc.txt
    endlocal
  )
)

3) Use Unicode characters via environment variables
There is a complex bullet proof solution, but it takes a good bit of background information before you can understand how it works.
The cmd.exe command processor represents all strings internally as Unicode, as are environment variables - Any Unicode code point other than 0x00 can be used. This also applies to FOR variable characters. The sequence of FOR variable characters is based on the numeric value of the Unicode code point.
But cmd.exe code, either from a batch script, or else typed into the command prompt, is restricted to characters supported by the active code page. That might seem like a dead end - what good are Unicode characters if you cannot access them with your code?
Well there is a simple, though non-intuitive solution: cmd.exe can work with predefined environment variable values that contain Unicode values outside the active code page!
All FOR variable modifiers are ASCII characters that are within the first 128 Unicode code points. So if you define variables named $1 through $n to contain a contiguous range of Unicode characters starting with say code point 256 (0x100), then you are guaranteed that your FOR variable can never be confused with a modifier.
So if $1 contains code point 0x100, then you would refer to the FOR variable as %%%$1%. And you can freely use modifiers like `%%~dp%$1%.
This strategy has an added benefit in that it is relatively easy to keep track of FOR variables when parsing a range of tokens with something like "tokens=1-30" because the variable names are inherently sequential. The active code page character sequencing usually does not match the sequence of the Unicode code points, which makes it difficult to access all 30 tokens unless you use the Unicode variable hack.
Now defining the $n variables with Unicode code points is not a trivial development effort. Thankfully it has already been done :-) Below is some code that demonstrates how to define and use the $n variables.
@echo off
setlocal disableDelayedExpansion
call :defineForChars 1
for /f "tokens=1-16" %%%$1% in (file) do echo %%~d%$16%abc.txt
exit /b

:defineForChars  Count
::
:: Defines variables to be used as FOR /F tokens, from $1 to $n, where n = Count*256
:: Also defines $max = Count*256.
:: No other variables are defined or tampered with.
::
:: Once defined, the variables are very useful for parsing lines with many tokens, as
:: the values are guaranteed to be contiguous within the FOR /F mapping scheme.
::
:: For example, you can use $1 as a FOR variable by using %%%$1%.
::
::   FOR /F "TOKENS=1-31" %%%$1% IN (....) DO ...
::
::      %%%$1% = token 1, %%%$2% = token 2, ... %%%$31% = token 31
::
:: This routine never uses SETLOCAL, and works regardless whether delayed expansion
:: is enabled or disabled.
::
:: Three temporary files are created and deleted in the %TEMP% folder, and the active
:: code page is temporarily set to 65001, and then restored to the starting value
:: before returning. Once defined, the $n variables can be used with any code page.
::
for /f "tokens=2 delims=:." %%P in ('chcp') do call :DefineForCharsInternal %1
exit /b
:defineForCharsInternal
set /a $max=%1*256
>"%temp%\forVariables.%~1.hex.txt" (
  echo FF FE
  for %%H in (
    "0 1 2 3 4 5 6 7 8 9 A B C D E F"
  ) do for /l %%N in (1 1 %~1) do for %%A in (%%~H) do for %%B in (%%~H) do (
    echo %%A%%B 0%%N 0D 00 0A 00
  )
)
>nul certutil.exe -decodehex -f "%temp%\forVariables.%~1.hex.txt" "%temp%\forVariables.%~1.utf-16le.bom.txt"
>nul chcp 65001
>"%temp%\forVariables.%~1.utf8.txt" type "%temp%\forVariables.%~1.utf-16le.bom.txt"
<"%temp%\forVariables.%~1.utf8.txt" (for /l %%N in (1 1 %$max%) do set /p "$%%N=")
for %%. in (dummy) do >nul chcp %%P
del "%temp%\forVariables.%~1.*.txt"
exit /b

The :defineForChars routine was developed at DosTips as part of a larger group effort to easily access many tokens with a FOR /F statement.
The :defineForChars routine and variants are introduced in the following posts within that thread:

*

*Work with a fixed number of columns

*Work with varying numbers of columns

*Dynamically choose which tokens to expand within the DO clause

A: This behaviour is caused by the kind of greedy nature of the parsing of for variable references and its ~-modifiers. Basically it follows these rules, given the preceding %/%%-signs have already been detected:

*

*if Command Extensions are enabled (default), check if next character is ~; if yes, then:

*

*take as many as possible of the following characters in the case-insensitive set fdpnxsatz (even multiple times each) that are preceding a character that defines a for variable reference or a $-sign; if such a $-sign is encountered, then:

*

*scan for a :1; if found, then:

*

*if there is a character other than % following the :, use it as a for variable reference and expand as expected, unless it is not defined, then do not expand;

*if the : is the last character, cmd.exe will crash!

*else (no : is found) do not expand anything;

*else (if no $-sign is encountered) expand the for variable using all the modifiers;

*else (if no ~ is found or Command Extensions are disabled) use the next character as a for variable reference, except it is a %-sign2, and expand, unless such is not defined, or there is not even a character following, then do not expand;

1)  The string between $ and : is considered as the name of an environment variable, which may even be empty; since an environment variable cannot have an empty name, the behaviour is just the same as for an undefined environment variable.

2)  A %-sign can be the name of a for meta-variable, but it cannot be expanded without a ~-modifier.

This answer has meanwhile been posted in an augmented manner as a community answer to the thread How does the Windows Command Interpreter (CMD.EXE) parse scripts?.

A: As already explained in the for meta-variable parsing rules, the ~-modifier detection happens in a greedy manner. But you can stop parsing by another for meta-variable, which eventually expands to nothing, or by the ~$-modifier as suggested by jeb in a comment, which does not even require another for meta-variable, so any existing one can be used:
rem // Using `%%~#` will expand to an empty string (note that `#` is not a valid `~`-modifier):
for %%# in ("") do (
    rem // Establish a `for`-loop that defines meta-variables `%%a` to `%%p`:
    for /F "tokens=1-16" %%a in ("1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16") do (
        rem /* Since `d`, `p` and `a` are all valid `~`-modifiers and a `for` meta-variable
        rem    `%%b` exists while `b` is not a valid `~`-modifier, `%%~dpab` is expanded: */
        echo(%%~dpabc.txt
        rem /* `for` meta-variable parsing is stopped after `%%~dp`, because the following `%`
        rem    is not a valid `~`-modifier, and neither exists a `for` meta-variable named `%`;
        rem    `%%~#` is expanded to an empty sting then (parsing surely stops at `#`): */
        echo(%%~dp%%~#abc.txt
        rem /* The following does not even require a particular `for` meta-variable like `%%#`,
        rem    it just uses the existing one `%%p` with the `~$`-modifier that specifies an
        rem    environment variable; since there is no variable name in between `$` and `:`,
        rem    there is certainly no such variable (since they must have names), hence `$~%:p`
        rem    expands to an empty string; note that `~$` is always the very last modifier: */
        echo(%%~dp%%~$:pabc.txt
    )
)

Note that this approach fails in case there is a for meta-variable named % (which is not quite common but possible).


text:
Q: .net core application can't find the correct appsettings using environment variables I have a simple .net core application. It's using WebApplicationBuilder to create the instance of the application at runtime.
The code in the program.cs looks like this:
    var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

var logger = new LoggerConfiguration()
    .ReadFrom.Configuration(builder.Configuration)
    .Enrich.FromLogContext()
    .CreateLogger();

builder.WebHost.ConfigureLogging(logging =>
{
    logging.ClearProviders();
    logging.AddConsole();
    logging.AddSerilog(logger);
});

My launchsetting.json looks like this:
{
  "$schema": "https://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:29881",
      "sslPort": 44344
    }
  },
  "profiles": {
    "MyApp.Api": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "https://localhost:7134;http://localhost:5134",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

When running this app using the MyApp.Api profile locally, it works. It uses appsetting.Development.json and transforms it's json values over appsetting.json.
However, when I publish and deploy the application to a server outside of my local environment, it doesn't use the provided appsetting.CURRENT.json.
The environment variables are set as follow:
Environment=ASPNETCORE_ENVIRONMENT=CURRENT
Environment=DOTNET_ENVIRONMENT=CURRENT

And I can see the files being deployed to the correct directory.
-rw-r--r--  1 root root    2397 Oct 13  2022 appsettings.CURRENT.json
-rw-r--r--  1 root root    1527 Oct 13  2022 appsettings.json

I'm completely out of ideas. Any help is deeply appreciated.

A: I think you're looking to use CreateDefaultBuilder.
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/web-host?view=aspnetcore-6.0
That one will use appsettings.{Environment}.json automatically (more detail on what it does at that link.

A: I suggest a different approach:
if(builder.Environment.IsProduction())
{
  builder.Configuration.AddJsonFile(
    "appsettings.CURRENT.json",
    optional: false, reloadOnChange: true
  );
}

https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.configuration.jsonconfigurationextensions

redpajama_set_name: RedPajamaStackExchange


text:
Q: The value of attribute "if" associated with an element type "null" must not contain the '<' character I'm double condition to do a test on my progressmeter. This the fist condition that I use:
<zk if="${item.progres <= '33'}">
  <style> span.z-progressmeter-image{ background-image:url('images/vert.GIF'); } </style>
</zk>

When I run the program I have this error:

The value of attribute "if" associated with an element type "null" must not contain the '<' character.


text:
Q: Make individual async post requests I want to write a simple function that makes a post request asynchronously. It would be great if it worked on 2.7 and 3.x, but i'm fine with it just working on 3.x. I'm having trouble finding something to do this though. All the examples i've found have been get requests, and it bundled many requests together. I just want:
def fun1(self, arg1, arg2, ...):
    ... #construct payload from args
    return requests.post("myurl", data=payload) #takes 10 seconds

def fun2(self, arg1, arg2, ...):
    ... #construct payload from args
    return requests.post("some other url", data=payload) #takes 20 seconds

def main():
   # do some stuff
   fun1("foo")
   # do some other stuff immediately
   fun2("bar")

Is this actually possible? I just want to call fun1(), but not block the rest of the code waiting for it to complete.

A: The common practice is to use the multiprocessing module to run a function with a pool of processes.
The introduction show this simple example:
from multiprocessing import Pool

def f(x):
     return x*x

if __name__ == '__main__':
     p = Pool(5)
     print(p.map(f, [1, 2, 3]))

will print to standard output ::
[1, 4, 9]

For your problem, you can write something like this:
p.map(requests.post, [("myurl", data...), ("myurl2", data), ...])


text:
Q: Generic methods type inference Let's say I have a class with two generic methods:
TMyClass = class
  procedure DoWith<T: class> (obj: T);
  procedure DoFor<T: class> ( proc: TProc<T> );
end;

Now, when I want to call either of these two methods with a specific type parameter, Delphi can infer the type for the DoWith method, so I can call it with either
MyClass.DoWith <TButton> ( MyButton )

or
MyClass.DoWith ( MyButton )

The Delphi Compiler will happily compile both.
But if I omit the type parameter in the DoFor method, the Delphi compiler complains about the missing type parameter:
MyClass.DoFor<TButton>(procedure (Button: TButton) begin .... end);  // compiles

MyClass.DoFor(procedure (Button: TButton) begin .... end);  // doesn't compile

Now my question is: Is this just a shortcoming of the compiler, or is there any logical reason (that I haven't figured out yet) that prohibits the compiler from correctly inferring the type for the DoFor method?

A: The reason it cannot infer T from a TProc<T>argument is that at that time TProc<TButton> is a constructed type without any information that it originally was a TProc<T>.
To do that it would have to infer the type from the anonymous method signature which does not work (I guess Barry Kelly could explain that better and I think he once wrote about the difficulties of lambdas and type inference in Delphi).
The only type inference the Delphi compiler is capable of is an argument of type T. Even with multiple arguments that does not work often and even less if you have more than one generic type parameters.
Edit: I found a comment where Barry explained a bit about the difficulties of type inference and lambdas in the Delphi compiler: http://www.deltics.co.nz/blog/posts/244/comment-page-1#comment-107


text:
Q: fast-xml-parser parsing xml input incorrectly Why is this test not passing with fastxmlparser
 import parser from 'fast-xml-parser'
    test("fastxmlparser", () => {
            let parsed = parser.parse('<detail><name>john</name><value>116347579610481033</value></detail>')
            expect(parsed.detail.value).toBe('116347579610481033')
        })

Expected value to be:
          "116347579610481033"
        Received:
          116347579610481040

        Difference:

          Comparing two different types of values. Expected string but received number.

           95 | test("fastxmlparser", () => {
           96 |     let parsed = parser.parse('<detail><name>john</name><value>116347579610481033</value></detail>')
        >  97 |     expect(parsed.detail.value).toBe('116347579610481033')
           98 | })
           99 |
          100 |


text:
Q: Converting string into JSON from MySQL, Unexpected token N I am executing an MYSQL query using AWS RDS. The table structure stored in the database returns the result something like this (sample):
patient_id | calculation_time | calculation_parameters | comprehensive

4b53bb2567 | 12:19:04 | {"a":1, "b":2} | [{"label": "label1", "cat4_cnt":{"status":"critical", "count": 2},"cat3_cnt":{"status":"high", "count":8},"median":1.05}, {"label": "label2", "cat4_cnt":{"status":"critical", "count":4}, "cat3_cnt":{"status": "high", "count":3}, "median":1.25}]

My AWS handler.js file sends the response in the way:
..... //
    const response = {
          body: {
            statusCode: 200,
            data: comprehensive,
          }
        };

        callback(null, response);
// .......

After executing the handler, the final data received in postman is of the form:
{
    "body": {
        "statusCode": 200,
        "data": "[{\"label\": \"label1\", \"cat4_cnt\":{\"status\":\"critical\", \"count\": 2},\"cat3_cnt\":{\"status\":\"high\", \"count\":8}, \"median\":1.05}, {\"label\": \label2\", \"cat4_cnt\":{\"status\":\"critical\", \"count\":4}, \"cat3_cnt\":{\"status\": \"high\", \"count\":3}, \"median\":1.25}]",
    }
}

What I required, is to convert the data received into a proper JSON. I simply did(in handler.js itself):
..... //
        const response = {
              body: {
                statusCode: 200,
                data: JSON.parse(comprehensive),
              }
            };

            callback(null, response);
// .......

Which throws an error:
{
    "body": {
        "message": "Unexpected token N in JSON at position 30",
        "data": null
    }
}

The typeof data returned from the database that I need to convert is a string (checked with console.log(typeof comprehensive) already)
I know many questions are already available on the same topic, but doesn't seems to work for me. Any help to convert the database response into proper JSON is appreciated.
Thanks in advance :)


text:
Q: Styling an input type="file" button How do you style an input type="file" button?

<input type="file" />

A: All rendering engines automatically generate a button when an <input type="file"> is created. Historically, that button has been completely un-styleable. However, Trident and WebKit have added hooks through pseudo-elements.
Trident
As of IE10, the file input button can be styled using the ::-ms-browse pseudo-element. Basically, any CSS rules that you apply to a regular button can be applied to the pseudo-element. For example:

::-ms-browse {
  background: black;
  color: red;
  padding: 1em;
}
<input type="file">

This displays as follows in IE10 on Windows 8:

WebKit
WebKit provides a hook for its file input button with the ::-webkit-file-upload-button pseudo-element. Again, pretty much any CSS rule can be applied, therefore the Trident example will work here as well:

::-webkit-file-upload-button {
  background: black;
  color: red;
  padding: 1em;
}
<input type="file">

This displays as follows in Chrome 26 on OS X:

A: <input type="file" name="media" style="display-none" onchange="document.media.submit()">

I would normally use simple javascript to customize the file input tag.A hidden input field,on click of button,javascript call the hidden field,simple solution with out any css or bunch of jquery.
<button id="file" onclick="$('#file').click()">Upload File</button>

A: VISIBILITY:hidden TRICK
I usually go for the visibility:hidden trick
this is my styled button

Upload

this is the input type=file button. Note the visibility:hidden rule
<input type="file" id="upload" style="visibility:hidden;">

this is the JavaScript bit to glue them together. It works

A: Multiple file solution with converted filename
Bootstrap EXAMPLE
HTML:

    <input name="file1" type="file" style="display:None;"> Choose file

  No file selected

    <input name="file2" type="file" style="display:None;"> Choose file

  No file selected

1. JS with jQuery:
$().ready(function($){
    $('.search-file-btn').children("input").bind('change', function() {
    var fileName = '';
    fileName = $(this).val().split("\\").slice(-1)[0];
    $(this).parent().next("span").html(fileName);
  })
});

2. JS without jQuery
Array.prototype.forEach.call(document.getElementsByTagName('input'), function(item) {
  item.addEventListener("change", function() {
    var fileName = '';
    fileName = this.value.split("\\").slice(-1)[0];
    this.parentNode.nextElementSibling.innerHTML = fileName;
  });
});

A: Hide it with css and use a custom button with $(selector).click() to activate the the browse button. then set an interval to check the value of the file input type. the interval can display the value for the user so the user can see whats getting uploaded. the interval will clear when the form is submitted [EDIT] Sorry i have been very busy was meaning to update this post, here is an example
<form action="uploadScript.php" method="post" enctype="multipart/form-data">

    <input class="display-none" id="file-type" type="file" size="4" name="file"/>

    <input id="browse-click" type="button" class="button" value="Browse for files"/>

    <input type="submit" class="button" value="Change"/>

$(window).load(function () {
    var intervalFunc = function () {
        $('#file-name').html($('#file-type').val());
    };
    $('#browse-click').on('click', function () { // use .live() for older versions of jQuery
        $('#file-type').click();
        setInterval(intervalFunc, 1);
        return false;
    });
});

A: ::file-selector-button
https://developer.mozilla.org/en-US/docs/Web/CSS/::file-selector-button
This is a new selector that can be used to style the file selector button.
It has full support on recent browser versions.

input[type=file]::file-selector-button {
  border: 2px solid #6c5ce7;
  padding: .2em .4em;
  border-radius: .2em;
  background-color: #a29bfe;
  transition: 1s;
}

input[type=file]::file-selector-button:hover {
  background-color: #81ecec;
  border: 2px solid #00cec9;
}
<form>
  Upload file
  <input type="file" id="fileUpload">
</form>

Here is another snippet that demonstrates different styling:

.input_container {
  border: 1px solid #e5e5e5;
}

input[type=file]::file-selector-button {
  background-color: #fff;
  color: #000;
  border: 0px;
  border-right: 1px solid #e5e5e5;
  padding: 10px 15px;
  margin-right: 20px;
  transition: .5s;
}

input[type=file]::file-selector-button:hover {
  background-color: #eee;
  border: 0px;
  border-right: 1px solid #e5e5e5;
}
<form>

    <input type="file" id="fileUpload">

</form>

I felt that this answer was needed as most answers here are outdated.

A:

$('.new_Btn').click(function() {
  $('#html_btn').click();
});
.new_Btn {
  // your css propterties
}

#html_btn {
  display: none;
}

SelectPicture

<input id="html_btn" type='file' />

You can reach your goals too without jQuery with normal JavaScript.
Now the newBtn is linkes with the html_btn and you can style your new btn like you want :D

A: the only way i can think of is to find the button with javascript after it gets rendered and assign a style to it
you might also look at this writeup

A: Here we use a span to trigger input of type file and we simply customized that span, so we can add any styling using this way.
Note that we use input tag with visibility:hidden option and trigger it in the span.

.attachFileSpan{
color:#2b6dad;
cursor:pointer;
}
.attachFileSpan:hover{
text-decoration: underline;
}

 Customized input of type file

<input id="myInput" type="file" style="visibility:hidden"/>

        Attach file

Reference

A: Here is a solution, that also shows the chosen file name:
http://jsfiddle.net/raft9pg0/1/
HTML:
Chose file
<input id="file-upload" type="file"/>
File: -

JS:
$(function() {
    $("input:file[id=file-upload]").change(function() {
        $("#file-upload-value").html( $(this).val() );
    });
});

CSS:
input[type="file"] {
    display: none;
}

.custom-file-upload {
      background: #ddd;
      border: 1px solid #aaa;
      border-top: 1px solid #ccc;
      border-left: 1px solid #ccc;
      -moz-border-radius: 3px;
      -webkit-border-radius: 3px;
      border-radius: 3px;
      color: #444;
      display: inline-block;
      font-size: 11px;
      font-weight: bold;
      text-decoration: none;
      text-shadow: 0 1px rgba(255, 255, 255, .75);
      cursor: pointer;
      margin-bottom: 20px;
      line-height: normal;
      padding: 8px 10px; }

A: This is a nice way to do it with material / angular file upload.
You could do the same with a bootstrap button.
Note I used  instead of <button> this allows the click events to bubble up.

    <input type="file" (change)="setFile($event)" style="display:none" />

      <mat-icon>file_upload</mat-icon>
      Upload Document

A: If you are using Bootstrap 3, this worked for me:
See https://www.abeautifulsite.net/posts/whipping-file-inputs-into-shape-with-bootstrap-3/

.btn-file {
  position: relative;
  overflow: hidden;
}
.btn-file input[type=file] {
  position: absolute;
  top: 0;
  right: 0;
  min-width: 100%;
  min-height: 100%;
  font-size: 100px;
  text-align: right;
  filter: alpha(opacity=0);
  opacity: 0;
  outline: none;
  background: white;
  cursor: inherit;
  display: block;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

    Browse...<input type="file">

Which produces the following file input button:

Seriously, check out https://www.abeautifulsite.net/posts/whipping-file-inputs-into-shape-with-bootstrap-3/

A: Update Nevermind, this doesn't work in IE or it's new brother, FF. Works on every other type of element as expected, but doesn't work on file inputs. A much better way to do this is to just create a file input and a label that links to it. Make the file input display none and boom, it works in IE9+ seamlessly.
Warning: Everything below this is crap!
By using pseudo elements positioned/sized against their container, we can get by with only one input file (no additional markup needed), and style as per usual.
Demo
<input type="file" class="foo">

Enjoy guys!
Old Update
Turned this into a Stylus mixin. Should be easy enough for one of you cool SCSS cats to convert it.
    file-button(button_width = 150px)
      display block
      position relative
      margin auto
      cursor pointer
      border 0
      height 0
      width 0
      outline none
      &:after
        position absolute
        top 0
        text-align center
        display block
        width button_width
        left -(button_width / 2)

Usage:
<input type="file">

input[type="file"]
    file-button(200px)

A: Maybe a lot of awnsers. But I like this in pure CSS with fa-buttons:

.divs {
    position: relative;
    display: inline-block;
    background-color: #fcc;
}

.inputs {
    position:absolute;
    left: 0px;
    height: 100%;
    width: 100%;
    opacity: 0;
    background: #00f;
    z-index:999;
}

.icons {
    position:relative;
}

<input type='file' id='image' class="inputs">

<input type='file' id='book' class="inputs">

<input type='file' id='data' class="inputs">

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

Fiddle: https://jsfiddle.net/zoutepopcorn/v2zkbpay/1/

A: Don't be fooled by "great" CSS-only solutions that are actually very browser-specific, or that overlay the styled button on top of the real button, or that force you to use a  instead of a <button>, or any other such hack. JavaScript IS necessary to get it working for general usage. Please study how gmail and DropZone do it if you don't believe me.
Just style a normal button however you want, then call a simple JS function to create and link a hidden input element to your styled button.
<!DOCTYPE html>
<meta charset="utf-8">

<button id="upload">Styled upload button!</button>

Notice how the above code re-links it after every time the user chooses a file. This is important because "onchange" is only called if the user changes the filename. But you probably want to get the file every time the user provides it.

A: Working example here with native Drag and drop support : https://jsfiddle.net/j40xvkb3/
When styling a file input, you shouldn't break any of native interaction
the input provides.
The display: none approach breaks the native drag and drop support.
To not break anything, you should use the opacity: 0 approach for the input, and position it using relative / absolute pattern in a wrapper.
Using this technique, you can easily style a click / drop zone for the user, and add custom class in javascript on dragenter event to update styles and give user a feedback to let him see that he can drop a file.
HTML :

Click or drop something here

  <input type="file" id="test">

CSS :
input[type="file"] {
  position: absolute;
  left: 0;
  opacity: 0;
  top: 0;
  bottom: 0;
  width: 100%;
}

div {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #ccc;
  border: 3px dotted #bebebe;
  border-radius: 10px;
}

label {
  display: inline-block;
  position: relative;
  height: 100px;
  width: 400px;
}

Here is a working example (with additional JS to handle dragover event and dropped files).
https://jsfiddle.net/j40xvkb3/
Hope this helped !

A: Styling file inputs are notoriously difficult, as most browsers will not change the appearance from either CSS or javascript.
Even the size of the input will not respond to the likes of:
<input type="file" style="width:200px">

Instead, you will need to use the size attribute:
<input type="file" size="60" />

For any styling more sophisticated than that (e.g. changing the look of the browse button) you will need to look at the tricksy approach of overlaying a styled button and input box on top of the native file input. The article already mentioned by rm at www.quirksmode.org/dom/inputfile.html is the best one I've seen.
UPDATE
Although it's difficult to style an <input> tag directly, this is easily possible with the help of a  tag. See answer below from @JoshCrozier: https://stackoverflow.com/a/25825731/10128619

A: I've found a very easy method to switch the file button to a picture.
You just label a picture and place it on top of the file button.

        <input type="file" id="fileButton"/>

When clicking on the labeled image, you select the file button.

A: This week I also needed to custom the button and display the selected file name aside it, so after reading some of the answers above (Thanks BTW) I came up with the following implementation:
HTML:

Choose file
<input type="file" name="fileInput" id="fileInput" accept=".yaml" ngf-select ngf-change="onFileSelect($files)" />

{{fileName}}

CSS
   input[type='file'] {
    color: #a1bbd5;
    display: none;

}

.custom-file-upload {
    border: 1px solid #a1bbd5;
    display: inline-block;
    padding: 2px 8px;
    cursor: pointer;
}

label{
    color: #a1bbd5;
    border-radius: 3px;
}

Javascript (Angular)
app.controller('MainCtrl', function($scope) {

        $scope.fileName = 'No file chosen';

          $scope.onFileSelect = function ($files) {
          $scope.selectedFile = $files;
          $scope.fileName = $files[0].name;
    };
});

Basically I'm working with ng-file-upload lib, Angular-wise I'm binding the filename to my $scope and giving it the initial value of 'No file chosen', I'm also binding the onFileSelect() function to my scope so when a file gets selected I'm getting the filename using ng-upload API and assign it to the $scope.filename.

A: Simply simulate a click on the <input> by using the trigger() function when clicking on a styled
. I created my own button out of a
 and then triggered a click on the input when clicking my
. This allows you to create your button however you want because it's a
 and simulates a click on your file <input>. Then use display: none on your <input>.
// div styled as my load file button

Load from backup

<input type="file" id="readFile" />

// Click function for input
$("#readFile").click(function() {
    readFile();
});

// Simulate click on the input when clicking div
$("#simClick").click(function() {
    $("#readFile").trigger("click");
});

A: The best way I have found is having an input type: file then setting it to display: none. Give it an id. Create a button or any other element you want to open the file input.
Then add an event listener on it (button) which when clicked simulates a click on the original file input.
Like clicking a button named hello but it opens a file window.
Example code
//i am using semantic ui

<button class="ui circular icon button purple send-button" id="send-btn">

    </button>
  <input type="file" id="file" class="input-file" />

javascript
var attachButton=document.querySelector('.attach-button');
    attachButton.addEventListener('click', e=>{
        $('#file').trigger("click")
    })

A: ONLY CSS
Use this very simple and EASY

.choose::-webkit-file-upload-button {
  color: white;
  display: inline-block;
  background: #1CB6E0;
  border: none;
  padding: 7px 15px;
  font-weight: 700;
  border-radius: 3px;
  white-space: nowrap;
  cursor: pointer;
  font-size: 10pt;
}
Attach your screenshort
<input type="file" multiple class="choose">

A: I am able to do it with pure CSS using below code. I have used bootstrap and font-awesome.

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet" />

  <input type="file" style="display: none;">

A:
    <input type="file" />

You can wrap your input type="file" inside of a label for the input. Style the label however you'd like and hide the input with display: none;

A: follow these steps then you can create custom styles for your file upload form:

*

*this is the simple HTML form(please read the HTML comments I have written here below)
<form action="#type your action here" method="POST" enctype="multipart/form-data">

Click to upload!

<input id="upfile" type="file" value="upload"/>

  <input type="submit" value='submit' >
</form>

*then use this simple script to pass the click event to file input tag.
function getFile(){
     document.getElementById("upfile").click();
}

Now you can use any type of styling without worrying about how to change default styles.
I know this very well because I have been trying to change the default styles for a month and a half. believe me, it's very hard because different browsers have different upload input tag. So use this one to build your custom file upload forms. Here is the full AUTOMATED UPLOAD code.

function getFile() {
  document.getElementById("upfile").click();
}

function sub(obj) {
  var file = obj.value;
  var fileName = file.split("\\");
  document.getElementById("yourBtn").innerHTML = fileName[fileName.length - 1];
  document.myForm.submit();
  event.preventDefault();
}
#yourBtn {
  position: relative;
  top: 150px;
  font-family: calibri;
  width: 150px;
  padding: 10px;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border: 1px dashed #BBB;
  text-align: center;
  background-color: #DDD;
  cursor: pointer;
}
<form action="#type your action here" method="POST" enctype="multipart/form-data" name="myForm">

click to upload a file

<input id="upfile" type="file" value="upload" onchange="sub(this)" />

</form>

A: css can do a lot here... with a little trickery...

    <input type='file' id='browse'>

::reference::http://site-o-matic.net/?viewpost=19
-abbey

A: As JGuo and CorySimmons mentioned, you can use the clickable behaviour of a stylable label, hiding the less flexible file input element.
<!DOCTYPE html>

<title>Custom file input</title>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">

 Choose file...
<input id="upload-file" type="file" style="display: none"
onchange="this.nextElementSibling.textContent = this.previousElementSibling.title = this.files[0].name">

A: The best way is using the pseudo element :after or :before as an element overt the de input. Then style that pseudo element as you wish. I recomend you to do as a general style for all input files as follows:
input {
  height: 0px;
  outline: none;
}

input[type="file"]:before {
  content: "Browse";
  background: #fff;
  width: 100%;
  height: 35px;
  display: block;
  text-align: left;
  position: relative;
  margin: 0;
  margin: 0 5px;
  left: -6px;
  border: 1px solid #e0e0e0;
  top: -1px;
  line-height: 35px;
  color: #b6b6b6;
  padding-left: 5px;
  display: block;
}

A: A demo for image upload application suitable for most of the backend with nice animation features.

// common
function render_element(styles, el) {
    for (const [kk, vv] of Object.entries(styles)) {
        el.style[kk] = vv;
    }
}

function hoverOpacity(el) {
    el.addEventListener('mouseenter', function() {
        el.style.opacity = 0.75
    }.bind(el));
    el.addEventListener('mouseleave', function() {
        el.style.opacity = 1
    }.bind(el));
}

// return void event handler on setTimeout
function buffer(func, time){
    return e=>{
        if(func.still)return;
        // first runtime
        if(!func.pft){
            func(e);
            func.pft = true;
            func.still = false;
            return;
        }
        func.still = true;
        setTimeout(e=>{
            func(e);
            func.still = false;
        }, time);
    }
}
// end of common

const imageUploadButton = document.getElementById('image-upload-button');
imageUploadButton.addEventListener('click', e=>{
    // pulse animation total time
    const d1 = document.getElementById('image-form');
    let time = 600;

    if(d1.rendered){
        d1.ready();
    }else{
        d1.ready = function(){
            d1.style.display = 'flex';
            d1.style.background = '#c5edd0';
            this.d2.style.background = '#b4dbbf';
            this.d3.style.background = '#95dea9';
            this.d4.innerHTML = 'Drag and Drop or Click Above to Upload';
        }
        let dismiss_btn = document.createElement('div');
        render_element({
            position: 'absolute',
            height: '30px',
            width: '30px',
            top: '0',
            right: '0',
            background: '#fff',
            borderRadius: '30px',
            cursor: 'pointer',
            margin: '2px',
            zIndex: '10',
        }, dismiss_btn);
        dismiss_btn.addEventListener('mouseenter', function(){this.style.background = '#fc4f30'});
        dismiss_btn.addEventListener('mouseleave', function(){this.style.background = '#fff'});
        dismiss_btn.addEventListener('click', ()=>{d1.style.display = 'none'});
        d1.appendChild(dismiss_btn);
        const d3 = d1.querySelector('#image-input');
        const d5 = d1.querySelector('#image-submit');
        d5.style.visibility = 'hidden';
        d1.parentNode.removeChild(d1);
        document.body.appendChild(d1);
        d1.removeChild(d3);
        let [
            d2,
            d4,
        ] = Array.from({length: 3}, ()=>document.createElement('div'));
        let width = window.innerWidth;
        let d_styles = {
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
        };
        render_element({
            position: 'fixed',
            left: ((width - 430) / 2).toString() + 'px',
            width: '430px',
            top: '60px',
            height: '280px',
            zIndex: '10',
        }, d1);
        render_element(d_styles, d1);

        render_element({
            width: '90%',
            height: '90%',
        }, d2);
        render_element(d_styles, d2);

        render_element({
            width: '80%',
            height: '70%',
            fontSize: '0',
            cursor: 'pointer',
        }, d3);
        hoverOpacity(d3);
        render_element(d_styles, d3);

        d1.appendChild(d2);
        d2.appendChild(d3);

        let tt = time / 3;
        let ht = tt / 2;
        d1.addEventListener('dragover', buffer(e=>{
            d1.style.background = '#ebf9f0';
            setTimeout(()=>{
                d1.style.background = '#95dea9';
            }, ht);
            setTimeout(()=>{
                d2.style.background = '#b6e3c2';
                setTimeout(()=>{
                    d2.style.background = '#c4eed2';
                }, ht);
            }, tt);
            setTimeout(()=>{
                d3.style.background = '#cae3d1';
                setTimeout(()=>{
                    d3.style.background = '#9ce2b4';
                }, ht);
            }, tt);
        }, time));

        d2.style.flexDirection = 'column';
        render_element({
            fontSize: '16px',
            textAlign: 'center',
            fontFamily: 'Verdana',
        }, d4);
        d2.appendChild(d4);

        d3.addEventListener('change', e=>{
            // backend
            // d5.click();
            // if backend succeed, run frontend
            setTimeout(()=>{
                d1.style.background = '#dbcea2';
                setTimeout(()=>{
                    d2.style.background = '#dbc169';
                    setTimeout(()=>{
                        d3.style.background = '#ebc034';
                    }, ht);
                }, tt);
            }, time);
            // display backend path here
            // now only display filename
            d4.innerHTML = d3.files[0].name;
        });
        d1.d2 = d2;
        d1.d3 = d3;
        d1.d4 = d4;
        d1.ready();
        d1.rendered = true;
    }
});
#image-upload-button{
    width: 200px;
    height: 40px;
    background: lightgrey;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}

#image-form{
    display: none;
}

::-webkit-file-upload-button {
    visibility: hidden;
}

Upload Image
    <form id="image-form" action="post">
        <input id="image-input" type="file" />
        <button id="image-submit" type="submit"></button>
    </form>

A: This approach gives you the whole flexibility! ES6 / VanillaJS!
html:
<input type="file" style="display:none;"></input>
<button>Upload file</button>

javascript:
document.querySelector('button').addEventListener('click', () => {
  document.querySelector('input[type="file"]').click();
});

This hides the input-file button, but under the hood clicks it from another normal button, that you can obviously style like any other button. This is the only solution with no downside apart from a useless DOM-node. Thanks to display:none;, the input-button does not reserve any visible space in the DOM.
(I don't know anymore to whom to give props for this. But I got that idea from somewhere here on Stackoverflow.)

A: You don't need JavaScript for this! Here is a cross-browser solution:
See this example! - It works in Chrome/FF/IE - (IE10/9/8/7)
The best approach would be to have a custom label element with a for attribute attached to a hidden file input element. (The label's for attribute must match the file element's id in order for this to work).

    Custom Upload

<input id="file-upload" type="file"/>

As an alternative, you could also just wrap the file input element with a label directly: (example)

    <input type="file"/>
    Custom Upload

In terms of styling, just hide1 the input element using the attribute selector.
input[type="file"] {
    display: none;
}

Then all you need to do is style the custom label element. (example).
.custom-file-upload {
    border: 1px solid #ccc;
    display: inline-block;
    padding: 6px 12px;
    cursor: pointer;
}

1 - It's worth noting that if you hide the element using display: none, it won't work in IE8 and below. Also be aware of the fact that jQuery validate doesn't validate hidden fields by default. If either of those things are an issue for you, here are two different methods to hide the input (1, 2) that work in these circumstances.

A: Put upload file button over your nice button or element and hide it.
Very simple and will work on any browser

    <button type="button" class="nice-button">upload_file</button>
    <input type="file" name="file" class="upload-btn">

Styles
.upload-wrap {
    position: relative;
}

.upload-btn {
    position: absolute;
    left: 0;
    opacity: 0;
}

A: Here is a solution which doesn't really style the <input type="file" /> element but instead uses a <input type="file" /> element on top of other elements (which can be styled). The <input type="file" /> element is not really visible hence, the overall illusion is of a nicely styled file upload control.
I came across this problem recently and despite the plethora of answers on Stack Overflow, none really seemed to fit the bill. In the end, I ended up customizing this so as to have a simple and an elegant solution.
I have also tested this on Firefox, IE (11, 10 & 9), Chrome and Opera, iPad and a few android devices.
Here's the JSFiddle link -> http://jsfiddle.net/umhva747/

$('input[type=file]').change(function(e) {
    $in = $(this);
    $in.next().html($in.val());

});

$('.uploadButton').click(function() {
    var fileName = $("#fileUpload").val();
    if (fileName) {
        alert(fileName + " can be uploaded.");
    }
    else {
        alert("Please select a file to upload");
    }
});
body {
    background-color:Black;
}

div.upload {
    background-color:#fff;
    border: 1px solid #ddd;
    border-radius:5px;
    display:inline-block;
    height: 30px;
    padding:3px 40px 3px 3px;
    position:relative;
    width: auto;
}

div.upload:hover {
    opacity:0.95;
}

div.upload input[type="file"] {
    display: input-block;
    width: 100%;
    height: 30px;
    opacity: 0;
    cursor:pointer;
    position:absolute;
    left:0;
}
.uploadButton {
    background-color: #425F9C;
    border: none;
    border-radius: 3px;
    color: #FFF;
    cursor:pointer;
    display: inline-block;
    height: 30px;
    margin-right:15px;
    width: auto;
    padding:0 20px;
    box-sizing: content-box;
}

.fileName {
    font-family: Arial;
    font-size:14px;
}

.upload + .uploadButton {
    height:38px;
}

<form action="" method="post" enctype="multipart/form-data">

        <input type="button" class="uploadButton" value="Browse" />
        <input type="file" name="upload" accept="image/*" id="fileUpload" />
        Select file..

    <input type="button" class="uploadButton" value="Upload File" />
</form>

Hope this helps!!!

A: This is simple with jquery. To give a code example of Ryan's suggestion with a slight modification.
Basic html:

<input id="the_real_file_input" name="foobar" type="file">

Be sure to set the styling on the input when you're ready: opacity: 0
You can't set display: none because it needs to be clickable. But you can position it under the "new" button or tuck in under something else with z-index if you prefer.
Setup some jquery to click the real input when you click the image.
$('#image_icon').click(function() {
    $('#the_real_file_input').click();
});

Now your button is working. Just cut and paste the value when changed.
$('input[type=file]').bind('change', function() {
    var str = "";
    str = $(this).val();
    $("#filename").text(str);
}).change();

Tah dah! You may need to parse the val() to something more meaningful but you should be all set.

A: Here is a PURE CSS, Javascript-free, Bootstrap-free, 100% cross-browser solution! Just cut-and-paste one block of styles, then test your file upload control.
This solution does NOT attempt to hide then recreate the original HTML element like the other posts here do. It uses plain CSS without any circus tricks or third party tools to style the original file upload form control for all the major browsers. You do not need to even change your HTML code! Just cut-and-paste the code below into your web page to test it...

<input type="file" id="fileupload" name="fileupload"
value="" tabindex="0" enctype="multipart/form-data"
accept="image/*" autocomplete="off" multiple="multiple"
aria-multiselectable="true" title="Multiple File Upload"
aria-label="Multiple File Upload" />

<input disabled="disabled" type="file" id="fileupload"
name="fileupload" value="" tabindex="0"
enctype="multipart/form-data" accept="image/*"
autocomplete="off" multiple="multiple"
aria-multiselectable="true" title="Disabled Multiple File Upload"
aria-label="Disabled Multiple File Upload" />

This is what the file upload control looks like in Firefox, Chrome, and Edge using the CSS below. This is a very simple clean design. You can change it to look any way you like:

Internet Explorer gives you limited design control, but at least you can manipulate the control using CSS enough to change a few things, including rounded borders and colors:

The advantages to my solution are:

*

*You stick with simple CSS to style the original HTML input control

*You can see one or more file names in the file input textbox

*Screen readers and ARIA-friendly devices can interact normally with your file upload control

*You can set tabindex on your HTML element so its part of the tab order

*Because you are using plain HTML and CSS, your file input button works perfectly in old and new browsers

*ZERO JavaScript required!

*Runs and loads lighting fast in even the oldest of browsers

*Because your are not using "display:none" to hide the control, its file block stream data is never disabled from reaching the server in any old or new browser version known

You do not need goofy JavaScript tricks, Bootstrap, or to try and hide/recreate your file input control. That just destroys usability for everyone online. Styling the original HTML control means your file upload control is guaranteed to work well in 25 years worth of web browsers, old and new.
This is why you cannot trust all these scripted hacks here that erase, rewrite, or destroy HTML just to try and recreate some visual experience. That shows that you do not understand how HTML is used or why its been around for 30 years practically unchanged. You should never try and rewrite HTML's native form control functionality. Why? There is more to using natural HTML in websites than just manipulation of markup for some forced visual experience. The trade-offs of limited visual design in these replaced HTML elements was designed that way for a reason.
My advice: Stay with simple HTML and CSS solutions and you will have ZERO problems as a web developer.

A: Here's a simple css only solution, that creates a consistent target area, and lets you style your faux elements however you like.
The basic idea is this:

*

*Have two "fake" elements (a text input/link) as siblings to your real file input. Absolutely position them so they're exactly on top of your target area.

*Wrap your file input with a div. Set overflow to hidden (so the file input doesn't spill out), and make it exactly the size that you want your target area to be.

*Set opacity to 0 on the file input so it's hidden but still clickable. Give it a large font size so the you can click on all portions of the target area.

Here's the jsfiddle: http://jsfiddle.net/gwwar/nFLKU/
<form>
    <input id="faux" type="text" placeholder="Upload a file from your computer" />
    Browse

        <input id="input" size="100" type="file" />

</form>

A: In case you're looking for a javascript library - out of the box solution, jquery-fileinput works fine.

A: These answers are nice, and they all work for very specific use cases. That is to say, they are opinionated.
So, here's an answer that assumes nothing, but will work no matter how you modify it. You can change design with css, add javascript to maybe show a file name on change, etc. it will still always work.
Code:
Here is the core css
.file-input{
  pointer-events: none;
  position: relative;
  overflow: hidden;
}
.file-input > * {
  pointer-events: none;
}
.file-input > input[type="file"]{
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  opacity: 0;
  pointer-events: all;
  cursor: pointer;
  height: 100%;
  width: 100%;
}

and the core html:

  <input type="file"/>

As you can see, we are forcing any pointer event(click) that happens on the .file-input element, or any of its children, to be proxied to the file input. This is because the file input is positioned absolute and will consume the width/height of the container always. You can therefore customize to fit your need. style the wrapper into a button, use some js to display file name on select, etc. nothing will break so long as the above core code remains intact.
As you will see in the demo, i have added a span with text "Select file" and a class with extra styles to style the .file-input div. This should be the canonical starting point for anyone intending to create a custom file upload element.
Demo:JSFIDDLE

A: You can make an awesome ( unfinished ) File Uploader to a <button> element or any other element:

function selectFile() {
    document.getElementById("fileSelector").click();
}
input#fileSelector[type="file"] {
    display: none;
}

button[onclick*="()"] {
    cursor: pointer;
}
<input type="file" id="fileSelector">
<button onclick="selectFile()">Select file from computer...</button>

A: jquery  version of teshguru script for automatically detect input[file] and style

<?php
    var_dump($_FILES);
?>

<form action="" method="post" enctype="multipart/form-data" name="myForm">

<input id="upfile" name="file" type="file" value="upload"/>
<input type="submit" value='submit' >
</form>

A: Plug-in solutions I found were too heavy-weight, so, I made my own jQuery plug-in called Drolex FileStyle.
This plug-in allows you to style file input fields however you want. Actually, you style div elements to look like a tricked out file input, and the actual file input is automatically overlaid with 0% opacity. No additional HTML is required. Just include the css and js files in the page you want Drolex FileStyle and that's it! Edit the css file to your liking. Don't forget the jQuery library if your page doesn't already have it. If the client does not run JavaScript, then the file input will not be modified by js or css.
Tested to work in Chrome 24, Firefox 18, Internet Explorer 9.
Expected to work in previous versions of those and others.
Download: http://web.drolex.net/Drolex-FileStyle.zip

A: A really clever solution using jQuery that works in all older browsers as well as in the new ones, I found here.
It takes care of all the styling and click() problems, using the actual file browse button.
I made a plain javascript version: fiddle
The solution is as simple as genius: make the file-input invisible, and use a piece of code to place it under the mousecursor.

browse
    <input id="file_1" name="file_1" type="file" value="" onchange="file_ch(1)">

A: Here's a cross compatible method which will work in Chrome, Firefox, Safari, and IE.

$(window).on('resize',function() {
 var eqw = $('input[type=text]').width();
 $('textarea').width(eqw - 32);
 $('.fileoutline').width(eqw);
}).trigger('resize');

$('.file+.file').hide();

$(".file").click(function() {
    var input = $(this).next().find('input');
    input.click();
});
$("input[id='file1']").change(function () {
 $('.file+.file').show();
 var filename = $(this).val();
 $('.filename1').html(filename);
 $('.file').find('span').html('CHANGE FILE');
});
$("input[id='file2']").change(function() {
 var filename = $(this).val();
 $('.filename2').html(filename);
 $('.file').find('span').html('CHANGE FILE');
});

form { width:55%;margin:0 auto;padding-left:3vw;text-align:left; }
fieldset{border:0;margin:0;padding:0;}
textarea{overflow: auto;height:25vh;resize:none;outline:none;width:93%;background:none;padding:8px 15px;display:block;text-align:left;border:1px solid #000;margin:0;color:#000;font:700 0.85em/2.2 'Futura Book',Arial,sans-serif;}
input:focus{outline:none;}
input[type=text]{font-weight:700;font-size:0.85em;line-height:2.2;background:none;text-align:left;letter-spacing:0.02em;height:33px;display:block;width:100%;border:none;border-bottom:1px solid #000;margin:0 0 28px;color:#000;}
input:focus{outline:0;}
.fileoutline { width:100%;margin:25px auto 0px;left:0;right:0;height:40px;border:1px solid #000;position:relative; }
input[type=file] { -webkit-appearance: none;-moz-appearance:none;appearance: none;opacity:0;position:relative;width:100%;height:35px;font-weight:700;font-size:0.5em;line-height:28px;letter-spacing:0.2em;position: absolute;left: 0;top: 0;height: 100%;z-index:10; }
.file,.filename1,.filename2,#submit { font-size:10px;letter-spacing:0.02em;text-transform:uppercase;color:#ffffff;text-align:center;width:35%;}
.file,.filename1,.filename2 { font-weight:200;line-height:28px;}
.filename1,.filename2 { width:375px;overflow:hidden;top:0;text-align:right;position:absolute;display:block;height:26px;color:#000;}
.file { position:absolute;width:100px;top:6px;left:10px;background:#000;border-radius:14px; }
::-webkit-file-upload-button,::-ms-browse { width: 100%;height:25px;opacity: 0;-webkit-appearance: none;appearance: none; }
#submit{border:none;height:32px;background: #000;box-shadow:0 0 0 0.5px #fff,0 0 0 5px #000;margin:35px 0;float:right;display:block;}
<form action="" method="post" enctype="multipart/form-data">
    <input type="text" name="email" id="email" placeholder="Email address" />
    <input type="text"  type="text" name="name" id="title" placeholder="Name" />
    <textarea rows="7" cols="40" name="description" id="description" placeholder="Description"></textarea>

CHOOSE FILE<input type="file" name="file[]" id="file1">
NO CHOSEN FILE

CHOOSE FILE<input type="file" name="file[]" id="file2">
NO CHOSEN FILE

    <input type="submit" name="submit" value="Submit" id="submit">
</form>

A: If anyone still cares on how to do this without JavaScript, let me complete Josh answer:
How to display the text of the filename:
The easiest way is to set both elements to a position:relative, give the label a higher z-index and give the input file negative margin until the label text is where you want it to be. Do not use display:none on the input!
Example:
input[type="file"] {
  position:relative;
  z-index:1;
  margin-left:-90px;
}

.custom-file-upload {
  border: 1px solid #ccc;
  display: inline-block;
  padding: 6px 12px;
  cursor: pointer;
  position:relative;
  z-index:2;
  background:white;

}

A: I found this approach the simplest and lightest.
Here is the working example: http://codepen.io/c3zar22/pen/QNoYXN
Below are the explanations:

*

*this would be the markup:

    x

Click to select a file

<input id="attach-project-file" type="file">

*hide the input in a hacky way like this:
#attach-project-file {
    width: 0.1px;
    height: 0.1px;
    opacity: 0;
    overflow: hidden;
    position: absolute;
    z-index: -1;
}

*style the corresponding label instead
[for="attach-project-file"] {
    /* your styles here */
}

*style "remove file" button
.close {
    font-size: 16px;
    padding: 10px;
    position: absolute;
    top: 0;
    right: 0;
    cursor: pointer;
    font-style: normal;
}

*.filename element will be used to display the selected file

*below is the commented JS code needed (using jQuery) to make it work:
var $attach = $('#attach-project-file'),
    $remove = $('#remove-project-file'),
    $name = $('#attached-project-file');

// initially hide the remove button
$remove.hide();

// do this when file input has changed
// i.e.: a file has been selected
$attach.on('change', function() {
    var val = $(this).val();
    if (val !== '') {
        // if value different than empty

        // show the file name as text
        // hide/text/fadeIn creates a nice effect when changing the text
        $name
            .hide()
            .text(val)
            .fadeIn();

        // show the remove button
        $remove.fadeIn();
    } else {
        // if value empty, means the file has been removed

        // show the default text
        $name
            .hide()
            .text('Click to select a file')
            .fadeIn();

        // hide remove button
        $remove.fadeOut();
    }
});

// remove selected file when clicking the remove button
// prevent click bubbling to the parent label and triggering file selection
$remove.on('click', function(e) {
    e.preventDefault();
    e.stopPropagation();

    $attach
        .val('')
        .change(); // trigger change event
});

A: A quick and crude way is to set the label as a button and set position to absolute so it floats over original button, you still see file name. I am thinking about a mobile solution however.


text:
Q: Dynamic data frame filtering in rMarkdown ioslides_presentation Is there any way, without using shiny, how to filter the data using html drop down in rMarkdown ioslides_presentation (or some kind of javascript function)?
I have very simple code using mtcars data and html drop down menu. I'd like to filter the mtcars data frame via html drop down, something like mtcars[mtcars$mpg > 'value1'.
Is it possible to do that in rMarkdown ioslides_presentation or there is only way to do that via Shiny reactive programming. Thanks a lot for your advice in advance.
---
date: "`r Sys.Date()`"
output: ioslides_presentation
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## Slide 1

<div>
<select name="mpgFilter" id="mpgFilter">
<option value="1">mpg > 21</option>
<option value="2">mpg > 18</option>
<option value="3">mpg > 15</option>
</select>
</div>

```{r echo=FALSE}
data("mtcars")
mtcarsData <- mtcars[mtcars$mpg > 21,]
plot(mtcarsData$mpg, mtcarsData$disp)
```


text:
Q: Check if first radio button w/jQuery If i build a list of items with radiobuttons next to them, how do I check the first one by default?

A: <input type="radio" name="group1" value="a" checked>

Simply include the checked attribute.
Or through jQuery,
$("#groupids:first").prop('checked', 'checked');

A: $(".radio_identifier:first").prop('checked', 'checked');


text:
Q: Какие есть программы на Ubuntu для создания gif через терминал? Какие вообще есть варианты из программ создающих анимированный гиф, с возможностью их запуска с параметрами из терминала, например через nodejs или php exec?
Возможно кто то посоветует хорошо оптимизированную програму, чтоб не сильно грузило сервер. Мне пока знакомы только GMagick и IMagick именно как отдельное ПО.

A: QGifer - это отличный инструмент для создания анимированных GIF-файлов в Ubuntu Linux. Данное приложение отличается от других тем, что оно написано на Qt и позволяет конвертировать небольшие видеоролики в GIF-анимации.
sudo apt-get install libav-tools

A: ffmpeg - https://medium.com/@colten_jackson/doing-the-gif-thing-on-debian-82b9760a8483
пачка статичных изображений конвертируется в gif в 2 шага
ffmpeg -f image2 -i image%d.jpg video.avi
ffmpeg -i video.avi -pix_fmt rgb24 -loop_output 0 out.gif


text:
Q: Springboot test fails to autowire TestRestTemplate when using junit5 I am using springboot version 2.2.2.RELEASE.
I am trying to add tests with junit5, here is how I set it in my build.gradle:
testImplementation('org.springframework.boot:spring-boot-starter-test') {
    exclude group: 'junit', module: 'junit'
}
testImplementation "org.junit.jupiter:junit-jupiter-api:5.5.2"
testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:5.5.2"

And here is my test class:
//@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT, classes = UserServiceApplication.class)
@ActiveProfiles("it")
public class UserControllerIntegrationTest {
    @Autowired
    private TestRestTemplate testRestTemplate;

}

The problem is that restRestTemplate is null. The only way it works is when I use:

@RunWith(SpringRunner.class)

However, for my understanding this is for support of junit4, right?
I am using the not deprecated TestRestTemplate (org.springframework.boot.test.web.client.TestRestTemplate).
I also tried to add the following, but it didn't work too:

@ExtendWith(SpringExtension.class)

What am I missing?
Thank you.

A: Make sure your whole test is using JUnit 5 related annotations. Maybe your @Test annotation is still using JUnit 4.
The following example works for JUnit 5 and Spring Boot:

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import static org.junit.jupiter.api.Assertions.assertNotNull;

@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = YourApplication.class)
public class TestOne {

  @Autowired
  private TestRestTemplate testRestTemplate;

  @Test
  public void test() {
    assertNotNull(testRestTemplate);
  }
}

A: Use below annotation to class level
pom dependency
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>

    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>

    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

Test class
import static org.assertj.core.api.Assertions.assertThat;
import java.net.URI;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.ResponseEntity;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ApplicationTests{
        @LocalServerPort
        int randomServerPort;
     @Autowired
    private TestRestTemplate template;

    @Test
    public void contextLoads() {

    }
    @Test
    public void hello_ok() throws Exception {
        ResponseEntity<String> response = template.getForEntity(new URI("http://localhost:" + randomServerPort + "/"),
                String.class);

        assertThat(response.getBody()).isEqualTo("Greetings from Spring Boot!");
    }
}

Controller class
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    @GetMapping("/")
    public String index() {
        return "Greetings from Spring Boot!";
    }
}


text:
Q: What do we call the "rd" in "3ʳᵈ" and the "th" in "9ᵗʰ"? Our numbers have a specific two-letter combination that tells us how the number sounds.
For example

*

*9th

*3rd

*301st
What do we call these special sounds?

A: It's an ordinal indicator:

In written languages, an ordinal indicator is a letter, or group of letters, following a numeral denoting that it is an ordinal number, rather than a cardinal number. Historically these letters were "elevated terminals", that is to say the last few letters of the full word denoting the ordinal form of the number displayed as a superscript. The exact letters used vary in different languages.

(source: Wikipedia)

A: In the case of 9th, the superscript shown is indeed called the 'ordinal indicator' as Matt Gutting has noted in his answer.
The addition of -th/ -eth relates to numbers 4 to 20 (and similarly,) and is a suffix to the cardinal number.
However, as in the second and third examples, the rd & st simply come from the right-end of the word for the ordinal number:
3rd: thi rd
301st: (three-hundred-) fir st (shouldn't that be 301 th ?, I'm not going there).
Of course, in general, we call all these superscripts 'ordinal indicators,' and "suffixes," 'ordinal suffixes.' (We can see that there's no suffix as such until we come to 4, as we have ordinal names.)

A: First, these abbreviations are not onomatopoeia.
In fact, your question is about writing rather than sounds.
In the written number 2nd, the letters nd are the superscript.
More generally, these letters form the ordinal indicator in english.

A: These are ordinal suffixes.

Ordinal formatter: add ordinal suffixes (-st, -nd, -rd, -th) to numbers. finzi.psych.upenn.edu


text:
Q: Edit all controls in an Access 2013 continuous form I have a button on my main form that marks all controls in a continuous subform as "Yes", however it only changes the first record in the continuous form. The second, third, etc. records will not change. I found an answer using DAO recordsets but the comboboxes I'm using are unbound.
This is the code I have. It modifies all comboboxes in the first record in the subform.
For Each ctl In Me![SubformName].Controls
    If ctl.ControlType = acComboBox Then
        If ctl.Name <> "Yes" Then
            ctl.Value = "Yes"
        End If
    End If
Next ctl

What do I change in my code to allow me to modify records past the first? Is there a way to directly refer to continuous form records?
Edited to add:
I still can't get it working for unbound comboboxes, but the following does work for bound ones.
Set rst = Me.SubformName.Form.RecordsetClone
rst.MoveFirst
Do While rst.EOF = False
    rst.Edit
    rst!FieldName = "Yes"
    rst.Update
rst.MoveNext
Loop

A: Open the RecordsetClone of the subform control.
Loop through this, and for each record set the value of the fields which are bound to a combobox to True.


text:
Q: can I add custom nested CloudFormation stack to AWS Amplify OR can I create a custom Lambda function/SQS with GraphQL/AppSync? Spending more than a day I doubt the answer is Yes.
Want to double check though.
Creating Lambda functions is possible with REST APIs. But I need it with GraphQL. As I understand, currently creating Lambda function from CLI for GraphQl is not supported - right ?
In my app one party places an order => mutates DynamoDB table Orders => DynamoDB triggers a Lambda function that in turn mutates DynamoDB table Offers (changes offer's status). This change should notify subscribed parties.
I could do it in a separate Lambda function or in a Lambda function that serves as a Resolver. But either way I do not see a way of doing it using AWS Amplify.
Resolver Lambda function should also be manually added in console (providing Lambda ARN). Is there a way of adding it using CLI or config files or nesting a CloudFormation stack template ?
I know I can do all manually in console. But I need to find a way using AWS Amplify so that I have a parent and nested CloudFormation stack templates.
Possible workaround I see is:

*

*setting up GraphQL API using AWS Amplify;

*setting up rest of the serverless environment with AWS SAM or Serverless Framework;

*have to manually connect (in console) Lambda and SQS with AppSync's DynamoDB.
Is my understanding correct? Is there a better way than this workaround ?
I am building my front end app in React. This AWS Amplify page shows how resources such as SQS can be created for iOS. Is there anything similar for React ?
Thank you


text:
Q: rsync works fine until I put it in crontab (UPDATE: 'date' doesn't work in crontab) I've got this rsync command that works just fine when I run it from the command line (Ubuntu Server 12.04.1 LTS). I'd like it to run every hour, on the hour, and output the results (along with errors) to a log file. Here's the command I've put into crontab:
0 * * * * root rsync -av --delete -e "ssh -i /root/.ssh/id_rsa"
user@host:/path/to/dir/ user@host:/path/to/another/dir/ /destination/dir
--exclude='.DS_Store' &> /var/log/backup/`date '+%Y_%m_%d_%H:%M'`_hourlybackup.log

Despite working exactly as I expected from bash, nothing happens when it's in crontab. It doesn't even write any errors to the file. Running ps aux | grep rsync shows nothing of interest. I can't seem to find the issue. Any ideas?
UPDATE: Thanks to the answers I received I was able to tweak the command so that it works properly, although none of them solved the issue on their own. Here's what I found works this morning:
0 * * * * /usr/bin/rsync -av --delete -e "ssh -i /root/.ssh/id_rsa"
user@host:/path/to/dir/ user@host:/path/to/another/dir/ /destination/dir
--exclude='.DS_Store' > /var/log/backup/_hourlybackup.log 2>&1

For some reason the date '+%Y_%m_%d_%H:%M' (enclosed in backticks) is causing the issue. If I remove that from the command, it works just fine ... although it's important to me that I have comprehensive backup logs,  so I'd still like to find a solution to this. I'll keep hacking away at it, but if anyone knows, be my guest.

A: The problem, as I mentioned in the update, is with the date command. It turns out, if you're writing the command directly into the crontab, and not into a shell script, you need to escape the % in the date option string. Here's what ended up working:
0 * * * * rsync -av --delete user@host:/path/to/dir
user@host:/path/to/another/dir /path/to/destination
--exclude='.DS_Store' >
/var/log/backup/`date '+\%Y_\%m_\%d_\%H'`h_hourlybackup.log 2>&1

Thanks for everyone who helped me figure this one out. This command will probably get longer and more complex in the future and will thus be better suited to its own shell script, but for now it's fine directly in crontab, I think.

A: Most of the time it's because you didn't put a full path to your rsync
like
/usr/bin/rsync -av ...
Also you can try to create a small shell script and put that command there
and just execute that single script from your cron

A: It could be a path problem, but not likely since root should have /usr/bin in its path.
However, the crontab commands are most probably not run with Bash, but Dash. The &> construct is a "Bashism" [1] [2].
Replace
command >& file

with
command > file 2>&1

to make it work as intended in Dash.

A: put your rsync command into an .sh (shell) script to launch it with crontab

*

*search about shell script like this sample
test.sh

#!/bin/sh

echo $2 echo $1

*

*in your script use this syntax to name your backup file

now=$(date +"%m_%d_%Y")

.. &> /var/log/backup/{$now}_hourlybackup.log

A: Would have simply commented to checked answer but new and can't comment yet.
I just wanted to explain why you were seeing this issue.  % signifies a newline and any text after the first one is supplied to the command as stdin.
So your cron command:
rsync -av --delete -e "ssh -i /root/.ssh/id_rsa" user@host:/path/to/dir/ \
  user@host:/path/to/another/dir/ /destination/dir --exclude='.DS_Store' \
  &> /var/log/backup/`date '+%Y_%m_%d_%H:%M'`_hourlybackup.log

gets interpreted as:
rsync -av --delete -e "ssh -i /root/.ssh/id_rsa" user@host:/path/to/dir/ \
  user@host:/path/to/another/dir/ /destination/dir --exclude='.DS_Store' \
  &> /var/log/backup/`date '+<<EOI
Y_
m_
d_
H:
M'`_hourlybackup.log
EOI

When the shell tries to execute it, it can't find the second ` as it is now present as part of the command's stdin.  The key is to realize all % characters need to be escaped unless you really want newlines.


text:
Q: How to trigger a function when KivyMD Speed Dial Button pressed? I am trying to get a function to trigger when a button on The KivyMD Speed Dial is pressed.
I am currently using a callback from the .kv code as seen here:
MDFloatingActionButtonSpeedDial:
        bg_hint_color: app.theme_cls.primary_light
        data: app.data
        root_button_anim: True
        callback: app.btn

This then call the python code:
#DATA FOR THE SPEED DIAL
data = {
        'Create': 'file-document',
        'Open': 'folder-open'

    }
#FUNCTION HERE
    def btn(self, button):
        print(button)
        if button =="<kivymd.uix.button.MDFloatingBottomButton object at 0x000001BBCAF5BA50>":
            print("test")

I enter the argument button to get the name of the button so I put that in a if statement to see if it is all working so far but the text is not being printed. The button is being printed so that's why I put it in the if statement put text is not being printed so I really don't know what is going on here.
Hope the community can help.

A: isinstance checks which class the object belongs to.
from kivy.lang import Builder

from kivymd.app import MDApp
from kivymd.uix.button import MDFloatingBottomButton

KV = '''
MDScreen:

    MDFloatingActionButtonSpeedDial:
        data: app.data
        root_button_anim: True
        callback: app.callback
'''

class Example(MDApp):
    data = {
        'Create': 'file-document',
        'Open': 'folder-open',
    }

    def build(self):
        return Builder.load_string(KV)

    def callback(self, instance):
        print('callback')
        icon = instance.icon
        # if you want check button, use
        if isinstance(instance, MDFloatingBottomButton):
            if icon == 'file-document':
                print('Read file')
            elif icon == 'folder-open':
                print('Open folder')

Example().run()


text:
Q: Need assistance on final bit of script if possible Here are the prequisites for my script
"Generate a string with N opening brackets ("[") and N closing brackets     ("]"), in some
arbitrary order. You will need to use random numbers.
Determine whether the generated string is balanced; that is, whether it     consists entirely of
pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples:
 [] OK ][ NOT OK
[][] OK ][][ NOT OK
[[][]] OK []][[] NOT OK

"
I have come up with this and thought i was done, however i just reliased that it doesnt quite get over the line because i get a positive result with "[]]["
can someone help me with achieving this part "pairs of opening/closing brackets (in that order),"
#!/usr/bin/python

import string
import random

def brackets():
count = 0

sample = [random.choice(['[', ']', '[]']) for _ in range(random.randint(1, 10))]
sample2 =''.join([random.choice(['[', ']', '[]']) for _ in range(random.randint(1, 10))])

count1 = sample2.count('[')
count2 = sample2.count(']')

for x in sample2:
    if x == "[":
        count +=1
    if x == "]":
        count -=1

if count != 0 or count < 0 :
    print "The generated sample is %s " % (sample2,)
    print "There are %d [ in the generated string" % (count1,)
    print "There are %d ] in the generated string" % (count2,)
    print "This string is Not ok"

if count == 0 :
    print "The generated sample is %s " % (sample2,)
    print "There are %d [ in the generated string" % (count1,)
    print "There are %d ] in the generated string" % (count2,)
    print "This string is ok"

print brackets()

A: Here's a funny little idea I had. It basically works by seeing whether or not all the bracket pairs can be turned into individual lists:
from ast import literal_eval

def valid(s):
    if any(c not in '[]' for c in s): return False
    try:
        literal_eval(s.replace('[]', '[],'))
        return True
    except SyntaxError:
        return False

This (I believe) should work every time, including with the examples you gave:
>>> valid('[]')
True
>>> valid('][')
False
>>> valid('[][]')
True
>>> valid('][][')
False
>>> valid('[[][]]')
True
>>> valid('[]][[]')
False

A: The easiest way to do this is to use Staks. Code below will give you the answer:
from pythonds.basic.stack import Stack

def parChecker(symbolString):
    s = Stack()
    balanced = True
    index = 0
    while index < len(symbolString) and balanced:
        symbol = symbolString[index]
        if symbol in "([{":
            s.push(symbol)
        else:
            if s.isEmpty():
                balanced = False
            else:
                top = s.pop()
                if not matches(top,symbol):
                       balanced = False
        index = index + 1
    if balanced and s.isEmpty():
        return True
    else:
        return False

def matches(open,close):
    opens = "([{"
    closers = ")]}"
    return opens.index(open) == closers.index(close)

print(parChecker('{{([][])}()}'))
print(parChecker('[{()]'))

In this code each opening symbol is simply pushed on the stack to wait for the matching closing symbol to appear later in the sequence. When a closing symbol does appear, we must check to be sure that it correctly matches the type of the opening symbol on top of the stack. If the two symbols do not match, the string is not balanced. If the entire string is processed and nothing is left on the stack, the string is correctly balanced.


text:
Q: :only-child not showing in Webkit/Safari I'm trying to get this to work:
<!doctype html>

This should be visible

I believe that the text 'This should be visible' should be visible! This is also the case in Firefox. Firebug, as well as Safari's Web Inspector think so as well.
However, if you open the page in Safari (OSX and iPhone), the text is not showing. Why is this?

A: I tested your code, also with a doctype, and with a non-HTML5 element (a div). All webkit browsers I could test had issue: Safari-on-Windows 5, Chrome Windows, Chrome Linux, Epiphany-webkit.
When I changed from display states to background colours, however, webkit worked fine. Changing other display states like float also worked fine.
This is very likely a bug (though I didn't see one via search engines, but I did not search bugs.webkit.org) purely to do with changing display states. It also works fine if the element is first set to block and :only-child is set to none, so it would specifically be overriding the display: none. Opening element inspectors seems to trigger the CSS display which remains until refresh.
Your code (if you add a doctype too) seems to be a pretty good test case. If this bug isn't already on bugs.webkit.org you could submit this code.
*edit okay I definitely have Javascript on, still don't see the ability to have this be a comment rather than an answer, which is what I originally intended.

A: I have the same problem and I found this workaround:
http://jsfiddle.net/ZxAnH/
section {
    height: 0;
    overflow: none;
}
section:only-child {
    height: auto;
}

It wouldn't hide the elements margins but as a wrapper it could be enough to hide some elements. Did you found another workaround?


text:
Q: Add Select and Write Privileges to User for Specific Table Names I have created a new user using the below in sql developer (Oracle 11g).  I have only two tables titled FEED_DATA_A and FEED_DATA_B that I want this user to be able to select, update and insert into.  Can someone help me understand the SQL to create the proper privileges to accomplish that?  I'm currently logged in as the system user.
CREATE USER "USER_A" IDENTIFIED BY "test123";

A: If you want to grant the privileges directly to the user
GRANT select, update, insert
   ON table_owner.feed_data_a
   TO user_a;
GRANT select, update, insert
   ON table_owner.feed_data_b
   TO user_a;

More commonly, though, you would create a role, grant the role to the user, and grant the privileges to the role.  That makes it easier in the future when there is a new user created that you want to have the same privileges as USER_A to just grant a couple of roles rather than figuring out all the privileges that potentially need to be granted.  It also makes it easier as new tables are created and new privileges are granted to ensure that users that should have the same privileges continue to have the same privileges.
CREATE ROLE feed_data_role;

GRANT select, update, insert
   ON table_owner.feed_data_a
   TO feed_data_role;
GRANT select, update, insert
   ON table_owner.feed_data_b
   TO feed_data_role;

GRANT feed_data_role
   TO user_a


text:
Q: Continuously update a UILabel in Swift I have a function, shown below, that I would like to continuously update. It is taking data from a webpage, and every so often that webpage is updated to reflect current information. Is there a way that I can catch this update and reflect that in my application? I'm pretty new to Swift and iOS programming. Some of the code made seem very bizarre, but it currently works for whatever song is playing when you first open the app (that is, it updates the text to show that song playing but doesn't update later).
    let url = NSURL(string: "http://api.vicradio.org/songs/current")!
    let request = NSMutableURLRequest(URL: url)

    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithRequest(request) { (data: NSData?, response: NSURLResponse?, error: NSError?) in

    if error != nil {
        return
    }

    let name = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String
    var songName = ""
    var artistName = "by "
    var quoteNumber = 0

    for character in name.characters {

        if character == "\"" {
            quoteNumber++
        }

        if quoteNumber == 3 && character != "\"" {
            songName += String(character)
        } else if quoteNumber == 7 && character != "\"" {
            artistName += String(character)
        }

    }

    if (songName != "no song metadata provided") {
        self.SongNowText.text = songName
        self.ArtistNowText.text = artistName
        self.SongNowText.setNeedsDisplay()
        self.ArtistNowText.setNeedsDisplay()
    } else if (songName == "no song metadata provided") {
        self.SongNowText.text = "The Best of What's Next!"
        self.ArtistNowText.text = "only on VIC Radio"
    }

    }

    task!.resume()

A: It looks like the URL you're accessing there is an API endpoint putting out JSON. I highly recommend using NSJSONSerialization.JSONObjectWithData to parse the response body into a dictionary and use that instead of rolling your own solution by counting quote marks.
The callback to dataTaskWithURL is executed on a background thread. Avoid updating the UI on anything besides the main thread because it can cause problems. Use dispatch_async to execute your UI update function on the main thread as in the example.
All you can do with this API is send it requests and read the responses. You can poll the endpoint at a regular interval while the app is open and get decent results from that. NSTimer is one way to do that, and it requires you put the method you want to execute repeatedly in a class inheriting from NSObject because it depends on Objective-C style message sending.
Throw this in a playground and try it:
import Cocoa
import XCPlayground
XCPSetExecutionShouldContinueIndefinitely()

class RadioDataAccessor : NSObject {
    private let callback: [String : AnyObject] -> Void

    init(callback: [String : AnyObject] -> Void) {
        self.callback = callback

        super.init()

        NSTimer.scheduledTimerWithTimeInterval(5.0, target: self,
            selector: "updateData", userInfo: nil, repeats: true)
        // just so it happens quickly the first time
        updateData()
    }

    func updateData() {
        let session = NSURLSession.sharedSession()
        let url = NSURL(string: "http://api.vicradio.org/songs/current")!
        session.dataTaskWithURL(url) { data, response, error in
            if error != nil {
                return
            }

            var jsonError = NSErrorPointer()
            let json = NSJSONSerialization.JSONObjectWithData(data,
                options: NSJSONReadingOptions.allZeros,
                error: jsonError) as? [String : AnyObject]

            if jsonError != nil {
                return
            }
            dispatch_async(dispatch_get_main_queue()) { self.callback(json!) }

        }.resume()
    }
}

RadioDataAccessor() { data in
    println(data)
}

You may want to save the timer to a variable and expose a function that lets you invalidate it.


text:
Q: Trying to delete two rows using javascript I'm trying to delete two table rows at the same time in a dynamic table, but I'm having trouble deleting multiple rows at the same time. I have a table which displays text and a delete button in one tr and other related text in the next tr immediately after it. When I press the delete button on the first row, the row gets deleted but the one after it does not get removed. I have tried to get the value/address of the next row using this link but it does not seem to be working for me.
Fiddle in the works: http://jsfiddle.net/DLqLW/3/
The button for deleting the row is coded this way:
<input type="button" id="<?php echo $str; ?>" class="button-add" name="butcli" value="-" onClick="deleteRow(this)"></input>

and the function that it calls is:
function deleteRow(el) {

                            while (el.parentNode && el.tagName.toLowerCase() != 'tr') {
                                el = el.parentNode;
                            }
                            if (el.parentNode && el.parentNode.rows.length > 1) {
                                el.parentNode.removeChild(el);
                            }
                        }

I'm struggling with how to delete the next row after it. If anyone could provide some help, that would be great!

A: Do you have just two rows?
You are testing:
parentNode.rows.length > 1

If you have only two rows, it will not delete the second row.
Change it to:
parentNode.rows.length > 0

A: Try this
http://www.w3schools.com/dom/dom_nodes_navigate.asp
function get_nextSibling(n)
{
y=n.nextSibling;
while (y.nodeType!=1)
  {
  y=y.nextSibling;
  }
return y;
}

A: Alternate (simpler?) approach: Use a
 rather than a sibling

A different approach, to keep it simple, avoid jQuery, and avoid nextSibling and related problems:

*

*Working fiddle: http://jsfiddle.net/digitalextremist/9Zv83/3/
...using this HTML approach:

    1

this row should be deleted if the one above is removed.

        <input type="button" id="<?php echo $str; ?>" class="button-add" name="butcli" value="-" onClick="javascript:deleteRow(this)"></input>

Also, your existing version relies on a
 which is short one cell. If you add colspan=2 to your sibling row, then the formatting is thrown off too... hence this approach I am proposing.

A: Using Jquery this is working
function deleteRow(el) {
   var tr = $(el).closest('tr');
        tr.css("background-color","#FF3700");
        tr.fadeOut(400, function(){
            tr.remove();
        });
    var tr2 = $(tr).closest('tr').next();
        tr2.css("background-color","#FF3700");
        tr2.fadeOut(400, function(){
            tr.remove();
        });
}

Looks pretty swanky too I used your jfiddle with jQuery 2.02


text:
Q: Rails and Devise - Add a Field To Log-In I have set up a blog with secure log-in using the Devise plugin and its working well. I'm going to add an additional 'username' field at sign-up and article posts will then display this info. How do I achieve this so the username goes into the db - any code help would be appreciated?
User names will need to be unique but I will look into this later.

A: As the Devise wiki sez:
Create a migration
rails generate migration add_username_to_users username:string

Run the migration
rake db:migrate

Modify the User model and add username to attr_accessible
 attr_accessible :username

more info here
For uniqueness you could just do a validation on the User model
Hope this helps!

A: Okay so you have 2 questions in the same topic.
The first one has been answered and you followed these steps: Add custom fields to devise
Then for your next question: the problem isn't the user but @article because this variable is nil. So Rails can't find the User related to something that is nil.
You should post your controller and your _article view so I can help further.
Also I don't understand what you meant by :

I changed the object from 'email' to 'username' to stop it showing the submitters email address in the article

..You can choose whatever you want to display without replacing anything. If you want to display the user's username, just do user.username

A: *

*add belongs_to :user in your article.rb and has_many :articles to your user.rb

*update your migration of article to include a user_id:integer field (or use t.references :user)

*update your ArticlesController#create action to use current_user.create_article or build_article

*be sure to invoke the authenticate_user! before_filter for the :create action
before_filter :authenticate_user!, only => :only => [:new, :create, :edit, :update, :destroy]

ref:
http://guides.rubyonrails.org/association_basics.html


text:
Q: Define: Play! Statelessness Play's statelesness is undoubtedly one of its great advantages over more bulky, stateful alternatives. I am unable however to comprehend to what extent Play is stateless - does statelessness only concerns sessions and cookies or also all of the domain objects?
It would strike me as quite peculiar to reload all the objects in memory from persistent storage between every request, especially when several requests may concern the same objects (shared objects, or often used objects). It makes no doubt to me that one would benefit from implementing Data Source Architectural Patterns as well as Behavioural ORM Patterns (Unit of Work, Identity Map).
Hence my inquiry - to which extent is Play! truly stateless?