Programs & Examples On #Android livefolders

Bootstrap Datepicker - Months and Years Only

To view the months of the current year, and only the months, use this format - it only takes the months of that year. It can also be restricted so that a certain number of months is displayed.

<input class="form-control" id="txtDateMMyyyy"  autocomplete="off" required readonly/>

<script>
('#txtDateMMyyyy').datetimepicker({
    format: "mm/yyyy",
    startView: "year",
    minView: "year"
}).datetimepicker("setDate", new Date());
</script>

How to use multiprocessing pool.map with multiple arguments?

I think the below will be better

def multi_run_wrapper(args):
   return add(*args)
def add(x,y):
    return x+y
if __name__ == "__main__":
    from multiprocessing import Pool
    pool = Pool(4)
    results = pool.map(multi_run_wrapper,[(1,2),(2,3),(3,4)])
    print results

output

[3, 5, 7]

Authorize attribute in ASP.NET MVC

Real power comes with understanding and implementation membership provider together with role provider. You can assign users into roles and according to that restriction you can apply different access roles for different user to controller actions or controller itself.

 [Authorize(Users = "Betty, Johnny")]
 public ActionResult SpecificUserOnly()
 {
     return View();
 }

or you can restrict according to group

[Authorize(Roles = "Admin, Super User")]
public ActionResult AdministratorsOnly()
{
    return View();
}

SQL Developer with JDK (64 bit) cannot find JVM

I was trying to use the sqldeveloper that comes with the Oracle installation under:

C:\oracle\product\11.2.0\dbhome_1\sqldeveloper

I tried most of the suggestions in this post to no avail, so I downloaded the one from oracle's download page (you must register) which asks for the location of the jdk folder (rather than the location of java.exe). This worked for me without any problems.

How to disable editing of elements in combobox for c#?

This is another method I use because changing DropDownSyle to DropDownList makes it look 3D and sometimes its just plain ugly.

You can prevent user input by handling the KeyPress event of the ComboBox like this.

private void ComboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
      e.Handled = true;
}

How to empty the content of a div

you can .remove() each child:

const div = document.querySelector('div.my-div')
while(div.firstChild) div.firstChild.remove()

How can I require at least one checkbox be checked before a form can be submitted?

This should have what you need, check out the jsfiddle at the bottom:

$(document).ready(function () {
$('#txt').val($("input[type=checkbox]:checked").length);
$('#txt2').val($("input[type=checkbox]").length);

$('input[type=checkbox]').change(function () {
checked = $("input[type=checkbox]:checked").length;
$('#block').show();
$('#block2').hide();
if (checked > 0) {
  $('#block').hide();
  $('#block2').show();
  $('#txt').val(checked);
 }
});
});

Can't install APK from browser downloads

I had this problem. Couldn't install apk via the Downloads app. However opening the apk in a file manager app allowed me to install it fine. Using OI File Manager on stock Nexus 7 4.2.1

Floating point exception( core dump

You are getting Floating point exception because Number % i, when i is 0:

int Is_Prime( int Number ){

  int i ;

  for( i = 0 ; i < Number / 2 ; i++ ){

    if( Number % i != 0 ) return -1 ;

  }

  return Number ;

}

Just start the loop at i = 2. Since i = 1 in Number % i it always be equal to zero, since Number is a int.

How to get the top position of an element?

If you want the position relative to the document then:

$("#myTable").offset().top;

but often you will want the position relative to the closest positioned parent:

$("#myTable").position().top;

Change the content of a div based on selection from dropdown menu

I am not a coder, but you could save a few lines:

<div>
            <select onchange="if(selectedIndex!=0)document.getElementById('less_is_more').innerHTML=options[selectedIndex].value;">
                <option value="">hire me for real estate</option>
                <option value="me!!!">Who is a good Broker? </option>
                <option value="yes!!!">Can I buy a house with no down payment</option>
                <option value="send me a note!">Get my contact info?</option>
            </select>
        </div>

<div id="less_is_more"></div>

Here is demo.

How to import classes defined in __init__.py

Edit, since i misunderstood the question:

Just put the Helper class in __init__.py. Thats perfectly pythonic. It just feels strange coming from languages like Java.

How to send cookies in a post request with the Python Requests library?

If you want to pass the cookie to the browser, you have to append to the headers to be sent back. If you're using wsgi:

import requests
...


def application(environ, start_response):
    cookie = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918558'}
    response_headers = [('Content-type', 'text/plain')]
    response_headers.append(('Set-Cookie',cookie))
...

    return [bytes(post_env),response_headers]

I'm successfully able to authenticate with Bugzilla and TWiki hosted on the same domain my python wsgi script is running by passing auth user/password to my python script and pass the cookies to the browser. This allows me to open the Bugzilla and TWiki pages in the same browser and be authenticated. I'm trying to do the same with SuiteCRM but i'm having trouble with SuiteCRM accepting the session cookies obtained from the python script even though it has successfully authenticated.

How to validate date with format "mm/dd/yyyy" in JavaScript?

Use the following regular expression to validate:

var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/;
if (!(date_regex.test(testDate))) {
    return false;
}

This is working for me for MM/dd/yyyy.

Java Try Catch Finally blocks without Catch

A small note on try/finally: The finally will always execute unless

  • System.exit() is called.
  • The JVM crashes.
  • The try{} block never ends (e.g. endless loop).

How do I remove  from the beginning of a file?

Use Total Commander to search for all BOMed files:

Elegant way to search for UTF-8 files with BOM?

  • Open these files in some proper editor (that recognizes BOM) like Eclipse.

  • Change the file's encoding to ISO (right click, properties).

  • Cut  from the beginning of the file, save

  • Change the file's encoding back to UTF-8

...and do not even think about using n...d again!

"continue" in cursor.forEach()

Making use of JavaScripts short-circuit evaluation. If el.shouldBeProcessed returns true, doSomeLengthyOperation

elementsCollection.forEach( el => 
  el.shouldBeProcessed && doSomeLengthyOperation()
);

Finding all cycles in a directed graph

DFS from the start node s, keep track of the DFS path during traversal, and record the path if you find an edge from node v in the path to s. (v,s) is a back-edge in the DFS tree and thus indicates a cycle containing s.

Submit form using a button outside the <form> tag

This work perfectly! ;)

This can be done using Ajax and with what I call: "a form mirror element". Instead to send a form with an element outside, you can create a fake form. The previous form is not needed.

<!-- This will do the trick -->
<div >
    <input id="mirror_element" type="text" name="your_input_name">
    <input type="button" value="Send Form">
</div>

Code ajax would be like:

    <script>
        ajax_form_mirror("#mirror_element", "your_file.php", "#your_element_response", "POST");

        function ajax_form_mirror(form, file, element, method) {
            $(document).ready(function() {
                // Ajax
                $(form).change(function() { // catch the forms submit event
                    $.ajax({                // create an AJAX call...
                        data: $(this).serialize(),      // get the form data
                        type: method,                   // GET or POST
                        url: file,                      // the file to call
                        success: function (response) {   // on success..
                        $(element).html(response);  // update the DIV
                        }
                    });

                    return false; // cancel original event to prevent form submitting
                });
            });
        }
   </script>

This is very usefull if you want to send some data inside another form without submit the parent form.

This code probably can be adapted/optimized according to the need. It works perfectly!! ;) Also works if you want a select option box like this:

<div>
    <select id="mirror_element" name="your_input_name">
        <option id="1" value="1">A</option>
        <option id="2" value="2">B</option>
        <option id="3" value="3">C</option>
        <option id="4" value="4">D</option>
    </select>
</div>

I hope it helped someone like it helped me. ;)

How to parse a CSV in a Bash script?

CSV isn't quite that simple. Depending on the limits of the data you have, you might have to worry about quoted values (which may contain commas and newlines) and escaping quotes.

So if your data are restricted enough can get away with simple comma-splitting fine, shell script can do that easily. If, on the other hand, you need to parse CSV ‘properly’, bash would not be my first choice. Instead I'd look at a higher-level scripting language, for example Python with a csv.reader.

Is there a cross-browser onload event when clicking the back button?

Bill, I dare answer your question, however I am not 100% sure with my guesses. I think other then IE browsers when taking user to a page in history will not only load the page and its resources from cache but they will also restore the entire DOM (read session) state for it. IE doesn't do DOM restoration (or at lease did not do) and thus the onload event looks to be necessary for proper page re-initialization there.

How to properly use jsPDF library

how about in vuejs how is it applicable?

_x000D_
_x000D_
function onClick() {_x000D_
  var pdf = new jsPDF('p', 'pt', 'letter');_x000D_
  pdf.canvas.height = 72 * 11;_x000D_
  pdf.canvas.width = 72 * 8.5;_x000D_
_x000D_
  pdf.fromHTML(document.body);_x000D_
_x000D_
  pdf.save('test.pdf');_x000D_
};_x000D_
_x000D_
var element = document.getElementById("clickbind");_x000D_
element.addEventListener("click", onClick);
_x000D_
<h1>Dsdas</h1>_x000D_
_x000D_
<a id="clickbind" href="#">Click</a>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>
_x000D_
_x000D_
_x000D_

When to use reinterpret_cast?

template <class outType, class inType>
outType safe_cast(inType pointer)
{
    void* temp = static_cast<void*>(pointer);
    return static_cast<outType>(temp);
}

I tried to conclude and wrote a simple safe cast using templates. Note that this solution doesn't guarantee to cast pointers on a functions.

How to list containers in Docker

To list all running and stopped containers

docker ps -a

To list all running containers (just stating the obvious and also example use of -f filtering option)

docker ps -a -f status=running

To list all running and stopped containers, showing only their container id

docker ps -aq

To remove all containers that are NOT running

docker rm `docker ps -aq -f status=exited`

Replace CRLF using powershell

Below is my script for converting all files recursively. You can specify folders or files to exclude.

$excludeFolders = "node_modules|dist|.vs";
$excludeFiles = ".*\.map.*|.*\.zip|.*\.png|.*\.ps1"

Function Dos2Unix {
    [CmdletBinding()]
    Param([Parameter(ValueFromPipeline)] $fileName)

    Write-Host -Nonewline "."

    $fileContents = Get-Content -raw $fileName
    $containsCrLf = $fileContents | %{$_ -match "\r\n"}
    If($containsCrLf -contains $true)
    {
        Write-Host "`r`nCleaing file: $fileName"
        set-content -Nonewline -Encoding utf8 $fileName ($fileContents -replace "`r`n","`n")
    }
}

Get-Childitem -File "." -Recurse |
Where-Object {$_.PSParentPath -notmatch $excludeFolders} |
Where-Object {$_.PSPath -notmatch $excludeFiles} |
foreach { $_.PSPath | Dos2Unix }

Media Queries: How to target desktop, tablet, and mobile?

$xs : "extra-small";
$s  : "small";
$m  : "medium";
$l  : "large";
$xl : "extra-large";

@mixin respond($breakpoint) {
  @if($breakpoint == $xs)  {
    @media only screen and (min-width: 320px) and (max-width: 479px) { @content; }
  }
  @if($breakpoint == $s)  {
    @media only screen and (min-width: 480px) and (max-width: 767px) { @content; }
  }
  @if($breakpoint == $m)  {
    @media only screen and (min-width: 768px) and (max-width: 991px) { @content; }
  }
  @if($breakpoint == $l)  {
    @media only screen and (min-width: 992px) and (max-width: 1199px) { @content; }
  }
  @if($breakpoint == $xl)  {
    @media only screen and (min-width: 1200px) { @content; }
  }
}

you can also add one more for for sceen smaller then 320px like Galaxy fold

Get values from other sheet using VBA

Sub TEST()
Dim value1 As String
Dim value2 As String
value1 = ThisWorkbook.Sheets(1).Range("A1").Value 'value from sheet1
value2 = ThisWorkbook.Sheets(2).Range("A1").Value 'value from sheet2
If value1 = value2 Then ThisWorkbook.Sheets(2).Range("L1").Value = value1 'or 2
End Sub

This will compare two sheets cells values and if they match place the value on sheet 2 in column L.

How to add an image in Tkinter?

There is no "Syntax Error" in the code above - it either ocurred in some other line (the above is not all of your code, as there are no imports, neither the declaration of your path variable) or you got some other error type.

The example above worked fine for me, testing on the interactive interpreter.

What is the memory consumption of an object in Java?

The rules about how much memory is consumed depend on the JVM implementation and the CPU architecture (32 bit versus 64 bit for example).

For the detailed rules for the SUN JVM check my old blog

Regards, Markus

Filename too long in Git for Windows

This might help:

git config core.longpaths true

Basic explanation: This answer suggests not to have such setting applied to the global system (to all projects so avoiding --system or --global tag) configurations. This command only solves the problem by being specific to the current project.

EDIT:

This is an important answer related to the "permission denied" issue for those whom does not granted to change git settings globally.

Hadoop/Hive : Loading data from .csv on a local machine

For csv file formate data will be in below format

"column1", "column2","column3","column4"

And if we will use field terminated by ',' then each column will get values like below.

"column1"    "column2"     "column3"     "column4"

also if any of the column value has comma as value then it will not work at all .

So the correct way to create a table would be by using OpenCSVSerde

create table tableName (column1 datatype, column2 datatype , column3 datatype , column4 datatype)
ROW FORMAT SERDE 
'org.apache.hadoop.hive.serde2.OpenCSVSerde' 
STORED AS TEXTFILE ;

Kill detached screen session

== ISSUE THIS COMMAND
[xxx@devxxx ~]$ screen -ls


== SCREEN RESPONDS
There are screens on:
        23487.pts-0.devxxx      (Detached)
        26727.pts-0.devxxx      (Attached)
2 Sockets in /tmp/uscreens/S-xxx.


== NOW KILL THE ONE YOU DONT WANT
[xxx@devxxx ~]$ screen -X -S 23487.pts-0.devxxx kill


== WANT PROOF?
[xxx@devxxx ~]$ screen -ls
There is a screen on:
        26727.pts-0.devxxx      (Attached)
1 Socket in /tmp/uscreens/S-xxx.

html5 audio player - jquery toggle click play/pause?

Simply Use

$('audio').trigger('pause');

Export data from Chrome developer tool

You can use fiddler web debugger to import the HAR and then it is very easy from their on... Ctrl+A (select all) then Ctrl+c (copy summary) then paste in excel and have fun

How to do a HTTP HEAD request from the windows command line?

There is a Win32 port of wget that works decently.

PowerShell's Invoke-WebRequest -Method Head would work as well.

How to restore/reset npm configuration to default values?

For what it's worth, you can reset to default the value of a config entry with npm config delete <key> (or npm config rm <key>, but the usage of npm config rm is not mentioned in npm help config).

Example:

# set registry value
npm config set registry "https://skimdb.npmjs.com/registry"
# revert change back to default
npm config delete registry

Select an Option from the Right-Click Menu in Selenium Webdriver - Java

Right click can be achieved using Java script executor as well(in cases where action class is not supported):

JavascriptExecutor js = (JavascriptExecutor) driver;

String javaScript = "var evt = document.createEvent('MouseEvents');"
                + "var RIGHT_CLICK_BUTTON_CODE = 2;"
                + "evt.initMouseEvent('contextmenu', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, RIGHT_CLICK_BUTTON_CODE, null);"
                + "arguments[0].dispatchEvent(evt)";

js.executeScript(javaScript, element);

Using cURL with a username and password?

This is MUCH more than the OP asked for, but since this is a top result for securely passing passwords to curl, I'm adding these solutions here for others who arrive here searching for that.


NOTE: -s arg for read command is not POSIX, and so is not available everywhere, so it won't be used below. We will use stty -echo and stty echo instead.

NOTE: All bash variables below could instead be declared as locals if in a function, rather than unsetting.

NOTE: perl is pretty generally available on all systems I've tried due to it being a dependency for many things, whereas ruby and python are not, so using perl here. If you can guarantee ruby/python where you're doing this, you can replace the perl command with their equivalent.

NOTE: Tested in bash 3.2.57 on macOS 10.14.4. Some small translation may be required for other shells/installs.


Securely prompt a user for a (reusable) password to pass to curl. Particularly useful if you need to call curl multiple times.

For modern shells, where echo is a built-in (check via which echo):

url='https://example.com'
printf "Username: "
read username
printf "Password: "
stty -echo  # disables echoing user input, POSIX equivalent for 'read -s'
read pass
printf "\n" # we need to move the line ahead
stty echo   # re-enable echoing user input
echo ${pass} | sed -e "s/^/-u ${username}:/" | curl --url "${url}" -K-
unset username
unset pass

For older shells, where echo is something like /bin/echo (where whatever it echos can be seen in the process list):
THIS VERSION CANNOT REUSE THE PASSWORD, see lower down instead.

url='https://example.com'
printf "Username: "
read username
printf "Password: "
stty -echo  # disables echoing user input, POSIX equivalent for 'read -s'
perl -e '
    my $val=<STDIN>;
    chomp $val;
    print STDERR "\n";  # we need to move the line ahead, but not send a newline down the pipe
    print $val;
' | sed -e "s/^/-u ${username}:/" | curl --url "${url}" -K-
stty echo   # re-enable echoing user input
unset username



If you happen to need to store the password temporarily to a file, to re-use it for multiple commands before clearing it (say because you're using functions for code re-use and don't want to repeat code and can't pass the value around via echo). (Yes, these are a little contrived looking in this form not being functions in different libraries; I tried to reduce them to the minimum code needed to show it.)

When echo is built-in (this is especially contrived, since echo is a built-in, but provided for completeness):

url='https://example.com'
filepath="$(mktemp)"  # random path, only readable by current user
printf "Username: "
read username
printf "Password: "
stty -echo  # disables echoing user input, POSIX equivalent for 'read -s'
read pass
echo "${pass}" > "${filepath}"
unset pass
printf "\n" # we need to move the line ahead
stty echo   # re-enable echoing user input

cat "${filepath}" | sed -e "s/^/-u ${username}:/" | curl --url "${url}" -K-

rm "${filepath}"  # don't forget to delete the file when done!!
unset username

When echo is something like /bin/echo:

url='https://example.com'
filepath="$(mktemp)"  # random path, only readable by current user
printf "Username: "
read username
printf "Password: "
stty -echo  # disables echoing user input, POSIX equivalent for 'read -s'
$(perl -e '
    my $val=<STDIN>;
    chomp $val;
    open(my $fh, ">", $ARGV[0]) or die "Could not open file \"$ARGV[0]\" $\!";
    print $fh $val;
    close $fh;
' "$filepath")
printf "\n" # we need to move the line ahead
stty echo   # re-enable echoing user input

cat "${filepath}" | sed -e "s/^/-u ${username}:/" | curl --url "${url}" -K-

rm "${filepath}"  # don't forget to delete the file when done!!
unset username

Java POI : How to read Excel cell value and not the formula computing it?

If you want to extract a raw-ish value from a HSSF cell, you can use something like this code fragment:

CellBase base = (CellBase) cell;
CellType cellType = cell.getCellType();
base.setCellType(CellType.STRING);
String result = cell.getStringCellValue();
base.setCellType(cellType);

At least for strings that are completely composed of digits (and automatically converted to numbers by Excel), this returns the original string (e.g. "12345") instead of a fractional value (e.g. "12345.0"). Note that setCellType is available in interface Cell(as of v. 4.1) but deprecated and announced to be eliminated in v 5.x, whereas this method is still available in class CellBase. Obviously, it would be nicer either to have getRawValue in the Cell interface or at least to be able use getStringCellValue on non STRING cell types. Unfortunately, all replacements of setCellType mentioned in the description won't cover this use case (maybe a member of the POI dev team reads this answer).

The project type is not supported by this installation

As a addition to this, 'the project type is not supported by this installation' can occur if you're trying to open a project on a computer which does not contain the framework version that is targeted.

In my case I was trying to open a class library which was created on a machine with VS2012 and had defaulted the targeted framework to 4.5. Since I knew this library wasn't using any 4.5 bits, I resolved the issue by editing the .csproj file from <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> to <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> (or whatever is appropriate for your project) and the library opened.

SVN upgrade working copy

On MacOS:

  1. Get the latest compiled SVN client binaries from here.
  2. Install.
  3. Add binaries to path (the last installation screen explains how).
  4. Open terminal and run the following command on your project directory:

    svn upgrade

Error converting data types when importing from Excel to SQL Server 2008

There is a workaround.

  1. Import excel sheet with numbers as float (default).
  2. After importing, Goto Table-Design
  3. Change DataType of the column from Float to Int or Bigint
  4. Save Changes
  5. Change DataType of the column from Bigint to any Text Type (Varchar, nvarchar, text, ntext etc)
  6. Save Changes.

That's it.

How can I edit javascript in my browser like I can use Firebug to edit CSS/HTML?

I know that you can modify a javascript file when using Google Chrome.

  1. Open up Chrome Inspector, go to the "Scripts" tab.
  2. Press the drop-down menu and select the javascript file that you want to edit.
  3. Double click in the text field, type in what ever you want and delete whatever you want.
  4. Then all you have to do is press Ctrl + S to save the file.

Warning: If you refresh the page, all changes will go back to original file. I recommend to copy/paste the code somewhere else if you want to use it again.

Hope this helps!

Python Script Uploading files via FTP

Use ftplib, you can write it like this:

import ftplib
session = ftplib.FTP('server.address.com','USERNAME','PASSWORD')
file = open('kitten.jpg','rb')                  # file to send
session.storbinary('STOR kitten.jpg', file)     # send the file
file.close()                                    # close file and FTP
session.quit()

Use ftplib.FTP_TLS instead if you FTP host requires TLS.


To retrieve it, you can use urllib.retrieve:

import urllib 

urllib.urlretrieve('ftp://server/path/to/file', 'file')

EDIT:

To find out the current directory, use FTP.pwd():

FTP.pwd(): Return the pathname of the current directory on the server.

To change the directory, use FTP.cwd(pathname):

FTP.cwd(pathname): Set the current directory on the server.

Error: EACCES: permission denied, access '/usr/local/lib/node_modules'

I have used sudo, but it didnt solve the problem, I have fixed the issue by changing the node_modules folder permission,

sudo chmod -R 777 node_modules

If you want you can replace 777 with any other code if you dont set the permission for all user/group.

What is the simplest way to swap each pair of adjoining chars in a string with Python?

def revstr(a):
    b=''
    if len(a)%2==0:
        for i in range(0,len(a),2):
            b += a[i + 1] + a[i]
        a=b
    else:
        c=a[-1]
        for i in range(0,len(a)-1,2):
            b += a[i + 1] + a[i]
        b=b+a[-1]
        a=b
    return b
a=raw_input('enter a string')
n=revstr(a)
print n

RegEx for validating an integer with a maximum length of 10 characters

Don't forget that integers can be negative:

^\s*-?[0-9]{1,10}\s*$

Here's the meaning of each part:

  • ^: Match must start at beginning of string
  • \s: Any whitespace character
    • *: Occurring zero or more times
  • -: The hyphen-minus character, used to denote a negative integer
    • ?: May or may not occur
  • [0-9]: Any character whose ASCII code (or Unicode code point) is between '0' and '9'
    • {1,10}: Occurring at least one, but not more than ten times
  • \s: Any whitespace character
    • *: Occurring zero or more times
  • $: Match must end at end of string

This ignores leading and trailing whitespace and would be more complex if you consider commas acceptable or if you need to count the minus sign as one of the ten allowed characters.

How to change the background color of Action Bar's Option Menu in Android 4.2?

<style name="customTheme" parent="any_parent_theme">
    <item name="android:itemBackground">#424242</item>
    <item name="android:itemTextAppearance">@style/TextAppearance</item>
</style>

<style name="TextAppearance">
    <item name="android:textColor">#E9E2BF</item>
</style>

Could not read JSON: Can not deserialize instance of hello.Country[] out of START_OBJECT token

For Spring-boot 1.3.3 the method exchange() for List is working as in the related answer

Spring Data Rest - _links

remove borders around html input

border: 0 should be enough, but if it isn't, perhaps the button's browser-default styling in interfering. Have you tried setting appearance to none (e.g. -webkit-appearance: none)

CSS text-align: center; is not centering things

I don't Know you use any Bootstrap version but the useful helper class for centering and block an element in center it is .center-block because this class contain margin and display CSS properties but the .text-center class only contain the text-align property

Bootstrap Helper Class center-block

How to download PDF automatically using js?

Please try this

_x000D_
_x000D_
(function ($) {
    $(document).ready(function(){
       function validateEmail(email) {
            const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            return re.test(email);
           }
       
       if($('.submitclass').length){
            $('.submitclass').click(function(){
                $email_id = $('.custom-email-field').val();
                if (validateEmail($email_id)) {
                  var url= $(this).attr('pdf_url');
                  var link = document.createElement('a');
                  link.href = url;
                  link.download = url.split("/").pop();
                  link.dispatchEvent(new MouseEvent('click'));
                }
            });
       }
    });
}(jQuery));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post">
        <div class="form-item form-type-textfield form-item-email-id form-group">
            <input placeholder="please enter email address" class="custom-email-field form-control" type="text" id="edit-email-id" name="email_id" value="" size="60" maxlength="128" required />
        </div>
        <button type="submit" class="submitclass btn btn-danger" pdf_url="https://file-examples-com.github.io/uploads/2017/10/file-sample_150kB.pdf">Submit</button>
</form>
_x000D_
_x000D_
_x000D_

Or use download attribute to tag in HTML5

EditText non editable

android:editable="false" should work, but it is deprecated, you should be using android:inputType="none" instead.

Alternatively, if you want to do it in the code you could do this :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);

This is also a viable alternative :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);

If you're going to make your EditText non-editable, may I suggest using the TextView widget instead of the EditText, since using a EditText seems kind of pointless in that case.

EDIT: Altered some information since I've found that android:editable is deprecated, and you should use android:inputType="none", but there is a bug about it on android code; So please check this.

handling DATETIME values 0000-00-00 00:00:00 in JDBC

If, after adding lines:

<property
name="hibernate.connection.zeroDateTimeBehavior">convertToNull</property>

hibernate.connection.zeroDateTimeBehavior=convertToNull

<connection-property
name="zeroDateTimeBehavior">convertToNull</connection-property>

continues to be an error:

Illegal DATETIME, DATE, or TIMESTAMP values are converted to the “zero” value of the appropriate type ('0000-00-00 00:00:00' or '0000-00-00').

find lines:

1) resultSet.getTime("time"); // time = 00:00:00
2) resultSet.getTimestamp("timestamp"); // timestamp = 00000000000000
3) resultSet.getDate("date"); // date = 0000-00-00 00:00:00

replace with the following lines, respectively:

1) Time.valueOf(resultSet.getString("time"));
2) Timestamp.valueOf(resultSet.getString("timestamp"));
3) Date.valueOf(resultSet.getString("date"));

Changing Font Size For UITableView Section Headers

Swift 4 version of Leo Natan answer is

UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self]).font = UIFont.boldSystemFont(ofSize: 28)

If you wanted to set a custom font you could use

if let font = UIFont(name: "font-name", size: 12) {
    UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self]).font = font
}

Initializing select with AngularJS and ng-repeat

If you are using md-select and ng-repeat ing md-option from angular material then you can add ng-model-options="{trackBy: '$value.id'}" to the md-select tag ash shown in this pen

Code:

_x000D_
_x000D_
<md-select ng-model="user" style="min-width: 200px;" ng-model-options="{trackBy: '$value.id'}">_x000D_
  <md-select-label>{{ user ? user.name : 'Assign to user' }}</md-select-label>_x000D_
  <md-option ng-value="user" ng-repeat="user in users">{{user.name}}</md-option>_x000D_
</md-select>
_x000D_
_x000D_
_x000D_

How to get the last row of an Oracle a table

There is no such thing as the "last" row in a table, as an Oracle table has no concept of order.

However, assuming that you wanted to find the last inserted primary key and that this primary key is an incrementing number, you could do something like this:

select *
  from ( select a.*, max(pk) over () as max_pk
           from my_table a
                )
 where pk = max_pk

If you have the date that each row was created this would become, if the column is named created:

select *
  from ( select a.*, max(created) over () as max_created
           from my_table a
                )
 where created = max_created

Alternatively, you can use an aggregate query, for example:

select *
  from my_table
 where pk = ( select max(pk) from my_table )

Here's a little SQL Fiddle to demonstrate.

Border length smaller than div width?

I have case to have some bottom border between pictures in div container and the best one line code was - border-bottom-style: inset;

SyntaxError: unexpected EOF while parsing

Here is one of my mistakes that produced this exception: I had a try block without any except or finally blocks. This will not work:

try:
    lets_do_something_beneficial()

To fix this, add an except or finally block:

try:
    lets_do_something_beneficial()
finally:
    lets_go_to_sleep()

How to call a View Controller programmatically?

        UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone_iOS7" bundle:nil];
            AccountViewController * controller = [storyboard instantiateViewControllerWithIdentifier:@"accountView"];
            //            [self presentViewController:controller animated:YES completion:nil];

        UIViewController *topRootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
        while (topRootViewController.presentedViewController)
        {
            topRootViewController = topRootViewController.presentedViewController;
        }

        [topRootViewController presentViewController:controller animated:YES completion:nil];

How to detect Windows 64-bit platform with .NET?

This is a solution based on Microsoft's code at http://1code.codeplex.com/SourceControl/changeset/view/39074#842775. It uses extension methods for easy code reuse.

Some possible usage is shown below:

bool bIs64BitOS = System.Environment.OSVersion.IsWin64BitOS();

bool bIs64BitProc = System.Diagnostics.Process.GetCurrentProcess().Is64BitProc();

//Hosts the extension methods  
public static class OSHelperTools  
{  
    /// <summary>     
    /// The function determines whether the current operating system is a      
    /// 64-bit operating system.     
    /// </summary>     
    /// <returns>     
    /// The function returns true if the operating system is 64-bit;      
    /// otherwise, it returns false.     
    /// </returns>    
    public static bool IsWin64BitOS(this OperatingSystem os)  
    {  
        if (IntPtr.Size == 8)  
        // 64-bit programs run only on Win64           
            return true;   
        else// 32-bit programs run on both 32-bit and 64-bit Windows     
        {   // Detect whether the current process is a 32-bit process                
            // running on a 64-bit system.               
            return Process.GetCurrentProcess().Is64BitProc();  
        }  
    }  

    /// <summary>  
    /// Checks if the process is 64 bit  
    /// </summary>  
    /// <param name="os"></param>  
    /// <returns>  
    /// The function returns true if the process is 64-bit;        
    /// otherwise, it returns false.  
    /// </returns>    
    public static bool Is64BitProc(this System.Diagnostics.Process p)  
    {  
        // 32-bit programs run on both 32-bit and 64-bit Windows           
        // Detect whether the current process is a 32-bit process                
        // running on a 64-bit system.               
        bool result;  
        return ((DoesWin32MethodExist("kernel32.dll", "IsWow64Process") && IsWow64Process(p.Handle, out result)) && result);  
    }  

    /// <summary>     
    /// The function determins whether a method exists in the export      
    /// table of a certain module.     
    /// </summary>     
    /// <param name="moduleName">The name of the module</param>     
    /// <param name="methodName">The name of the method</param>     
    /// <returns>     
    /// The function returns true if the method specified by methodName      
    /// exists in the export table of the module specified by moduleName.     
    /// </returns>       
    static bool DoesWin32MethodExist(string moduleName, string methodName)  
    {  
        IntPtr moduleHandle = GetModuleHandle(moduleName);  
        if (moduleHandle == IntPtr.Zero)  
            return false;    
        return (GetProcAddress(moduleHandle, methodName) != IntPtr.Zero);   
    }  
    [DllImport("kernel32.dll")]  
    static extern IntPtr GetCurrentProcess();  

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]  
    static extern IntPtr GetModuleHandle(string moduleName);  

    [DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]  
    static extern IntPtr GetProcAddress(IntPtr hModule, [MarshalAs(UnmanagedType.LPStr)]string procName);  

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]  
    [return: MarshalAs(UnmanagedType.Bool)]  
    static extern bool IsWow64Process(IntPtr hProcess, out bool wow64Process);  
}

Android Studio: Drawable Folder: How to put Images for Multiple dpi?

You need to access image IDs using R.mipmap.yourImageName

Java Currency Number format

this best way to do that.

    public static String formatCurrency(String amount) {
        DecimalFormat formatter = new DecimalFormat("###,###,##0.00");
        return formatter.format(Double.parseDouble(amount));
    }

100 -> "100.00"
100.1 -> "100.10"

Getting Cannot read property 'offsetWidth' of undefined with bootstrap carousel script

I have got the same error, but in my case I wrote class names for carousel item as .carousel-item the bootstrap.css is referring .item. SO ERROR solved. carosel-item is renamed to item

<div class="carousel-item active"></div>

RENAMED To the following:

<div class="item active"></div>

How do I run a simple bit of code in a new thread?

Put that code in a function (the code that can't be executed on the same thread as the GUI), and to trigger that code's execution put the following.

Thread myThread= new Thread(nameOfFunction);

workerThread.Start();

Calling the start function on the thread object will cause the execution of your function call in a new thread.

Fatal error: Call to undefined function mysqli_connect()

Mine was a bit different for php7 on centos7.

In /etc/php.ini

; extension=mysqli

to

extension=mysqli

How to deal with a slow SecureRandom generator?

I haven't hit against this problem myself, but I'd spawn a thread at program start which immediately tries to generate a seed, then dies. The method which you call for randoms will join to that thread if it is alive so the first call only blocks if it occurs very early in program execution.

Python : List of dict, if exists increment a dict value, if not append a new dict

Using the default works, but so does:

urls[url] = urls.get(url, 0) + 1

using .get, you can get a default return if it doesn't exist. By default it's None, but in the case I sent you, it would be 0.

Convert List into Comma-Separated String

We can try like this to separate list enties by comma

string stations = 
haul.Routes != null && haul.Routes.Count > 0 ?String.Join(",",haul.Routes.Select(y => 
y.RouteCode).ToList()) : string.Empty;

What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming?

Shuffling is the process by which intermediate data from mappers are transferred to 0,1 or more reducers. Each reducer receives 1 or more keys and its associated values depending on the number of reducers (for a balanced load). Further the values associated with each key are locally sorted.

In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself?

== Equality operator evaluates the arguments after converting them to numbers. So string zero "0" is converted to Number data type and boolean false is converted to Number 0. So

"0" == false // true

Same applies to `

false == "0" //true

=== Strict equality check evaluates the arguments with the original data type

"0" === false // false, because "0" is a string and false is boolean

Same applies to

false === "0" // false

In

if("0") console.log("ha");

The String "0" is not comparing with any arguments, and string is a true value until or unless it is compared with any arguments. It is exactly like

if(true) console.log("ha");

But

if (0) console.log("ha"); // empty console line, because 0 is false

`

How to make a window always stay on top in .Net?

I was searching to make my WinForms application "Always on Top" but setting "TopMost" did not do anything for me. I knew it was possible because WinAmp does this (along with a host of other applications).

What I did was make a call to "user32.dll." I had no qualms about doing so and it works great. It's an option, anyway.

First, import the following namespace:

using System.Runtime.InteropServices;

Add a few variables to your class declaration:

private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
private const UInt32 SWP_NOSIZE = 0x0001;
private const UInt32 SWP_NOMOVE = 0x0002;
private const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;

Add prototype for user32.dll function:

[DllImport("user32.dll")] 
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

Then in your code (I added the call in Form_Load()), add the call:

SetWindowPos(this.Handle, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);

Hope that helps. Reference

How to detect duplicate values in PHP array?

Perhaps something like this (untested code but should give you an idea)?

$new = array();

foreach ($array as $value)
{
    if (isset($new[$value]))
        $new[$value]++;
    else
        $new[$value] = 1;
}

Then you'll get a new array with the values as keys and their value is the number of times they existed in the original array.

Is there any simple way to convert .xls file to .csv file? (Excel)

Install these 2 packages

<packages>
  <package id="ExcelDataReader" version="3.3.0" targetFramework="net451" />
  <package id="ExcelDataReader.DataSet" version="3.3.0" targetFramework="net451" />
</packages>

Helper function

using ExcelDataReader;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExcelToCsv
{
    public class ExcelFileHelper
    {
        public static bool SaveAsCsv(string excelFilePath, string destinationCsvFilePath)
        {

            using (var stream = new FileStream(excelFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                IExcelDataReader reader = null;
                if (excelFilePath.EndsWith(".xls"))
                {
                    reader = ExcelReaderFactory.CreateBinaryReader(stream);
                }
                else if (excelFilePath.EndsWith(".xlsx"))
                {
                    reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
                }

                if (reader == null)
                    return false;

                var ds = reader.AsDataSet(new ExcelDataSetConfiguration()
                {
                    ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
                    {
                        UseHeaderRow = false
                    }
                });

                var csvContent = string.Empty;
                int row_no = 0;
                while (row_no < ds.Tables[0].Rows.Count)
                {
                    var arr = new List<string>();
                    for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
                    {
                        arr.Add(ds.Tables[0].Rows[row_no][i].ToString());
                    }
                    row_no++;
                    csvContent += string.Join(",", arr) + "\n";
                }
                StreamWriter csv = new StreamWriter(destinationCsvFilePath, false);
                csv.Write(csvContent);
                csv.Close();
                return true;
            }
        }
    }
}

Usage :

var excelFilePath = Console.ReadLine();
string output = Path.ChangeExtension(excelFilePath, ".csv");
ExcelFileHelper.SaveAsCsv(excelFilePath, output);

Vertical Align text in a Label

To do this you should alter the vertical-align property of the input.

<dd><label class="<?=$email_confirm_class;?>" style="text-align:right; padding-right:3px">Confirm Email</label><input class="text" type="text" style="vertical-align: middle; border:none;" name="email_confirm" id="email_confirm" size="18" value="<?=$_POST['email_confirm'];?>" tabindex="4" /> *</dd>

Here is a more complete version. It has been tested in IE 8 and it works. see the difference by removing the vertical-align: middle from the input:

<html><head></head><body><dl><dt>test</dt><dd><label class="test" style="text-align:right; padding-right:3px">Confirm Email</label><input class="text" type="text" style="vertical-align: middle; font-size: 22px" name="email_confirm" id="email_confirm" size="28" value="test" tabindex="4" /> *</dd></dl></body></html>

Equal height rows in CSS Grid Layout

Short Answer

If the goal is to create a grid with equal height rows, where the tallest cell in the grid sets the height for all rows, here's a quick and simple solution:

  • Set the container to grid-auto-rows: 1fr

How it works

Grid Layout provides a unit for establishing flexible lengths in a grid container. This is the fr unit. It is designed to distribute free space in the container and is somewhat analogous to the flex-grow property in flexbox.

If you set all rows in a grid container to 1fr, let's say like this:

grid-auto-rows: 1fr;

... then all rows will be equal height.

It doesn't really make sense off-the-bat because fr is supposed to distribute free space. And if several rows have content with different heights, then when the space is distributed, some rows would be proportionally smaller and taller.

Except, buried deep in the grid spec is this little nugget:

7.2.3. Flexible Lengths: the fr unit

...

When the available space is infinite (which happens when the grid container’s width or height is indefinite), flex-sized (fr) grid tracks are sized to their contents while retaining their respective proportions.

The used size of each flex-sized grid track is computed by determining the max-content size of each flex-sized grid track and dividing that size by the respective flex factor to determine a “hypothetical 1fr size”.

The maximum of those is used as the resolved 1fr length (the flex fraction), which is then multiplied by each grid track’s flex factor to determine its final size.

So, if I'm reading this correctly, when dealing with a dynamically-sized grid (e.g., the height is indefinite), grid tracks (rows, in this case) are sized to their contents.

The height of each row is determined by the tallest (max-content) grid item.

The maximum height of those rows becomes the length of 1fr.

That's how 1fr creates equal height rows in a grid container.


Why flexbox isn't an option

As noted in the question, equal height rows are not possible with flexbox.

Flex items can be equal height on the same row, but not across multiple rows.

This behavior is defined in the flexbox spec:

6. Flex Lines

In a multi-line flex container, the cross size of each line is the minimum size necessary to contain the flex items on the line.

In other words, when there are multiple lines in a row-based flex container, the height of each line (the "cross size") is the minimum height necessary to contain the flex items on the line.

How do I perform an insert and return inserted identity with Dapper?

I see answer for sql server, well here it is for MySql using a transaction


    Dim sql As String = "INSERT INTO Empleado (nombres, apepaterno, apematerno, direccion, colonia, cp, municipio, estado, tel, cel, correo, idrol, relojchecadorid, relojchecadorid2, `activo`,`extras`,`rfc`,`nss`,`curp`,`imagen`,sueldoXHra, IMSSCotiza, thumb) VALUES (@nombres, @apepaterno, @apematerno, @direccion, @colonia, @cp, @municipio, @estado, @tel, @cel, @correo, @idrol, @relojchecadorid, @relojchecadorid2, @activo, @extras, @rfc, @nss, @curp, @imagen,@sueldoXHra,@IMSSCotiza, @thumb)"
    
            Using connection As IDbConnection = New MySqlConnection(getConnectionString())
                connection.Open()
                Using transaction = connection.BeginTransaction
                    Dim res = connection.Execute(sql, New With {reg.nombres, reg.apepaterno, reg.apematerno, reg.direccion, reg.colonia, reg.cp, reg.municipio, reg.estado, reg.tel, reg.cel, reg.correo, reg.idrol, reg.relojchecadorid, reg.relojchecadorid2, reg.activo, reg.extras, reg.rfc, reg.nss, reg.curp, reg.imagen, reg.thumb, reg.sueldoXHra, reg.IMSSCotiza}, commandTimeout:=180, transaction:=transaction)
                    lastInsertedId = connection.ExecuteScalar("SELECT LAST_INSERT_ID();", transaction:=transaction)
                    If res > 0 Then 
transaction.Commit()
return true
end if
                    
                End Using
            End Using

Put byte array to JSON and vice versa

Here is a good example of base64 encoding byte arrays. It gets more complicated when you throw unicode characters in the mix to send things like PDF documents. After encoding a byte array the encoded string can be used as a JSON property value.

Apache commons offers good utilities:

 byte[] bytes = getByteArr();
 String base64String = Base64.encodeBase64String(bytes);
 byte[] backToBytes = Base64.decodeBase64(base64String);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding

Java server side example:

public String getUnsecureContentBase64(String url)
        throws ClientProtocolException, IOException {

            //getUnsecureContent will generate some byte[]
    byte[] result = getUnsecureContent(url);

            // use apache org.apache.commons.codec.binary.Base64
            // if you're sending back as a http request result you may have to
            // org.apache.commons.httpclient.util.URIUtil.encodeQuery
    return Base64.encodeBase64String(result);
}

JavaScript decode:

//decode URL encoding if encoded before returning result
var uriEncodedString = decodeURIComponent(response);

var byteArr = base64DecToArr(uriEncodedString);

//from mozilla
function b64ToUint6 (nChr) {

  return nChr > 64 && nChr < 91 ?
      nChr - 65
    : nChr > 96 && nChr < 123 ?
      nChr - 71
    : nChr > 47 && nChr < 58 ?
      nChr + 4
    : nChr === 43 ?
      62
    : nChr === 47 ?
      63
    :
      0;

}

function base64DecToArr (sBase64, nBlocksSize) {

  var
    sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length,
    nOutLen = nBlocksSize ? Math.ceil((nInLen * 3 + 1 >> 2) / nBlocksSize) * nBlocksSize : nInLen * 3 + 1 >> 2, taBytes = new Uint8Array(nOutLen);

  for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) {
    nMod4 = nInIdx & 3;
    nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4;
    if (nMod4 === 3 || nInLen - nInIdx === 1) {
      for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) {
        taBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255;
      }
      nUint24 = 0;

    }
  }

  return taBytes;
}

JQuery, Spring MVC @RequestBody and JSON - making it work together

I'm pretty sure you only have to register MappingJacksonHttpMessageConverter

(the easiest way to do that is through <mvc:annotation-driven /> in XML or @EnableWebMvc in Java)

See:


Here's a working example:

Maven POM

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>json</artifactId><packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version><name>json test</name>
    <dependencies>
        <dependency><!-- spring mvc -->
            <groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>3.0.5.RELEASE</version>
        </dependency>
        <dependency><!-- jackson -->
            <groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-asl</artifactId><version>1.4.2</version>
        </dependency>
    </dependencies>
    <build><plugins>
            <!-- javac --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version><configuration><source>1.6</source><target>1.6</target></configuration></plugin>
            <!-- jetty --><plugin><groupId>org.mortbay.jetty</groupId><artifactId>jetty-maven-plugin</artifactId>
            <version>7.4.0.v20110414</version></plugin>
    </plugins></build>
</project>

in folder src/main/webapp/WEB-INF

web.xml

<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
    <servlet><servlet-name>json</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>json</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

json-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="classpath:mvc-context.xml" />

</beans>

in folder src/main/resources:

mvc-context.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <mvc:annotation-driven />
    <context:component-scan base-package="test.json" />
</beans>

In folder src/main/java/test/json

TestController.java

@Controller
@RequestMapping("/test")
public class TestController {

    @RequestMapping(method = RequestMethod.POST, value = "math")
    @ResponseBody
    public Result math(@RequestBody final Request request) {
        final Result result = new Result();
        result.setAddition(request.getLeft() + request.getRight());
        result.setSubtraction(request.getLeft() - request.getRight());
        result.setMultiplication(request.getLeft() * request.getRight());
        return result;
    }

}

Request.java

public class Request implements Serializable {
    private static final long serialVersionUID = 1513207428686438208L;
    private int left;
    private int right;
    public int getLeft() {return left;}
    public void setLeft(int left) {this.left = left;}
    public int getRight() {return right;}
    public void setRight(int right) {this.right = right;}
}

Result.java

public class Result implements Serializable {
    private static final long serialVersionUID = -5054749880960511861L;
    private int addition;
    private int subtraction;
    private int multiplication;

    public int getAddition() { return addition; }
    public void setAddition(int addition) { this.addition = addition; }
    public int getSubtraction() { return subtraction; }
    public void setSubtraction(int subtraction) { this.subtraction = subtraction; }
    public int getMultiplication() { return multiplication; }
    public void setMultiplication(int multiplication) { this.multiplication = multiplication; }
}

You can test this setup by executing mvn jetty:run on the command line, and then sending a POST request:

URL:        http://localhost:8080/test/math
mime type:  application/json
post body:  { "left": 13 , "right" : 7 }

I used the Poster Firefox plugin to do this.

Here's what the response looks like:

{"addition":20,"subtraction":6,"multiplication":91}

How do operator.itemgetter() and sort() work?

Looks like you're a little bit confused about all that stuff.

operator is a built-in module providing a set of convenient operators. In two words operator.itemgetter(n) constructs a callable that assumes an iterable object (e.g. list, tuple, set) as input, and fetches the n-th element out of it.

So, you can't use key=a[x][1] there, because python has no idea what x is. Instead, you could use a lambda function (elem is just a variable name, no magic there):

a.sort(key=lambda elem: elem[1])

Or just an ordinary function:

def get_second_elem(iterable):
    return iterable[1]

a.sort(key=get_second_elem)

So, here's an important note: in python functions are first-class citizens, so you can pass them to other functions as a parameter.

Other questions:

  1. Yes, you can reverse sort, just add reverse=True: a.sort(key=..., reverse=True)
  2. To sort by more than one column you can use itemgetter with multiple indices: operator.itemgetter(1,2), or with lambda: lambda elem: (elem[1], elem[2]). This way, iterables are constructed on the fly for each item in list, which are than compared against each other in lexicographic(?) order (first elements compared, if equal - second elements compared, etc)
  3. You can fetch value at [3,2] using a[2,1] (indices are zero-based). Using operator... It's possible, but not as clean as just indexing.

Refer to the documentation for details:

  1. operator.itemgetter explained
  2. Sorting list by custom key in Python

VBScript to send email without running Outlook

Yes. Blat or any other self contained SMTP mailer. Blat is a fairly full featured SMTP client that runs from command line

Blat is here

Setting a property by reflection with a string value

I will answer this with a general answer. Usually these answers not working with guids. Here is a working version with guids too.

var stringVal="6e3ba183-89d9-e611-80c2-00155dcfb231"; // guid value as string to set
var prop = obj.GetType().GetProperty("FooGuidProperty"); // property to be setted
var propType = prop.PropertyType;

// var will be type of guid here
var valWithRealType = TypeDescriptor.GetConverter(propType).ConvertFrom(stringVal); 

Creating a border like this using :before And :after Pseudo-Elements In CSS?

#footer:after
{
   content: "";
    width: 40px;
    height: 3px;
    background-color: #529600;
    left: 0;
    position: relative;
    display: block;
    top: 10px;
}

How to show another window from mainwindow in QT

  1. Implement a slot in your QMainWindow where you will open your new Window,
  2. Place a widget on your QMainWindow,
  3. Connect a signal from this widget to a slot from the QMainWindow (for example: if the widget is a QPushButton connect the signal click() to the QMainWindow custom slot you have created).

Code example:

MainWindow.h

// ...
include "newwindow.h"
// ...
public slots:
   void openNewWindow();
// ...
private:
   NewWindow *mMyNewWindow;
// ...
}

MainWindow.cpp

// ...
   MainWindow::MainWindow()
   {
      // ...
      connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
      // ...
   }
// ...
void MainWindow::openNewWindow()
{
   mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
   mMyNewWindow->show();
   // ...
}

This is an example on how display a custom new window. There are a lot of ways to do this.

Execution failed for task 'app:mergeDebugResources' Crunching Cruncher....png failed

  1. Look at the folders drawable-hdpi, drawable-mdpi, drawable-xhdpi and so on.
  2. If there is a wrong bitmap file, Delete it and resave.
  3. Go to Build->Rebuild Project

Choosing the best concurrency list in Java

You might want to look at ConcurrentDoublyLinkedList written by Doug Lea based on Paul Martin's "A Practical Lock-Free Doubly-Linked List". It does not implement the java.util.List interface, but offers most methods you would use in a List.

According to the javadoc:

A concurrent linked-list implementation of a Deque (double-ended queue). Concurrent insertion, removal, and access operations execute safely across multiple threads. Iterators are weakly consistent, returning elements reflecting the state of the deque at some point at or since the creation of the iterator. They do not throw ConcurrentModificationException, and may proceed concurrently with other operations.

Performance differences between ArrayList and LinkedList

Ignore this answer for now. The other answers, particularly that of aix, are mostly correct. Over the long term they're the way to bet. And if you have enough data (on one benchmark on one machine, it seemed to be about one million entries) ArrayList and LinkedList do currently work as advertized. However, there are some fine points that apply in the early 21st century.

Modern computer technology seems, by my testing, to give an enormous edge to arrays. Elements of an array can be shifted and copied at insane speeds. As a result arrays and ArrayList will, in most practical situations, outperform LinkedList on inserts and deletes, often dramatically. In other words, ArrayList will beat LinkedList at its own game.

The downside of ArrayList is it tends to hang onto memory space after deletions, where LinkedList gives up space as it gives up entries.

The bigger downside of arrays and ArrayList is they fragment free memory and overwork the garbage collector. As an ArrayList expands, it creates new, bigger arrays, copies the old array to the new one, and frees the old one. Memory fills with big contiguous chunks of free memory that are not big enough for the next allocation. Eventually there's no suitable space for that allocation. Even though 90% of memory is free, no individual piece is big enough to do the job. The GC will work frantically to move things around, but if it takes too long to rearrange the space, it will throw an OutOfMemoryException. If it doesn't give up, it can still slow your program way down.

The worst of it is this problem can be hard to predict. Your program will run fine one time. Then, with a bit less memory available, with no warning, it slows or stops.

LinkedList uses small, dainty bits of memory and GC's love it. It still runs fine when you're using 99% of your available memory.

So in general, use ArrayList for smaller sets of data that are not likely to have most of their contents deleted, or when you have tight control over creation and growth. (For instance, creating one ArrayList that uses 90% of memory and using it without filling it for the duration of the program is fine. Continually creating and freeing ArrayList instances that use 10% of memory will kill you.) Otherwise, go with LinkedList (or a Map of some sort if you need random access). If you have very large collections (say over 100,000 elements), no concerns about the GC, and plan lots of inserts and deletes and no random access, run a few benchmarks to see what's fastest.

JSHint and jQuery: '$' is not defined

If you're using an IntelliJ editor such as WebStorm, PyCharm, RubyMine, or IntelliJ IDEA:

In the Environments section of File/Settings/JavaScript/Code Quality Tools/JSHint, click on the jQuery checkbox.

Java Comparator class to sort arrays

[...] How should Java Comparator class be declared to sort the arrays by their first elements in decreasing order [...]

Here's a complete example using Java 8:

import java.util.*;

public class Test {

    public static void main(String args[]) {

        int[][] twoDim = { {1, 2}, {3, 7}, {8, 9}, {4, 2}, {5, 3} };

        Arrays.sort(twoDim, Comparator.comparingInt(a -> a[0])
                                      .reversed());

        System.out.println(Arrays.deepToString(twoDim));
    }
}

Output:

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

For Java 7 you can do:

Arrays.sort(twoDim, new Comparator<int[]>() {
    @Override
    public int compare(int[] o1, int[] o2) {
        return Integer.compare(o2[0], o1[0]);
    }
});

If you unfortunate enough to work on Java 6 or older, you'd do:

Arrays.sort(twoDim, new Comparator<int[]>() {
    @Override
    public int compare(int[] o1, int[] o2) {
        return ((Integer) o2[0]).compareTo(o1[0]);
    }
});

Looping each row in datagridview

You could loop through DataGridView using Rows property, like:

foreach (DataGridViewRow row in datagridviews.Rows)
{
   currQty += row.Cells["qty"].Value;
   //More code here
}

Should C# or C++ be chosen for learning Games Programming (consoles)?

It depends

It depends on a lot of things - your goals, your experience, your timeframe, etc.

The majority of game programming isn't language specific. 3D math is 3D math in C# as much as it is in C++. While the APIs may be different, and different 'bookkeeping' may be required, the fundamental logic and math will remain the same.

And it's true that most AAA game engines are C++ with a scripting language on top of them. That is undeniable. However, most AAA engines also have a bunch of in-house tools supporting them, and those may be in anything - Java, C#, C++, etc.

If you want to write a game, and are an experienced developer then C++ and C# have a lot going for them. C# has less housekeeping, while C++ has more available libraries and tools. For anything highly complex, however, you'd be best off trying to use an existing engine as a starting point.

If you want to write a game, and are a new developer then don't write an engine. Use an existing engine, and mod it or use its facilities to write your game. Trust me.

If you want to learn how to write an engine, and are an experienced developer you should probably think about C++. C# is possible as well, but the amount of code and ease of integration of C++ probably puts it over the top.

If you want to learn how to write an engine, and are a new developer I'd probably recommend C#/XNA. You'll get to the game 'stuff' faster, with less headache of learning the ins and outs of C++.

If you want a job in the industry then you need to figure out what kind of job you want. A high-level language can help get a foot in the door dealing with tools and/or web development, which can lead to opportunities on actual game work. Even knowledge of scripting languages can help if you want to go for more of the game designer/scripter position. Chances are that you will not get a job working on core engine stuff immediately, as the skills required to do so are pretty high. Strong C++ development skills are always helpful, especially in real-time or networked scenarios.

AAA game engine development involves some serious brain-twisting code.

If you want to start a professional development house then you probably aren't reading this, but already know that C++ is probably the only viable answer.

If you want to do casual game development then you should probably consider Flash or a similar technology.

non static method cannot be referenced from a static context

In Java, static methods belong to the class rather than the instance. This means that you cannot call other instance methods from static methods unless they are called in an instance that you have initialized in that method.

Here's something you might want to do:

public class Foo
{
  public void fee()
  {
     //do stuff  
  }

  public static void main (String[]arg) 
  { 
     Foo foo = new Foo();
     foo.fee();
  } 
}

Notice that you are running an instance method from an instance that you've instantiated. You can't just call call a class instance method directly from a static method because there is no instance related to that static method.

Iterating Through a Dictionary in Swift

Here is an alternative for that experiment (Swift 3.0). This tells you exactly which kind of number was the largest.

let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]

var largest = 0
var whichKind: String? = nil

for (kind, numbers) in interestingNumbers {
    for number in numbers {
    if number > largest {
        whichKind = kind
        largest = number
    }
  }
}

print(whichKind)
print(largest)

OUTPUT:
Optional("Square")
25

jQuery Event Keypress: Which key was pressed?

Witch ;)

/*
This code is for example. In real life you have plugins like :
https://code.google.com/p/jquery-utils/wiki/JqueryUtils
https://github.com/jeresig/jquery.hotkeys/blob/master/jquery.hotkeys.js
https://github.com/madrobby/keymaster
http://dmauro.github.io/Keypress/

http://api.jquery.com/keydown/
http://api.jquery.com/keypress/
*/

var event2key = {'97':'a', '98':'b', '99':'c', '100':'d', '101':'e', '102':'f', '103':'g', '104':'h', '105':'i', '106':'j', '107':'k', '108':'l', '109':'m', '110':'n', '111':'o', '112':'p', '113':'q', '114':'r', '115':'s', '116':'t', '117':'u', '118':'v', '119':'w', '120':'x', '121':'y', '122':'z', '37':'left', '39':'right', '38':'up', '40':'down', '13':'enter'};

var documentKeys = function(event) {
    console.log(event.type, event.which, event.keyCode);

    var keycode = event.which || event.keyCode; // par exemple : 112
    var myKey = event2key[keycode]; // par exemple : 'p'

    switch (myKey) {
        case 'a':
            $('div').css({
                left: '+=50'
            });
            break;
        case 'z':
            $('div').css({
                left: '-=50'
            });
            break;
        default:
            //console.log('keycode', keycode);
    }
};

$(document).on('keydown keyup keypress', documentKeys);

Demo : http://jsfiddle.net/molokoloco/hgXyq/24/

Javascript: Load an Image from url and display

First, I strongly suggest to use a Library or Framework to do your Javascript. But just for something very very simple, or for the fun to learn, it is ok. (you can use jquery, underscore, knockoutjs, angular)

Second, it is not advised to bind directly to onclick, my first suggestion goes in that way too.

That's said What you need is to modify the src of a img in your page.

In the place where you want your image displayed, you should insert a img tag like this:

Next, you need to modify the onclick to update the src attribute. The easiest way I can think of is like his

onclick=""document.getElementById('image-placeholder').src = 'http://webpage.com/images/' + document.getElementById('imagename').value + '.png"

Then again, it is not the best way to do it, but it is a start. I recommend you to try jQuery and see how can you accomplish the same whitout using onclick (tip... check the section on jquery about events)

I did a simple fiddle as a example of your poblem using some google logos... type 4 o 3 in the box and you'll two images of different size. (sorry.. I have no time to search for better images as example)

http://jsfiddle.net/HsnSa/

How to find the minimum value of a column in R?

df <- read.table(text = 
             "X  Y
             1  2  3
             2  4  5
             3  6  7
             4  8  9
             5 10 11",
             header = TRUE)


y_min <- min(df[,"Y"])

# Corresponding X value
x_val_associated <- df[df$Y == y_min, "X"]

x_val_associated

First, you find the Y min using the min function on the "Y" column only. Notice the returned result is just an integer value. Then, to find the associated X value, you can subset the data.frame to only the rows where the minimum Y value is located and extract just the "X" column.

You now have two integer values for X and Y where Y is the min.

Calculating average of an array list?

sum += i;

You're adding the index; you should be adding the actual item in the ArrayList:

sum += marks.get(i);

Also, to ensure the return value isn't truncated, force one operand to double and change your method signature to double:

return (double)sum / marks.size();

Where does R store packages?

The install.packages command looks through the .libPaths variable. Here's what mine defaults to on OSX:

> .libPaths()
[1] "/Library/Frameworks/R.framework/Resources/library"

I don't install packages there by default, I prefer to have them installed in my home directory. In my .Rprofile, I have this line:

.libPaths( "/Users/tex/lib/R" )

This adds the directory "/Users/tex/lib/R" to the front of the .libPaths variable.

Form submit with AJAX passing form data to PHP without page refresh

In event handling, pass the object of event to the function and then add statement i.e. event.preventDefault();

This will pass data to webpage without refreshing it.

Resize UIImage by keeping Aspect ratio and width

thanks @Maverick1st the algorithm, I implemented it to Swift, in my case height is the input parameter

class func resizeImage(image: UIImage, newHeight: CGFloat) -> UIImage {

    let scale = newHeight / image.size.height
    let newWidth = image.size.width * scale
    UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight))
    image.drawInRect(CGRectMake(0, 0, newWidth, newHeight))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage
}

Reading text files using read.table

From ?read.table: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.

So, perhaps your data file isn't clean. Being more specific will help the data import:

d = read.table("foobar.txt", 
               sep="\t", 
               col.names=c("id", "name"), 
               fill=FALSE, 
               strip.white=TRUE)

will specify exact columns and fill=FALSE will force a two column data frame.

How do I check if a Sql server string is null or empty

Here's a solution, but I don't know if it's the best....

Select              
Coalesce(Case When Len(listing.Offer_Text) = 0 Then Null Else listing.Offer_Text End, company.Offer_Text, '') As Offer_Text,         
from tbl_directorylisting listing  
 Inner Join tbl_companymaster company            
  On listing.company_id= company.company_id

How to enable bulk permission in SQL Server

If you get an error saying "Cannot Bulk load file because you don't have access right"

First make sure the path and file name you have given are correct.

then try giving the bulkadmin role to the user. To do so follow the steps :- In Object Explorer -> Security -> Logins -> Select the user (right click) -> Properties -> Server Roles -> check the bulkadmin checkbox -> OK.

This worked for me.

SSRS custom number format

am assuming that you want to know how to format numbers in SSRS

Just right click the TextBox on which you want to apply formatting, go to its expression.

suppose its expression is something like below

=Fields!myField.Value

then do this

=Format(Fields!myField.Value,"##.##") 

or

=Format(Fields!myFields.Value,"00.00")

difference between the two is that former one would make 4 as 4 and later one would make 4 as 04.00

this should give you an idea.

also: you might have to convert your field into a numerical one. i.e.

  =Format(CDbl(Fields!myFields.Value),"00.00")

so: 0 in format expression means, when no number is present, place a 0 there and # means when no number is present, leave it. Both of them works same when numbers are present ie. 45.6567 would be 45.65 for both of them:

UPDATE :

if you want to apply variable formatting on the same column based on row values i.e. you want myField to have no formatting when it has no decimal value but formatting with double precision when it has decimal then you can do it through logic. (though you should not be doing so)

Go to the appropriate textbox and go to its expression and do this:

=IIF((Fields!myField.Value - CInt(Fields!myField.Value)) > 0, 
    Format(Fields!myField.Value, "##.##"),Fields!myField.Value)

so basically you are using IIF(condition, true,false) operator of SSRS, ur condition is to check whether the number has decimal value, if it has, you apply the formatting and if no, you let it as it is.

this should give you an idea, how to handle variable formatting.

Insert text with single quotes in PostgreSQL

select concat('''','abc','''')

Plot smooth line with PyPlot

I presume you mean curve-fitting and not anti-aliasing from the context of your question. PyPlot doesn't have any built-in support for this, but you can easily implement some basic curve-fitting yourself, like the code seen here, or if you're using GuiQwt it has a curve fitting module. (You could probably also steal the code from SciPy to do this as well).

"Items collection must be empty before using ItemsSource."

In my case, it was not using a DataTemplate for the ItemsControl.

Old:

<ItemsControl Width="243" ItemsSource="{Binding List, Mode=TwoWay}">
    <StackPanel Orientation="Horizontal">
        <TextBox Width="25" Margin="0,0,5,0" Text="{Binding Path=Property1}"/>
        <Label Content="{Binding Path=Property2}"/>
    </StackPanel>
</ItemsControl>

New:

<ItemsControl Width="243" ItemsSource="{Binding List, Mode=TwoWay}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBox Width="25" Margin="0,0,5,0" Text="{Binding Path=Property1}"/>
                <Label Content="{Binding Path=Property2}"/>
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Order by descending date - month, day and year

If you restructured your date format into YYYY/MM/DD then you can use this simple string ordering to achieve the formating you need.

Alternatively, using the SUBSTR(store_name,start,length) command you should be able to restructure the sorting term into the above format

perhaps using the following

SELECT     *
FROM         vw_view
ORDER BY SUBSTR(EventDate,6,4) + SUBSTR(EventDate, 0, 5) DESC

What are good message queue options for nodejs?

You could use the node STOMP client. This would let you integrate with a variety of message queues including:

  • ActiveMQ
  • RabbitMQ
  • HornetQ

I haven't used this library before, so I can't vouch for its quality. But STOMP is a pretty simple protocol so I suspect you can hack it into submission if necessary.

Another option is to use beanstalkd with node. beanstalkd is a very fast "task queue" written in C that is very good if you don't need the feature flexibility of the brokers listed above.

React Error: Target Container is not a DOM Element

Also, the best practice of moving your <script></script> to the bottom of the html file fixes this too.

Storing SHA1 hash values in MySQL

If you need an index on the sha1 column, I suggest CHAR(40) for performance reasons. In my case the sha1 column is an email confirmation token, so on the landing page the query enters only with the token. In this case CHAR(40) with INDEX, in my opinion, is the best choice :)

If you want to adopt this method, remember to leave $raw_output = false.

Expected initializer before function name

Try adding a semi colon to the end of your structure:

 struct sotrudnik {
    string name;
    string speciality;
    string razread;
    int zarplata;
} //Semi colon here

Font Awesome not working, icons showing as squares

According to the documentation (step 3), you need to modify the supplied CSS file to point to the font location on your site.

How to stop a setTimeout loop?

I know this is an old question, I'd like to post my approach anyway. This way you don't have to handle the 0 trick that T. J. Crowder expained.

var keepGoing = true;

function myLoop() {
    // ... Do something ...

    if(keepGoing) {
        setTimeout(myLoop, 1000);
    }
}

function startLoop() {
    keepGoing = true;
    myLoop();
}

function stopLoop() {
    keepGoing = false;
}

How to clear the cache of nginx?

For those who have tried deleting the nginx cache files, and either it hasn't worked or has worked intermittently, have a look at your setting for open_file_cache. If this is enabled and configured to cache a file descriptor for a long time, then Nginx may still see a version of the cached file, even after you've deleted it from disk. I had to reduce open_file_cache_valid to 1s (I'm not certain if this is essentially the same as disabling the file cache completely).

Codeigniter: does $this->db->last_query(); execute a query?

The query execution happens on all get methods like

$this->db->get('table_name');
$this->db->get_where('table_name',$array);

While last_query contains the last query which was run

$this->db->last_query();

If you want to get query string without execution you will have to do this. Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions

public function _compile_select($select_override = FALSE)
public function _reset_select()

Now you can write query and get it in a variable

$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();

Now reset query so if you want to write another query the object will be cleared.

$this->db->_reset_select();

And the thing is done. Cheers!!! Note : While using this way you must use

$this->db->from('myTable')

instead of

$this->db->get('myTable')

which runs the query.

Take a look at this example

How can I color a UIImage in Swift?

Add this extension in your code and change image color in storyboard itself.

Swift 4 & 5:

extension UIImageView {
    @IBInspectable
    var changeColor: UIColor? {
        get {
            let color = UIColor(cgColor: layer.borderColor!);
            return color
        }
        set {
            let templateImage = self.image?.withRenderingMode(.alwaysTemplate)
            self.image = templateImage
            self.tintColor = newValue
        }
    }
}

Storyboard Preview:

enter image description here

Visually managing MongoDB documents and collections

I use MongoVUE, it's good for viewing data, but there is almost no editing abilities.

Delete last N characters from field in a SQL Server database

This should do it, removing characters from the left by one or however many needed.

lEFT(columnX,LEN(columnX) - 1) AS NewColumnName

Mongoimport of json file

If you try to export this test collection:

> db.test.find()
{ "_id" : ObjectId("5131c2bbfcb94ddb2549d501"), "field" : "Sat Mar 02 2013 13:13:31 GMT+0400"}
{"_id" : ObjectId("5131c2d8fcb94ddb2549d502"), "field" : ISODate("2012-05-31T11:59:39Z")}

with mongoexport (the first date created with Date(...) and the second one created with new Date(...) (if use ISODate(...) will be the same as in the second line)) so mongoexport output will be looks like this:

{ "_id" : { "$oid" : "5131c2bbfcb94ddb2549d501" }, "field" : "Sat Mar 02 2013 13:13:31 GMT+0400" }
{ "_id" : { "$oid" : "5131c2d8fcb94ddb2549d502" }, "field" : { "$date" : 1338465579000 } }

So you should use the same notation, because strict JSON doesn't have type Date( <date> ).

Also your JSON is not valid: all fields name must be enclosed in double quotes, but mongoimport works fine without them.

You can find additional information in mongodb documentation and here.

GitHub - failed to connect to github 443 windows/ Failed to connect to gitHub - No Error

I have wide experience working with corporate proxies. Configuration is usually working well with

But if you have configured the proxy and it's impossible to work with git (always getting 443 error) try to check if you have a remote.origin.proxy bypassing your configuration.

git config --list --show-origin

If you check that "remote.origin.proxy" is configured as empty value try to unset it or almost set it with your corporate proxy:

git config --add remote.origin.proxy "http://[yourproxy]:[yourport]"

And since several enterprise sites have untrusted certificates I recomend you to avoid certificate checking if you are using ssl:

git config http.sslverify false    
git config --global http.sslverify false

Parsing JSON object in PHP using json_decode

This appears to work:

$url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710%22';
$content = file_get_contents($url);
$json = json_decode($content, true);

foreach($json['data']['weather'] as $item) {
    print $item['date'];
    print ' - ';
    print $item['weatherDesc'][0]['value'];
    print ' - ';
    print '<img src="' . $item['weatherIconUrl'][0]['value'] . '" border="0" alt="" />';
    print '<br>';
}

If you set the second parameter of json_decode to true, you get an array, so you cant use the -> syntax. I would also suggest you install the JSONview Firefox extension, so you can view generated json documents in a nice formatted tree view similiar to how Firefox displays XML structures. This makes things a lot easier.

How to fix homebrew permissions?

I used these two commands and saved my problem

sudo chown -R $(whoami) /usr/local

sudo chown -R $(whoami) /usr/local/etc/bash_completion.d /usr/local/lib/python3.7/site-packages /usr/local/share/aclocal /usr/local/share/locale /usr/local/share/man/man7 /usr/local/share/man/man8 /usr/local/share/zsh /usr/local/share/zsh/site-functions /usr/local/var/homebrew/locks

Check if string is neither empty nor space in shell script

For checking the empty string in shell

if [ "$str" == "" ];then
   echo NULL
fi

OR

if [ ! "$str" ];then
   echo NULL
fi

DataGridView checkbox column - value and functionality

If you try it on CellContentClick Event

Use:

dataGridView1.EndEdit();  //Stop editing of cell.
MessageBox.Show("0 = " + dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());

How to add a constant column in a Spark DataFrame?

As the other answers have described, lit and typedLit are how to add constant columns to DataFrames. lit is an important Spark function that you will use frequently, but not for adding constant columns to DataFrames.

You'll commonly be using lit to create org.apache.spark.sql.Column objects because that's the column type required by most of the org.apache.spark.sql.functions.

Suppose you have a DataFrame with a some_date DateType column and would like to add a column with the days between December 31, 2020 and some_date.

Here's your DataFrame:

+----------+
| some_date|
+----------+
|2020-09-23|
|2020-01-05|
|2020-04-12|
+----------+

Here's how to calculate the days till the year end:

val diff = datediff(lit(Date.valueOf("2020-12-31")), col("some_date"))
df
  .withColumn("days_till_yearend", diff)
  .show()
+----------+-----------------+
| some_date|days_till_yearend|
+----------+-----------------+
|2020-09-23|               99|
|2020-01-05|              361|
|2020-04-12|              263|
+----------+-----------------+

You could also use lit to create a year_end column and compute the days_till_yearend like so:

import java.sql.Date

df
  .withColumn("yearend", lit(Date.valueOf("2020-12-31")))
  .withColumn("days_till_yearend", datediff(col("yearend"), col("some_date")))
  .show()
+----------+----------+-----------------+
| some_date|   yearend|days_till_yearend|
+----------+----------+-----------------+
|2020-09-23|2020-12-31|               99|
|2020-01-05|2020-12-31|              361|
|2020-04-12|2020-12-31|              263|
+----------+----------+-----------------+

Most of the time, you don't need to use lit to append a constant column to a DataFrame. You just need to use lit to convert a Scala type to a org.apache.spark.sql.Column object because that's what's required by the function.

See the datediff function signature:

enter image description here

As you can see, datediff requires two Column arguments.

Apply a function to every row of a matrix or a data frame

Another approach if you want to use a varying portion of the dataset instead of a single value is to use rollapply(data, width, FUN, ...). Using a vector of widths allows you to apply a function on a varying window of the dataset. I've used this to build an adaptive filtering routine, though it isn't very efficient.

fe_sendauth: no password supplied

This occurs if the password for the database is not given.

default="postgres://postgres:[email protected]:5432/DBname"

How npm start runs a server on port 8000

If you will look at package.json file.

you will see something like this

 "start": "http-server -a localhost -p 8000"

This tells start a http-server at address of localhost on port 8000

http-server is a node-module.

Update:- Including comment by @Usman, ideally it should be present in your package.json but if it's not present you can include it in scripts section.

How to find the index of an element in an array in Java?

This way should work, change "char" to "Character":

public static void main(String[] args){
  Character[] list = {'m', 'e', 'y'};
  System.out.println(Arrays.asList(list).indexOf('e')); // print "1"
}

BATCH file asks for file or folder

echo f | xcopy /s/y J:\"My Name"\"FILES IN TRANSIT"\JOHN20101126\"Missing file"\Shapes.atc C:\"Documents and Settings"\"His name"\"Application Data"\Autodesk\"AutoCAD 2010"\"R18.0"\enu\Support\Shapes.atc

How to create a temporary directory and get the path / file name in Python

To expand on another answer, here is a fairly complete example which can cleanup the tmpdir even on exceptions:

import contextlib
import os
import shutil
import tempfile

@contextlib.contextmanager
def cd(newdir, cleanup=lambda: True):
    prevdir = os.getcwd()
    os.chdir(os.path.expanduser(newdir))
    try:
        yield
    finally:
        os.chdir(prevdir)
        cleanup()

@contextlib.contextmanager
def tempdir():
    dirpath = tempfile.mkdtemp()
    def cleanup():
        shutil.rmtree(dirpath)
    with cd(dirpath, cleanup):
        yield dirpath

def main():
    with tempdir() as dirpath:
        pass # do something here

How do I enable EF migrations for multiple contexts to separate databases?

I just bumped into the same problem and I used the following solution (all from Package Manager Console)

PM> Enable-Migrations -MigrationsDirectory "Migrations\ContextA" -ContextTypeName MyProject.Models.ContextA
PM> Enable-Migrations -MigrationsDirectory "Migrations\ContextB" -ContextTypeName MyProject.Models.ContextB

This will create 2 separate folders in the Migrations folder. Each will contain the generated Configuration.cs file. Unfortunately you still have to rename those Configuration.cs files otherwise there will be complaints about having two of them. I renamed my files to ConfigA.cs and ConfigB.cs

EDIT: (courtesy Kevin McPheat) Remember when renaming the Configuration.cs files, also rename the class names and constructors /EDIT

With this structure you can simply do

PM> Add-Migration -ConfigurationTypeName ConfigA
PM> Add-Migration -ConfigurationTypeName ConfigB

Which will create the code files for the migration inside the folder next to the config files (this is nice to keep those files together)

PM> Update-Database -ConfigurationTypeName ConfigA
PM> Update-Database -ConfigurationTypeName ConfigB

And last but not least those two commands will apply the correct migrations to their corrseponding databases.

EDIT 08 Feb, 2016: I have done a little testing with EF7 version 7.0.0-rc1-16348

I could not get the -o|--outputDir option to work. It kept on giving Microsoft.Dnx.Runtime.Common.Commandline.CommandParsingException: Unrecognized command or argument

However it looks like the first time an migration is added it is added into the Migrations folder, and a subsequent migration for another context is automatically put into a subdolder of migrations.

The original names ContextA seems to violate some naming conventions so I now use ContextAContext and ContextBContext. Using these names you could use the following commands: (note that my dnx still works from the package manager console and I do not like to open a separate CMD window to do migrations)

PM> dnx ef migrations add Initial -c "ContextAContext"
PM> dnx ef migrations add Initial -c "ContextBContext"

This will create a model snapshot and a initial migration in the Migrations folder for ContextAContext. It will create a folder named ContextB containing these files for ContextBContext

I manually added a ContextA folder and moved the migration files from ContextAContext into that folder. Then I renamed the namespace inside those files (snapshot file, initial migration and note that there is a third file under the initial migration file ... designer.cs). I had to add .ContextA to the namespace, and from there the framework handles it automatically again.

Using the following commands would create a new migration for each context

PM>  dnx ef migrations add Update1 -c "ContextAContext"
PM>  dnx ef migrations add Update1 -c "ContextBContext"

and the generated files are put in the correct folders.

What is the difference between PUT, POST and PATCH?

here is a simple description of all:

  • POST is always for creating a resource ( does not matter if it was duplicated )
  • PUT is for checking if resource is exists then update , else create new resource
  • PATCH is always for update a resource

Prevent RequireJS from Caching Required Scripts

RequireJS can be configured to append a value to each of the script urls for cache busting.

From the RequireJS documentation (http://requirejs.org/docs/api.html#config):

urlArgs: Extra query string arguments appended to URLs that RequireJS uses to fetch resources. Most useful to cache bust when the browser or server is not configured correctly.

Example, appending "v2" to all scripts:

require.config({
    urlArgs: "bust=v2"
});

For development purposes, you can force RequireJS to bypass the cache by appending a timestamp:

require.config({
    urlArgs: "bust=" + (new Date()).getTime()
});

About the Full Screen And No Titlebar from manifest

In AndroidManifest.xml, set android:theme="@android:style/Theme.NoTitleBar.Fullscreen"in application tag.

Individual activities can override the default by setting their own theme attributes.

Pass mouse events through absolutely-positioned element

The reason you are not receiving the event is because the absolutely positioned element is not a child of the element you are wanting to "click" (blue div). The cleanest way I can think of is to put the absolute element as a child of the one you want clicked, but I'm assuming you can't do that or you wouldn't have posted this question here :)

Another option would be to register a click event handler for the absolute element and call the click handler for the blue div, causing them both to flash.

Due to the way events bubble up through the DOM I'm not sure there is a simpler answer for you, but I'm very curious if anyone else has any tricks I don't know about!

How can I remove the last character of a string in python?

As you say, you don't need to use a regex for this. You can use rstrip.

my_file_path = my_file_path.rstrip('/')

If there is more than one / at the end, this will remove all of them, e.g. '/file.jpg//' -> '/file.jpg'. From your question, I assume that would be ok.

The model backing the <Database> context has changed since the database was created

For Entity Framework 5.0.0.0 - 6.1.3

You DO indeed want to do the following:

1. using System.Data.Entity;   to startup file (console app --> Program.cs / mvc --> global.asax
2. Database.SetInitializer<YourDatabaseContext>(null);

Yes, Matt Frear is correct. UPDATE -EDIT: Caveat is that I agree with others in that instead of adding this code to global.asax added to your DbContext class

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // other code 
    Database.SetInitializer<YOURContext>(null);
    // more code here.
}

As others mentioned this also is good for handling the unit testing.

Currently I am using this with Entity Framework 6.1.3 /.net 4.6.1

I will come back to provide a CORE snippet in the near future.

Formatting struct timespec

You could use a std::stringstream. You can stream anything into it:

std::stringstream stream;
stream << 5.7;
stream << foo.bar;

std::string s = stream.str();

That should be a quite general approach. (Works only for C++, but you asked the question for this language too.)

How do I get column datatype in Oracle with PL-SQL with low privileges?

Oracle: Get a list of the full datatype in your table:

select data_type || '(' || data_length || ')' 
from user_tab_columns where TABLE_NAME = 'YourTableName'

How can I access each element of a pair in a pair list?

If you want to use names, try a namedtuple:

from collections import namedtuple

Pair = namedtuple("Pair", ["first", "second"])

pairs = [Pair("a", 1), Pair("b", 2), Pair("c", 3)]

for pair in pairs:
    print("First = {}, second = {}".format(pair.first, pair.second))

What is the proper declaration of main in C++?

Details on return values and their meaning

Per 3.6.1 ([basic.start.main]):

A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling std::exit with the return value as the argument. If control reaches the end of main without encountering a return statement, the effect is that of executing

return 0;

The behavior of std::exit is detailed in section 18.5 ([support.start.term]), and describes the status code:

Finally, control is returned to the host environment. If status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.

How to append a jQuery variable value inside the .html tag

See this Link

HTML

<div id="products"></div>

JS

var someone = {
"name":"Mahmoude Elghandour",
"price":"174 SR",
"desc":"WE Will BE WITH YOU"
 };
 var name = $("<div/>",{"text":someone.name,"class":"name"
});

var price = $("<div/>",{"text":someone.price,"class":"price"});
var desc = $("<div />", {   
"text": someone.desc,
"class": "desc"
});
$("#products").fadeIn(1500);
$("#products").append(name).append(price).append(desc);

httpd Server not started: (13)Permission denied: make_sock: could not bind to address [::]:88

I happened to run into this problem because of missing SELinux permissions. By default, SELinux only allowed apache/httpd to bind to the following ports:

80, 81, 443, 488, 8008, 8009, 8443, 9000

So binding to my httpd.conf-configured Listen 88 HTTP port and config.d/ssl.conf-configured Listen 8445 TLS/SSL port would fail with that default SELinux configuration.

To fix my problem, I had to add ports 88 and 8445 to my system's SELinux configuration:

  1. Install semanage tools: sudo yum -y install policycoreutils-python
  2. Allow port 88 for httpd: sudo semanage port -a -t http_port_t -p tcp 88
  3. Allow port 8445 for httpd: sudo semanage port -a -t http_port_t -p tcp 8445

Are global variables bad?

Using global variables is kind of like sweeping dirt under a rug. It's a quick fix, and a lot easier in the short term than getting a dust-pan or vacuum to clean it up. However, if you ever end up moving the rug later, you're gonna have a big surprise mess underneath.

Pandas - Plotting a stacked Bar Chart

That should help

df.groupby(['NFF', 'ABUSE']).size().unstack().plot(kind='bar', stacked=True)

Build not visible in itunes connect

Wow this was super annoying! Honestly I don't know what the problem was because I've uploaded many apps to the appstore via Xcode over the past few years but past couple days I tried like 8 different build uploads over span of 12 hours but NONE of them would show up in iTunesConnect as Processing or anywhere else. I eventually tried Application Loader even though I've NEVER had to use that before. The first try timed out "Fetching Apple Connect token" or something. I CMD+Q and tried Application Loader again and the 2nd time the upload finished ... and now my build shows up in iTunesConnect as processing. OMG that was annoying, confusing and a huge waste of time (typical Apple Dev experience I guess).

Anyhow ... thought I would share my results.

Using PI in python 2.7

To have access to stuff provided by math module, like pi. You need to import the module first:

import math
print (math.pi)

Using "label for" on radio buttons

(Firstly read the other answers which has explained the for in the <label></label> tags. Well, both the tops answers are correct, but for my challenge, it was when you have several radio boxes, you should select for them a common name like name="r1" but with different ids id="r1_1" ... id="r1_2"

So this way the answer is more clear and removes the conflicts between name and ids as well.

You need different ids for different options of the radio box.

_x000D_
_x000D_
<input type="radio" name="r1" id="r1_1" />_x000D_
_x000D_
       <label for="r1_1">button text one</label>_x000D_
       <br/>_x000D_
       <input type="radio" name="r1" id="r1_2" />_x000D_
_x000D_
       <label for="r1_2">button text two</label>_x000D_
       <br/>_x000D_
       <input type="radio" name="r1" id="r1_3" />_x000D_
_x000D_
       <label for="r1_3">button text three</label>
_x000D_
_x000D_
_x000D_

Adding maven nexus repo to my pom.xml

From the Apache Maven site

<project>
  ...
  <repositories>
    <repository>
      <id>my-internal-site</id>
      <url>http://myserver/repo</url>
    </repository>
  </repositories>
  ...
</project>

"The repositories for download and deployment are defined by the repositories and distributionManagement elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml." - Apache Maven site - settings reference

<servers>
    <server>
        <id>server001</id>
        <username>my_login</username>
        <password>my_password</password>
        <privateKey>${user.home}/.ssh/id_dsa</privateKey>
        <passphrase>some_passphrase</passphrase>
        <filePermissions>664</filePermissions>
        <directoryPermissions>775</directoryPermissions>
        <configuration></configuration>
    </server>
</servers>

Get first date of current month in java

Works Like a charm!

public static String  getCurrentMonthFirstDate(){
    Calendar c = Calendar.getInstance();   
    c.set(Calendar.DAY_OF_MONTH, 1);
    DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
    //System.out.println(df.format(c.getTime())); 
    return df.format(c.getTime());
}

//Correction :output =02-01-2018enter image description here

Errors in pom.xml with dependencies (Missing artifact...)

It means maven is not able to download artifacts from repository. Following steps will help you:

  1. Go to repository browser and check if artifact exist.
  2. Check settings.xml to see if proper respository is specified.
  3. Check proxy settings.

How to parse freeform street/postal address out of text, and into components

I'm late to the party, here is an Excel VBA script I wrote years ago for Australia. It can be easily modified to support other Countries. I've made a GitHub repository of the C# code here. I've hosted it on my site and you can download it here: http://jeremythompson.net/rocks/ParseAddress.xlsm

Strategy

For any country with a PostCode that's numeric or can be matched with a RegEx my strategy works very well:

  1. First we detect the First and Surname which are assumed to be the top line. Its easy to skip the name and start with the address by unticking the checkbox (called 'Name is top row' as shown below).

  2. Next its safe to expect the Address consisting of the Street and Number come before the Suburb and the St, Pde, Ave, Av, Rd, Cres, loop, etc is a separator.

  3. Detecting the Suburb vs the State and even Country can trick the most sophisticated parsers as there can be conflicts. To overcome this I use a PostCode look up based on the fact that after stripping Street and Apartment/Unit numbers as well as the PoBox,Ph,Fax,Mobile etc, only the PostCode number will remain. This is easy to match with a regEx to then look up the suburb(s) and country.

Your National Post Office Service will provide a list of post codes with Suburbs and States free of charge that you can store in an excel sheet, db table, text/json/xml file, etc.

  1. Finally, since some Post Codes have multiple Suburbs we check which suburb appears in the Address.

Example

enter image description here

VBA Code

DISCLAIMER, I know this code is not perfect, or even written well however its very easy to convert to any programming language and run in any type of application.The strategy is the answer depending on your country and rules, take this code as an example:

Option Explicit

Private Const TopRow As Integer = 0

Public Sub ParseAddress()
Dim strArr() As String
Dim sigRow() As String
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim Stat As String
Dim SpaceInName As Integer
Dim Temp As String
Dim PhExt As String

On Error Resume Next

Temp = ActiveSheet.Range("Address")

'Split info into array
strArr = Split(Temp, vbLf)

'Trim the array
For i = 0 To UBound(strArr)
strArr(i) = VBA.Trim(strArr(i))
Next i

'Remove empty items/rows    
ReDim sigRow(LBound(strArr) To UBound(strArr))
For i = LBound(strArr) To UBound(strArr)
    If Trim(strArr(i)) <> "" Then
        sigRow(j) = strArr(i)
        j = j + 1
    End If
Next i
ReDim Preserve sigRow(LBound(strArr) To j)

'Find the name (MUST BE ON THE FIRST ROW UNLESS CHECKBOX UNTICKED)
i = TopRow
If ActiveSheet.Shapes("chkFirst").ControlFormat.Value = 1 Then

SpaceInName = InStr(1, sigRow(i), " ", vbTextCompare) - 1

If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
ActiveSheet.Range("FirstName") = VBA.Left(sigRow(i), SpaceInName)
Else
 If MsgBox("First Name: " & VBA.Mid$(sigRow(i), 1, SpaceInName), vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("FirstName") = VBA.Left(sigRow(i), SpaceInName)
End If

If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
ActiveSheet.Range("Surname") = VBA.Mid(sigRow(i), SpaceInName + 2)
Else
  If MsgBox("Surame: " & VBA.Mid(sigRow(i), SpaceInName + 2), vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("Surname") = VBA.Mid(sigRow(i), SpaceInName + 2)
End If
sigRow(i) = ""
End If

'Find the Street by looking for a "St, Pde, Ave, Av, Rd, Cres, loop, etc"
For i = 1 To UBound(sigRow)
If Len(sigRow(i)) > 0 Then
    For j = 0 To 8
    If InStr(1, VBA.UCase(sigRow(i)), Street(j), vbTextCompare) > 0 Then

    'Find the position of the street in order to get the suburb
    SpaceInName = InStr(1, VBA.UCase(sigRow(i)), Street(j), vbTextCompare) + Len(Street(j)) - 1

    'If its a po box then add 5 chars
    If VBA.Right(Street(j), 3) = "BOX" Then SpaceInName = SpaceInName + 5

    If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
    ActiveSheet.Range("Street") = VBA.Mid(sigRow(i), 1, SpaceInName)
    Else
      If MsgBox("Street Address: " & VBA.Mid(sigRow(i), 1, SpaceInName), vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("Street") = VBA.Mid(sigRow(i), 1, SpaceInName)
    End If
    'Trim the Street, Number leaving the Suburb if its exists on the same line
    sigRow(i) = VBA.Mid(sigRow(i), SpaceInName) + 2
    sigRow(i) = Replace(sigRow(i), VBA.Mid(sigRow(i), 1, SpaceInName), "")

    GoTo PastAddress:
    End If
    Next j
End If
Next i
PastAddress:

'Mobile
For i = 1 To UBound(sigRow)
If Len(sigRow(i)) > 0 Then
    For j = 0 To 3
    Temp = Mb(j)
        If VBA.Left(VBA.UCase(sigRow(i)), Len(Temp)) = Temp Then
        If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
        ActiveSheet.Range("Mobile") = VBA.Mid(sigRow(i), Len(Temp) + 2)
        Else
          If MsgBox("Mobile: " & VBA.Mid(sigRow(i), Len(Temp) + 2), vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("Mobile") = VBA.Mid(sigRow(i), Len(Temp) + 2)
        End If
    sigRow(i) = ""
    GoTo PastMobile:
    End If
    Next j
End If
Next i
PastMobile:

'Phone
For i = 1 To UBound(sigRow)
If Len(sigRow(i)) > 0 Then
    For j = 0 To 1
    Temp = Ph(j)
        If VBA.Left(VBA.UCase(sigRow(i)), Len(Temp)) = Temp Then

            'TODO: Detect the intl or national extension here.. or if we can from the postcode.
            If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
            ActiveSheet.Range("Phone") = VBA.Mid(sigRow(i), Len(Temp) + 3)
            Else
              If MsgBox("Phone: " & VBA.Mid(sigRow(i), Len(Temp) + 3), vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("Phone") = VBA.Mid(sigRow(i), Len(Temp) + 3)
            End If

        sigRow(i) = ""
        GoTo PastPhone:
        End If
    Next j
End If
Next i
PastPhone:


'Email
For i = 1 To UBound(sigRow)
    If Len(sigRow(i)) > 0 Then
        'replace with regEx search
        If InStr(1, sigRow(i), "@", vbTextCompare) And InStr(1, VBA.UCase(sigRow(i)), ".CO", vbTextCompare) Then
        Dim email As String
        email = sigRow(i)
        email = Replace(VBA.UCase(email), "EMAIL:", "")
        email = Replace(VBA.UCase(email), "E-MAIL:", "")
        email = Replace(VBA.UCase(email), "E:", "")
        email = Replace(VBA.UCase(Trim(email)), "E ", "")
        email = VBA.LCase(email)

            If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
            ActiveSheet.Range("Email") = email
            Else
              If MsgBox("Email: " & email, vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("Email") = email
            End If
        sigRow(i) = ""
        Exit For
        End If
    End If
Next i

'Now the only remaining items will be the postcode, suburb, country
'there shouldn't be any numbers (eg. from PoBox,Ph,Fax,Mobile) except for the Post Code

'Join the string and filter out the Post Code
Temp = Join(sigRow, vbCrLf)
Temp = Trim(Temp)

For i = 1 To Len(Temp)

Dim postCode As String
postCode = VBA.Mid(Temp, i, 4)

'In Australia PostCodes are 4 digits
If VBA.Mid(Temp, i, 1) <> " " And IsNumeric(postCode) Then

    If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
    ActiveSheet.Range("PostCode") = postCode
    Else
      If MsgBox("Post Code: " & postCode, vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("PostCode") = postCode
    End If

    'Lookup the Suburb and State based on the PostCode, the PostCode sheet has the lookup
    Dim mySuburbArray As Range
    Set mySuburbArray = Sheets("PostCodes").Range("A2:B16670")

    Dim suburbs As String
    For j = 1 To mySuburbArray.Columns(1).Cells.Count
    If mySuburbArray.Cells(j, 1) = postCode Then
        'Check if the suburb is listed in the address
        If InStr(1, UCase(Temp), mySuburbArray.Cells(j, 2), vbTextCompare) > 0 Then

        'Set the Suburb and State
        ActiveSheet.Range("Suburb") = mySuburbArray.Cells(j, 2)
        Stat = mySuburbArray.Cells(j, 3)
        ActiveSheet.Range("State") = Stat

        'Knowing the State - for Australia we can get the telephone Ext
        PhExt = PhExtension(VBA.UCase(Stat))
        ActiveSheet.Range("PhExt") = PhExt

        'remove the phone extension from the number
        Dim prePhone As String
        prePhone = ActiveSheet.Range("Phone")
        prePhone = Replace(prePhone, PhExt & " ", "")
        prePhone = Replace(prePhone, "(" & PhExt & ") ", "")
        prePhone = Replace(prePhone, "(" & PhExt & ")", "")
        ActiveSheet.Range("Phone") = prePhone
        Exit For
        End If
    End If
    Next j
Exit For
End If
Next i

End Sub


Private Function PhExtension(ByVal State As String) As String
Select Case State
Case Is = "NSW"
PhExtension = "02"
Case Is = "QLD"
PhExtension = "07"
Case Is = "VIC"
PhExtension = "03"
Case Is = "NT"
PhExtension = "04"
Case Is = "WA"
PhExtension = "05"
Case Is = "SA"
PhExtension = "07"
Case Is = "TAS"
PhExtension = "06"
End Select
End Function

Private Function Ph(ByVal Num As Integer) As String
Select Case Num
Case Is = 0
Ph = "PH"
Case Is = 1
Ph = "PHONE"
'Case Is = 2
'Ph = "P"
End Select
End Function

Private Function Mb(ByVal Num As Integer) As String
Select Case Num
Case Is = 0
Mb = "MB"
Case Is = 1
Mb = "MOB"
Case Is = 2
Mb = "CELL"
Case Is = 3
Mb = "MOBILE"
'Case Is = 4
'Mb = "M"
End Select
End Function

Private Function Fax(ByVal Num As Integer) As String
Select Case Num
Case Is = 0
Fax = "FAX"
Case Is = 1
Fax = "FACSIMILE"
'Case Is = 2
'Fax = "F"
End Select
End Function

Private Function State(ByVal Num As Integer) As String
Select Case Num
Case Is = 0
State = "NSW"
Case Is = 1
State = "QLD"
Case Is = 2
State = "VIC"
Case Is = 3
State = "NT"
Case Is = 4
State = "WA"
Case Is = 5
State = "SA"
Case Is = 6
State = "TAS"
End Select
End Function

Private Function Street(ByVal Num As Integer) As String
Select Case Num
Case Is = 0
Street = " ST"
Case Is = 1
Street = " RD"
Case Is = 2
Street = " AVE"
Case Is = 3
Street = " AV"
Case Is = 4
Street = " CRES"
Case Is = 5
Street = " LOOP"
Case Is = 6
Street = "PO BOX"
Case Is = 7
Street = " STREET"
Case Is = 8
Street = " ROAD"
Case Is = 9
Street = " AVENUE"
Case Is = 10
Street = " CRESENT"
Case Is = 11
Street = " PARADE"
Case Is = 12
Street = " PDE"
Case Is = 13
Street = " LANE"
Case Is = 14
Street = " COURT"
Case Is = 15
Street = " BLVD"
Case Is = 16
Street = "P.O. BOX"
Case Is = 17
Street = "P.O BOX"
Case Is = 18
Street = "PO BOX"
Case Is = 19
Street = "POBOX"
End Select
End Function

How to embed YouTube videos in PHP?

Do not store the embed code in your database -- YouTube may change the embed code and URL parameters from time to time. For example the <object> embed code has been retired in favor of <iframe> embed code. You should parse out the video id from the URL/embed code (using regular expressions, URL parsing functions or HTML parser) and store it. Then display it using whatever mechanism currently offered by YouTube API.

A naive PHP example for extracting the video id is as follows:

<?php
    preg_match(
        '/[\\?\\&]v=([^\\?\\&]+)/',
        'http://www.youtube.com/watch?v=OzHvVoUGTOM&feature=channel',
        $matches
    );
    // $matches[1] should contain the youtube id
?>

I suggest that you look at these articles to figure out what to do with these ids:

To create your own YouTube video player:

How to read lines of a file in Ruby

I believe my answer covers your new concerns about handling any type of line endings since both "\r\n" and "\r" are converted to Linux standard "\n" before parsing the lines.

To support the "\r" EOL character along with the regular "\n", and "\r\n" from Windows, here's what I would do:

line_num=0
text=File.open('xxx.txt').read
text.gsub!(/\r\n?/, "\n")
text.each_line do |line|
  print "#{line_num += 1} #{line}"
end

Of course this could be a bad idea on very large files since it means loading the whole file into memory.

regular expression for DOT

You should use contains not matches

if(nom.contains("."))
    System.out.println("OK");
else
    System.out.println("Bad");

Android check null or empty string in Android

From @Jon Skeet comment, really the String value is "null". Following code solved it

if (userEmail != null && !userEmail.isEmpty() && !userEmail.equals("null")) 

Creating a Plot Window of a Particular Size

As the accepted solution of @Shane is not supported in RStudio (see here) as of now (Sep 2015), I would like to add an advice to @James Thompson answer regarding workflow:

If you use SumatraPDF as viewer you do not need to close the PDF file before making changes to it. Sumatra does not put a opened file in read-only and thus does not prevent it from being overwritten. Therefore, once you opened your PDF file with Sumatra, changes out of RStudio (or any other R IDE) are immediately displayed in Sumatra.

Setting property 'source' to 'org.eclipse.jst.jee.server:JSFTut' did not find a matching property

Remove the project from the server from the Server View. Then run the project under the same server.

The problem is as @BalusC told corrupt of server.xml of tomcat which is configured in the eclipse. So when you do the above process server.xml will be recreated .

How to clear radio button in Javascript?

if the id of the radio buttons are 'male' and 'female', value reset can be done by using jquery

$('input[id=male]').attr('checked',false);
$('input[id=female]').attr('checked',false);

How do I concatenate strings?

2020 Update: Concatenation by String Interpolation

RFC 2795 issued 2019-10-27: Suggests support for implicit arguments to do what many people would know as "string interpolation" -- a way of embedding arguments within a string to concatenate them.

RFC: https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html

Latest issue status can be found here: https://github.com/rust-lang/rust/issues/67984

At the time of this writing (2020-9-24), I believe this feature should be available in the Rust Nightly build.

This will allow you to concatenate via the following shorthand:

format_args!("hello {person}")

It is equivalent to this:

format_args!("hello {person}", person=person)

There is also the "ifmt" crate, which provides its own kind of string interpolation:

https://crates.io/crates/ifmt

How to create a localhost server to run an AngularJS project

cd <your project folder> (where your angularjs's deployable code is there)

sudo npm install serve -g

serve

You can hit your page at

localhost:3000 or IPaddress:3000

List file names based on a filename pattern and file content?

It can be done without find as well by using grep's "--include" option.

grep man page says:

--include=GLOB
Search only files whose base name matches GLOB (using wildcard matching as described under --exclude).

So to do a recursive search for a string in a file matching a specific pattern, it will look something like this:

grep -r --include=<pattern> <string> <directory>

For example, to recursively search for string "mytarget" in all Makefiles:

grep -r --include="Makefile" "mytarget" ./

Or to search in all files starting with "Make" in filename:

grep -r --include="Make*" "mytarget" ./

Automated way to convert XML files to SQL database?

If there is XML file with 2 different tables then will:

LOAD XML LOCAL INFILE 'table1.xml' INTO TABLE table1 
LOAD XML LOCAL INFILE 'table1.xml' INTO TABLE table2

work

What does upstream mean in nginx?

It's used for proxying requests to other servers.

An example from http://wiki.nginx.org/LoadBalanceExample is:

http {
  upstream myproject {
    server 127.0.0.1:8000 weight=3;
    server 127.0.0.1:8001;
    server 127.0.0.1:8002;    
    server 127.0.0.1:8003;
  }

  server {
    listen 80;
    server_name www.domain.com;
    location / {
      proxy_pass http://myproject;
    }
  }
}

This means all requests for / go to the any of the servers listed under upstream XXX, with a preference for port 8000.

Sending HTML email using Python

Actually, yagmail took a bit different approach.

It will by default send HTML, with automatic fallback for incapable email-readers. It is not the 17th century anymore.

Of course, it can be overridden, but here goes:

import yagmail
yag = yagmail.SMTP("[email protected]", "mypassword")

html_msg = """<p>Hi!<br>
              How are you?<br>
              Here is the <a href="http://www.python.org">link</a> you wanted.</p>"""

yag.send("[email protected]", "the subject", html_msg)

For installation instructions and many more great features, have a look at the github.

Django MEDIA_URL and MEDIA_ROOT

Your setting is all right. Some web servers require to specify the media and static folder files specifically. For example in pythonanywhere.com you have to go to the 'Web' section and add the url od the media folders and static folder. For example:

  URL                     Directory                
/static/            /home/Saidmamad/discoverthepamirs/static     
/accounts/static/   /home/Saidmamad/discoverthepamirs/accounts/static    
/media/            /home/Saidmamad/discoverthepamirs/discoverthepamirs/media    

I know that it is late, but just to help those who visit this link because of the same problem ;)

How do I "break" out of an if statement?

You probably need to break up your if statement into smaller pieces. That being said, you can do two things:

  • wrap the statement into do {} while (false) and use real break (not recommended!!! huge kludge!!!)

  • put the statement into its own subroutine and use return This may be the first step to improving your code.

How do I supply an initial value to a text field?

class _YourClassState extends State<YourClass> {
  TextEditingController _controller = TextEditingController();

  @override
  void initState() {
    super.initState();
    _controller.text = 'Your message';
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: TextFormField(
        controller: _controller,
        decoration: InputDecoration(labelText: 'Send message...'),
      ),
    );
  }
}

webpack: Module not found: Error: Can't resolve (with relative path)

Had the same issue with module not found. Turns out I had a component import Picture from './Picture/Picture'; at the very bottom of all the imports. When I moved it below import React, { Component } from 'react';, it worked.

How do I get a human-readable file size in bytes abbreviation using .NET?

Mixture of all solutions :-)

    /// <summary>
    /// Converts a numeric value into a string that represents the number expressed as a size value in bytes,
    /// kilobytes, megabytes, or gigabytes, depending on the size.
    /// </summary>
    /// <param name="fileSize">The numeric value to be converted.</param>
    /// <returns>The converted string.</returns>
    public static string FormatByteSize(double fileSize)
    {
        FileSizeUnit unit = FileSizeUnit.B;
        while (fileSize >= 1024 && unit < FileSizeUnit.YB)
        {
            fileSize = fileSize / 1024;
            unit++;
        }
        return string.Format("{0:0.##} {1}", fileSize, unit);
    }

    /// <summary>
    /// Converts a numeric value into a string that represents the number expressed as a size value in bytes,
    /// kilobytes, megabytes, or gigabytes, depending on the size.
    /// </summary>
    /// <param name="fileInfo"></param>
    /// <returns>The converted string.</returns>
    public static string FormatByteSize(FileInfo fileInfo)
    {
        return FormatByteSize(fileInfo.Length);
    }
}

public enum FileSizeUnit : byte
{
    B,
    KB,
    MB,
    GB,
    TB,
    PB,
    EB,
    ZB,
    YB
}

IE8 crashes when loading website - res://ieframe.dll/acr_error.htm

I had this happening with a Drupal theme. None of the many suggestions on various threads (change IE security settings or some other advanced settings, update Java, update Flash, fiddle with registry, remove certain Windows updates, check plugins, scan for malware, completely reinstall IE8) worked for me.

In this case, it turned out to be a problem with setting a background-image on a body element - changing body to an html element fixed things. It is apparently related to loading respond.js - try putting that at the bottom.

How is a JavaScript hash map implemented?

<html>
<head>
<script type="text/javascript">
function test(){
var map= {'m1': 12,'m2': 13,'m3': 14,'m4': 15}
     alert(map['m3']);
}
</script>
</head>
<body>
<input type="button" value="click" onclick="test()"/>
</body>
</html>

How do I install TensorFlow's tensorboard?

The pip package you are looking for is tensorflow-tensorboard developed by Google.

Using @property versus getters and setters

I think both have their place. One issue with using @property is that it is hard to extend the behaviour of getters or setters in subclasses using standard class mechanisms. The problem is that the actual getter/setter functions are hidden in the property.

You can actually get hold of the functions, e.g. with

class C(object):
    _p = 1
    @property
    def p(self):
        return self._p
    @p.setter
    def p(self, val):
        self._p = val

you can access the getter and setter functions as C.p.fget and C.p.fset, but you can't easily use the normal method inheritance (e.g. super) facilities to extend them. After some digging into the intricacies of super, you can indeed use super in this way:

# Using super():
class D(C):
    # Cannot use super(D,D) here to define the property
    # since D is not yet defined in this scope.
    @property
    def p(self):
        return super(D,D).p.fget(self)

    @p.setter
    def p(self, val):
        print 'Implement extra functionality here for D'
        super(D,D).p.fset(self, val)

# Using a direct reference to C
class E(C):
    p = C.p

    @p.setter
    def p(self, val):
        print 'Implement extra functionality here for E'
        C.p.fset(self, val)

Using super() is, however, quite clunky, since the property has to be redefined, and you have to use the slightly counter-intuitive super(cls,cls) mechanism to get an unbound copy of p.

Cannot download Docker images behind a proxy

The complete solution for Windows, to configure the proxy settings.

< user>:< password>@< proxy-host>:< proxy-port>

You can configure it directly by right-clicking on settings, in the Docker icon, and then Proxies.

There you can configure the proxy address, port, user name, and password.

In this format:

< user>:< password>@< proxy-host>:< proxy-port>

Example:

"geronimous:[email protected]:8080"

Nothing more than this.

For each row return the column name of the largest value

Here is an answer that works with data.table and is simpler. This assumes your data.table is named yourDF:

j1 <- max.col(yourDF[, .(V1, V2, V3, V4)], "first")
yourDF$newCol <- c("V1", "V2", "V3", "V4")[j1]

Replace ("V1", "V2", "V3", "V4") and (V1, V2, V3, V4) with your column names

Turning off auto indent when pasting text into vim

Add this to your ~/.vimrc and you will only have to press F2 before and after pasting:

set pastetoggle=<F2>

Circle line-segment collision detection algorithm?

I have created this function for iOS following the answer given by chmike

+ (NSArray *)intersectionPointsOfCircleWithCenter:(CGPoint)center withRadius:(float)radius toLinePoint1:(CGPoint)p1 andLinePoint2:(CGPoint)p2
{
    NSMutableArray *intersectionPoints = [NSMutableArray array];

    float Ax = p1.x;
    float Ay = p1.y;
    float Bx = p2.x;
    float By = p2.y;
    float Cx = center.x;
    float Cy = center.y;
    float R = radius;


    // compute the euclidean distance between A and B
    float LAB = sqrt( pow(Bx-Ax, 2)+pow(By-Ay, 2) );

    // compute the direction vector D from A to B
    float Dx = (Bx-Ax)/LAB;
    float Dy = (By-Ay)/LAB;

    // Now the line equation is x = Dx*t + Ax, y = Dy*t + Ay with 0 <= t <= 1.

    // compute the value t of the closest point to the circle center (Cx, Cy)
    float t = Dx*(Cx-Ax) + Dy*(Cy-Ay);

    // This is the projection of C on the line from A to B.

    // compute the coordinates of the point E on line and closest to C
    float Ex = t*Dx+Ax;
    float Ey = t*Dy+Ay;

    // compute the euclidean distance from E to C
    float LEC = sqrt( pow(Ex-Cx, 2)+ pow(Ey-Cy, 2) );

    // test if the line intersects the circle
    if( LEC < R )
    {
        // compute distance from t to circle intersection point
        float dt = sqrt( pow(R, 2) - pow(LEC,2) );

        // compute first intersection point
        float Fx = (t-dt)*Dx + Ax;
        float Fy = (t-dt)*Dy + Ay;

        // compute second intersection point
        float Gx = (t+dt)*Dx + Ax;
        float Gy = (t+dt)*Dy + Ay;

        [intersectionPoints addObject:[NSValue valueWithCGPoint:CGPointMake(Fx, Fy)]];
        [intersectionPoints addObject:[NSValue valueWithCGPoint:CGPointMake(Gx, Gy)]];
    }

    // else test if the line is tangent to circle
    else if( LEC == R ) {
        // tangent point to circle is E
        [intersectionPoints addObject:[NSValue valueWithCGPoint:CGPointMake(Ex, Ey)]];
    }
    else {
        // line doesn't touch circle
    }

    return intersectionPoints;
}

C# Interfaces. Implicit implementation versus Explicit implementation

One important use of explicit interface implementation is when in need to implement interfaces with mixed visibility.

The problem and solution are well explained in the article C# Internal Interface.

For example, if you want to protect leakage of objects between application layers, this technique allows you to specify different visibility of members that could cause the leakage.

How to silence output in a Bash script?

Redirect stderr to stdout

This will redirect the stderr (which is descriptor 2) to the file descriptor 1 which is the the stdout.

2>&1

Redirect stdout to File

Now when perform this you are redirecting the stdout to the file sample.s

myprogram > sample.s

Redirect stderr and stdout to File

Combining the two commands will result in redirecting both stderr and stdout to sample.s

myprogram > sample.s 2>&1

Redirect stderr and stdout to /dev/null

Redirect to /dev/null if you want to completely silent your application.

myprogram >/dev/null 2>&1

How do I authenticate a WebClient request?

What kind of authentication are you using? If it's Forms authentication, then at best, you'll have to find the .ASPXAUTH cookie and pass it in the WebClient request.

At worst, it won't work.

Position Relative vs Absolute?

Let's discuss a scenario to explain the difference between absolute vs relative.

Inside the body element say you have an header element whose height is 95% of viewheight i.e 95vh. Within this container you placed an image and reduced it's opacity to say 0.5. And now you want to place a logo image near the top left corner. I hope you understood the scenario. So you will have a lighter image in the header section with a logo on the top of it at the specified position.

But before starting this, i have set margin and padding to 0 like this

*{
   margin:0px;
   padding:0px;
   box-sizing: border-box; 
}

This ensures no default margins and padding is applied to elements.

So you can achieve your requirement in two ways.

First Way

  • you give a class to the image say logo.
  • in css you write

    .logo{ float:left; margin-top:40px; margin-left:40px; }

  • this placed the logo to the 40px from the top and left of the enclosing parent which is the header. The image will appear as if it placed as desired.

But my friend this is a bad design as to place an image you unnecessarily consumed so much of space around by giving it some margin when it was not required. All you needed is to place the image to that location. You managed it by cushioning it with margins around. The margin took space and pushed it's content deeper giving an impression that it is positioned exactly where you wanted. Hope you understood the issue by working it around like this. You are taking more space than required to place just an image at the desired location.

Now let's try a different approach.

Second Way

  • the image with logo class is inside the header element with say header class. So the parent class is header and the child class is logo as before.
  • you set the position property of the header class to relative like this

    .header{ position: relative; }

  • then you added the following properties to the logo class

    .logo{ position:absolute; top:40px; left:40px }

There you go. You placed the image at exactly the same place. There won't be any apparent difference in the positioning from the naked eye between the first approach and second approach. But if you inspect the image element , you will find that it has not taken any extra space. It's occupying exactly the same area as much as it's own width and height.

So how is this possible? I said to the image logo class that you will be placed relative to the header class as you are the child of this class and that i specifically mentioned it's position as relative. So that any child of it's will be placed relative to it's top left corner. And that Your position need to be fixed inside this parent element. so you are given absolute. And That you need to move a little from top and left to the position i want you to be. Hence you are given top and left property with 40px as value. In this way you will be placed relative to your parent only. So if tomorrow i move your parent up or down or just anywhere, you will always be 40px to the top and left of your parent header's top left corner. So your position is fixed inside your parent no matter whether your parent's position is fixed or not in future(as it is not absolute like you).

So use relative and absolute for parent and child respectively. Secondly use it when you want to only place the child element at some location inside it's parent element. Do not use fillers like margins to push it forcibly. Give parent relative value and child which you want to move, the absolute value. Specify top, left bottom or right property to child class to place it inside parent anywhere you want.

Thanks.

how to execute a scp command with the user name and password in one line

Using sshpass works best. To just include your password in scp use the ' ':

scp user1:'password'@xxx.xxx.x.5:sys_config /var/www/dev/

How do I find where JDK is installed on my windows machine?

More on Windows... variable java.home is not always the same location as the binary that is run.

As Denis The Menace says, the installer puts Java files into Program Files, but also java.exe into System32. With nothing Java related on the path java -version can still work. However when PeterMmm's program is run it reports the value of Program Files as java.home, this is not wrong (Java is installed there) but the actual binary being run is located in System32.

One way to hunt down the location of the java.exe binary, add the following line to PeterMmm's code to keep the program running a while longer:

try{Thread.sleep(60000);}catch(Exception e) {}

Compile and run it, then hunt down the location of the java.exe image. E.g. in Windows 7 open the task manager, find the java.exe entry, right click and select 'open file location', this opens the exact location of the Java binary. In this case it would be System32.

How to use patterns in a case statement?

Brace expansion doesn't work, but *, ? and [] do. If you set shopt -s extglob then you can also use extended pattern matching:

  • ?() - zero or one occurrences of pattern
  • *() - zero or more occurrences of pattern
  • +() - one or more occurrences of pattern
  • @() - one occurrence of pattern
  • !() - anything except the pattern

Here's an example:

shopt -s extglob
for arg in apple be cd meet o mississippi
do
    # call functions based on arguments
    case "$arg" in
        a*             ) foo;;    # matches anything starting with "a"
        b?             ) bar;;    # matches any two-character string starting with "b"
        c[de]          ) baz;;    # matches "cd" or "ce"
        me?(e)t        ) qux;;    # matches "met" or "meet"
        @(a|e|i|o|u)   ) fuzz;;   # matches one vowel
        m+(iss)?(ippi) ) fizz;;   # matches "miss" or "mississippi" or others
        *              ) bazinga;; # catchall, matches anything not matched above
    esac
done

from jquery $.ajax to angular $http

We can implement ajax request by using http service in AngularJs, which helps to read/load data from remote server.

$http service methods are listed below,

 $http.get()
 $http.post()
 $http.delete()
 $http.head()
 $http.jsonp()
 $http.patch()
 $http.put()

One of the Example:

    $http.get("sample.php")
        .success(function(response) {
            $scope.getting = response.data; // response.data is an array
    }).error(){

        // Error callback will trigger
    });

http://www.drtuts.com/ajax-requests-angularjs/

Difference between "include" and "require" in php

Use include if you don't mind your script continuing without loading the file (in case it doesn't exist etc) and you can (although you shouldn't) live with a Warning error message being displayed.

Using require means your script will halt if it can't load the specified file, and throw a Fatal error.

Add up a column of numbers at the Unix shell

sizes=( $(cat files.txt | xargs ls -l | cut -c 23-30) )
total=$(( $(IFS="+"; echo "${sizes[*]}") ))

Or you could just sum them as you read the sizes

declare -i total=0
while read x; total+=x; done < <( cat files.txt | xargs ls -l | cut -c 23-30 )

If you don't care about bite sizes and blocks is OK, then just

declare -i total=0
while read s junk; total+=s; done < <( cat files.txt | xargs ls -s )

require_once :failed to open stream: no such file or directory

It says that the file C:\wamp\www\mysite\php\includes\dbconn.inc doesn't exist, so the error is, you're missing the file.

Regular expression: find spaces (tabs/space) but not newlines

If you want to replace space below code worked for me in C#

Regex.Replace(Line,"\\\s","");

For Tab

Regex.Replace(Line,"\\\s\\\s","");

Android dex gives a BufferOverflowException when building

Same problem here. Reverted to build tools 18.1.1, restarted Eclipse and that fixed it.

Find the IP address of the client in an SSH session

who am i | awk '{print $5}' | sed 's/[()]//g' | cut -f1 -d "." | sed 's/-/./g'


export DISPLAY=`who am i | awk '{print $5}' | sed 's/[()]//g' | cut -f1 -d "." | sed 's/-/./g'`:0.0

I use this to determine my DISPLAY variable for the session when logging in via ssh and need to display remote X.

How do I auto-submit an upload form when a file is selected?

Try bellow code with jquery :

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>

<script>
$(document).ready(function(){
    $('#myForm').on('change', "input#MyFile", function (e) {
        e.preventDefault();
        $("#myForm").submit();
    });
});
</script>
<body>
    <div id="content">
        <form id="myForm" action="action.php" method="POST" enctype="multipart/form-data">
            <input type="file" id="MyFile" value="Upload" />
        </form>
    </div>
</body>
</html>