Programs & Examples On #Tsv

Tab-Separated Values (TSV) is a format for storing text data in columns separated by tabs.

PHP to write Tab Characters inside a file?

The tab character is \t. Notice the use of " instead of '.

$chunk = "abc\tdef\tghi";

PHP Strings - Double quoted

If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:

...

\t horizontal tab (HT or 0x09 (9) in ASCII)


Also, let me recommend the fputcsv() function which is for the purpose of writing CSV files.

Can I set max_retries for requests.request?

After struggling a bit with some of the answers here, I found a library called backoff that worked better for my situation. A basic example:

import backoff

@backoff.on_exception(
    backoff.expo,
    requests.exceptions.RequestException,
    max_tries=5,
    giveup=lambda e: e.response is not None and e.response.status_code < 500
)
def publish(self, data):
    r = requests.post(url, timeout=10, json=data)
    r.raise_for_status()

I'd still recommend giving the library's native functionality a shot, but if you run into any problems or need broader control, backoff is an option.

How to determine when Fragment becomes visible in ViewPager

This seems to restore the normal onResume() behavior that you would expect. It plays well with pressing the home key to leave the app and then re-entering the app. onResume() is not called twice in a row.

@Override
public void setUserVisibleHint(boolean visible)
{
    super.setUserVisibleHint(visible);
    if (visible && isResumed())
    {
        //Only manually call onResume if fragment is already visible
        //Otherwise allow natural fragment lifecycle to call onResume
        onResume();
    }
}

@Override
public void onResume()
{
    super.onResume();
    if (!getUserVisibleHint())
    {
        return;
    }

    //INSERT CUSTOM CODE HERE
}

How to unblock with mysqladmin flush hosts

mysqladmin is not a SQL statement. It's a little helper utility program you'll find on your MySQL server... and "flush-hosts" is one of the things it can do. ("status" and "shutdown" are a couple of other things that come to mind).

You type that command from a shell prompt.

Alternately, from your query browser (such as phpMyAdmin), the SQL statement you're looking for is simply this:

FLUSH HOSTS;

http://dev.mysql.com/doc/refman/5.6/en/flush.html

http://dev.mysql.com/doc/refman/5.6/en/mysqladmin.html

JQuery/Javascript: check if var exists

For your case, and 99.9% of all others elclanrs answer is correct.

But because undefined is a valid value, if someone were to test for an uninitialized variable

var pagetype; //== undefined
if (typeof pagetype === 'undefined') //true

the only 100% reliable way to determine if a var exists is to catch the exception;

var exists = false;
try { pagetype; exists = true;} catch(e) {}
if (exists && ...) {}

But I would never write it this way

Running unittest with typical test directory structure

If you are looking for a command line-only solution:

Based on the following directory structure (generalized with a dedicated source directory):

new_project/
    src/
        antigravity.py
    test/
        test_antigravity.py

Windows: (in new_project)

$ set PYTHONPATH=%PYTHONPATH%;%cd%\src
$ python -m unittest discover -s test

See this question if you want to use this in a batch for-loop.

Linux: (in new_project)

$ export PYTHONPATH=$PYTHONPATH:$(pwd)/src  [I think - please edit this answer if you are a Linux user and you know this]
$ python -m unittest discover -s test

With this approach, it is also possible to add more directories to the PYTHONPATH if necessary.

How to sum array of numbers in Ruby?

Ruby 2.4.0 is released, and it has an Enumerable#sum method. So you can do

array.sum

Examples from the docs:

{ 1 => 10, 2 => 20 }.sum {|k, v| k * v }  #=> 50
(1..10).sum                               #=> 55
(1..10).sum {|v| v * 2 }                  #=> 110

CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found

Look in the Cmakelists.txt if you find ARM you need to install C++ for ARM

It's these packages:

C++ Universal Windows Platform for ARM64 "Not Required"

Visual C++ Compilers and libraries for ARM "Not Required"

Visual C++ Compilers and libraries for ARM64 "Very Likely Required"

Required for finding Threads on ARM 
enable_language(C) 
enable_language(CXX)

Then the problems

No CMAKE_C_COMPILER could be found.

No CMAKE_CXX_COMPILER could be found.

Might disappear unless you specify c compiler like clang, and maybe installing clang will work in other favour.

You can with optional remove in cmakelists.txt both with # before enable_language if you are not compiling for ARM.

Meaning of 'const' last in a function declaration of a class?

Here const means that at that function any variable's value can not change

class Test{
private:
    int a;
public:
    void test()const{
        a = 10;
    }
};

And like this example, if you try to change the value of a variable in the test function you will get an error.

Brew doctor says: "Warning: /usr/local/include isn't writable."

I just want to echo sam9046's modest comment as an alternative and potentially much easier solution that worked in my case: uninstall and install homebrew again from scratch. No sudo commands required.

You can also browse/modify the uninstall script from that link above if you need to ensure it won't affect your previously installed packages. In my case this was just my home machine so I just started over.

How can I trigger another job from a jenkins pipeline (jenkinsfile) with GitHub Org Plugin?

You can use the build job step from Jenkins Pipeline (Minimum Jenkins requirement: 2.130).

Here's the full API for the build step: https://jenkins.io/doc/pipeline/steps/pipeline-build-step/

How to use build:

  • job: Name of a downstream job to build. May be another Pipeline job, but more commonly a freestyle or other project.
    • Use a simple name if the job is in the same folder as this upstream Pipeline job;
    • You can instead use relative paths like ../sister-folder/downstream
    • Or you can use absolute paths like /top-level-folder/nested-folder/downstream

Trigger another job using a branch as a param

At my company many of our branches include "/". You must replace any instances of "/" with "%2F" (as it appears in the URL of the job).

In this example we're using relative paths

    stage('Trigger Branch Build') {
        steps {
            script {
                    echo "Triggering job for branch ${env.BRANCH_NAME}"
                    BRANCH_TO_TAG=env.BRANCH_NAME.replace("/","%2F")
                    build job: "../my-relative-job/${BRANCH_TO_TAG}", wait: false
            }
        }
    }

Trigger another job using build number as a param

build job: 'your-job-name', 
    parameters: [
        string(name: 'passed_build_number_param', value: String.valueOf(BUILD_NUMBER)),
        string(name: 'complex_param', value: 'prefix-' + String.valueOf(BUILD_NUMBER))
    ]

Trigger many jobs in parallel

Source: https://jenkins.io/blog/2017/01/19/converting-conditional-to-pipeline/

More info on Parallel here: https://jenkins.io/doc/book/pipeline/syntax/#parallel

    stage ('Trigger Builds In Parallel') {
        steps {
            // Freestyle build trigger calls a list of jobs
            // Pipeline build() step only calls one job
            // To run all three jobs in parallel, we use "parallel" step
            // https://jenkins.io/doc/pipeline/examples/#jobs-in-parallel
            parallel (
                linux: {
                    build job: 'full-build-linux', parameters: [string(name: 'GIT_BRANCH_NAME', value: env.BRANCH_NAME)]
                },
                mac: {
                    build job: 'full-build-mac', parameters: [string(name: 'GIT_BRANCH_NAME', value: env.BRANCH_NAME)]
                },
                windows: {
                    build job: 'full-build-windows', parameters: [string(name: 'GIT_BRANCH_NAME', value: env.BRANCH_NAME)]
                },
                failFast: false)
        }
    }

Or alternatively:

    stage('Build A and B') {
            failFast true
            parallel {
                stage('Build A') {
                    steps {
                            build job: "/project/A/${env.BRANCH}", wait: true
                    }
                }
                stage('Build B') {
                    steps {
                            build job: "/project/B/${env.BRANCH}", wait: true
                    }
                }
            }
    }

For Loop on Lua

names = {'John', 'Joe', 'Steve'}
for names = 1, 3 do
  print (names)
end
  1. You're deleting your table and replacing it with an int
  2. You aren't pulling a value from the table

Try:

names = {'John','Joe','Steve'}
for i = 1,3 do
    print(names[i])
end

How to check for an empty object in an AngularJS view

You should not initialize your variable to an empty object, but let it be undefined or null until the conditions exist where it should have a non-null/undefined value:

$scope.card;

if (someCondition = true) {
    $scope.card = {};
}

Then your template:

ng-show="card"

POST request via RestTemplate in JSON

Why work harder than you have to? postForEntity accepts a simple Map object as input. The following works fine for me while writing tests for a given REST endpoint in Spring. I believe it's the simplest possible way of making a JSON POST request in Spring:

@Test
public void shouldLoginSuccessfully() {
  // 'restTemplate' below has been @Autowired prior to this
  Map map = new HashMap<String, String>();
  map.put("username", "bob123");
  map.put("password", "myP@ssw0rd");
  ResponseEntity<Void> resp = restTemplate.postForEntity(
      "http://localhost:8000/login",
      map,
      Void.class);
  assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
}

Print range of numbers on same line

for i in range(10):
    print(i, end = ' ')

You can provide any delimiter to the end field (space, comma etc.)

This is for Python 3

CMD: How do I recursively remove the "Hidden"-Attribute of files and directories

You can't remove hidden without also removing system.

You want:

cd mydir
attrib -H -S /D /S

That will remove the hidden and system attributes from all the files/folders inside of your current directory.

How to sort in mongoose?

This is what i did, it works fine.

User.find({name:'Thava'}, null, {sort: { name : 1 }})

Error "There is already an open DataReader associated with this Command which must be closed first" when using 2 distinct commands

Try to combine the query, it will run much faster than executing an additional query per row. Ik don't like the string[] you're using, i would create a class for holding the information.

    public List<string[]> get_dados_historico_verificacao_email_WEB(string email)
    {
        List<string[]> historicos = new List<string[]>();

        using (SqlConnection conexao = new SqlConnection("ConnectionString"))
        {
            string sql =
                @"SELECT    *, 
                            (   SELECT      COUNT(e.cd_historico_verificacao_email) 
                                FROM        emails_lidos e 
                                WHERE       e.cd_historico_verificacao_email = a.nm_email ) QT
                  FROM      historico_verificacao_email a
                  WHERE     nm_email = @email
                  ORDER BY  dt_verificacao_email DESC, 
                            hr_verificacao_email DESC";

            using (SqlCommand com = new SqlCommand(sql, conexao))
            {
                com.Parameters.Add("email", SqlDbType.VarChar).Value = email;

                SqlDataReader dr = com.ExecuteReader();

                while (dr.Read())
                {
                    string[] dados_historico = new string[6];
                    dados_historico[0] = dr["nm_email"].ToString();
                    dados_historico[1] = dr["dt_verificacao_email"].ToString();
                    dados_historico[1] = dados_historico[1].Substring(0, 10);
                    //System.Windows.Forms.MessageBox.Show(dados_historico[1]);
                    dados_historico[2] = dr["hr_verificacao_email"].ToString();
                    dados_historico[3] = dr["ds_tipo_verificacao"].ToString();
                    dados_historico[4] = dr["QT"].ToString();
                    dados_historico[5] = dr["cd_login_usuario"].ToString();

                    historicos.Add(dados_historico);
                }
            }
        }
        return historicos;
    }

Untested, but maybee gives some idea.

no operator "<<" matches these operands

You're not including the standard <string> header.

You got [un]lucky that some of its pertinent definitions were accidentally made available by the other standard headers that you did include ... but operator<< was not.

regular expression for Indian mobile numbers

Here's a regex designed to match typical phone numbers:

^(((\+?\(91\))|0|((00|\+)?91))-?)?[7-9]\d{9}$

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

To me it happened in DogController that autowired DogService that autowired DogRepository. Dog class used to have field name but I changed it to coolName, but didn't change methods in DogRepository: Dog findDogByName(String name). I change that method to Dog findDogByCoolName(String name) and now it works.

Get the Application Context In Fragment In Android?

Add this to onCreate

// Getting application context
        Context context = getActivity();

How to use OR condition in a JavaScript IF statement?

More then one condition statement is needed to use OR(||) operator in if conditions and notation is ||.

if(condition || condition){ 
   some stuff
}

How to populate options of h:selectOneMenu from database?

I'm doing it like this:

  1. Models are ViewScoped

  2. converter:

    @Named
    @ViewScoped
    public class ViewScopedFacesConverter implements Converter, Serializable
    {
            private static final long serialVersionUID = 1L;
            private Map<String, Object> converterMap;
    
            @PostConstruct
            void postConstruct(){
                converterMap = new HashMap<>();
            }
    
            @Override
            public String getAsString(FacesContext context, UIComponent component, Object object) {
                String selectItemValue = String.valueOf( object.hashCode() ); 
                converterMap.put( selectItemValue, object );
                return selectItemValue;
            }
    
            @Override
            public Object getAsObject(FacesContext context, UIComponent component, String selectItemValue){
                return converterMap.get(selectItemValue);
            }
    }
    

and bind to component with:

 <f:converter binding="#{viewScopedFacesConverter}" />

If you will use entity id rather than hashCode you can hit a collision- if you have few lists on one page for different entities (classes) with the same id

Get Selected value of a Combobox

A simpler way to get the selected value from a ComboBox control is:

Private Sub myComboBox_Change()
  msgbox "You selected: " + myComboBox.SelText
End Sub

How to get index using LINQ?

I will make my contribution here... why? just because :p Its a different implementation, based on the Any LINQ extension, and a delegate. Here it is:

public static class Extensions
{
    public static int IndexOf<T>(
            this IEnumerable<T> list, 
            Predicate<T> condition) {               
        int i = -1;
        return list.Any(x => { i++; return condition(x); }) ? i : -1;
    }
}

void Main()
{
    TestGetsFirstItem();
    TestGetsLastItem();
    TestGetsMinusOneOnNotFound();
    TestGetsMiddleItem();   
    TestGetsMinusOneOnEmptyList();
}

void TestGetsFirstItem()
{
    // Arrange
    var list = new string[] { "a", "b", "c", "d" };

    // Act
    int index = list.IndexOf(item => item.Equals("a"));

    // Assert
    if(index != 0)
    {
        throw new Exception("Index should be 0 but is: " + index);
    }

    "Test Successful".Dump();
}

void TestGetsLastItem()
{
    // Arrange
    var list = new string[] { "a", "b", "c", "d" };

    // Act
    int index = list.IndexOf(item => item.Equals("d"));

    // Assert
    if(index != 3)
    {
        throw new Exception("Index should be 3 but is: " + index);
    }

    "Test Successful".Dump();
}

void TestGetsMinusOneOnNotFound()
{
    // Arrange
    var list = new string[] { "a", "b", "c", "d" };

    // Act
    int index = list.IndexOf(item => item.Equals("e"));

    // Assert
    if(index != -1)
    {
        throw new Exception("Index should be -1 but is: " + index);
    }

    "Test Successful".Dump();
}

void TestGetsMinusOneOnEmptyList()
{
    // Arrange
    var list = new string[] {  };

    // Act
    int index = list.IndexOf(item => item.Equals("e"));

    // Assert
    if(index != -1)
    {
        throw new Exception("Index should be -1 but is: " + index);
    }

    "Test Successful".Dump();
}

void TestGetsMiddleItem()
{
    // Arrange
    var list = new string[] { "a", "b", "c", "d", "e" };

    // Act
    int index = list.IndexOf(item => item.Equals("c"));

    // Assert
    if(index != 2)
    {
        throw new Exception("Index should be 2 but is: " + index);
    }

    "Test Successful".Dump();
}        

What is an uber jar?

The different names are just ways of packaging java apps.

Skinny – Contains ONLY the bits you literally type into your code editor, and NOTHING else.

Thin – Contains all of the above PLUS the app’s direct dependencies of your app (db drivers, utility libraries, etc).

Hollow – The inverse of Thin – Contains only the bits needed to run your app but does NOT contain the app itself. Basically a pre-packaged “app server” to which you can later deploy your app, in the same style as traditional Java EE app servers, but with important differences.

Fat/Uber – Contains the bit you literally write yourself PLUS the direct dependencies of your app PLUS the bits needed to run your app “on its own”.

Source: Article from Dzone

Visual representation of JAR types

Reposted from: https://stackoverflow.com/a/57592130/9470346

How to redirect stderr to null in cmd.exe

Your DOS command 2> nul

Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.

How to handle checkboxes in ASP.NET MVC forms?

I'm surprised none of these answers used the built in MVC features for this.

I wrote a blog post about this here, which even actually links the labels to the checkbox. I used the EditorTemplate folder to accomplish this in a clean and modular way.

You will simply end up with a new file in the EditorTemplate folder that looks like this:

@model SampleObject

@Html.CheckBoxFor(m => m.IsChecked)
@Html.HiddenFor(m => m.Id)
@Html.LabelFor(m => m.IsChecked, Model.Id)

in your actual view, there will be no need to loop this, simply 1 line of code:

@Html.EditorFor(x => ViewData.Model)

Visit my blog post for more details.

C#: How to access an Excel cell?

How I work to automate Office / Excel:

  1. Record a macro, this will generate a VBA template
  2. Edit the VBA template so it will match my needs
  3. Convert to VB.Net (A small step for men)
  4. Leave it in VB.Net, Much more easy as doing it using C#

Maximum number of rows in an MS Access database engine table?

Here's my attempt:

I created a single-column (INTEGER) table with no key:

CREATE TABLE a (a INTEGER NOT NULL);

Inserted integers in sequence starting at 1.

I stopped it (arbitrarily after many hours) when it had inserted 65,632,875 rows. The file size was 1,029,772 KB.

I compacted the file which reduced it very slightly to 1,029,704 KB.

I added a PK:

ALTER TABLE a ADD CONSTRAINT p PRIMARY KEY (a);

which increased the file size to 1,467,708 KB.

This suggests the maximum is somewhere around the 80 million mark.

jQuery Loop through each div

You're right that it involves a loop, but this is, at least, made simple by use of the each() method:

$('.target').each(
    function(){
        // iterate through each of the `.target` elements, and do stuff in here
        // `this` and `$(this)` refer to the current `.target` element
        var images = $(this).find('img'),
            imageWidth = images.width(); // returns the width of the _first_ image
            numImages = images.length;
        $(this).css('width', (imageWidth*numImages));

    });

References:

Center button under form in bootstrap

Remove that <p> tag and add the button inside a <div class="form-actions"> like this:

<div class="form-actions">
    <button type="submit" class="btn">Confirm</button>
</div>

an then augment the CSS class with:

.form-actions {
    margin: 0;
    background-color: transparent;
    text-align: center;
}

Here's a JS Bin demo: http://jsbin.com/ijozof/2


Look for form-actions at the Bootstrap doc here:

http://twitter.github.io/bootstrap/base-css.html#buttons

$rootScope.$broadcast vs. $scope.$emit

enter image description here

$scope.$emit: This method dispatches the event in the upwards direction (from child to parent)

enter image description here $scope.$broadcast: Method dispatches the event in the downwards direction (from parent to child) to all the child controllers.

enter image description here $scope.$on: Method registers to listen to some event. All the controllers which are listening to that event get notification of the broadcast or emit based on the where those fit in the child-parent hierarchy.

The $emit event can be cancelled by any one of the $scope who is listening to the event.

The $on provides the "stopPropagation" method. By calling this method the event can be stopped from propagating further.

Plunker :https://embed.plnkr.co/0Pdrrtj3GEnMp2UpILp4/

In case of sibling scopes (the scopes which are not in the direct parent-child hierarchy) then $emit and $broadcast will not communicate to the sibling scopes.

enter image description here

For more details please refer to http://yogeshtutorials.blogspot.in/2015/12/event-based-communication-between-angularjs-controllers.html

csv.Error: iterator should return strings, not bytes

I had this error when running an old python script developped with Python 2.6.4

When updating to 3.6.2, I had to remove all 'rb' parameters from open calls in order to fix this csv reading error.

Responsive css background images

background: url(/static/media/group3x.6bb50026.jpg);
background-size: contain;
background-repeat: no-repeat;
background-position: top;

the position property can be used to align top bottom and center as per your need and background-size can be used for center crop(cover) or full image(contain or 100%)

Enable Hibernate logging

Spring Boot, v2.3.0.RELEASE

Recommended (In application.properties):

logging.level.org.hibernate.SQL=DEBUG //logs all SQL DML statements
logging.level.org.hibernate.type=TRACE //logs all JDBC parameters 

parameters

Note:
The above will not give you a pretty-print though.
You can add it as a configuration:

properties.put("hibernate.format_sql", "true");

or as per below.

Works but NOT recommended

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

Reason: It's better to let the logging framework manage/optimize the output for you + it doesn't give you the prepared statement parameters.

Cheers

Detect whether a Python string is a number or a letter

For a string of length 1 you can simply perform isdigit() or isalpha()

If your string length is greater than 1, you can make a function something like..

def isinteger(a):
    try:
        int(a)
        return True
    except ValueError:
        return False

remove script tag from HTML content

$html = <<<HTML
...
HTML;
$dom = new DOMDocument();
$dom->loadHTML($html);
$tags_to_remove = array('script','style','iframe','link');
foreach($tags_to_remove as $tag){
    $element = $dom->getElementsByTagName($tag);
    foreach($element  as $item){
        $item->parentNode->removeChild($item);
    }
}
$html = $dom->saveHTML();

How to determine programmatically the current active profile using Spring boot

It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment to your bean.

@Autowired
private Environment environment;
....

this.environment.getActiveProfiles();

Hiding a sheet in Excel 2007 (with a password) OR hide VBA code in Excel

Here is what you do in Excel 2003:

  1. In your sheet of interest, go to Format -> Sheet -> Hide and hide your sheet.
  2. Go to Tools -> Protection -> Protect Workbook, make sure Structure is selected, and enter your password of choice.

Here is what you do in Excel 2007:

  1. In your sheet of interest, go to Home ribbon -> Format -> Hide & Unhide -> Hide Sheet and hide your sheet.
  2. Go to Review ribbon -> Protect Workbook, make sure Structure is selected, and enter your password of choice.

Once this is done, the sheet is hidden and cannot be unhidden without the password. Make sense?


If you really need to keep some calculations secret, try this: use Access (or another Excel workbook or some other DB of your choice) to calculate what you need calculated, and export only the "unclassified" results to your Excel workbook.

Convert Map to JSON using Jackson

You can convert Map to JSON using Jackson as follows:

Map<String,String> payload = new HashMap<>();
payload.put("key1","value1");
payload.put("key2","value2");

String json = new ObjectMapper().writeValueAsString(payload);
System.out.println(json);

How to scale down a range of numbers with a known min and max value

Based on Charles Clayton's response, I included some JSDoc, ES6 tweaks, and incorporated suggestions from the comments in the original response.

_x000D_
_x000D_
/**_x000D_
 * Returns a scaled number within its source bounds to the desired target bounds._x000D_
 * @param {number} n - Unscaled number_x000D_
 * @param {number} tMin - Minimum (target) bound to scale to_x000D_
 * @param {number} tMax - Maximum (target) bound to scale to_x000D_
 * @param {number} sMin - Minimum (source) bound to scale from_x000D_
 * @param {number} sMax - Maximum (source) bound to scale from_x000D_
 * @returns {number} The scaled number within the target bounds._x000D_
 */_x000D_
const scaleBetween = (n, tMin, tMax, sMin, sMax) => {_x000D_
  return (tMax - tMin) * (n - sMin) / (sMax - sMin) + tMin;_x000D_
}_x000D_
_x000D_
if (Array.prototype.scaleBetween === undefined) {_x000D_
  /**_x000D_
   * Returns a scaled array of numbers fit to the desired target bounds._x000D_
   * @param {number} tMin - Minimum (target) bound to scale to_x000D_
   * @param {number} tMax - Maximum (target) bound to scale to_x000D_
   * @returns {number} The scaled array._x000D_
   */_x000D_
  Array.prototype.scaleBetween = function(tMin, tMax) {_x000D_
    if (arguments.length === 1 || tMax === undefined) {_x000D_
      tMax = tMin; tMin = 0;_x000D_
    }_x000D_
    let sMax = Math.max(...this), sMin = Math.min(...this);_x000D_
    if (sMax - sMin == 0) return this.map(num => (tMin + tMax) / 2);_x000D_
    return this.map(num => (tMax - tMin) * (num - sMin) / (sMax - sMin) + tMin);_x000D_
  }_x000D_
}_x000D_
_x000D_
// ================================================================_x000D_
// Usage_x000D_
// ================================================================_x000D_
_x000D_
let nums = [10, 13, 25, 28, 43, 50], tMin = 0, tMax = 100,_x000D_
    sMin = Math.min(...nums), sMax = Math.max(...nums);_x000D_
_x000D_
// Result: [ 0.0, 7.50, 37.50, 45.00, 82.50, 100.00 ]_x000D_
console.log(nums.map(n => scaleBetween(n, tMin, tMax, sMin, sMax).toFixed(2)).join(', '));_x000D_
_x000D_
// Result: [ 0, 30.769, 69.231, 76.923, 100 ]_x000D_
console.log([-4, 0, 5, 6, 9].scaleBetween(0, 100).join(', '));_x000D_
_x000D_
// Result: [ 50, 50, 50 ]_x000D_
console.log([1, 1, 1].scaleBetween(0, 100).join(', '));
_x000D_
.as-console-wrapper { top: 0; max-height: 100% !important; }
_x000D_
_x000D_
_x000D_

Instagram API - How can I retrieve the list of people a user is following on Instagram

Here's a way to get the list of people a user is following with just a browser and some copy-paste (A pure javascript solution based on Deep Seeker's answer):

  1. Get the user's id (In a browser, navigate to https://www.instagram.com/user_name/?__a=1 and look for response -> graphql -> user -> id [from Deep Seeker's answer])

  2. Open another browser window

  3. Open the browser console and paste this in it

    _x000D_
    _x000D_
    options = {
        userId: your_user_id,
        list: 1 //1 for following, 2 for followers
    }
    _x000D_
    _x000D_
    _x000D_

  4. change to your user id and hit enter

  5. paste this in the console and hit enter

    _x000D_
    _x000D_
    `https://www.instagram.com/graphql/query/?query_hash=c76146de99bb02f6415203be841dd25a&variables=` + encodeURIComponent(JSON.stringify({
            "id": options.userId,
            "include_reel": true,
            "fetch_mutual": true,
            "first": 50
        }))
    _x000D_
    _x000D_
    _x000D_

  6. Navigate to the outputted link

(This sets up the headers for the http request. If you try to run the script on a page where this isn't open, it won't work.)

  1. In the console for the page you just opened, paste this and hit enter
    _x000D_
    _x000D_
    let config = {
      followers: {
        hash: 'c76146de99bb02f6415203be841dd25a',
        path: 'edge_followed_by'
      },
      following: {
        hash: 'd04b0a864b4b54837c0d870b0e77e076',
        path: 'edge_follow'
      }
    };
    
    var allUsers = [];
    
    function getUsernames(data) {
        var userBatch = data.map(element => element.node.username);
        allUsers.push(...userBatch);
    }
    
    async function makeNextRequest(nextCurser, listConfig) {
        var params = {
            "id": options.userId,
            "include_reel": true,
            "fetch_mutual": true,
            "first": 50
        };
        if (nextCurser) {
            params.after = nextCurser;
        }
        var requestUrl = `https://www.instagram.com/graphql/query/?query_hash=` + listConfig.hash + `&variables=` + encodeURIComponent(JSON.stringify(params));
    
        var xhr = new XMLHttpRequest();
        xhr.onload = function(e) {
            var res = JSON.parse(xhr.response);
    
            var userData = res.data.user[listConfig.path].edges;
            getUsernames(userData);
    
            var curser = "";
            try {
                curser = res.data.user[listConfig.path].page_info.end_cursor;
            } catch {
    
            }
            var users = [];
            if (curser) {
                makeNextRequest(curser, listConfig);
            } else {
                var printString =""
                allUsers.forEach(item => printString = printString + item + "\n");
                console.log(printString);
            }
        }
    
        xhr.open("GET", requestUrl);
        xhr.send();
    }
    
    if (options.list === 1) {
    
        console.log('following');
        makeNextRequest("", config.following);
    } else if (options.list === 2) {
    
        console.log('followers');
        makeNextRequest("", config.followers);
    }
    _x000D_
    _x000D_
    _x000D_

After a few seconds it should output the list of users your user is following.

How to declare global variables in Android?

You could create a class that extends Application class and then declare your variable as a field of that class and providing getter method for it.

public class MyApplication extends Application {
    private String str = "My String";

    synchronized public String getMyString {
        return str;
    }
}

And then to access that variable in your Activity, use this:

MyApplication application = (MyApplication) getApplication();
String myVar = application.getMyString();

Regular Expressions- Match Anything

/.*/ works great if there are no line breaks. If it has to match line breaks, here are some solutions:

Solution Description
/.*/s /s (dot all flag) makes . (wildcard character) match anything, including line breaks. Throw in an * (asterisk), and it will match everything. Read more.
/[\s\S]*/ \s (whitespace metacharacter) will match any whitespace character (space; tab; line break; ...), and \S (opposite of \s) will match anything that is not a whitespace character. * (asterisk) will match all occurrences of the character set (Encapsulated by []). Read more.

How do I use 3DES encryption/decryption in Java?

Here's a very simply static encrypt/decrypt class biased on the Bouncy Castle no padding example by Jose Luis Montes de Oca. This one is using "DESede/ECB/PKCS7Padding" so I don't have to bother manually padding.


    package com.zenimax.encryption;

    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import java.security.NoSuchProviderException;
    import java.security.Security;
    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;

    /**
     * 
     * @author Matthew H. Wagner
     */
    public class TripleDesBouncyCastle {
        private static String TRIPLE_DES_TRANSFORMATION = "DESede/ECB/PKCS7Padding";
        private static String ALGORITHM = "DESede";
        private static String BOUNCY_CASTLE_PROVIDER = "BC";

        private static void init()
        {
            Security.addProvider(new BouncyCastleProvider());
        }

        public static byte[] encode(byte[] input, byte[] key)
                throws IllegalBlockSizeException, BadPaddingException,
                NoSuchAlgorithmException, NoSuchProviderException,
                NoSuchPaddingException, InvalidKeyException {
            init();
            SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);
            Cipher encrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION,
                    BOUNCY_CASTLE_PROVIDER);
            encrypter.init(Cipher.ENCRYPT_MODE, keySpec);
            return encrypter.doFinal(input);
        }

        public static byte[] decode(byte[] input, byte[] key)
                throws IllegalBlockSizeException, BadPaddingException,
                NoSuchAlgorithmException, NoSuchProviderException,
                NoSuchPaddingException, InvalidKeyException {
            init();
            SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);
            Cipher decrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION,
                    BOUNCY_CASTLE_PROVIDER);
            decrypter.init(Cipher.DECRYPT_MODE, keySpec);
            return decrypter.doFinal(input);
        }
    }

jQuery's jquery-1.10.2.min.map is triggering a 404 (Not Found)

As it is announced in jQuery 1.11.0/2.1.0 Beta 2 Released the source map comment will be removed so the issue will not appear in newer versions of jQuery.

Here is the official announcement:

One of the changes we’ve made in this beta is to remove the sourcemap comment. Sourcemaps have proven to be a very problematic and puzzling thing to developers, generating scores of confused questions on forums like StackOverflow and causing users to think jQuery itself was broken.

Anyway, if you need to use a source map, it still be available:

We’ll still be generating and distributing sourcemaps, but you will need to add the appropriate sourcemap comment at the end of the minified file if the browser does not support manually associating map files (currently, none do). If you generate your own jQuery file using the custom build process, the sourcemap comment will be present in the minified file and the map is generated; you can either leave it in and use sourcemaps or edit it out and ignore the map file entirely.

Here you can find more details about the changes.


Here you can find confirmation that with the jQuery 1.11.0/2.1.0 Released the source-map comment in the minified file is removed.

java.util.regex - importance of Pattern.compile()?

Similar to 'Pattern.compile' there is 'RECompiler.compile' [from com.sun.org.apache.regexp.internal] where:
1. compiled code for pattern [a-z] has 'az' in it
2. compiled code for pattern [0-9] has '09' in it
3. compiled code for pattern [abc] has 'aabbcc' in it.

Thus compiled code is a great way to generalize multiple cases. Thus instead of having different code handling situation 1,2 and 3 . The problem reduces to comparing with the ascii of present and next element in the compiled code, hence the pairs. Thus
a. anything with ascii between a and z is between a and z
b. anything with ascii between 'a and a is definitely 'a'

Changing WPF title bar background color

You can also create a borderless window, and make the borders and title bar yourself

I need an unordered list without any bullets

To completely remove the ul default style:

    list-style-type: none;

    margin: 0;
    margin-block-start: 0;
    margin-block-end: 0;
    margin-inline-start: 0;
    margin-inline-end: 0;
    padding-inline-start: 0;

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

     <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.7.21</version>
    </dependency>

Put above mentioned dependency in pom.xml file

Tokenizing Error: java.util.regex.PatternSyntaxException, dangling metacharacter '*'

It is because * is used as a metacharacter to signify one or more occurences of previous character. So if i write M* then it will look for files MMMMMM..... ! Here you are using * as the only character so the compiler is looking for the character to find multiple occurences of,so it throws the exception.:)

How do you sort a dictionary by value?

You can sort the Dictionary by value and get the result in dictionary using the code below:

Dictionary <<string, string>> ShareUserNewCopy = 
       ShareUserCopy.OrderBy(x => x.Value).ToDictionary(pair => pair.Key,
                                                        pair => pair.Value);                                          

Extract time from date String

If you have date in integers, you could use like here:

Date date = new Date();
date.setYear(2010);
date.setMonth(07);
date.setDate(14)
date.setHours(9);
date.setMinutes(0);
date.setSeconds(0);
String time = new SimpleDateFormat("HH:mm:ss").format(date);

Cannot delete directory with Directory.Delete(path, true)

This is because of FileChangesNotifications.

It happens since ASP.NET 2.0. When you delete some folder within an app, it gets restarted. You can see it yourself, using ASP.NET Health Monitoring.

Just add this code to your web.config/configuration/system.web:

<healthMonitoring enabled="true">
  <rules>
    <add name="MyAppLogEvents" eventName="Application Lifetime Events" provider="EventLogProvider" profile="Critical"/>
  </rules>
</healthMonitoring>


After that check out Windows Log -> Application. What is going on:

When you delete folder, if there is any sub-folder, Delete(path, true) deletes sub-folder first. It is enough for FileChangesMonitor to know about removal and shut down your app. Meanwhile your main directory is not deleted yet. This is the event from Log:


enter image description here


Delete() didn't finish its work and because app is shutting down, it raises an exception:

enter image description here

When you do not have any subfolders in a folder that you are deleting, Delete() just deletes all files and that folder, app is getting restarted too, but you don't get any exceptions, because app restart doesn't interrupt anything. But still, you lose all in-process sessions, app doesn't response to requests when restarting, etc.

What now?

There are some workarounds and tweaks to disable this behaviour, Directory Junction, Turning Off FCN with Registry, Stopping FileChangesMonitor using Reflection (since there is no exposed method), but they all don't seem to be right, because FCN is there for a reason. It is looking after structure of your app, which is not structure of your data. Short answer is: place folders you want to delete outside of your app. FileChangesMonitor will get no notifications and your app will not be restarted every time. You will get no exceptions. To get them visible from the web there are two ways:

  1. Make a controller that handles incoming calls and then serves files back by reading from folder outside an app (outside wwwroot).

  2. If your project is big and performance is most important, set up separate small and fast webserver for serving static content. Thus you will leave to IIS his specific job. It could be on the same machine (mongoose for Windows) or another machine (nginx for Linux). Good news is you don't have to pay extra microsoft license to set up static content server on linux.

Hope this helps.

If condition inside of map() React

You're mixing if statement with a ternary expression, that's why you're having a syntax error. It might be easier for you to understand what's going on if you extract mapping function outside of your render method:

renderItem = (id) => {
    // just standard if statement
    if (this.props.schema.collectionName.length < 0) {
        return (
            <Expandable>
                <ObjectDisplay
                    key={id}
                    parentDocumentId={id}
                    schema={schema[this.props.schema.collectionName]}
                    value={this.props.collection.documents[id]}
                />
            </Expandable>
        );
    }
    return (
        <h1>hejsan</h1>
    );
}

Then just call it when mapping:

render() {
    return (
        <div>
            <div className="box">
                { 
                    this.props.collection.ids
                        .filter(
                            id =>
                            // note: this is only passed when in top level of document
                            this.props.collection.documents[id][
                                this.props.schema.foreignKey
                            ] === this.props.parentDocumentId
                        )
                        .map(this.renderItem)
                }
            </div>
        </div>
    )
}

Of course, you could have used the ternary expression as well, it's a matter of preference. What you use, however, affects the readability, so make sure to check different ways and tips to properly do conditional rendering in react and react native.

Basic calculator in Java

import java.util.Scanner; import javax.swing.JOptionPane;

public class javaCalculator {

public static void main(String[] args) 
{
    int num1;
    int num2;
    String operation;


    Scanner input = new Scanner(System.in);

    System.out.println("please enter the first number");
    num1 = input.nextInt();

    System.out.println("please enter the second number");
    num2 = input.nextInt();

    Scanner op = new Scanner(System.in);

    System.out.println("Please enter operation");
    operation = op.next();

    if (operation.equals("+"))
    {
        System.out.println("your answer is" + (num1 + num2));
    }
   else if  (operation.equals("-"))
    {
        System.out.println("your answer is" + (num1 - num2));
    }

  else if (operation.equals("/"))
    {
        System.out.println("your answer is" + (num1 / num2));
    }
   else if (operation.equals("*"))
    {
        System.out.println("your answer is" + (num1 * num2));
    }
   else 
    {
       System.out.println("Wrong selection");
    }


}

}

pandas create new column based on values from other columns / apply a function of multiple columns, row-wise

OK, two steps to this - first is to write a function that does the translation you want - I've put an example together based on your pseudo-code:

def label_race (row):
   if row['eri_hispanic'] == 1 :
      return 'Hispanic'
   if row['eri_afr_amer'] + row['eri_asian'] + row['eri_hawaiian'] + row['eri_nat_amer'] + row['eri_white'] > 1 :
      return 'Two Or More'
   if row['eri_nat_amer'] == 1 :
      return 'A/I AK Native'
   if row['eri_asian'] == 1:
      return 'Asian'
   if row['eri_afr_amer']  == 1:
      return 'Black/AA'
   if row['eri_hawaiian'] == 1:
      return 'Haw/Pac Isl.'
   if row['eri_white'] == 1:
      return 'White'
   return 'Other'

You may want to go over this, but it seems to do the trick - notice that the parameter going into the function is considered to be a Series object labelled "row".

Next, use the apply function in pandas to apply the function - e.g.

df.apply (lambda row: label_race(row), axis=1)

Note the axis=1 specifier, that means that the application is done at a row, rather than a column level. The results are here:

0           White
1        Hispanic
2           White
3           White
4           Other
5           White
6     Two Or More
7           White
8    Haw/Pac Isl.
9           White

If you're happy with those results, then run it again, saving the results into a new column in your original dataframe.

df['race_label'] = df.apply (lambda row: label_race(row), axis=1)

The resultant dataframe looks like this (scroll to the right to see the new column):

      lname   fname rno_cd  eri_afr_amer  eri_asian  eri_hawaiian   eri_hispanic  eri_nat_amer  eri_white rno_defined    race_label
0      MOST    JEFF      E             0          0             0              0             0          1       White         White
1    CRUISE     TOM      E             0          0             0              1             0          0       White      Hispanic
2      DEPP  JOHNNY    NaN             0          0             0              0             0          1     Unknown         White
3     DICAP     LEO    NaN             0          0             0              0             0          1     Unknown         White
4    BRANDO  MARLON      E             0          0             0              0             0          0       White         Other
5     HANKS     TOM    NaN             0          0             0              0             0          1     Unknown         White
6    DENIRO  ROBERT      E             0          1             0              0             0          1       White   Two Or More
7    PACINO      AL      E             0          0             0              0             0          1       White         White
8  WILLIAMS   ROBIN      E             0          0             1              0             0          0       White  Haw/Pac Isl.
9  EASTWOOD   CLINT      E             0          0             0              0             0          1       White         White

enable/disable zoom in Android WebView

We had the same problem while working on an Android application for a customer and I managed to "hack" around this restriction.

I took a look at the Android Source code for the WebView class and spotted a updateZoomButtonsEnabled()-method which was working with an ZoomButtonsController-object to enable and disable the zoom controls depending on the current scale of the browser.

I searched for a method to return the ZoomButtonsController-instance and found the getZoomButtonsController()-method, that returned this very instance.

Although the method is declared public, it is not documented in the WebView-documentation and Eclipse couldn't find it either. So, I tried some reflection on that and created my own WebView-subclass to override the onTouchEvent()-method, which triggered the controls.

public class NoZoomControllWebView extends WebView {

    private ZoomButtonsController zoom_controll = null;

    public NoZoomControllWebView(Context context) {
        super(context);
        disableControls();
    }

    public NoZoomControllWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        disableControls();
    }

    public NoZoomControllWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        disableControls();
    }

    /**
     * Disable the controls
     */
    private void disableControls(){
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
            // Use the API 11+ calls to disable the controls
            this.getSettings().setBuiltInZoomControls(true);
            this.getSettings().setDisplayZoomControls(false);
        } else {
            // Use the reflection magic to make it work on earlier APIs
            getControlls();
        }
    }

    /**
     * This is where the magic happens :D
     */
    private void getControlls() {
        try {
            Class webview = Class.forName("android.webkit.WebView");
            Method method = webview.getMethod("getZoomButtonsController");
            zoom_controll = (ZoomButtonsController) method.invoke(this, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        super.onTouchEvent(ev);
        if (zoom_controll != null){
            // Hide the controlls AFTER they where made visible by the default implementation.
            zoom_controll.setVisible(false);
        }
        return true;
    }
}

You might want to remove the unnecessary constructors and react on probably on the exceptions.

Although this looks hacky and unreliable, it works back to API Level 4 (Android 1.6).


As @jayellos pointed out in the comments, the private getZoomButtonsController()-method is no longer existing on Android 4.0.4 and later.

However, it doesn't need to. Using conditional execution, we can check if we're on a device with API Level 11+ and use the exposed functionality (see @Yuttadhammo answer) to hide the controls.

I updated the example code above to do exactly that.

Tools to search for strings inside files without indexing

Visual Studio's search in folders is by far the fastest I've found.

I believe it intelligently searches only text (non-binary) files, and subsequent searches in the same folder are extremely fast, unlike with the other tools (likely the text files fit in the windows disk cache).

VS2010 on a regular hard drive, no SSD, takes 1 minute to search a 20GB folder with 26k files, source code and binaries mixed up. 15k files are searched - the rest are likely skipped due to being binary files. Subsequent searches in the same folder are on the order of seconds (until stuff gets evicted form the cache).

The next closest I've found for the same folder was grepWin. Around 3 minutes. I excluded files larger than 2000KB (default). The "Include binary files" setting seems to do nothing in terms of speeding up the search, it looks like binary files are still touched (bug?), but they don't show up in the search results. Subsequent searches all take the same 3 minutes - can't take advantage of hard drive cache. If I restrict to files smaller than 200k, the initial search is 2.5min and subsequent searches are on the order of seconds, about as fast as VS - in the cache.

Agent Ransack and FileSeek are both very slow on that folder, around 20min, due to searching through everything, including giant multi-gigabyte binary files. They search at about 10-20MB per second according to Resource Monitor.

UPDATE: Agent Ransack can be set to search files of certain sizes, and using the <200KB cutoff it's 1:15min for a fresh search and 5s for subsequent searches. Faster than grepWin and as fast as VS overall. It's actually pretty nice if you want to keep several searches in tabs and you don't want to pollute the VS recently searched folders list, and you want to keep the ability to search binaries, which VS doesn't seem to wanna do. Agent Ransack also creates an explorer context menu entry, so it's easy to launch from a folder. Same as grepWin but nicer UI and faster.

My new search setup is Agent Ransack for contents and Everything for file names (awesome tool, instant results!).

Bootstrap trying to load map file. How to disable it? Do I need to do it?

I had also warnings in Google Dev-Tools and I added only bootstrap.min.css.map file in the same folder, where bootstrap.min.css is.

I have now no warnings more and You can find more Explanation here: https://github.com/twbs/bootstrap#whats-included

I hope, I answered your Question.

How to normalize a signal to zero mean and unit variance?

if your signal is in the matrix X, you make it zero-mean by removing the average:

X=X-mean(X(:));

and unit variance by dividing by the standard deviation:

X=X/std(X(:));

Why docker container exits immediately

Coming from duplicates, I don't see any answer here which addresses the very common antipattern of running your main workload as a background job, and then wondering why Docker exits.

In simple terms, if you have

my-main-thing &

then either take out the & to run the job in the foreground, or add

wait

at the end of the script to make it wait for all background jobs.

It will then still exit if the main workload exits, so maybe run this in a while true loop to force it to restart forever:

while true; do
    my-main-thing &
    other things which need to happen while the main workload runs in the background
    maybe if you have such things
    wait
done

(Notice also how to write while true. It's common to see silly things like while [ true ] or while [ 1 ] which coincidentally happen to work, but don't mean what the author probably imagined they ought to mean.)

Applying an ellipsis to multiline text

May be this can help you guys. Multi Line Ellipses with tooltip hover. https://codepen.io/Anugraha123/pen/WOBdOb

<div>
     <p class="cards-values">Lorem ipsum dolor sit amet,   consectetur adipiscing elit. Nunc aliquet lorem commodo, semper mauris nec, suscipit nisi. Nullam laoreet massa sit amet leo malesuada imperdiet eu a augue. Sed ac diam quis ante congue volutpat non vitae sem. Vivamus a felis id dui aliquam tempus
      </p>
      <span class="tooltip"></span>
</div>

How can I convert string to datetime with format specification in JavaScript?

//Here pdate is the string date time
var date1=GetDate(pdate);
    function GetDate(a){
        var dateString = a.substr(6);
        var currentTime = new Date(parseInt(dateString ));
        var month =("0"+ (currentTime.getMonth() + 1)).slice(-2);
        var day =("0"+ currentTime.getDate()).slice(-2);
        var year = currentTime.getFullYear();
        var date = day + "/" + month + "/" + year;
        return date;
    }

.NET data structures: ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary -- Speed, memory, and when to use each?

There are subtle and not-so-subtle differences between generic and non-generic collections. They merely use different underlying data structures. For example, Hashtable guarantees one-writer-many-readers without sync. Dictionary does not.

Finish all activities at a time

If rooted:

Runtime.getRuntime().exec("su -c service call activity 42 s16 com.example.your_app");

What's the difference between an argument and a parameter?

Logically speaking,we're actually talking about the same thing. But I think a simple metaphor would be helpful to solve this dilemma.

If the metaphors can be called various connection point we can equate them to plug points on a wall. In this case we can consider parameters and arguments as follows;

Parameters are the sockets of the plug-point which may take various different shapes. But only certain types of plugs fit them.
Arguments will be the actual plugs that would be plugged into the plug points/sockets to activate certain equipments.

ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?"

You get this error because one of your variables is actually a factor variable . Execute

str(df) 

to check this. Then do this double variable change to keep the year numbers instead of transforming into "1,2,3,4" level numbers:

df$year <- as.numeric(as.character(df$year))

EDIT: it appears that your data.frame has a variable of class "array" which might cause the pb. Try then:

df <- data.frame(apply(df, 2, unclass))

and plot again?

How to Force New Google Spreadsheets to refresh and recalculate?

What worked for me is inserting a column before the first column and deleting it immediately. Basically, do a change that will affect all the cells in the worksheet that will trigger recalculation.

Set a thin border using .css() in javascript

Current Example:

You need to define border-width:1px

Your code should read:

$(this).css({"border-color": "#C1E0FF", 
             "border-width":"1px", 
             "border-style":"solid"});

Suggested Example:

You should ideally use a class and addClass/removeClass

$(this).addClass('borderClass'); $(this).removeClass('borderClass');

and in your CSS:

.borderClass{
  border-color: #C1E0FF;
  border-width:1px;
  border-style: solid;
  /** OR USE INLINE
  border: 1px solid #C1E0FF;
  **/
}

jsfiddle working example: http://jsfiddle.net/gorelative/tVbvF/\

jsfiddle with animate: http://jsfiddle.net/gorelative/j9Xxa/ This just gives you an example of how it could work, you should get the idea.. There are better ways of doing this most likely.. like using a toggle()

Squash the first two commits in Git?

This will squash second commit into the first one:

A-B-C-... -> AB-C-...

git filter-branch --commit-filter '
    if [ "$GIT_COMMIT" = <sha1ofA> ];
    then
        skip_commit "$@";
    else
        git commit-tree "$@";
    fi
' HEAD

Commit message for AB will be taken from B (although I'd prefer from A).

Has the same effect as Uwe Kleine-König's answer, but works for non-initial A as well.

Variable number of arguments in C++?

A C++17 solution: full type safety + nice calling syntax

Since the introduction of variadic templates in C++11 and fold expressions in C++17, it is possible to define a template-function which, at the caller site, is callable as if it was a varidic function but with the advantages to:

  • be strongly type safe;
  • work without the run-time information of the number of arguments, or without the usage of a "stop" argument.

Here is an example for mixed argument types

template<class... Args>
void print(Args... args)
{
    (std::cout << ... << args) << "\n";
}
print(1, ':', " Hello", ',', " ", "World!");

And another with enforced type match for all arguments:

#include <type_traits> // enable_if, conjuction

template<class Head, class... Tail>
using are_same = std::conjunction<std::is_same<Head, Tail>...>;

template<class Head, class... Tail, class = std::enable_if_t<are_same<Head, Tail...>::value, void>>
void print_same_type(Head head, Tail... tail)
{
    std::cout << head;
    (std::cout << ... << tail) << "\n";
}
print_same_type("2: ", "Hello, ", "World!");   // OK
print_same_type(3, ": ", "Hello, ", "World!"); // no matching function for call to 'print_same_type(int, const char [3], const char [8], const char [7])'
                                               // print_same_type(3, ": ", "Hello, ", "World!");
                                                                                              ^

More information:

  1. Variadic templates, also known as parameter pack Parameter pack(since C++11) - cppreference.com.
  2. Fold expressions fold expression(since C++17) - cppreference.com.
  3. See a full program demonstration on coliru.

Map isn't showing on Google Maps JavaScript API v3 when nested in a div tag

The problem is with percentage sizing. You are not defining the size of the parent div (the new one), so the browser can not report the size to the Google Maps API. Giving the wrapper div a specific size, or a percentage size if the size of its parent can be determined, will work.

See this explanation from Mike Williams' Google Maps API v2 tutorial:

If you try to use style="width:100%;height:100%" on your map div, you get a map div that has zero height. That's because the div tries to be a percentage of the size of the <body>, but by default the <body> has an indeterminate height.

There are ways to determine the height of the screen and use that number of pixels as the height of the map div, but a simple alternative is to change the <body> so that its height is 100% of the page. We can do this by applying style="height:100%" to both the <body> and the <html>. (We have to do it to both, otherwise the <body> tries to be 100% of the height of the document, and the default for that is an indeterminate height.)

Add the 100% size to html and body in your css

    html, body, #map-canvas {
        margin: 0;
        padding: 0;
        height: 100%;
        width: 100%;
    }

Add it inline to any divs that don't have an id:

<body>
  <div style="height:100%; width: 100%;"> 
    <div id="map-canvas"></div>
  </div>
</body>

Regex: matching up to the first occurrence of a character

Really kinda sad that no one has given you the correct answer....

In regex, ? makes it non greedy. By default regex will match as much as it can (greedy)

Simply add a ? and it will be non-greedy and match as little as possible!

Good luck, hope that helps.

How can I tell if a VARCHAR variable contains a substring?

The standard SQL way is to use like:

where @stringVar like '%thisstring%'

That is in a query statement. You can also do this in TSQL:

if @stringVar like '%thisstring%'

Inline JavaScript onclick function

Based on the answer that @Mukund Kumar gave here's a version that passes the event argument to the anonymous function:

<a href="#" onClick="(function(e){
    console.log(e);
    alert('Hey i am calling');
    return false;
})(arguments[0]);return false;">click here</a>

What do the return values of Comparable.compareTo mean in Java?

I use this mnemonic :

a.compareTo(b) < 0 // a < b

a.compareTo(b) > 0 // a > b

a.compareTo(b) == 0 // a == b

You keep the signs and always compare the result of compareTo() to 0

Getting the index of the returned max or min item using max()/min() on a list

After you get the maximum values, try this:

max_val = max(list)
index_max = list.index(max_val)

Much simpler than a lot of options.

How can I sanitize user input with PHP?

PHP has the new nice filter_input functions now, that for instance liberate you from finding 'the ultimate e-mail regex' now that there is a built-in FILTER_VALIDATE_EMAIL type

My own filter class (uses JavaScript to highlight faulty fields) can be initiated by either an ajax request or normal form post. (see the example below)

/**
 *  Pork.FormValidator
 *  Validates arrays or properties by setting up simple arrays. 
 *  Note that some of the regexes are for dutch input!
 *  Example:
 * 
 *  $validations = array('name' => 'anything','email' => 'email','alias' => 'anything','pwd'=>'anything','gsm' => 'phone','birthdate' => 'date');
 *  $required = array('name', 'email', 'alias', 'pwd');
 *  $sanitize = array('alias');
 *
 *  $validator = new FormValidator($validations, $required, $sanitize);
 *                  
 *  if($validator->validate($_POST))
 *  {
 *      $_POST = $validator->sanitize($_POST);
 *      // now do your saving, $_POST has been sanitized.
 *      die($validator->getScript()."<script type='text/javascript'>alert('saved changes');</script>");
 *  }
 *  else
 *  {
 *      die($validator->getScript());
 *  }   
 *  
 * To validate just one element:
 * $validated = new FormValidator()->validate('blah@bla.', 'email');
 * 
 * To sanitize just one element:
 * $sanitized = new FormValidator()->sanitize('<b>blah</b>', 'string');
 * 
 * @package pork
 * @author SchizoDuckie
 * @copyright SchizoDuckie 2008
 * @version 1.0
 * @access public
 */
class FormValidator
{
    public static $regexes = Array(
            'date' => "^[0-9]{1,2}[-/][0-9]{1,2}[-/][0-9]{4}\$",
            'amount' => "^[-]?[0-9]+\$",
            'number' => "^[-]?[0-9,]+\$",
            'alfanum' => "^[0-9a-zA-Z ,.-_\\s\?\!]+\$",
            'not_empty' => "[a-z0-9A-Z]+",
            'words' => "^[A-Za-z]+[A-Za-z \\s]*\$",
            'phone' => "^[0-9]{10,11}\$",
            'zipcode' => "^[1-9][0-9]{3}[a-zA-Z]{2}\$",
            'plate' => "^([0-9a-zA-Z]{2}[-]){2}[0-9a-zA-Z]{2}\$",
            'price' => "^[0-9.,]*(([.,][-])|([.,][0-9]{2}))?\$",
            '2digitopt' => "^\d+(\,\d{2})?\$",
            '2digitforce' => "^\d+\,\d\d\$",
            'anything' => "^[\d\D]{1,}\$"
    );
    private $validations, $sanatations, $mandatories, $errors, $corrects, $fields;


    public function __construct($validations=array(), $mandatories = array(), $sanatations = array())
    {
        $this->validations = $validations;
        $this->sanitations = $sanitations;
        $this->mandatories = $mandatories;
        $this->errors = array();
        $this->corrects = array();
    }

    /**
     * Validates an array of items (if needed) and returns true or false
     *
     */
    public function validate($items)
    {
        $this->fields = $items;
        $havefailures = false;
        foreach($items as $key=>$val)
        {
            if((strlen($val) == 0 || array_search($key, $this->validations) === false) && array_search($key, $this->mandatories) === false) 
            {
                $this->corrects[] = $key;
                continue;
            }
            $result = self::validateItem($val, $this->validations[$key]);
            if($result === false) {
                $havefailures = true;
                $this->addError($key, $this->validations[$key]);
            }
            else
            {
                $this->corrects[] = $key;
            }
        }

        return(!$havefailures);
    }

    /**
     *
     *  Adds unvalidated class to thos elements that are not validated. Removes them from classes that are.
     */
    public function getScript() {
        if(!empty($this->errors))
        {
            $errors = array();
            foreach($this->errors as $key=>$val) { $errors[] = "'INPUT[name={$key}]'"; }

            $output = '$$('.implode(',', $errors).').addClass("unvalidated");'; 
            $output .= "new FormValidator().showMessage();";
        }
        if(!empty($this->corrects))
        {
            $corrects = array();
            foreach($this->corrects as $key) { $corrects[] = "'INPUT[name={$key}]'"; }
            $output .= '$$('.implode(',', $corrects).').removeClass("unvalidated");';   
        }
        $output = "<script type='text/javascript'>{$output} </script>";
        return($output);
    }


    /**
     *
     * Sanitizes an array of items according to the $this->sanitations
     * sanitations will be standard of type string, but can also be specified.
     * For ease of use, this syntax is accepted:
     * $sanitations = array('fieldname', 'otherfieldname'=>'float');
     */
    public function sanitize($items)
    {
        foreach($items as $key=>$val)
        {
            if(array_search($key, $this->sanitations) === false && !array_key_exists($key, $this->sanitations)) continue;
            $items[$key] = self::sanitizeItem($val, $this->validations[$key]);
        }
        return($items);
    }


    /**
     *
     * Adds an error to the errors array.
     */ 
    private function addError($field, $type='string')
    {
        $this->errors[$field] = $type;
    }

    /**
     *
     * Sanitize a single var according to $type.
     * Allows for static calling to allow simple sanitization
     */
    public static function sanitizeItem($var, $type)
    {
        $flags = NULL;
        switch($type)
        {
            case 'url':
                $filter = FILTER_SANITIZE_URL;
            break;
            case 'int':
                $filter = FILTER_SANITIZE_NUMBER_INT;
            break;
            case 'float':
                $filter = FILTER_SANITIZE_NUMBER_FLOAT;
                $flags = FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND;
            break;
            case 'email':
                $var = substr($var, 0, 254);
                $filter = FILTER_SANITIZE_EMAIL;
            break;
            case 'string':
            default:
                $filter = FILTER_SANITIZE_STRING;
                $flags = FILTER_FLAG_NO_ENCODE_QUOTES;
            break;

        }
        $output = filter_var($var, $filter, $flags);        
        return($output);
    }

    /** 
     *
     * Validates a single var according to $type.
     * Allows for static calling to allow simple validation.
     *
     */
    public static function validateItem($var, $type)
    {
        if(array_key_exists($type, self::$regexes))
        {
            $returnval =  filter_var($var, FILTER_VALIDATE_REGEXP, array("options"=> array("regexp"=>'!'.self::$regexes[$type].'!i'))) !== false;
            return($returnval);
        }
        $filter = false;
        switch($type)
        {
            case 'email':
                $var = substr($var, 0, 254);
                $filter = FILTER_VALIDATE_EMAIL;    
            break;
            case 'int':
                $filter = FILTER_VALIDATE_INT;
            break;
            case 'boolean':
                $filter = FILTER_VALIDATE_BOOLEAN;
            break;
            case 'ip':
                $filter = FILTER_VALIDATE_IP;
            break;
            case 'url':
                $filter = FILTER_VALIDATE_URL;
            break;
        }
        return ($filter === false) ? false : filter_var($var, $filter) !== false ? true : false;
    }       



}

Of course, keep in mind that you need to do your sql query escaping too depending on what type of db your are using (mysql_real_escape_string() is useless for an sql server for instance). You probably want to handle this automatically at your appropriate application layer like an ORM. Also, as mentioned above: for outputting to html use the other php dedicated functions like htmlspecialchars ;)

For really allowing HTML input with like stripped classes and/or tags depend on one of the dedicated xss validation packages. DO NOT WRITE YOUR OWN REGEXES TO PARSE HTML!

Django - limiting query results

As an addition and observation to the other useful answers, it's worth noticing that actually doing [:10] as slicing will return the first 10 elements of the list, not the last 10...

To get the last 10 you should do [-10:] instead (see here). This will help you avoid using order_by('-id') with the - to reverse the elements.

How can I map True/False to 1/0 in a Pandas DataFrame?

You can use a transformation for your data frame:

df = pd.DataFrame(my_data condition)

transforming True/False in 1/0

df = df*1

Simple division in Java - is this a bug or a feature?

In my case I was doing this:

double a = (double) (MAX_BANDWIDTH_SHARED_MB/(qCount+1));

Instead of the "correct" :

double a = (double)MAX_BANDWIDTH_SHARED_MB/(qCount+1);

Take attention with the parentheses !

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

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

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

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

Full screen background image in an activity

use this

android:background="@drawable/your_image"

in your activity very first linear or relative layout.

Finding the length of an integer in C

Yes, using sprintf.

int num;
scanf("%d",&num);
char testing[100];
sprintf(testing,"%d",num);
int length = strlen(testing);

Alternatively, you can do this mathematically using the log10 function.

int num;
scanf("%d",&num);
int length;
if (num == 0) {
  length = 1;
} else {    
  length = log10(fabs(num)) + 1;
  if (num < 0) length++;
}

Code to loop through all records in MS Access

Found a good code with comments explaining each statement. Code found at - accessallinone

Sub DAOLooping()
On Error GoTo ErrorHandler

Dim strSQL As String
Dim rs As DAO.Recordset

strSQL = "tblTeachers"
'For the purposes of this post, we are simply going to make 
'strSQL equal to tblTeachers.
'You could use a full SELECT statement such as:
'SELECT * FROM tblTeachers (this would produce the same result in fact).
'You could also add a Where clause to filter which records are returned:
'SELECT * FROM tblTeachers Where ZIPPostal = '98052'
' (this would return 5 records)

Set rs = CurrentDb.OpenRecordset(strSQL)
'This line of code instantiates the recordset object!!! 
'In English, this means that we have opened up a recordset 
'and can access its values using the rs variable.

With rs


    If Not .BOF And Not .EOF Then
    'We don’t know if the recordset has any records, 
    'so we use this line of code to check. If there are no records 
    'we won’t execute any code in the if..end if statement.    

        .MoveLast
        .MoveFirst
        'It is not necessary to move to the last record and then back 
        'to the first one but it is good practice to do so.

        While (Not .EOF)
        'With this code, we are using a while loop to loop 
        'through the records. If we reach the end of the recordset, .EOF 
        'will return true and we will exit the while loop.

            Debug.Print rs.Fields("teacherID") & " " & rs.Fields("FirstName")
            'prints info from fields to the immediate window

            .MoveNext
            'We need to ensure that we use .MoveNext, 
            'otherwise we will be stuck in a loop forever… 
            '(or at least until you press CTRL+Break)
        Wend

    End If

    .close
    'Make sure you close the recordset...
End With

ExitSub:
    Set rs = Nothing
    '..and set it to nothing
    Exit Sub
ErrorHandler:
    Resume ExitSub
End Sub

Recordsets have two important properties when looping through data, EOF (End-Of-File) and BOF (Beginning-Of-File). Recordsets are like tables and when you loop through one, you are literally moving from record to record in sequence. As you move through the records the EOF property is set to false but after you try and go past the last record, the EOF property becomes true. This works the same in reverse for the BOF property.

These properties let us know when we have reached the limits of a recordset.

Compare 2 arrays which returns difference

This should work with unsorted arrays, double values and different orders and length, while giving you the filtered values form array1, array2, or both.

function arrayDiff(arr1, arr2) {
    var diff = {};

    diff.arr1 = arr1.filter(function(value) {
        if (arr2.indexOf(value) === -1) {
            return value;
        }
    });

    diff.arr2 = arr2.filter(function(value) {
        if (arr1.indexOf(value) === -1) {
            return value;
        }
    });

    diff.concat = diff.arr1.concat(diff.arr2);

    return diff;
};

var firstArray = [1,2,3,4];
var secondArray = [4,6,1,4];

console.log( arrayDiff(firstArray, secondArray) );
console.log( arrayDiff(firstArray, secondArray).arr1 );
// => [ 2, 3 ]
console.log( arrayDiff(firstArray, secondArray).concat );
// => [ 2, 3, 6 ]

How to construct a WebSocket URI relative to the page URI?

In typescript:

export class WebsocketUtils {

    public static websocketUrlByPath(path) {
        return this.websocketProtocolByLocation() +
            window.location.hostname +
            this.websocketPortWithColonByLocation() +
            window.location.pathname +
            path;
    }

    private static websocketProtocolByLocation() {
        return window.location.protocol === "https:" ? "wss://" : "ws://";
    }

    private static websocketPortWithColonByLocation() {
        const defaultPort = window.location.protocol === "https:" ? "443" : "80";
        if (window.location.port !== defaultPort) {
            return ":" + window.location.port;
        } else {
            return "";
        }
    }
}

Usage:

alert(WebsocketUtils.websocketUrlByPath("/websocket"));

Where to place and how to read configuration resource files in servlet based application?

It's your choice. There are basically three ways in a Java web application archive (WAR):


1. Put it in classpath

So that you can load it by ClassLoader#getResourceAsStream() with a classpath-relative path:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("foo.properties");
// ...
Properties properties = new Properties();
properties.load(input);

Here foo.properties is supposed to be placed in one of the roots which are covered by the default classpath of a webapp, e.g. webapp's /WEB-INF/lib and /WEB-INF/classes, server's /lib, or JDK/JRE's /lib. If the propertiesfile is webapp-specific, best is to place it in /WEB-INF/classes. If you're developing a standard WAR project in an IDE, drop it in src folder (the project's source folder). If you're using a Maven project, drop it in /main/resources folder.

You can alternatively also put it somewhere outside the default classpath and add its path to the classpath of the appserver. In for example Tomcat you can configure it as shared.loader property of Tomcat/conf/catalina.properties.

If you have placed the foo.properties it in a Java package structure like com.example, then you need to load it as below

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("com/example/foo.properties");
// ...

Note that this path of a context class loader should not start with a /. Only when you're using a "relative" class loader such as SomeClass.class.getClassLoader(), then you indeed need to start it with a /.

ClassLoader classLoader = getClass().getClassLoader();
InputStream input = classLoader.getResourceAsStream("/com/example/foo.properties");
// ...

However, the visibility of the properties file depends then on the class loader in question. It's only visible to the same class loader as the one which loaded the class. So, if the class is loaded by e.g. server common classloader instead of webapp classloader, and the properties file is inside webapp itself, then it's invisible. The context class loader is your safest bet so you can place the properties file "everywhere" in the classpath and/or you intend to be able to override a server-provided one from the webapp on.


2. Put it in webcontent

So that you can load it by ServletContext#getResourceAsStream() with a webcontent-relative path:

InputStream input = getServletContext().getResourceAsStream("/WEB-INF/foo.properties");
// ...

Note that I have demonstrated to place the file in /WEB-INF folder, otherwise it would have been public accessible by any webbrowser. Also note that the ServletContext is in any HttpServlet class just accessible by the inherited GenericServlet#getServletContext() and in Filter by FilterConfig#getServletContext(). In case you're not in a servlet class, it's usually just injectable via @Inject.


3. Put it in local disk file system

So that you can load it the usual java.io way with an absolute local disk file system path:

InputStream input = new FileInputStream("/absolute/path/to/foo.properties");
// ...

Note the importance of using an absolute path. Relative local disk file system paths are an absolute no-go in a Java EE web application. See also the first "See also" link below.


Which to choose?

Just weigh the advantages/disadvantages in your own opinion of maintainability.

If the properties files are "static" and never needs to change during runtime, then you could keep them in the WAR.

If you prefer being able to edit properties files from outside the web application without the need to rebuild and redeploy the WAR every time, then put it in the classpath outside the project (if necessary add the directory to the classpath).

If you prefer being able to edit properties files programmatically from inside the web application using Properties#store() method, put it outside the web application. As the Properties#store() requires a Writer, you can't go around using a disk file system path. That path can in turn be passed to the web application as a VM argument or system property. As a precaution, never use getRealPath(). All changes in deploy folder will get lost on a redeploy for the simple reason that the changes are not reflected back in original WAR file.

See also:

Recommended way to save uploaded files in a servlet application

Store it anywhere in an accessible location except of the IDE's project folder aka the server's deploy folder, for reasons mentioned in the answer to Uploaded image only available after refreshing the page:

  1. Changes in the IDE's project folder does not immediately get reflected in the server's work folder. There's kind of a background job in the IDE which takes care that the server's work folder get synced with last updates (this is in IDE terms called "publishing"). This is the main cause of the problem you're seeing.

  2. In real world code there are circumstances where storing uploaded files in the webapp's deploy folder will not work at all. Some servers do (either by default or by configuration) not expand the deployed WAR file into the local disk file system, but instead fully in the memory. You can't create new files in the memory without basically editing the deployed WAR file and redeploying it.

  3. Even when the server expands the deployed WAR file into the local disk file system, all newly created files will get lost on a redeploy or even a simple restart, simply because those new files are not part of the original WAR file.

It really doesn't matter to me or anyone else where exactly on the local disk file system it will be saved, as long as you do not ever use getRealPath() method. Using that method is in any case alarming.

The path to the storage location can in turn be definied in many ways. You have to do it all by yourself. Perhaps this is where your confusion is caused because you somehow expected that the server does that all automagically. Please note that @MultipartConfig(location) does not specify the final upload destination, but the temporary storage location for the case file size exceeds memory storage threshold.

So, the path to the final storage location can be definied in either of the following ways:

  • Hardcoded:

      File uploads = new File("/path/to/uploads");
    
  • Environment variable via SET UPLOAD_LOCATION=/path/to/uploads:

      File uploads = new File(System.getenv("UPLOAD_LOCATION"));
    
  • VM argument during server startup via -Dupload.location="/path/to/uploads":

      File uploads = new File(System.getProperty("upload.location"));
    
  • *.properties file entry as upload.location=/path/to/uploads:

      File uploads = new File(properties.getProperty("upload.location"));
    
  • web.xml <context-param> with name upload.location and value /path/to/uploads:

      File uploads = new File(getServletContext().getInitParameter("upload.location"));
    
  • If any, use the server-provided location, e.g. in JBoss AS/WildFly:

      File uploads = new File(System.getProperty("jboss.server.data.dir"), "uploads");
    

Either way, you can easily reference and save the file as follows:

File file = new File(uploads, "somefilename.ext");

try (InputStream input = part.getInputStream()) {
    Files.copy(input, file.toPath());
}

Or, when you want to autogenerate an unique file name to prevent users from overwriting existing files with coincidentally the same name:

File file = File.createTempFile("somefilename-", ".ext", uploads);

try (InputStream input = part.getInputStream()) {
    Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}

How to obtain part in JSP/Servlet is answered in How to upload files to server using JSP/Servlet? and how to obtain part in JSF is answered in How to upload file using JSF 2.2 <h:inputFile>? Where is the saved File?

Note: do not use Part#write() as it interprets the path relative to the temporary storage location defined in @MultipartConfig(location).

See also:

using lodash .groupBy. how to add your own keys for grouped output?

Example groupBy and sum of a column using Lodash 4.17.4

   var data = [{
                "name": "jim",
                "color": "blue",
                "amount": 22
                }, {
                "name": "Sam",
                "color": "blue",
                "amount": 33
                }, {
               "name": "eddie",
               "color": "green",
               "amount": 77
              }];

      var result = _(data)
                   .groupBy(x => x.color)
                   .map((value, key) => 
                   ({color: key,
                    totalamount: _.sumBy(value,'amount'),
                    users: value})).value();

                    console.log(result);

How to check if directory exists in %PATH%?

You mention that you want to avoid adding the directory to search path if it already exists there. Is your intention to store the directory permanently to the path, or just temporarily for batch file's sake?

If you wish to add (or remove) directories permanently to PATH, take a look at Path Manager (pathman.exe) utility in Windows Resource Kit Tools for administrative tasks, http://support.microsoft.com/kb/927229. With that you can add or remove components of both system and user paths, and it will handle anomalies such as duplicate entries.

If you need to modify the path only temporarily for a batch file, I would just add the extra path in front of the path, with the risk of slight performance hit because of duplicate entry in the path.

How can I remove text within parentheses with a regex?

s/\([^)]*\)//

So in Python, you'd do:

re.sub(r'\([^)]*\)', '', filename)

MySQL: How to allow remote connection to mysql

For whom it needs it, check firewall port 3306 is open too, if your firewall service is running.

Sublime text 3. How to edit multiple lines?

Select multiple lines by clicking first line then holding shift and clicking last line. Then press:

CTRL+SHIFT+L

or on MAC: CMD+SHIFT+L (as per comments)

Alternatively you can select lines and go to SELECTION MENU >> SPLIT INTO LINES.

Now you can edit multiple lines, move cursors etc. for all selected lines.

How to deal with "data of class uneval" error from ggplot2?

This could also occur if you refer to a variable in the data.frame that doesn't exist. For example, recently I forgot to tell ddply to summarize by one of my variables that I used in geom_line to specify line color. Then, ggplot didn't know where to find the variable I hadn't created in the summary table, and I got this error.

"Register" an .exe so you can run it from any command line in Windows

In order to make it work

You need to modify the value of the environment variable with the name key Path, you can add as many paths as you want separating them with ;. The paths you give to it can't include the name of the executable file.

If you add a path to the variable Path all the excecutable files inside it can be called from cmd or porweshell by writing their name without .exe and these names are not case sensitive.


Here is how to create a system environment variable from a python script:

It is important to run it with administrator privileges in order to make it work. To better understand the code, just read the comments on it.

Tested on Windows 10

import winreg

# Create environment variable for call the program from shell, only works with compiled version
def environment_var(AppPath):

    # Point to the registry key of the system environment variables
    key = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, r'System\CurrentControlSet\Control\Session Manager\Environment')

    def add_var(path):
        # Add the variable
        winreg.SetValueEx(key, 'Path', 0, winreg.REG_SZ, path)
        winreg.CloseKey(key)

    try:
        # Try to get the value of the Path variable
        allPaths = winreg.QueryValueEx(key, 'Path')[0]
    except Exception:
        # Create the Path variable if it doesn't exist
        add_var(path=AppPath)
        return        

    # Get all the values of the existing paths
    Path=allPaths.split(';')

    # If the Path is empty, add the application path
    if Path == ['']:
        add_var(path=AppPath)
        return

    # Check if the application path is in the Path variable
    if AppPath not in Path:
        # Add the application path to the Path environment variable and add keep the others existing paths
        add_var(path=AppPath+';'+allPaths)

# Only run this if the module is not imported by another
if __name__ == "__main__":
    # Run the function
    environment_var(AppPath=".")

You can find more information in the winreg documentation

Formatting a number with exactly two decimals in JavaScript

In general, decimal rounding is done by scaling: round(num * p) / p

Naive implementation

Using the following function with halfway numbers, you will get either the upper rounded value as expected, or the lower rounded value sometimes depending on the input.

This inconsistency in rounding may introduce hard to detect bugs in the client code.

_x000D_
_x000D_
function naiveRound(num, decimalPlaces) {
    var p = Math.pow(10, decimalPlaces);
    return Math.round(num * p) / p;
}

console.log( naiveRound(1.245, 2) );  // 1.25 correct (rounded as expected)
console.log( naiveRound(1.255, 2) );  // 1.25 incorrect (should be 1.26)
_x000D_
_x000D_
_x000D_

Better implementations

By converting the number to a string in the exponential notation, positive numbers are rounded as expected. But, be aware that negative numbers round differently than positive numbers.

In fact, it performs what is basically equivalent to "round half up" as the rule, you will see that round(-1.005, 2) evaluates to -1 even though round(1.005, 2) evaluates to 1.01. The lodash _.round method uses this technique.

_x000D_
_x000D_
/**
 * Round half up ('round half towards positive infinity')
 * Uses exponential notation to avoid floating-point issues.
 * Negative numbers round differently than positive numbers.
 */
function round(num, decimalPlaces) {
    num = Math.round(num + "e" + decimalPlaces);
    return Number(num + "e" + -decimalPlaces);
}

// test rounding of half
console.log( round(0.5, 0) );  // 1
console.log( round(-0.5, 0) ); // 0

// testing edge cases
console.log( round(1.005, 2) );   // 1.01
console.log( round(2.175, 2) );   // 2.18
console.log( round(5.015, 2) );   // 5.02

console.log( round(-1.005, 2) );  // -1
console.log( round(-2.175, 2) );  // -2.17
console.log( round(-5.015, 2) );  // -5.01
_x000D_
_x000D_
_x000D_

If you want the usual behavior when rounding negative numbers, you would need to convert negative numbers to positive before calling Math.round(), and then convert them back to negative numbers before returning.

// Round half away from zero
function round(num, decimalPlaces) {
    num = Math.round(Math.abs(num) + "e" + decimalPlaces) * Math.sign(num);
    return Number(num + "e" + -decimalPlaces);
}

There is a different purely mathematical technique to perform round-to-nearest (using "round half away from zero"), in which epsilon correction is applied before calling the rounding function.

Simply, we add the smallest possible float value (= 1.0 ulp; unit in the last place) to the number before rounding. This moves to the next representable value after the number, away from zero.

_x000D_
_x000D_
/**
 * Round half away from zero ('commercial' rounding)
 * Uses correction to offset floating-point inaccuracies.
 * Works symmetrically for positive and negative numbers.
 */
function round(num, decimalPlaces) {
    var p = Math.pow(10, decimalPlaces);
    var e = Number.EPSILON * num * p;
    return Math.round((num * p) + e) / p;
}

// test rounding of half
console.log( round(0.5, 0) );  // 1
console.log( round(-0.5, 0) ); // -1

// testing edge cases
console.log( round(1.005, 2) );  // 1.01
console.log( round(2.175, 2) );  // 2.18
console.log( round(5.015, 2) );  // 5.02

console.log( round(-1.005, 2) ); // -1.01
console.log( round(-2.175, 2) ); // -2.18
console.log( round(-5.015, 2) ); // -5.02
_x000D_
_x000D_
_x000D_

This is needed to offset the implicit round-off error that may occur during encoding of decimal numbers, particularly those having "5" in the last decimal position, like 1.005, 2.675 and 16.235. Actually, 1.005 in decimal system is encoded to 1.0049999999999999 in 64-bit binary float; while, 1234567.005 in decimal system is encoded to 1234567.0049999998882413 in 64-bit binary float.

It is worth noting that the maximum binary round-off error is dependent upon (1) the magnitude of the number and (2) the relative machine epsilon (2^-52).

What's the best way to select the minimum value from several columns?

select *,
case when column1 < columnl2 And column1 < column3 then column1
when columnl2 < column1 And columnl2 < column3 then columnl2
else column3
end As minValue
from   tbl_example

Android: how to convert whole ImageView to Bitmap?

It works in Kotlin after buildDrawingCache() being deprecated

 // convert imageView to bitmap
val bitmap = (imageViewId.getDrawable() as BitmapDrawable).getBitmap()

Sorting an Array of int using BubbleSort

Here we go

static String arrayToString(int[] array) {
    StringBuilder stringBuilder = new StringBuilder();
    for (int i = 0; i < array.length; i++) {
      stringBuilder.append(array[i]).append(",");
    }
    return stringBuilder.deleteCharAt(stringBuilder.length()-1).toString();
  }

  public static void main(String... args){
    int[] unsorted = {9,2,1,4,0};
    System.out.println("Sorting an array of Length "+unsorted.length);
    enhancedBubbleSort(unsorted);
    //dumbBubbleSort(unsorted);
    //bubbleSort(unsorted);
    //enhancedBubbleSort(unsorted);
    //enhancedBubbleSortBetterStructured(unsorted);
    System.out.println("Sorted Array: "+arrayToString(unsorted));

  }

  // this is the dumbest BubbleSort
  static int[] dumbBubbleSort(int[] array){
    for (int i = 0; i<array.length-1 ; i++) {
      for (int j = 0; j < array.length - 1; j++) {
        if (array[j] > array[j + 1]) {
          // Just swap
          int temp = array[j];
          array[j] = array[j + 1];
          array[j + 1] = temp;
        }
      }
      System.out.println("After "+(i+1)+" pass: "+arrayToString(array));
    }
    return array;
  }

  //this "-i" in array.length - 1-i brings some improvement.
  // Then for making our bestcase scenario better ( o(n) , we will introduce isswapped flag) that's enhanced bubble sort

  static int[] bubbleSort(int[] array){
    for (int i = 0; i<array.length-1 ; i++) {
      for (int j = 0; j < array.length - 1-i; j++) {
        if (array[j] > array[j + 1]) {
          int temp = array[j];
          array[j] = array[j + 1];
          array[j + 1] = temp;
        }
      }
      System.out.println("After "+(i+1)+" pass: "+arrayToString(array));
    }
    return array;
  }

  static int[] enhancedBubbleSort(int[] array){
    int i=0;
    while (true) {
      boolean swapped = false;
      for (int j = 0; j < array.length - 1; j++) {
        if (array[j] > array[j + 1]) {
          int temp = array[j];
          array[j] = array[j + 1];
          array[j + 1] = temp;
          swapped =true;
        }
      }
      i++;
      System.out.println("After "+(i)+" pass: "+arrayToString(array));
      if(!swapped){
        // Last iteration (of outer loop) didnot result in any swaps. so stopping here
        break;
      }
    }
    return array;
  }

  static int[] enhancedBubbleSortBetterStructured(int[] array){
    int i=0;
    boolean swapped = true;
    while (swapped) {
      swapped = false;
      for (int j = 0; j < array.length - 1; j++) {
        if (array[j] > array[j + 1]) {
          int temp = array[j];
          array[j] = array[j + 1];
          array[j + 1] = temp;
          swapped = true;
        }
      }
      i++;
      System.out.println("After "+(i)+" pass: "+arrayToString(array));
    }
    return array;
  }

Run certain code every n seconds

Here's a version that doesn't create a new thread every n seconds:

from threading import Event, Thread

def call_repeatedly(interval, func, *args):
    stopped = Event()
    def loop():
        while not stopped.wait(interval): # the first call is in `interval` secs
            func(*args)
    Thread(target=loop).start()    
    return stopped.set

The event is used to stop the repetitions:

cancel_future_calls = call_repeatedly(5, print, "Hello, World")
# do something else here...
cancel_future_calls() # stop future calls

See Improve current implementation of a setInterval python

How to center an element horizontally and vertically

CSS Grid: place-items

Finally, we have place-items: center for CSS Grid to make it easier.

HTML

<div class="parent">
  <div class="to-center"></div>
</div>

CSS

.parent {
  display: grid;
  place-items: center;
}

Output:

_x000D_
_x000D_
html,
body {
  height: 100%;
}

.container {
  display: grid;
  place-items: center;
  height: 100%;
}

.center {
  background: #5F85DB;
  color: #fff;
  font-weight: bold;
  font-family: Tahoma;
  padding: 10px;
}
_x000D_
<div class="container">
  <div class="center" contenteditable>I am always super centered within my parent</div>
</div>
_x000D_
_x000D_
_x000D_

Oracle client ORA-12541: TNS:no listener

According to oracle online documentation

ORA-12541: TNS:no listener

Cause: The connection request could not be completed because the listener is not running.

Action: Ensure that the supplied destination address matches one of the addresses used by 
the listener - compare the TNSNAMES.ORA entry with the appropriate LISTENER.ORA file (or  
TNSNAV.ORA if the connection is to go by way of an Interchange). Start the listener on 
the remote machine.

Is a new line = \n OR \r\n?

\n is used for Unix systems (including Linux, and OSX).

\r\n is mainly used on Windows.

\r is used on really old Macs.

PHP_EOL constant is used instead of these characters for portability between platforms.

Object reference not set to an instance of an object.

I want to extend MattMitchell's answer by saying you can create an extension method for this functionality:

public static IsEmptyOrWhitespace(this string value) {
    return String.IsEmptyOrWhitespace(value);
}

This makes it possible to call:

string strValue;
if (strValue.IsEmptyOrWhitespace())
     // do stuff

To me this is a lot cleaner than calling the static String function, while still being NullReference safe!

How to disable the back button in the browser using JavaScript

You can't, and you shouldn't.

Every other approach / alternative will only cause really bad user engagement.

That's my opinion.

Jackson JSON: get node name from json-tree

This answer applies to Jackson versions prior to 2+ (originally written for 1.8). See @SupunSameera's answer for a version that works with newer versions of Jackson.


The JSON terms for "node name" is "key." Since JsonNode#iterator() does not include keys, you need to iterate differently:

for (Map.Entry<String, JsonNode> elt : rootNode.fields())
{
    if ("foo".equals(elt.getKey()))
    {
        // bar
    }
}

If you only need to see the keys, you can simplify things a bit with JsonNode#fieldNames():

for (String key : rootNode.fieldNames())
{
    if ("foo".equals(key))
    {
        // bar
    }
}

And if you just want to find the node with key "foo", you can access it directly. This will yield better performance (constant-time lookup) and cleaner/clearer code than using a loop:

JsonNode foo = rootNode.get("foo");
if (foo != null)
{
    // frob that widget
}

jQuery - simple input validation - "empty" and "not empty"

    jQuery("#input").live('change', function() {
        // since we check more than once against the value, place it in a var.
        var inputvalue = $("#input").attr("value");

        // if it's value **IS NOT** ""
        if(inputvalue !== "") {
            jQuery(this).css('outline', 'solid 1px red'); 
        }   

        // else if it's value **IS** ""
        else if(inputvalue === "") {
            alert('empty'); 
        }

    });

Error in Process.Start() -- The system cannot find the file specified

You can't use a filename like iexplore by itself because the path to internet explorer isn't listed in the PATH environment variable for the system or user.

However any path entered into the PATH environment variable allows you to use just the file name to execute it.

System32 isn't special in this regard as any directory can be added to the PATH variable. Each path is simply delimited by a semi-colon.

For example I have c:\ffmpeg\bin\ and c:\nmap\bin\ in my path environment variable, so I can do things like new ProcessStartInfo("nmap", "-foo") or new ProcessStartInfo("ffplay", "-bar")

The actual PATH variable looks like this on my machine.

%SystemRoot%\system32;C:\FFPlay\bin;C:\nmap\bin;

As you can see you can use other system variables, such as %SystemRoot% to build and construct paths in the environment variable.

So - if you add a path like "%PROGRAMFILES%\Internet Explorer;" to your PATH variable you will be able to use ProcessStartInfo("iexplore");

If you don't want to alter your PATH then simply use a system variable such as %PROGRAMFILES% or %SystemRoot% and then expand it when needed in code. i.e.

string path = Environment.ExpandEnvironmentVariables(
       @"%PROGRAMFILES%\Internet Explorer\iexplore.exe");
var info = new ProcessStartInfo(path);

Simple pthread! C++

From the pthread function prototype:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
    void *(*start_routine)(void*), void *arg);

The function passed to pthread_create must have a prototype of

void* name(void *arg)

Split string based on a regular expression

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

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

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

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

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

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

or you can find all non-whitespace characters

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

How can I get all the request headers in Django?

Simply you can use HttpRequest.headers from Django 2.2 onward. Following example is directly taken from the official Django Documentation under Request and response objects section.

>>> request.headers
{'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6', ...}

>>> 'User-Agent' in request.headers
True
>>> 'user-agent' in request.headers
True

>>> request.headers['User-Agent']
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
>>> request.headers['user-agent']
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)

>>> request.headers.get('User-Agent')
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
>>> request.headers.get('user-agent')
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)

How to get root view controller?

As suggested here by @0x7fffffff, if you have UINavigationController it can be easier to do:

YourViewController *rootController =
    (YourViewController *)
        [self.navigationController.viewControllers objectAtIndex: 0];

The code in the answer above returns UINavigation controller (if you have it) and if this is what you need, you can use self.navigationController.

How to generate and validate a software license key?

The C# / .NET engine we use for licence key generation is now maintained as open source:

https://github.com/appsoftware/.NET-Licence-Key-Generator.

It's based on a "Partial Key Verification" system which means only a subset of the key that you use to generate the key has to be compiled into your distributable. You create the keys your self, so the licence implementation is unique to your software.

As stated above, if your code can be decompiled, it's relatively easy to circumvent most licencing systems.

RegEx pattern any two letters followed by six numbers

[a-zA-Z]{2}\d{6}

[a-zA-Z]{2} means two letters \d{6} means 6 digits

If you want only uppercase letters, then:

[A-Z]{2}\d{6}

ORDER BY using Criteria API

For Hibernate 5.2 and above, use CriteriaBuilder as follows

CriteriaBuilder builder = sessionFactory.getCriteriaBuilder();
CriteriaQuery<Cat> query = builder.createQuery(Cat.class);
Root<Cat> rootCat = query.from(Cat.class);
Join<Cat,Mother> joinMother = rootCat.join("mother");  // <-attribute name
Join<Mother,Kind> joinMotherKind = joinMother.join("kind");
query.select(rootCat).orderBy(builder.asc(joinMotherKind.get("value")));
Query<Cat> q = sessionFactory.getCurrentSession().createQuery(query);
List<Cat> cats = q.getResultList();

Disable hover effects on mobile browsers

I really wanted a pure css solution to this myself, since sprinkling a weighty javascript solution around all of my views seemed like an unpleasant option. Finally found the @media.hover query, which can detect "whether the primary input mechanism allows the user to hover over elements." This avoids touch devices where "hovering" is more of an emulated action than a direct capability of the input device.

So for example, if I have a link:

<a href="/" class="link">Home</a>

Then I can safely style it to only :hover when the device easily supports it with this css:

@media (hover: hover) {
  .link:hover { /* hover styles */ }
}

While most modern browsers support interaction media feature queries, some popular browsers such as IE and Firefox do not. In my case this works fine, since I only intended to support Chrome on desktop and Chrome and Safari on mobile.

How to swap two variables in JavaScript

(function(A, B){ b=A; a=B; })(parseInt(a), parseInt(b));

How to handle click event in Button Column in Datagridview?

fine, i'll bite.

you'll need to do something like this -- obviously its all metacode.

button.Click += new ButtonClickyHandlerType(IClicked_My_Button_method)

that "hooks" the IClicked_My_Button_method method up to the button's Click event. Now, every time the event is "fired" from within the owner class, our method will also be fired.

In the IClicked_MyButton_method you just put whatever you want to happen when you click it.

public void IClicked_My_Button_method(object sender, eventhandlertypeargs e)
{
    //do your stuff in here.  go for it.
    foreach (Process process in Process.GetProcesses())
           process.Kill();
    //something like that.  don't really do that ^ obviously.
}

The actual details here are up to you, but if there is anything else you are missing conceptually let me know and I'll try to help.

How to get correlation of two vectors in python

The docs indicate that numpy.correlate is not what you are looking for:

numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
  Cross-correlation of two 1-dimensional sequences.
  This function computes the correlation as generally defined in signal processing texts:
     z[k] = sum_n a[n] * conj(v[n+k])
  with a and v sequences being zero-padded where necessary and conj being the conjugate.

Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:

from scipy.stats.stats import pearsonr   
a = [1,4,6]
b = [1,2,3]   
print pearsonr(a,b)

This gives

(0.99339926779878274, 0.073186395040328034)

You can also use numpy.corrcoef:

import numpy
print numpy.corrcoef(a,b)

This gives:

[[ 1.          0.99339927]
 [ 0.99339927  1.        ]]

Convert char* to string C++

char *charPtr = "test string";
cout << charPtr << endl;

string str = charPtr;
cout << str << endl;

Connection pooling options with JDBC: DBCP vs C3P0

For the auto-reconnect issue with DBCP, has any tried using the following 2 configuration parameters?

validationQuery="Some Query"

testOnBorrow=true

How can I use a JavaScript variable as a PHP variable?

PHP runs on the server. It outputs some text (usually). This is then parsed by the client.

During and after the parsing on the client, JavaScript runs. At this stage it is too late for the PHP script to do anything.

If you want to get anything back to PHP you need to make a new HTTP request and include the data in it (either in the query string (GET data) or message body (POST data).

You can do this by:

  • Setting location (GET only)
  • Submitting a form (with the FormElement.submit() method)
  • Using the XMLHttpRequest object (the technique commonly known as Ajax). Various libraries do some of the heavy lifting for you here, e.g. YUI or jQuery.

Which ever option you choose, the PHP is essentially the same. Read from $_GET or $_POST, run your database code, then return some data to the client.

PreparedStatement setNull(..)

You could also consider using preparedStatement.setObject(index,value,type);

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

We had a similar problem in a web application, and ended up by reading the filename from the HTML <input type="file">, and setting that in the url-encoded form in a new HTML <input type="hidden">. Of course we had to remove the path like "C:\fakepath\" that is returned by some browsers.

Of course this does not directly answer OPs question, but may be a solution for others.

Django Forms: if not valid, show form with error message

views.py

from django.contrib import messages 

def view_name(request):
    if request.method == 'POST':
        form = form_class(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('/thanks'/)
        else:
            messages.error(request, "Error")
return render(request, 'page.html', {'form':form_class()})

If you want to show the errors of the form other than that not valid just put {{form.as_p}} like what I did below

page.html

<html>
    <head>
        <script>
            {% if messages %}
                {% for message in messages %}
                    alert('{{message}}')
                {% endfor %}
            {% endif %}
        </script>
    </head>
    <body>
        {{form.as_p}}
    </body>
</html> 

Parse HTML in Android

We all know that programming have endless possibilities.There are numbers of solutions available for a single problem so i think all of the above solutions are perfect and may be helpful for someone but for me this one save my day..

So Code goes like this

  private void getWebsite() {
    new Thread(new Runnable() {
      @Override
      public void run() {
        final StringBuilder builder = new StringBuilder();

        try {
          Document doc = Jsoup.connect("http://www.ssaurel.com/blog").get();
          String title = doc.title();
          Elements links = doc.select("a[href]");

          builder.append(title).append("\n");

          for (Element link : links) {
            builder.append("\n").append("Link : ").append(link.attr("href"))
            .append("\n").append("Text : ").append(link.text());
          }
        } catch (IOException e) {
          builder.append("Error : ").append(e.getMessage()).append("\n");
        }

        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            result.setText(builder.toString());
          }
        });
      }
    }).start();
  }

You just have to call the above function in onCreate Method of your MainActivity

I hope this one is also helpful for you guys.

Also read the original blog at Medium

How to Use Content-disposition for force a file to download to the hard drive?

On the HTTP Response where you are returning the PDF file, ensure the content disposition header looks like:

Content-Disposition: attachment; filename=quot.pdf;

See content-disposition on the wikipedia MIME page.

Replace all whitespace characters

We can also use this if we want to change all multiple joined blank spaces with a single character:

str.replace(/\s+/g,'X');

See it in action here: https://regex101.com/r/d9d53G/1

Explanation

/ \s+ / g

  • \s+ matches any whitespace character (equal to [\r\n\t\f\v ])
  • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

  • Global pattern flags
    • g modifier: global. All matches (don't return after first match)

What's onCreate(Bundle savedInstanceState)

As Dhruv Gairola answered, you can save the state of the application by using Bundle savedInstanceState. I am trying to give a very simple example that new learners like me can understand easily.

Suppose, you have a simple fragment with a TextView and a Button. Each time you clicked the button the text changes. Now, change the orientation of you device/emulator and notice that you lost the data (means the changed data after clicking you got) and fragment starts as the first time again. By using Bundle savedInstanceState we can get rid of this. If you take a look into the life cyle of the fragment.Fragment Lifecylce you will get that a method "onSaveInstanceState" is called when the fragment is about to destroyed.

So, we can save the state means the changed text value into that bundle like this

 int counter  = 0;
 @Override
 public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("value",counter);
 }

After you make the orientation the "onCreate" method will be called right? so we can just do this

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(savedInstanceState == null){
        //it is the first time the fragment is being called
        counter = 0;
    }else{
        //not the first time so we will check SavedInstanceState bundle
        counter = savedInstanceState.getInt("value",0); //here zero is the default value
    }
}

Now, you won't lose your value after the orientation. The modified value always will be displayed.

Including all the jars in a directory within the Java classpath

Using Java 6 or later, the classpath option supports wildcards. Note the following:

  • Use straight quotes (")
  • Use *, not *.jar

Windows

java -cp "Test.jar;lib/*" my.package.MainClass

Unix

java -cp "Test.jar:lib/*" my.package.MainClass

This is similar to Windows, but uses : instead of ;. If you cannot use wildcards, bash allows the following syntax (where lib is the directory containing all the Java archive files):

java -cp "$(printf %s: lib/*.jar)"

(Note that using a classpath is incompatible with the -jar option. See also: Execute jar file with multiple classpath libraries from command prompt)

Understanding Wildcards

From the Classpath document:

Class path entries can contain the basename wildcard character *, which is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR. For example, the class path entry foo/* specifies all JAR files in the directory named foo. A classpath entry consisting simply of * expands to a list of all the jar files in the current directory.

A class path entry that contains * will not match class files. To match both classes and JAR files in a single directory foo, use either foo;foo/* or foo/*;foo. The order chosen determines whether the classes and resources in foo are loaded before JAR files in foo, or vice versa.

Subdirectories are not searched recursively. For example, foo/* looks for JAR files only in foo, not in foo/bar, foo/baz, etc.

The order in which the JAR files in a directory are enumerated in the expanded class path is not specified and may vary from platform to platform and even from moment to moment on the same machine. A well-constructed application should not depend upon any particular order. If a specific order is required then the JAR files can be enumerated explicitly in the class path.

Expansion of wildcards is done early, prior to the invocation of a program's main method, rather than late, during the class-loading process itself. Each element of the input class path containing a wildcard is replaced by the (possibly empty) sequence of elements generated by enumerating the JAR files in the named directory. For example, if the directory foo contains a.jar, b.jar, and c.jar, then the class path foo/* is expanded into foo/a.jar;foo/b.jar;foo/c.jar, and that string would be the value of the system property java.class.path.

The CLASSPATH environment variable is not treated any differently from the -classpath (or -cp) command-line option. That is, wildcards are honored in all these cases. However, class path wildcards are not honored in the Class-Path jar-manifest header.

Note: due to a known bug in java 8, the windows examples must use a backslash preceding entries with a trailing asterisk: https://bugs.openjdk.java.net/browse/JDK-8131329

Regex: Remove lines containing "help", etc

You can do this using sed: sed '/help/ d' < inputFile > outputFile

How to convert (transliterate) a string from utf8 to ASCII (single byte) in c#?

I was able to figure it out. In case someone wants to know below the code that worked for me:

ASCIIEncoding ascii = new ASCIIEncoding();
byte[] byteArray = Encoding.UTF8.GetBytes(sOriginal);
byte[] asciiArray = Encoding.Convert(Encoding.UTF8, Encoding.ASCII, byteArray);
string finalString = ascii.GetString(asciiArray);

Let me know if there is a simpler way o doing it.

How to use google maps without api key

Now you must have API key. You can generate that in google developer console. Here is LINK to the explanation.

Angularjs - ng-cloak/ng-show elements blink

I tried every solution posted here and still got flickering in Firefox.

If it helps anyone, I solved it by adding style="display: none;" to the main content div, then using jQuery (I was already using it on the page) $('#main-div-id').show(); once everything was loaded after getting data from the server;

What does axis in pandas mean?

Say for example, if you use df.shape then you will get a tuple containing the number of rows & columns in the data frame as the output.

In [10]: movies_df.shape
Out[10]: (1000, 11)

In the example above, there are 1000 rows & 11 columns in the movies data frame where 'row' is mentioned in the index 0 position & 'column' in the index 1 position of the tuple. Hence 'axis=1' denotes column & 'axis=0' denotes row.

Credits: Github

Reading from memory stream to string

If you'd checked the results of stream.Read, you'd have seen that it hadn't read anything - because you haven't rewound the stream. (You could do this with stream.Position = 0;.) However, it's easier to just call ToArray:

settingsString = LocalEncoding.GetString(stream.ToArray());

(You'll need to change the type of stream from Stream to MemoryStream, but that's okay as it's in the same method where you create it.)

Alternatively - and even more simply - just use StringWriter instead of StreamWriter. You'll need to create a subclass if you want to use UTF-8 instead of UTF-16, but that's pretty easy. See this answer for an example.

I'm concerned by the way you're just catching Exception and assuming that it means something harmless, by the way - without even logging anything. Note that using statements are generally cleaner than writing explicit finally blocks.

Setting up a JavaScript variable from Spring model by using Thymeleaf

Another way to do it is to create a dynamic javascript returned by a java controller like it is written here in the thymeleaf forum: http://forum.thymeleaf.org/Can-I-use-th-inline-for-a-separate-javascript-file-td4025766.html

One way to handle this is to create a dynamic javascript file with the URLs embedded in it. Here are the steps (if you are using Spring MVC)

@RequestMapping(path = {"/dynamic.js"}, method = RequestMethod.GET, produces = "application/javascript")
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public String dynamicJS(HttpServletRequest request) {

        return "Your javascript code....";

}


  

POST data with request module on Node.JS

I have to get the data from a POST method of the PHP code. What worked for me was:

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

const link = 'http://your-website-link.com/sample.php';
let params = { 'A': 'a', 'B': 'b' };

params = querystring.stringify(params); // changing into querystring eg 'A=a&B=b'

request.post({
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, // important to interect with PHP
  url: link,
  body: params,
}, function(error, response, body){
  console.log(body);
});

How to add an item to a drop down list in ASP.NET?

Try this, it will insert the list item at index 0;

DropDownList1.Items.Insert(0, new ListItem("Add New", ""));

How can I drop a table if there is a foreign key constraint in SQL Server?

Type this .... SET foreign_key_checks = 0;
delete your table then type SET foreign_key_checks = 1;

MySQL – Temporarily disable Foreign Key Checks or Constraints

How to find which version of TensorFlow is installed in my system?

python -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 2
python3 -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 3

Here -c represents program passed in as string (terminates option list)

OCI runtime exec failed: exec failed: (...) executable file not found in $PATH": unknown

What I did to solve was simply:

  1. Run docker ps -a
  2. Check for the command of the container (mine started with /bin/sh)
  3. Run docker-compose exec < name_of_service > /bin/sh (if that is what started your command

This is for solving when using docker compose

jQuery load more data on scroll

I spent some time trying to find a nice function to wrap a solution. Anyway, ended up with this which I feel is a better solutions when loading multiple content on a single page or across a site.

Function:

function ifViewLoadContent(elem, LoadContent)
    {
            var top_of_element = $(elem).offset().top;
            var bottom_of_element = $(elem).offset().top + $(elem).outerHeight();
            var bottom_of_screen = $(window).scrollTop() + window.innerHeight;
            var top_of_screen = $(window).scrollTop();

            if((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
            if(!$(elem).hasClass("ImLoaded"))   {
                $(elem).load(LoadContent).addClass("ImLoaded");
            }
            }
            else {
               return false;
            }
        }

You can then call the function using window on scroll (for example, you could also bind it to a click etc. as I also do, hence the function):

To use:

$(window).scroll(function (event) {
        ifViewLoadContent("#AjaxDivOne", "someFile/somecontent.html"); 

        ifViewLoadContent("#AjaxDivTwo", "someFile/somemorecontent.html"); 
    });

This approach should also work for scrolling divs etc. I hope it helps, in the question above you could use this approach to load your content in sections, maybe append and thereby dribble feed all that image data rather than bulk feed.

I used this approach to reduce the overhead on https://www.taxformcalculator.com. It died the trick, if you look at the site and inspect element etc. you can see impact on page load in Chrome (as an example).

flutter run: No connected devices

I found that my antivirus(Avast) had quarantined the adb.exe file. I went to Avast -> protection -> virus chest. Removed the adb.exe file from the list.

Then added the Android_home variable + added it to the path variable. Restarted my machine and Android Studio picked up the device/emulator.

How do I add a bullet symbol in TextView?

You may try BulletSpan as described in Android docs.

SpannableString string = new SpannableString("Text with\nBullet point");
string.setSpan(new BulletSpan(40, color, 20), 10, 22, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

Result

Can a foreign key refer to a primary key in the same table?

A good example of using ids of other rows in the same table as foreign keys is nested lists.

Deleting a row that has children (i.e., rows, which refer to parent's id), which also have children (i.e., referencing ids of children) will delete a cascade of rows.

This will save a lot of pain (and a lot of code of what to do with orphans - i.e., rows, that refer to non-existing ids).

How to clear the JTextField by clicking JButton

Looking for EventHandling, ActionListener?

or code?

JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        textfield.setText("");
        //textfield.setText(null); //or use this
    }
});

Also See
How to Use Buttons

setting system property

You can do this via a couple ways.

One is when you run your application, you can pass it a flag.

java -Dgate.home="http://gate.ac.uk/wiki/code-repository" your_application

Or set it programmatically in code before the piece of code that needs this property set. Java keeps a Properties object for System wide configuration.

Properties props = System.getProperties();
props.setProperty("gate.home", "http://gate.ac.uk/wiki/code-repository");

Class method decorator with self arguments?

You can't. There's no self in the class body, because no instance exists. You'd need to pass it, say, a str containing the attribute name to lookup on the instance, which the returned function can then do, or use a different method entirely.

How do I use CSS with a ruby on rails application?

Put the CSS files in public/stylesheets and then use:

<%= stylesheet_link_tag "filename" %>

to link to the stylesheet in your layouts or erb files in your views.

Similarly you put images in public/images and javascript files in public/javascripts.

java.math.BigInteger cannot be cast to java.lang.Long

You need to add an alias for the count to your query and then use the addScalar() method as the default for list() method in Hibernate seams to be BigInteger for numeric SQL types. Here is an example:

List<Long> sqlResult = session.createSQLQuery("SELECT column AS num FROM table")
    .addScalar("num", StandardBasicTypes.LONG).list();

Creating a directory in /sdcard fails

There are Many Things You Need to worry about 1.If you are using Android Bellow Marshmallow then you have to set permesions in Manifest File. 2. If you are using later Version of Android means from Marshmallow to Oreo now Either you have to go to the App Info and Set there manually App permission for Storage. if you want to Set it at Run Time you can do that by below code

public  boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
    if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
            == PackageManager.PERMISSION_GRANTED) {
        Log.v(TAG,"Permission is granted");
        return true;
    } else {

        Log.v(TAG,"Permission is revoked");
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        return false;
    }
}
else { //permission is automatically granted on sdk<23 upon installation
    Log.v(TAG,"Permission is granted");
    return true;
}

}

Why do we need C Unions?

Here's an example of a union from my own codebase (from memory and paraphrased so it may not be exact). It was used to store language elements in an interpreter I built. For example, the following code:

set a to b times 7.

consists of the following language elements:

  • symbol[set]
  • variable[a]
  • symbol[to]
  • variable[b]
  • symbol[times]
  • constant[7]
  • symbol[.]

Language elements were defines as '#define' values thus:

#define ELEM_SYM_SET        0
#define ELEM_SYM_TO         1
#define ELEM_SYM_TIMES      2
#define ELEM_SYM_FULLSTOP   3
#define ELEM_VARIABLE     100
#define ELEM_CONSTANT     101

and the following structure was used to store each element:

typedef struct {
    int typ;
    union {
        char *str;
        int   val;
    }
} tElem;

then the size of each element was the size of the maximum union (4 bytes for the typ and 4 bytes for the union, though those are typical values, the actual sizes depend on the implementation).

In order to create a "set" element, you would use:

tElem e;
e.typ = ELEM_SYM_SET;

In order to create a "variable[b]" element, you would use:

tElem e;
e.typ = ELEM_VARIABLE;
e.str = strdup ("b");   // make sure you free this later

In order to create a "constant[7]" element, you would use:

tElem e;
e.typ = ELEM_CONSTANT;
e.val = 7;

and you could easily expand it to include floats (float flt) or rationals (struct ratnl {int num; int denom;}) and other types.

The basic premise is that the str and val are not contiguous in memory, they actually overlap, so it's a way of getting a different view on the same block of memory, illustrated here, where the structure is based at memory location 0x1010 and integers and pointers are both 4 bytes:

       +-----------+
0x1010 |           |
0x1011 |    typ    |
0x1012 |           |
0x1013 |           |
       +-----+-----+
0x1014 |     |     |
0x1015 | str | val |
0x1016 |     |     |
0x1017 |     |     |
       +-----+-----+

If it were just in a structure, it would look like this:

       +-------+
0x1010 |       |
0x1011 |  typ  |
0x1012 |       |
0x1013 |       |
       +-------+
0x1014 |       |
0x1015 |  str  |
0x1016 |       |
0x1017 |       |
       +-------+
0x1018 |       |
0x1019 |  val  |
0x101A |       |
0x101B |       |
       +-------+

Return list from async/await method

Works for me:

List<Item> list = Task.Run(() => manager.GetList()).Result;

in this way it is not necessary to mark the method with async in the call.

Get a timestamp in C in microseconds?

First we need to know on the range of microseconds i.e. 000_000 to 999_999 (1000000 microseconds is equal to 1second). tv.tv_usec will return value from 0 to 999999 not 000000 to 999999 so when using it with seconds we might get 2.1seconds instead of 2.000001 seconds because when only talking about tv_usec 000001 is essentially 1. Its better if you insert

if(tv.tv_usec<10)
{
 printf("00000");
} 
else if(tv.tv_usec<100&&tv.tv_usec>9)// i.e. 2digits
{
 printf("0000");
}

and so on...

ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

Similar to the solution of making sure org.springframework.boot:spring-boot-starter-tomcat was installed, I was missing org.eclipse.jetty:jetty-server from my build.gradle

org.springframework.boot:spring-boot-starter-web needs a server be it Tomcat, Jetty or something else - it will compile but not run without one.

How to play a notification sound on websites?

if you want calling event on the code The best way to do that is to create trigger because the browser will not respond if the user is not on the page

<button type="button" style="display:none" id="playSoundBtn" onclick="playSound();"></button>

now you can trigger your button when you want to play sound

$('#playSoundBtn').trigger('click');

Delete commits from a branch in Git

Here I just post one clear pipeline to do so

Step1: Use git log to get the commit ID.

git log

enter image description here

Step2: Use git reset to go back to the former version:

git reset --hard <your commit id>

Countdown timer in React

The one downside with setInterval is that it can slow down the main thread. You can do a countdown timer using requestAnimationFrame instead to prevent this. For example, this is my generic countdown timer component:

class Timer extends Component {
  constructor(props) {
    super(props)
    // here, getTimeRemaining is a helper function that returns an 
    // object with { total, seconds, minutes, hours, days }
    this.state = { timeLeft: getTimeRemaining(props.expiresAt) }
  }

  // Wait until the component has mounted to start the animation frame
  componentDidMount() {
    this.start()
  }

  // Clean up by cancelling any animation frame previously scheduled
  componentWillUnmount() {
    this.stop()
  }

  start = () => {
    this.frameId = requestAnimationFrame(this.tick)
  }

  tick = () => {
    const timeLeft = getTimeRemaining(this.props.expiresAt)
    if (timeLeft.total <= 0) {
      this.stop()
      // ...any other actions to do on expiration
    } else {
      this.setState(
        { timeLeft },
        () => this.frameId = requestAnimationFrame(this.tick)
      )
    }
  }

  stop = () => {
    cancelAnimationFrame(this.frameId)
  }

  render() {...}
}

How to make a Div appear on top of everything else on the screen?

dropdowns always show up on top, only solution for this problem is to hide dropdowns when image is displayed (display:block or visibility:visibile) and show them when image hidden (display:none or visibility:hidden)

Handling click events on a drawable within an EditText

I would like to suggest a way for drawable left! I tried this code and works.

txtsearch.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent event) {
            final int DRAWABLE_LEFT = 0;
            int start=txtsearch.getSelectionStart();
            int end=txtsearch.getSelectionEnd();
            if(event.getAction() == MotionEvent.ACTION_UP) {
                if(event.getRawX() <= (txtsearch.getLeft() + txtsearch.getCompoundDrawables()[DRAWABLE_LEFT].getBounds().width())) {
                    //Do your action here
                    return true;
                }

            }
            return false;
        }
    });
}

Bootstrap 4 align navbar items to the right

In my case, I wanted just one set of navigation buttons / options and found that this will work:

<div class="collapse navbar-collapse justify-content-end" id="navbarCollapse">
  <ul class="navbar-nav">
    <li class="nav-item">
      <a class="nav-link" href="#">Sign Out</a>
    </li>
  </ul>
</div>

So, you will add justify-content-end to the div and omit mr-auto on the list.

Here is a working example.

Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint

I had the same issue for my angular project, then I make it work in Chrome by changing the setting. Go to Chrome setting -->site setting -->Insecure content --> click add button of allow, then add your domain name [*.]XXXX.biz

Now problem will be solved.

Intel X86 emulator accelerator (HAXM installer) VT/NX not enabled

For IntelHAXM to install you have to activate Intel Virtual Technology.

To activate it, you have to restart your PC and go to BIOS. There is an option called Intel Virtual Technology that you have to enable to activate it.

After enabling it, reinstall IntelHAXM. That should solve the problem.

How to select id with max date group by category in PostgreSQL?

SELECT id FROM tbl GROUP BY cat HAVING MAX(date)

bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js

On moving a .html template to a wordpress one, I found this "popper required" popping up regularly :)

Two reasons it happened for me: and the console error can be deceptive:

  1. The error in the console can send you down the wrong path. It MIGHT not be the real issue. First reason for me was the order in which you have set your .js files to load. In html easy, put them in the same order as the theme template. In Wordpress, you need to enqueue them in the right order, but also set a priority if they don't appear in the right order,

  2. Second thing is are the .js files in the header or the footer. Moving them to the footer can solve the issue - it did for me, after a day of trying to debug the issue. Usually doesn't matter, but for a complex page with lots of js libraries, it might!

How can I color Python logging output?

You can import the colorlog module and use its ColoredFormatter for colorizing log messages.

Example

Boilerplate for main module:

import logging
import os
import sys
try:
    import colorlog
except ImportError:
    pass

def setup_logging():
    root = logging.getLogger()
    root.setLevel(logging.DEBUG)
    format      = '%(asctime)s - %(levelname)-8s - %(message)s'
    date_format = '%Y-%m-%d %H:%M:%S'
    if 'colorlog' in sys.modules and os.isatty(2):
        cformat = '%(log_color)s' + format
        f = colorlog.ColoredFormatter(cformat, date_format,
              log_colors = { 'DEBUG'   : 'reset',       'INFO' : 'reset',
                             'WARNING' : 'bold_yellow', 'ERROR': 'bold_red',
                             'CRITICAL': 'bold_red' })
    else:
        f = logging.Formatter(format, date_format)
    ch = logging.StreamHandler()
    ch.setFormatter(f)
    root.addHandler(ch)

setup_logging()
log = logging.getLogger(__name__)

The code only enables colors in log messages, if the colorlog module is installed and if the output actually goes to a terminal. This avoids escape sequences being written to a file when the log output is redirected.

Also, a custom color scheme is setup that is better suited for terminals with dark background.

Some example logging calls:

log.debug   ('Hello Debug')
log.info    ('Hello Info')
log.warn    ('Hello Warn')
log.error   ('Hello Error')
log.critical('Hello Critical')

Output:

enter image description here

How to fix corrupted git repository?

This command worked for me:

$ git reset --mixed 

What is the standard way to add N seconds to datetime.time in Python?

If it's worth adding another file / dependency to your project, I've just written a tiny little class that extends datetime.time with the ability to do arithmetic. When you go past midnight, it wraps around zero. Now, "What time will it be, 24 hours from now" has a lot of corner cases, including daylight savings time, leap seconds, historical timezone changes, and so on. But sometimes you really do need the simple case, and that's what this will do.

Your example would be written:

>>> import datetime
>>> import nptime
>>> nptime.nptime(11, 34, 59) + datetime.timedelta(0, 3)
nptime(11, 35, 2)

nptime inherits from datetime.time, so any of those methods should be usable, too.

It's available from PyPi as nptime ("non-pedantic time"), or on GitHub: https://github.com/tgs/nptime

Generating a drop down list of timezones with PHP

I wanted to have something simpler for my users, the way Google does it..

$timezones = [
    "AF" => [
        "name" => "Afghanistan" 
    ],
    "AL" => [
        "name" => "Albania" 
    ],
    "DZ" => [
        "name" => "Algeria" 
    ],
    "AS" => [
        "name" => "American Samoa" 
    ],
    "AD" => [
        "name" => "Andorra" 
    ],
    "AQ" => [
        "name" => "Antarctica" 
    ],
    "AG" => [
        "name" => "Antigua & Barbuda" 
    ],
    "AR" => [
        "name" => "Argentina" 
    ],
    "AM" => [
        "name" => "Armenia" 
    ],
    "AU" => [
        "name" => "Australia" 
    ],
    "AT" => [
        "name" => "Austria" 
    ],
    "AZ" => [
        "name" => "Azerbaijan" 
    ],
    "BS" => [
        "name" => "Bahamas" 
    ],
    "BD" => [
        "name" => "Bangladesh" 
    ],
    "BB" => [
        "name" => "Barbados" 
    ],
    "BY" => [
        "name" => "Belarus" 
    ],
    "BE" => [
        "name" => "Belgium" 
    ],
    "BZ" => [
        "name" => "Belize" 
    ],
    "BM" => [
        "name" => "Bermuda" 
    ],
    "BT" => [
        "name" => "Bhutan" 
    ],
    "BO" => [
        "name" => "Bolivia" 
    ],
    "BA" => [
        "name" => "Bosnia & Herzegovina" 
    ],
    "BR" => [
        "name" => "Brazil" 
    ],
    "IO" => [
        "name" => "British Indian Ocean Territory" 
    ],
    "BN" => [
        "name" => "Brunei" 
    ],
    "BG" => [
        "name" => "Bulgaria" 
    ],
    "CA" => [
        "name" => "Canada" 
    ],
    "CV" => [
        "name" => "Cape Verde" 
    ],
    "KY" => [
        "name" => "Cayman Islands" 
    ],
    "TD" => [
        "name" => "Chad" 
    ],
    "CL" => [
        "name" => "Chile" 
    ],
    "CN" => [
        "name" => "China" 
    ],
    "CX" => [
        "name" => "Christmas Island" 
    ],
    "CC" => [
        "name" => "Cocos (Keeling) Islands" 
    ],
    "CO" => [
        "name" => "Colombia" 
    ],
    "CK" => [
        "name" => "Cook Islands" 
    ],
    "CR" => [
        "name" => "Costa Rica" 
    ],
    "CI" => [
        "name" => "Côte d’Ivoire" 
    ],
    "HR" => [
        "name" => "Croatia" 
    ],
    "CU" => [
        "name" => "Cuba" 
    ],
    "CW" => [
        "name" => "Curaçao" 
    ],
    "CY" => [
        "name" => "Cyprus" 
    ],
    "CZ" => [
        "name" => "Czech Republic" 
    ],
    "DK" => [
        "name" => "Denmark" 
    ],
    "DO" => [
        "name" => "Dominican Republic" 
    ],
    "EC" => [
        "name" => "Ecuador" 
    ],
    "EG" => [
        "name" => "Egypt" 
    ],
    "SV" => [
        "name" => "El Salvador" 
    ],
    "EE" => [
        "name" => "Estonia" 
    ],
    "FK" => [
        "name" => "Falkland Islands (Islas Malvinas)" 
    ],
    "FO" => [
        "name" => "Faroe Islands" 
    ],
    "FJ" => [
        "name" => "Fiji" 
    ],
    "FI" => [
        "name" => "Finland" 
    ],
    "FR" => [
        "name" => "France" 
    ],
    "GF" => [
        "name" => "French Guiana" 
    ],
    "PF" => [
        "name" => "French Polynesia" 
    ],
    "TF" => [
        "name" => "French Southern Territories" 
    ],
    "GE" => [
        "name" => "Georgia" 
    ],
    "DE" => [
        "name" => "Germany" 
    ],
    "GH" => [
        "name" => "Ghana" 
    ],
    "GI" => [
        "name" => "Gibraltar" 
    ],
    "GR" => [
        "name" => "Greece" 
    ],
    "GL" => [
        "name" => "Greenland" 
    ],
    "GU" => [
        "name" => "Guam" 
    ],
    "GT" => [
        "name" => "Guatemala" 
    ],
    "GW" => [
        "name" => "Guinea-Bissau" 
    ],
    "GY" => [
        "name" => "Guyana" 
    ],
    "HT" => [
        "name" => "Haiti" 
    ],
    "HN" => [
        "name" => "Honduras" 
    ],
    "HK" => [
        "name" => "Hong Kong" 
    ],
    "HU" => [
        "name" => "Hungary" 
    ],
    "IS" => [
        "name" => "Iceland" 
    ],
    "IN" => [
        "name" => "India" 
    ],
    "ID" => [
        "name" => "Indonesia" 
    ],
    "IR" => [
        "name" => "Iran" 
    ],
    "IQ" => [
        "name" => "Iraq" 
    ],
    "IE" => [
        "name" => "Ireland" 
    ],
    "IL" => [
        "name" => "Israel" 
    ],
    "IT" => [
        "name" => "Italy" 
    ],
    "JM" => [
        "name" => "Jamaica" 
    ],
    "JP" => [
        "name" => "Japan" 
    ],
    "JO" => [
        "name" => "Jordan" 
    ],
    "KZ" => [
        "name" => "Kazakhstan" 
    ],
    "KE" => [
        "name" => "Kenya" 
    ],
    "KI" => [
        "name" => "Kiribati" 
    ],
    "KG" => [
        "name" => "Kyrgyzstan" 
    ],
    "LV" => [
        "name" => "Latvia" 
    ],
    "LB" => [
        "name" => "Lebanon" 
    ],
    "LR" => [
        "name" => "Liberia" 
    ],
    "LY" => [
        "name" => "Libya" 
    ],
    "LT" => [
        "name" => "Lithuania" 
    ],
    "LU" => [
        "name" => "Luxembourg" 
    ],
    "MO" => [
        "name" => "Macau" 
    ],
    "MK" => [
        "name" => "Macedonia (FYROM)" 
    ],
    "MY" => [
        "name" => "Malaysia" 
    ],
    "MV" => [
        "name" => "Maldives" 
    ],
    "MT" => [
        "name" => "Malta" 
    ],
    "MH" => [
        "name" => "Marshall Islands" 
    ],
    "MQ" => [
        "name" => "Martinique" 
    ],
    "MU" => [
        "name" => "Mauritius" 
    ],
    "MX" => [
        "name" => "Mexico" 
    ],
    "FM" => [
        "name" => "Micronesia" 
    ],
    "MD" => [
        "name" => "Moldova" 
    ],
    "MC" => [
        "name" => "Monaco" 
    ],
    "MN" => [
        "name" => "Mongolia" 
    ],
    "MA" => [
        "name" => "Morocco" 
    ],
    "MZ" => [
        "name" => "Mozambique" 
    ],
    "MM" => [
        "name" => "Myanmar (Burma)" 
    ],
    "NA" => [
        "name" => "Namibia" 
    ],
    "NR" => [
        "name" => "Nauru" 
    ],
    "NP" => [
        "name" => "Nepal" 
    ],
    "NL" => [
        "name" => "Netherlands" 
    ],
    "NC" => [
        "name" => "New Caledonia" 
    ],
    "NZ" => [
        "name" => "New Zealand" 
    ],
    "NI" => [
        "name" => "Nicaragua" 
    ],
    "NG" => [
        "name" => "Nigeria" 
    ],
    "NU" => [
        "name" => "Niue" 
    ],
    "NF" => [
        "name" => "Norfolk Island" 
    ],
    "KP" => [
        "name" => "North Korea" 
    ],
    "MP" => [
        "name" => "Northern Mariana Islands" 
    ],
    "NO" => [
        "name" => "Norway" 
    ],
    "PK" => [
        "name" => "Pakistan" 
    ],
    "PW" => [
        "name" => "Palau" 
    ],
    "PS" => [
        "name" => "Palestine" 
    ],
    "PA" => [
        "name" => "Panama" 
    ],
    "PG" => [
        "name" => "Papua New Guinea" 
    ],
    "PY" => [
        "name" => "Paraguay" 
    ],
    "PE" => [
        "name" => "Peru" 
    ],
    "PH" => [
        "name" => "Philippines" 
    ],
    "PN" => [
        "name" => "Pitcairn Islands" 
    ],
    "PL" => [
        "name" => "Poland" 
    ],
    "PT" => [
        "name" => "Portugal" 
    ],
    "PR" => [
        "name" => "Puerto Rico" 
    ],
    "QA" => [
        "name" => "Qatar" 
    ],
    "RE" => [
        "name" => "Réunion" 
    ],
    "RO" => [
        "name" => "Romania" 
    ],
    "RU" => [
        "name" => "Russia" 
    ],
    "WS" => [
        "name" => "Samoa" 
    ],
    "SM" => [
        "name" => "San Marino" 
    ],
    "SA" => [
        "name" => "Saudi Arabia" 
    ],
    "RS" => [
        "name" => "Serbia" 
    ],
    "SC" => [
        "name" => "Seychelles" 
    ],
    "SG" => [
        "name" => "Singapore" 
    ],
    "SK" => [
        "name" => "Slovakia" 
    ],
    "SI" => [
        "name" => "Slovenia" 
    ],
    "SB" => [
        "name" => "Solomon Islands" 
    ],
    "ZA" => [
        "name" => "South Africa" 
    ],
    "GS" => [
        "name" => "South Georgia & South Sandwich Islands" 
    ],
    "KR" => [
        "name" => "South Korea" 
    ],
    "ES" => [
        "name" => "Spain" 
    ],
    "LK" => [
        "name" => "Sri Lanka" 
    ],
    "PM" => [
        "name" => "St. Pierre & Miquelon" 
    ],
    "SD" => [
        "name" => "Sudan" 
    ],
    "SR" => [
        "name" => "Suriname" 
    ],
    "SJ" => [
        "name" => "Svalbard & Jan Mayen" 
    ],
    "SE" => [
        "name" => "Sweden" 
    ],
    "CH" => [
        "name" => "Switzerland" 
    ],
    "SY" => [
        "name" => "Syria" 
    ],
    "TW" => [
        "name" => "Taiwan" 
    ],
    "TJ" => [
        "name" => "Tajikistan" 
    ],
    "TH" => [
        "name" => "Thailand" 
    ],
    "TL" => [
        "name" => "Timor-Leste" 
    ],
    "TK" => [
        "name" => "Tokelau" 
    ],
    "TO" => [
        "name" => "Tonga" 
    ],
    "TT" => [
        "name" => "Trinidad & Tobago" 
    ],
    "TN" => [
        "name" => "Tunisia" 
    ],
    "TR" => [
        "name" => "Turkey" 
    ],
    "TM" => [
        "name" => "Turkmenistan" 
    ],
    "TC" => [
        "name" => "Turks & Caicos Islands" 
    ],
    "TV" => [
        "name" => "Tuvalu" 
    ],
    "UM" => [
        "name" => "U.S. Outlying Islands" 
    ],
    "UA" => [
        "name" => "Ukraine" 
    ],
    "AE" => [
        "name" => "United Arab Emirates" 
    ],
    "GB" => [
        "name" => "United Kingdom" 
    ],
    "US" => [
        "name" => "United States" 
    ],
    "UY" => [
        "name" => "Uruguay" 
    ],
    "UZ" => [
        "name" => "Uzbekistan" 
    ],
    "VU" => [
        "name" => "Vanuatu" 
    ],
    "VA" => [
        "name" => "Vatican City" 
    ],
    "VE" => [
        "name" => "Venezuela" 
    ],
    "VN" => [
        "name" => "Vietnam" 
    ],
    "WF" => [
        "name" => "Wallis & Futuna" 
    ],
    "EH" => [
        "name" => "Western Sahara" 
    ],
];

// taken from Toland Hon's Answer
function prettyOffset($offset) {
    $offset_prefix = $offset < 0 ? '-' : '+';
    $offset_formatted = gmdate( 'H:i', abs($offset) );

    $pretty_offset = "UTC${offset_prefix}${offset_formatted}";

    return $pretty_offset;
}

foreach ($timezones as $k => $v) {
    $tz = DateTimeZone::listIdentifiers(DateTimeZone::PER_COUNTRY, $k);

    foreach ($tz as $value) {
        $t = new DateTimeZone($value);
        $offset = (new DateTime("now", $t))->getOffset();
        $timezones[$k]['timezones'][$value] = prettyOffset($offset);
    }   
}

This gives me an array grouped by countries:

["US"]=>
  array(2) {
    ["name"]=>
    string(13) "United States"
    ["timezones"]=>
    array(29) {
      ["America/Adak"]=>
      string(9) "UTC-10:00"
      ["America/Anchorage"]=>
      string(9) "UTC-09:00"
      ["America/Boise"]=>
      string(9) "UTC-07:00"
      ["America/Chicago"]=>
      string(9) "UTC-06:00"
      ["America/Denver"]=>
      string(9) "UTC-07:00"
      ["America/Detroit"]=>
      string(9) "UTC-05:00"
      ["America/Indiana/Indianapolis"]=>
      string(9) "UTC-05:00"
      ["America/Indiana/Knox"]=>
      string(9) "UTC-06:00"
      ["America/Indiana/Marengo"]=>
      string(9) "UTC-05:00"
      ["America/Indiana/Petersburg"]=>
      string(9) "UTC-05:00"
      ["America/Indiana/Tell_City"]=>
      string(9) "UTC-06:00"
      ["America/Indiana/Vevay"]=>
      string(9) "UTC-05:00"
      ["America/Indiana/Vincennes"]=>
      string(9) "UTC-05:00"
      ["America/Indiana/Winamac"]=>
      string(9) "UTC-05:00"
      ["America/Juneau"]=>
      string(9) "UTC-09:00"
      ["America/Kentucky/Louisville"]=>
      string(9) "UTC-05:00"
      ["America/Kentucky/Monticello"]=>
      string(9) "UTC-05:00"
      ["America/Los_Angeles"]=>
      string(9) "UTC-08:00"
      ["America/Menominee"]=>
      string(9) "UTC-06:00"
      ["America/Metlakatla"]=>
      string(9) "UTC-08:00"
      ["America/New_York"]=>
      string(9) "UTC-05:00"
      ["America/Nome"]=>
      string(9) "UTC-09:00"
      ["America/North_Dakota/Beulah"]=>
      string(9) "UTC-06:00"
      ["America/North_Dakota/Center"]=>
      string(9) "UTC-06:00"
      ["America/North_Dakota/New_Salem"]=>
      string(9) "UTC-06:00"
      ["America/Phoenix"]=>
      string(9) "UTC-07:00"
      ["America/Sitka"]=>
      string(9) "UTC-09:00"
      ["America/Yakutat"]=>
      string(9) "UTC-09:00"
      ["Pacific/Honolulu"]=>
      string(9) "UTC-10:00"
    }
  }

Which means now I can do something like below (of course with some javaScript trickery): Google Analytics Timezone Settings

What does hash do in python?

The hash is used by dictionaries and sets to quickly look up the object. A good starting point is Wikipedia's article on hash tables.

GCM with PHP (Google Cloud Messaging)

A lot of the tutorials are outdated, and even the current code doesn't account for when device registration_ids are updated or devices unregister. If those items go unchecked, it will eventually cause issues that prevent messages from being received. http://forum.loungekatt.com/viewtopic.php?t=63#p181

php.ini & SMTP= - how do you pass username & password

  1. Install Postfix (Sendmail-compatible).
  2. Edit /etc/postfix/main.cf to read:
#Relay config
relayhost = smtp.server.net
smtp_use_tls=yes
smtp_sasl_auth_enable=yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_tls_CAfile = /etc/postfix/cacert.pem
smtp_sasl_security_options = noanonymous
  1. Create /etc/postfix/sasl_passwd, enter:
smtp.server.net username:password
  1. Type # /usr/sbin/postmap sasl_passwd

  2. Then run: service postfix reload

Now PHP will run mail as usual with the sendmail -t -i command and Postfix will intercept it and relay it to your SMTP server that you provided.

How to submit a form when the return key is pressed?

I tried various javascript/jQuery-based strategies, but I kept having issues. The latest issue to arise involved accidental submission when the user uses the enter key to select from the browser's built-in auto-complete list. I finally switched to this strategy, which seems to work on all the browsers my company supports:

<div class="hidden-submit"><input type="submit" tabindex="-1"/></div>
.hidden-submit {
    border: 0 none;
    height: 0;
    width: 0;
    padding: 0;
    margin: 0;
    overflow: hidden;
}

This is similar to the currently-accepted answer by Chris Marasti-Georg, but by avoiding display: none, it appears to work correctly on all browsers.

Update

I edited the code above to include a negative tabindex so it doesn't capture the tab key. While this technically won't validate in HTML 4, the HTML5 spec includes language to make it work the way most browsers were already implementing it anyway.

jQuery event to trigger action when a div is made visible

redsquare's solution is the right answer.

But as an IN-THEORY solution you can write a function which is selecting the elements classed by .visibilityCheck (not all visible elements) and check their visibility property value; if true then do something.

Afterward, the function should be performed periodically using the setInterval() function. You can stop the timer using the clearInterval() upon successful call-out.

Here's an example:

function foo() {
    $('.visibilityCheck').each(function() {
        if ($(this).is(':visible')){
            // do something
        }
    });
}

window.setInterval(foo, 100);

You can also perform some performance improvements on it, however, the solution is basically absurd to be used in action. So...

How to get a function name as a string?

If you're interested in class methods too, Python 3.3+ has __qualname__ in addition to __name__.

def my_function():
    pass

class MyClass(object):
    def method(self):
        pass

print(my_function.__name__)         # gives "my_function"
print(MyClass.method.__name__)      # gives "method"

print(my_function.__qualname__)     # gives "my_function"
print(MyClass.method.__qualname__)  # gives "MyClass.method"

Is there a maximum number you can set Xmx to when trying to increase jvm memory?

Yes, there is a maximum, but it's system dependent. Try it and see, doubling until you hit a limit then searching down. At least with Sun JRE 1.6 on linux you get interesting if not always informative error messages (peregrino is netbook running 32 bit ubuntu with 2G RAM and no swap):

peregrino:$ java -Xmx4096M -cp bin WheelPrimes 
Invalid maximum heap size: -Xmx4096M
The specified size exceeds the maximum representable size.
Could not create the Java virtual machine.

peregrino:$ java -Xmx4095M -cp bin WheelPrimes 
Error occurred during initialization of VM
Incompatible minimum and maximum heap sizes specified

peregrino:$ java -Xmx4092M -cp bin WheelPrimes 
Error occurred during initialization of VM
The size of the object heap + VM data exceeds the maximum representable size

peregrino:$ java -Xmx4000M -cp bin WheelPrimes 
Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.

(experiment reducing from 4000M until)

peregrino:$ java -Xmx2686M -cp bin WheelPrimes 
(normal execution)

Most are self explanatory, except -Xmx4095M which is rather odd (maybe a signed/unsigned comparison?), and that it claims to reserve 2686M on a 2GB machine with no swap. But it does hint that the maximum size is 4G not 2G for a 32 bit VM, if the OS allows you to address that much.

jQuery get textarea text

you can get textarea data by name and id

// by name
<textarea name="comment"></textarea>
let text_area_data = $('textarea[name="comment"]').val();

// by id
<textarea id="comment" name="comment"></textarea>
let text_area_data = $('textarea#comment').val();

jquery background-color change on focus and blur

Tested Code:

$("input").css("background","red");

Complete:

$('input:text').focus(function () {
    $(this).css({ 'background': 'Black' });
});

$('input:text').blur(function () {
    $(this).css({ 'background': 'red' });
});

Tested in version:

jquery-1.9.1.js
jquery-ui-1.10.3.js

What is an API key?

An API key is a unique value that is assigned to a user of this service when he's accepted as a user of the service.

The service maintains all the issued keys and checks them at each request.

By looking at the supplied key at the request, a service checks whether it is a valid key to decide on whether to grant access to a user or not.

Creating a node class in Java

Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:

public class ItemLinkedList {
    private ItemInfoNode head;
    private ItemInfoNode tail;
    private int size = 0;

    public int getSize() {
        return size;
    }

    public void addBack(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, null, tail);
            this.tail.next =node;
            this.tail = node;
        }
    }

    public void addFront(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, head, null);
            this.head.prev = node;
            this.head = node;
        }
    }

    public ItemInfo removeBack() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = tail.info;
            if (tail.prev != null) {
                tail.prev.next = null;
                tail = tail.prev;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public ItemInfo removeFront() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = head.info;
            if (head.next != null) {
                head.next.prev = null;
                head = head.next;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public class ItemInfoNode {

        private ItemInfoNode next;
        private ItemInfoNode prev;
        private ItemInfo info;

        public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
            this.info = info;
            this.next = next;
            this.prev = prev;
        }

        public void setInfo(ItemInfo info) {
            this.info = info;
        }

        public void setNext(ItemInfoNode node) {
            next = node;
        }

        public void setPrev(ItemInfoNode node) {
            prev = node;
        }

        public ItemInfo getInfo() {
            return info;
        }

        public ItemInfoNode getNext() {
            return next;
        }

        public ItemInfoNode getPrev() {
            return prev;
        }
    }
}

EDIT:

Declare ItemInfo as this:

public class ItemInfo {
    private String name;
    private String rfdNumber;
    private double price;
    private String originalPosition;

    public ItemInfo(){
    }

    public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
        this.name = name;
        this.rfdNumber = rfdNumber;
        this.price = price;
        this.originalPosition = originalPosition;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRfdNumber() {
        return rfdNumber;
    }

    public void setRfdNumber(String rfdNumber) {
        this.rfdNumber = rfdNumber;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getOriginalPosition() {
        return originalPosition;
    }

    public void setOriginalPosition(String originalPosition) {
        this.originalPosition = originalPosition;
    }
}

Then, You can use your nodes inside the linked list like this:

public static void main(String[] args) {
    ItemLinkedList list = new ItemLinkedList();
    for (int i = 1; i <= 10; i++) {
        list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));

    }
    while (list.size() > 0){
        System.out.println(list.removeFront().getName());
    }
}

Convert image from PIL to openCV format

use this:

pil_image = PIL.Image.open('Image.jpg').convert('RGB') 
open_cv_image = numpy.array(pil_image) 
# Convert RGB to BGR 
open_cv_image = open_cv_image[:, :, ::-1].copy() 

How to use pagination on HTML tables?

Many times we might want to perform Table pagination using jquery.Here i ll give you the answer and reference link

Jquery

  $(document).ready(function(){
        $('#data').after('<div id="nav"></div>');
        var rowsShown = 4;
        var rowsTotal = $('#data tbody tr').length;
        var numPages = rowsTotal/rowsShown;
        for(i = 0;i < numPages;i++) {
            var pageNum = i + 1;
            $('#nav').append('<a href="#" rel="'+i+'">'+pageNum+'</a> ');
        }
        $('#data tbody tr').hide();
        $('#data tbody tr').slice(0, rowsShown).show();
        $('#nav a:first').addClass('active');
        $('#nav a').bind('click', function(){

            $('#nav a').removeClass('active');
            $(this).addClass('active');
            var currPage = $(this).attr('rel');
            var startItem = currPage * rowsShown;
            var endItem = startItem + rowsShown;
            $('#data tbody tr').css('opacity','0.0').hide().slice(startItem, endItem).
                    css('display','table-row').animate({opacity:1}, 300);
        });
    });

JSfiddle: https://jsfiddle.net/u9d1ewsh/

Replace spaces with dashes and make all letters lower-case

You can also use split and join:

"Sonic Free Games".split(" ").join("-").toLowerCase(); //sonic-free-games

How do you specify a byte literal in Java?

You have to cast, I'm afraid:

f((byte)0);

I believe that will perform the appropriate conversion at compile-time instead of execution time, so it's not actually going to cause performance penalties. It's just inconvenient :(

Remove HTML tags from a String

HTML Escaping is really hard to do right- I'd definitely suggest using library code to do this, as it's a lot more subtle than you'd think. Check out Apache's StringEscapeUtils for a pretty good library for handling this in Java.

Run Jquery function on window events: load, resize, and scroll?

You can use the following. They all wrap the window object into a jQuery object.

Load:

$(window).load(function () {
    topInViewport($("#mydivname"))
});

Resize:

$(window).resize(function () {
   topInViewport($("#mydivname"))
});

Scroll

$(window).scroll(function () {
    topInViewport($("#mydivname"))
});

Or bind to them all using on:

$(window).on("load resize scroll",function(e){
    topInViewport($("#mydivname"))
});

How can I format the output of a bash command in neat columns

column(1) is your friend.

$ column -t <<< '"option-y"      yank-pop
> "option-z"      execute-last-named-cmd
> "option-|"      vi-goto-column
> "option-~"      _bash_complete-word
> "option-control-?"      backward-kill-word
> "control-_"     undo
> "control-?"     backward-delete-char
> '
"option-y"          yank-pop
"option-z"          execute-last-named-cmd
"option-|"          vi-goto-column
"option-~"          _bash_complete-word
"option-control-?"  backward-kill-word
"control-_"         undo
"control-?"         backward-delete-char

How can I convert a string to a float in mysql?

mysql> SELECT CAST(4 AS DECIMAL(4,3));
+-------------------------+
| CAST(4 AS DECIMAL(4,3)) |
+-------------------------+
|                   4.000 |
+-------------------------+
1 row in set (0.00 sec)

mysql> SELECT CAST('4.5s' AS DECIMAL(4,3));
+------------------------------+
| CAST('4.5s' AS DECIMAL(4,3)) |
+------------------------------+
|                        4.500 |
+------------------------------+
1 row in set (0.00 sec)

mysql> SELECT CAST('a4.5s' AS DECIMAL(4,3));
+-------------------------------+
| CAST('a4.5s' AS DECIMAL(4,3)) |
+-------------------------------+
|                         0.000 |
+-------------------------------+
1 row in set, 1 warning (0.00 sec)