Programs & Examples On #Unlink

Refers to removing a file from a filesystem.

permission denied - php unlink

You (as in the process that runs b.php, either you through CLI or a webserver) need write access to the directory in which the files are located. You are updating the directory content, so access to the file is not enough.

Note that if you use the PHP chmod() function to set the mode of a file or folder to 777 you should use 0777 to make sure the number is correctly interpreted as an octal number.

Unlink of file Failed. Should I try again?

This may be a separate gitk window running to see some git history.

Just close that window to fix that problem.

PHP - Move a file into a different folder on the server

shell_exec('mv filename dest_filename');

Basic authentication for REST API using spring restTemplate

As of Spring 5.1 you can use HttpHeaders.setBasicAuth

Create Basic Authorization header:

String username = "willie";
String password = ":p@ssword";
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(username, password);
...other headers goes here...

Pass the headers to the RestTemplate:

HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<Account> response = restTemplate.exchange(url, HttpMethod.GET, request, Account.class);
Account account = response.getBody();

Documentation: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/HttpHeaders.html#setBasicAuth-java.lang.String-java.lang.String-

How to select element using XPATH syntax on Selenium for Python?

Check this blog by Martin Thoma. I tested the below code on MacOS Mojave and it worked as specified.

> def get_browser():
>     """Get the browser (a "driver")."""
>     # find the path with 'which chromedriver'
>     path_to_chromedriver = ('/home/moose/GitHub/algorithms/scraping/'
>                             'venv/bin/chromedriver')
>     download_dir = "/home/moose/selenium-download/"
>     print("Is directory: {}".format(os.path.isdir(download_dir)))
> 
>     from selenium.webdriver.chrome.options import Options
>     chrome_options = Options()
>     chrome_options.add_experimental_option('prefs', {
>         "plugins.plugins_list": [{"enabled": False,
>                                   "name": "Chrome PDF Viewer"}],
>         "download": {
>             "prompt_for_download": False,
>             "default_directory": download_dir
>         }
>     })
> 
>     browser = webdriver.Chrome(path_to_chromedriver,
>                                chrome_options=chrome_options)
>     return browser

AngularJS disable partial caching on dev machine

Here is another option in Chrome.

Hit F12 to open developer tools. Then Resources > Cache Storage > Refresh Caches.

enter image description here

I like this option because I don't have to disable cache as in other answers.

How to get the ActionBar height?

If you're using Xamarin/C#, this is the code you're looking for:

var styledAttributes = Context.Theme.ObtainStyledAttributes(new[] { Android.Resource.Attribute.ActionBarSize });
var actionBarSize = (int)styledAttributes.GetDimension(0, 0);
styledAttributes.Recycle();

Visual Studio Code always asking for git credentials

The following steps walk you through how to:

  1. Generate SSH keys (without passphrase**)
  2. Add the public key generated in step 1 to your Git repository
  3. Confirm the above steps have been completed successfully
  4. Make your first commit (without having to provide a username / password)

**Generating SSH keys without a passphrase is unwise if your work is particularly sensitive.

OS - Fedora 28 | Editor - VS Code v1.23.0 | Repository - Git

Generate SSH keys:

  • ssh-keygen -t rsa -C "[email protected]"
  • Enter file in which to save the key: Press Enter
  • Enter passphrase: Press Enter
  • Enter same passphrase again: Press Enter

After completing the above steps, the location of your public key is shown in the terminal window. If the currently logged in user is 'bob' the location of your public key would be /home/bob/.ssh/id_rsa.pub

Copy and import public key to GitHub:

  • cat /home/bob/.ssh/id_rsa.pub

  • Copy the whole public key that is now displayed in your terminal window to the clipboard

  • Go to https://github.com and sign in
  • Click the user icon in the top right corner of the screen and select Settings
  • Click SSH and GPG keys
  • Click New SSH key
  • Enter a title, paste the public key copied to the clipboard in the first bullet point, and click Add SSH key

Confirm the above steps:

  • ssh -T [email protected]

  • yes

  • Hi ! You've successfully authenticated, but GitHub does not provide shell access.

First commit / push without having to enter a username / password: - touch test.txt

  • git add test.txt

  • git commit - opens editor, enter a message and save the file. If vi is your editor, press i once the file opens, enter a message, press esc, and then enter :x to save changes.

  • git push

The only hiccup you may encounter is when you attempt to SSH to GitHub. This link will provide some assistance -

Happy hunting!

why $(window).load() is not working in jQuery?

in jquery-3.1.1

_x000D_
_x000D_
$("#id").load(function(){_x000D_
//code goes here});
_x000D_
_x000D_
_x000D_

will not work because load function is no more work

How to specify the private SSH-key to use when executing shell command on Git?

for the gitlab RSAAuthentication yes

Host gitlab.com
  RSAAuthentication yes
  IdentityFile ~/.ssh/your_private_key_name
  IdentitiesOnly yes

doc is here

OSX - How to auto Close Terminal window after the "exit" command executed.

In a terminal window, you can type:

kill -9 $(ps -p $PPID -o ppid=)

This will kill the Terminal application process, which is the parent of the parent of the current process, as seen by the kill command.

To close a Terminal window from within a running script, you need to go up one more level in the process hierarchy like this:

kill -9 $(ps -p $(ps -p $PPID -o ppid=) -o ppid=) 

concatenate char array in C

First copy the current string to a larger array with strcpy, then use strcat.

For example you can do:

char* str = "Hello";
char dest[12];

strcpy( dest, str );
strcat( dest, ".txt" );

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

One form to do this is insert the panel that you want to expand inside a DIV setted as relative: let me show you:

<div style="position:relative">
  <div style="position:absolute; z-index: 1000;">
    your code
  </div>
</div>

You use the first div to position the inner content in a specific area inside your page and the second absolute should be referred to the container (because is relative) The z-index in this case is referred also to container and if it higher that the container should be at top. You can put the style in a CSS class and change the size of the absolute div to expand it on hover or another action that you want to control.

I hope that this help

How to return a value from pthread threads in C?

You are returning the address of a local variable, which no longer exists when the thread function exits. In any case, why call pthread_exit? why not simply return a value from the thread function?

void *myThread()
{
   return (void *) 42;
}

and then in main:

printf("%d\n",(int)status);   

If you need to return a complicated value such a structure, it's probably easiest to allocate it dynamically via malloc() and return a pointer. Of course, the code that initiated the thread will then be responsible for freeing the memory.

Remove a JSON attribute

Simple:

delete myObj.test.key1;

Using ORDER BY and GROUP BY together

One way to do this that correctly uses group by:

select l.* 
from table l
inner join (
  select 
    m_id, max(timestamp) as latest 
  from table 
  group by m_id
) r
  on l.timestamp = r.latest and l.m_id = r.m_id
order by timestamp desc

How this works:

  • selects the latest timestamp for each distinct m_id in the subquery
  • only selects rows from table that match a row from the subquery (this operation -- where a join is performed, but no columns are selected from the second table, it's just used as a filter -- is known as a "semijoin" in case you were curious)
  • orders the rows

Is calculating an MD5 hash less CPU intensive than SHA family functions?

MD5 also benefits from SSE2 usage, check out BarsWF and then tell me that it doesn't. All it takes is a little assembler knowledge and you can craft your own MD5 SSE2 routine(s). For large amounts of throughput however, there is a tradeoff of the speed during hashing as opposed to the time spent rearranging the input data to be compatible with the SIMD instructions used.

When to Redis? When to MongoDB?

And you should use neither if you have plenty of RAM. Redis and MongoDB come to the price of a general purpose tool. This introduce a lot of overhead.

There was the saying that Redis is 10 times faster than Mongo. That might not be that true anymore. MongoDB (if i remember correctly) claimed to beat memcache for storing and caching documents as long as the memory configurations are the same.

Anyhow. Redis good, MongoDB is good. If you care about substructures and need aggregation go for MongoDB. If storing keys and values is your main concern its all about Redis. (or any other key value store).

Check if table exists and if it doesn't exist, create it in SQL Server 2008

IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE  TABLE_NAME = 'd020915'))
BEGIN
  declare @result int
  set @result=1
  select @result as result
END

Remove rows with all or some NAs (missing values) in data.frame

I am a synthesizer:). Here I combined the answers into one function:

#' keep rows that have a certain number (range) of NAs anywhere/somewhere and delete others
#' @param df a data frame
#' @param col restrict to the columns where you would like to search for NA; eg, 3, c(3), 2:5, "place", c("place","age")
#' \cr default is NULL, search for all columns
#' @param n integer or vector, 0, c(3,5), number/range of NAs allowed.
#' \cr If a number, the exact number of NAs kept
#' \cr Range includes both ends 3<=n<=5
#' \cr Range could be -Inf, Inf
#' @return returns a new df with rows that have NA(s) removed
#' @export
ez.na.keep = function(df, col=NULL, n=0){
    if (!is.null(col)) {
        # R converts a single row/col to a vector if the parameter col has only one col
        # see https://radfordneal.wordpress.com/2008/08/20/design-flaws-in-r-2-%E2%80%94-dropped-dimensions/#comments
        df.temp = df[,col,drop=FALSE]
    } else {
        df.temp = df
    }

    if (length(n)==1){
        if (n==0) {
            # simply call complete.cases which might be faster
            result = df[complete.cases(df.temp),]
        } else {
            # credit: http://stackoverflow.com/a/30461945/2292993
            log <- apply(df.temp, 2, is.na)
            logindex <- apply(log, 1, function(x) sum(x) == n)
            result = df[logindex, ]
        }
    }

    if (length(n)==2){
        min = n[1]; max = n[2]
        log <- apply(df.temp, 2, is.na)
        logindex <- apply(log, 1, function(x) {sum(x) >= min && sum(x) <= max})
        result = df[logindex, ]
    }

    return(result)
}

How to check if a radiobutton is checked in a radiogroup in Android?

If you want to check on just one RadioButton you can use the isChecked function

if(radioButton.isChecked())
{
  // is checked    
}
else
{
  // not checked
}

and if you have a RadioGroup you can use

if (radioGroup.getCheckedRadioButtonId() == -1)
{
  // no radio buttons are checked
}
else
{
  // one of the radio buttons is checked
}

git revert back to certain commit

git reset --hard 4a155e5 Will move the HEAD back to where you want to be. There may be other references ahead of that time that you would need to remove if you don't want anything to point to the history you just deleted.

Switch statement for greater-than/less-than

You can create a custom object with the criteria and the function corresponding to the criteria

var rules = [{ lowerLimit: 0,    upperLimit: 1000, action: function1 }, 
             { lowerLimit: 1000, upperLimit: 2000, action: function2 }, 
             { lowerLimit: 2000, upperLimit: 3000, action: function3 }];

Define functions for what you want to do in these cases (define function1, function2 etc)

And "evaluate" the rules

function applyRules(scrollLeft)
{
   for(var i=0; i>rules.length; i++)
   {
       var oneRule = rules[i];
       if(scrollLeft > oneRule.lowerLimit && scrollLeft < oneRule.upperLimit)
       {
          oneRule.action();
       }
   }
}

Note

I hate using 30 if statements

Many times if statements are easier to read and maintain. I would recommend the above only when you have a lot of conditions and a possibility of lot of growth in the future.

Update
As @Brad pointed out in the comments, if the conditions are mutually exclusive (only one of them can be true at a time), checking the upper limit should be sufficient:

if(scrollLeft < oneRule.upperLimit)

provided that the conditions are defined in ascending order (first the lowest one, 0 to 1000, and then 1000 to 2000 for example)

What is the difference between C# and .NET?

In addition to what Andrew said, it is worth noting that:

  • .NET isn't just a library, but also a runtime for executing applications.
  • The knowledge of C# implies some knowledge of .NET (because the C# object model corresponds to the .NET object model and you can do something interesting in C# just by using .NET libraries). The opposite isn't necessarily true as you can use other languages to write .NET applications.

The distinction between a language, a runtime, and a library is more strict in .NET/C# than for example in C++, where the language specification also includes some basic library functions. The C# specification says only a very little about the environment (basically, that it should contain some types such as int, but that's more or less all).

SQL Server: how to create a stored procedure

Try this:

 create procedure dept_count(@dept_name varchar(20),@d_count int)
       begin
         set @d_count=(select count(*)
                       from instructor
                        where instructor.dept_name=dept_count.dept_name)
         Select @d_count as count
       end

Or

create procedure dept_count(@dept_name varchar(20))
           begin
            select count(*)
                           from instructor
                            where instructor.dept_name=dept_count.dept_name
           end

jump to line X in nano editor

I am using Linux raspi 4.19.118+ #1311 via ssh Powershell on Win 10 Pro 1909 with German keyboard. nano shortcut Goto Line with "Crtl + Shift + -" was not working Solution: Step 1 - Do Current Position with "Crtl + C" Step 2 - Goto Line with "Crtl + Shift + -" IS working!

I dont know what effects it. But now its working without step 1!

Focus Next Element In Tab Index

I have a buch of 0-tabIndexes, which I wanted to navigate by keyboard.
Since in that case, only the ORDER of the elements mattered, I did it using document.createTreeWalker

So first you create the filter (you only want [visible] elements, which have an attribute "tabIndex" with a NUMERICAL value.

Then you set the root node, beyond which you don't want to search. In my case, this.m_tree is a ul-element containing a toggable tree. If you want the entire document instead, just replace this.m_tree with document.documentElement.

Then you set the current node to the current active element:

ni.currentNode = el; // el = document.activeElement

Then you return ni.nextNode() or ni.previousNode().

Note:
this will NOT return the tabs in the correct order if you have tabIndices != 0 and the element order is NOT the tabIndex order. In case of tabIndex = 0, the tabOrder is always the element order, which is why this works (in that case).

protected createFilter(fn?: (node: Node) => number): NodeFilter
{
    // Accept all currently filtered elements.
    function acceptNode(node: Node): number 
    {
        return NodeFilter.FILTER_ACCEPT;
    }

    if (fn == null)
        fn = acceptNode;


    // Work around Internet Explorer wanting a function instead of an object.
    // IE also *requires* this argument where other browsers don't.
    const safeFilter: NodeFilter = <NodeFilter><any>fn;
    (<any>safeFilter).acceptNode = fn;

    return safeFilter;
}



protected createTabbingFilter(): NodeFilter
{
    // Accept all currently filtered elements.
    function acceptNode(node: Node): number 
    {
        if (!node)
            return NodeFilter.FILTER_REJECT;

        if (node.nodeType !== Node.ELEMENT_NODE)
            return NodeFilter.FILTER_REJECT;

        if (window.getComputedStyle(<Element>node).display === "none")
            return NodeFilter.FILTER_REJECT;

        // "tabIndex": "0"
        if (!(<Element>node).hasAttribute("tabIndex"))
            return NodeFilter.FILTER_SKIP;

        let tabIndex = parseInt((<Element>node).getAttribute("tabIndex"), 10);
        if (!tabIndex || isNaN(tabIndex) || !isFinite(tabIndex))
            return NodeFilter.FILTER_SKIP;

        // if ((<Element>node).tagName !== "LI") return NodeFilter.FILTER_SKIP;

        return NodeFilter.FILTER_ACCEPT;
    }

    return this.createFilter(acceptNode);
}


protected getNextTab(el: HTMLElement): HTMLElement
{
    let currentNode: Node;
    // https://developer.mozilla.org/en-US/docs/Web/API/Document/createNodeIterator
    // https://developer.mozilla.org/en-US/docs/Web/API/Document/createTreeWalker

    // let ni = document.createNodeIterator(el, NodeFilter.SHOW_ELEMENT);
    // let ni = document.createTreeWalker(this.m_tree, NodeFilter.SHOW_ELEMENT);
    let ni = document.createTreeWalker(this.m_tree, NodeFilter.SHOW_ELEMENT, this.createTabbingFilter(), false);

    ni.currentNode = el;

    while (currentNode = ni.nextNode())
    {
        return <HTMLElement>currentNode;
    }

    return el;
}


protected getPreviousTab(el: HTMLElement): HTMLElement
{
    let currentNode: Node;
    let ni = document.createTreeWalker(this.m_tree, NodeFilter.SHOW_ELEMENT, this.createTabbingFilter(), false);
    ni.currentNode = el;

    while (currentNode = ni.previousNode())
    {
        return <HTMLElement>currentNode;
    }

    return el;
}

Note that the while-loop

while (currentNode = ni.nextNode())
{
    // Additional checks here
    // if(condition) return currentNode;
    // else the loop continues;
    return <HTMLElement>currentNode; // everything is already filtered down to what we need here
}

is only there if you want if you have additional criterias which you cannot filter in the filter passed to createTreeWalker.

Note this is TypeScript, you need to remove all tokens behind colons (:), and between angle-brackets (<>), e.g. <Element> or :(node: Node) => number to get valid JavaScript.

Here as a service, the transpiled JS:

"use strict";
function createFilter(fn) {
    // Accept all currently filtered elements.
    function acceptNode(node) {
        return NodeFilter.FILTER_ACCEPT;
    }
    if (fn == null)
        fn = acceptNode;
    // Work around Internet Explorer wanting a function instead of an object.
    // IE also *requires* this argument where other browsers don't.
    const safeFilter = fn;
    safeFilter.acceptNode = fn;
    return safeFilter;
}
function createTabbingFilter() {
    // Accept all currently filtered elements.
    function acceptNode(node) {
        if (!node)
            return NodeFilter.FILTER_REJECT;
        if (node.nodeType !== Node.ELEMENT_NODE)
            return NodeFilter.FILTER_REJECT;
        if (window.getComputedStyle(node).display === "none")
            return NodeFilter.FILTER_REJECT;
        // "tabIndex": "0"
        if (!node.hasAttribute("tabIndex"))
            return NodeFilter.FILTER_SKIP;
        let tabIndex = parseInt(node.getAttribute("tabIndex"), 10);
        if (!tabIndex || isNaN(tabIndex) || !isFinite(tabIndex))
            return NodeFilter.FILTER_SKIP;
        // if ((<Element>node).tagName !== "LI") return NodeFilter.FILTER_SKIP;
        return NodeFilter.FILTER_ACCEPT;
    }
    return createFilter(acceptNode);
}
function getNextTab(el) {
    let currentNode;
    // https://developer.mozilla.org/en-US/docs/Web/API/Document/createNodeIterator
    // https://developer.mozilla.org/en-US/docs/Web/API/Document/createTreeWalker
    // let ni = document.createNodeIterator(el, NodeFilter.SHOW_ELEMENT);
    // let ni = document.createTreeWalker(this.m_tree, NodeFilter.SHOW_ELEMENT);
    let ni = document.createTreeWalker(document.documentElement, NodeFilter.SHOW_ELEMENT, createTabbingFilter(), false);
    ni.currentNode = el;
    while (currentNode = ni.nextNode()) {
        return currentNode;
    }
    return el;
}
function getPreviousTab(el) {
    let currentNode;
    let ni = document.createTreeWalker(document.documentElement, NodeFilter.SHOW_ELEMENT, createTabbingFilter(), false);
    ni.currentNode = el;
    while (currentNode = ni.previousNode()) {
        return currentNode;
    }
    return el;
}

TypeError: $ is not a function WordPress

Either you're not including jquery toolkit/lib, as some have suggested, or there is a conflict of sorts. To test: include jQuery and test like this:

console.log($);
console.log($ === jQuery);

If $ is not undefined, and $ === jQuery logs false, you definitely have a conflict on your hands. Replacing your $ with jQuery solves that, but that can be quite tedious (all that extra typing...). Generally I start my scripts with $jq = _$ = jQuery; to at least have a shorter reference to the jQuery object.
Of course, before you do that, check to see if you're not accidentally overriding variables that have been set beforehand: console.log($jq, _jQ, _$); whichever is not undefined should be left alone, of course

NPM Install Error:Unexpected end of JSON input while parsing near '...nt-webpack-plugin":"0'

npm uninstall -g angular-cli

npm cache clear --force

OR

Delete this folder directory (In Windows)

rmdir C:\Users\<ProfileName>\AppData\Roaming\npm
rmdir C:\Users\<ProfileName>\AppData\Roaming\npm-cache

In Rails, how do you render JSON using a view?

Just add show.json.erb file with the contents

<%= @user.to_json %>

Sometimes it is useful when you need some extra helper methods that are not available in controller, i.e. image_path(@user.avatar) or something to generate additional properties in JSON:

<%= @user.attributes.merge(:avatar => image_path(@user.avatar)).to_json %>

Calling a function on bootstrap modal open

You can use the shown event/show event based on what you need:

$( "#code" ).on('shown', function(){
    alert("I want this to appear after the modal has opened!");
});

Demo: Plunker

Update for Bootstrap 3.0

For Bootstrap 3.0 you can still use the shown event but you would use it like this:

$('#code').on('shown.bs.modal', function (e) {
  // do something...
})

See the Bootstrap 3.0 docs here under "Events".

Is there a good jQuery Drag-and-drop file upload plugin?

I created a plugin which allows you to drop some files onto a given area. This plugin currently works in Firefox, Safari and Chrome.

http://code.google.com/p/dnd-file-upload/

Is it possible to use jQuery .on and hover?

You can provide one or multiple event types separated by a space.

So hover equals mouseenter mouseleave.

This is my sugession:

$("#foo").on("mouseenter mouseleave", function() {
    // do some stuff
});

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i input.mov -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i input.mov -q:v 0 output.mp4

jQuery selector for inputs with square brackets in the name attribute

You can use backslash to quote "funny" characters in your jQuery selectors:

$('#input\\[23\\]')

For attribute values, you can use quotes:

$('input[name="weirdName[23]"]')

Now, I'm a little confused by your example; what exactly does your HTML look like? Where does the string "inputName" show up, in particular?

edit fixed bogosity; thanks @Dancrumb

jQuery Mobile Page refresh mechanism

This answer did the trick for me http://view.jquerymobile.com/master/demos/faq/injected-content-is-not-enhanced.php.

In the context of a multi-pages template, I modify the content of a <div id="foo">...</div> in a Javascript 'pagebeforeshow' handler and trigger a refresh at the end of the script:

$(document).bind("pagebeforeshow", function(event,pdata) {
  var parsedUrl = $.mobile.path.parseUrl( location.href );
  switch ( parsedUrl.hash ) {
    case "#p_02":
      ... some modifications of the content of the <div> here ...
      $("#foo").trigger("create");
    break;
  }
});

Node.js: printing to console without a trailing newline?

In Windows console (Linux, too), you should replace '\r' with its equivalent code \033[0G:

process.stdout.write('ok\033[0G');

This uses a VT220 terminal escape sequence to send the cursor to the first column.

Check if a PHP cookie exists and if not set its value

Cookies are only sent at the time of the request, and therefore cannot be retrieved as soon as it is assigned (only available after reloading).

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.

Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.

Source

Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing

To solve the 2 (and 3) missing numbers question, you can modify quickselect, which on average runs in O(n) and uses constant memory if partitioning is done in-place.

  1. Partition the set with respect to a random pivot p into partitions l, which contain numbers smaller than the pivot, and r, which contain numbers greater than the pivot.

  2. Determine which partitions the 2 missing numbers are in by comparing the pivot value to the size of each partition (p - 1 - count(l) = count of missing numbers in l and n - count(r) - p = count of missing numbers in r)

  3. a) If each partition is missing one number, then use the difference of sums approach to find each missing number.

    (1 + 2 + ... + (p-1)) - sum(l) = missing #1 and ((p+1) + (p+2) ... + n) - sum(r) = missing #2

    b) If one partition is missing both numbers and the partition is empty, then the missing numbers are either (p-1,p-2) or (p+1,p+2) depending on which partition is missing the numbers.

    If one partition is missing 2 numbers but is not empty, then recurse onto that partiton.

With only 2 missing numbers, this algorithm always discards at least one partition, so it retains O(n) average time complexity of quickselect. Similarly, with 3 missing numbers this algorithm also discards at least one partition with each pass (because as with 2 missing numbers, at most only 1 partition will contain multiple missing numbers). However, I'm not sure how much the performance decreases when more missing numbers are added.

Here's an implementation that does not use in-place partitioning, so this example does not meet the space requirement but it does illustrate the steps of the algorithm:

<?php

  $list = range(1,100);
  unset($list[3]);
  unset($list[31]);

  findMissing($list,1,100);

  function findMissing($list, $min, $max) {
    if(empty($list)) {
      print_r(range($min, $max));
      return;
    }

    $l = $r = [];
    $pivot = array_pop($list);

    foreach($list as $number) {
      if($number < $pivot) {
        $l[] = $number;
      }
      else {
        $r[] = $number;
      }
    }

    if(count($l) == $pivot - $min - 1) {
      // only 1 missing number use difference of sums
      print array_sum(range($min, $pivot-1)) - array_sum($l) . "\n";
    }
    else if(count($l) < $pivot - $min) {
      // more than 1 missing number, recurse
      findMissing($l, $min, $pivot-1);
    }

    if(count($r) == $max - $pivot - 1) {
      // only 1 missing number use difference of sums
      print array_sum(range($pivot + 1, $max)) - array_sum($r) . "\n";
    } else if(count($r) < $max - $pivot) {
      // mroe than 1 missing number recurse
      findMissing($r, $pivot+1, $max);
    }
  }

Demo

TypeError: 'module' object is not callable

It seems like what you've done is imported the socket module as import socket. Therefore socket is the module. You either need to change that line to self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM), as well as every other use of the socket module, or change the import statement to from socket import socket.

Or you've got an import socket after your from socket import *:

>>> from socket import *
>>> serv = socket(AF_INET,SOCK_STREAM)
>>> import socket
>>> serv = socket(AF_INET,SOCK_STREAM)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'module' object is not callable

How to set "value" to input web element using selenium?

As Shubham Jain stated, this is working to me: driver.findElement(By.id("invoice_supplier_id")).sendKeys("value"??, "new value");

Basic HTML - how to set relative path to current folder?

You can use

 ../

to mean up one level. If you have a page called page2.html in the same folder as page.html then the relative path is:

 page2.html.

If you have page2.html at the same level with folder then the path is:

  ../page2.html

How to determine if binary tree is balanced?

Balancing usually depends on the length of the longest path on each direction. The above algorithm is not going to do that for you.

What are you trying to implement? There are self-balancing trees around (AVL/Red-black). In fact, Java trees are balanced.

What is the easiest way to get current GMT time in Unix timestamp format?

I would use time.time() to get a timestamp in seconds since the epoch.

import time

time.time()

Output:

1369550494.884832

For the standard CPython implementation on most platforms this will return a UTC value.

C# delete a folder and all files and folders within that folder

Try this.

namespace EraseJunkFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            DirectoryInfo yourRootDir = new DirectoryInfo(@"C:\somedirectory\");
            foreach (DirectoryInfo dir in yourRootDir.GetDirectories())
                    DeleteDirectory(dir.FullName, true);
        }
        public static void DeleteDirectory(string directoryName, bool checkDirectiryExist)
        {
            if (Directory.Exists(directoryName))
                Directory.Delete(directoryName, true);
            else if (checkDirectiryExist)
                throw new SystemException("Directory you want to delete is not exist");
        }
    }
}

Difference between JSON.stringify and JSON.parse

JavaScript Object <-> JSON String


JSON.stringify() <-> JSON.parse()

JSON.stringify(obj) - Takes any serializable object and returns the JSON representation as a string.

JSON.stringify() -> Object To String.

JSON.parse(string) - Takes a well formed JSON string and returns the corresponding JavaScript object.

JSON.parse() -> String To Object.

Explanation: JSON.stringify(obj [, replacer [, space]]);

Replacer/Space - optional or takes integer value or you can call interger type return function.

function replacer(key, value) {
    if (typeof value === 'number' && !isFinite(value)) {
        return String(value);
    }
    return value;
}
  • Replacer Just Use for replace non finite no with null.
  • Space use for indenting Json String by space

How to write a CSS hack for IE 11?

Here is a two steps solution here is a hack to IE10 and 11

    @media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {  
   /* IE10+ specific styles go here */  
}

because IE10 and IE11 Supports -ms-high-cotrast you can take the advantage of this to target this two browsers

and if you want to exclude the IE10 from this you must create a IE10 specific code as follow it's using the user agent trick you must add this Javascript

var doc = document.documentElement;
doc.setAttribute('data-useragent', navigator.userAgent);

and this HTML tag

<html data-useragent="Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)">

and now you can write your CSS code like this

html[data-useragent*='MSIE 10.0'] h1 {
  color: blue;
}

for more information please refer to this websites,wil tutorail, Chris Tutorial


And if you want to target IE11 and later,here is what I've found:

_:-ms-fullscreen, :root .selector {}

Here is a great resource for getting more information: browserhacks.com

Don't change link color when a link is clicked

Don't over complicate it. Just give the link a color using the tags. It will leave a constant color that won't change even if you click it. So in your case just set it to blue. If it is set to a particular color of blue just you want to copy, you can press "print scrn" on your keyboard, paste in paint, and using the color picker(shaped as a dropper) pick the color of the link and view the code in the color settings.

How to create a file in memory for user to download, but not through server?

You can use data URIs. Browser support varies; see Wikipedia. Example:

<a href="data:application/octet-stream;charset=utf-16le;base64,//5mAG8AbwAgAGIAYQByAAoA">text file</a>

The octet-stream is to force a download prompt. Otherwise, it will probably open in the browser.

For CSV, you can use:

<a href="data:application/octet-stream,field1%2Cfield2%0Afoo%2Cbar%0Agoo%2Cgai%0A">CSV Octet</a>

Try the jsFiddle demo.

CertPathValidatorException : Trust anchor for certificate path not found - Retrofit Android

Implementation in Kotlin : Retrofit 2.3.0

private fun getUnsafeOkHttpClient(mContext: Context) : 
OkHttpClient.Builder? {


var mCertificateFactory : CertificateFactory = 
CertificateFactory.getInstance("X.509")
var mInputStream = mContext.resources.openRawResource(R.raw.cert)
            var mCertificate : Certificate = mCertificateFactory.generateCertificate(mInputStream)
        mInputStream.close()
val mKeyStoreType = KeyStore.getDefaultType()
val mKeyStore = KeyStore.getInstance(mKeyStoreType)
mKeyStore.load(null, null)
mKeyStore.setCertificateEntry("ca", mCertificate)

val mTmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm()
val mTrustManagerFactory = TrustManagerFactory.getInstance(mTmfAlgorithm)
mTrustManagerFactory.init(mKeyStore)

val mTrustManagers = mTrustManagerFactory.trustManagers

val mSslContext = SSLContext.getInstance("SSL")
mSslContext.init(null, mTrustManagers, null)
val mSslSocketFactory = mSslContext.socketFactory

val builder = OkHttpClient.Builder()
builder.sslSocketFactory(mSslSocketFactory, mTrustManagers[0] as X509TrustManager)
builder.hostnameVerifier { _, _ -> true }
return builder

}

How to set a time zone (or a Kind) of a DateTime value?

While the DateTime.Kind property does not have a setter, the static method DateTime.SpecifyKind creates a DateTime instance with a specified value for Kind.

Altenatively there are several DateTime constructor overloads that take a DateTimeKind parameter

enable/disable zoom in Android WebView

The solution you posted seems to work in stopping the zoom controls from appearing when the user drags, however there are situations where a user will pinch zoom and the zoom controls will appear. I've noticed that there are 2 ways that the webview will accept pinch zooming, and only one of them causes the zoom controls to appear despite your code:

User Pinch Zooms and controls appear:

ACTION_DOWN
getSettings().setBuiltInZoomControls(false); getSettings().setSupportZoom(false);
ACTION_POINTER_2_DOWN
getSettings().setBuiltInZoomControls(true); getSettings().setSupportZoom(true);
ACTION_MOVE (Repeat several times, as the user moves their fingers)
ACTION_POINTER_2_UP
ACTION_UP

User Pinch Zoom and Controls don't appear:

ACTION_DOWN
getSettings().setBuiltInZoomControls(false); getSettings().setSupportZoom(false);
ACTION_POINTER_2_DOWN
getSettings().setBuiltInZoomControls(true); getSettings().setSupportZoom(true);
ACTION_MOVE (Repeat several times, as the user moves their fingers)
ACTION_POINTER_1_UP
ACTION_POINTER_UP
ACTION_UP

Can you shed more light on your solution?

How to create an empty R vector to add new items

As pointed out by Brani, vector() is a solution, e.g.

newVector <- vector(mode = "numeric", length = 50)

will return a vector named "newVector" with 50 "0"'s as initial values. It is also fairly common to just add the new scalar to an existing vector to arrive at an expanded vector, e.g.

aVector <- c(aVector, newScalar)

Get the index of a certain value in an array in PHP

Could you be a little more specific?

$key = array_search('string2',$list)

works fine for me. Are you trying to accomplish something more complex?

String.Format not work in TypeScript

You can declare it yourself quite easily:

interface StringConstructor {
    format: (formatString: string, ...replacement: any[]) => string;
}

String.format('','');

This is assuming that String.format is defined elsewhere. e.g. in Microsoft Ajax Toolkit : http://www.asp.net/ajaxlibrary/Reference.String-format-Function.ashx

Removing pip's cache?

Simply

rm -d -r "$(pip cache dir)"

How to initialise memory with new operator in C++?

std::fill is one way. Takes two iterators and a value to fill the region with. That, or the for loop, would (I suppose) be the more C++ way.

For setting an array of primitive integer types to 0 specifically, memset is fine, though it may raise eyebrows. Consider also calloc, though it's a bit inconvenient to use from C++ because of the cast.

For my part, I pretty much always use a loop.

(I don't like to second-guess people's intentions, but it is true that std::vector is, all things being equal, preferable to using new[].)

What is the purpose of using WHERE 1=1 in SQL statements?

The 1=1 is ignored by always all rdbms. There is no tradeoff executing a query with WHERE 1=1.

Building dynamic WHERE conditions, like ORM frameworks or other do very often, it is easier to append the real where conditions because you avoid checking for prepending an AND to the current condition.

stmt += "WHERE 1=1";
if (v != null) {
   stmt += (" AND col = " + v.ToString());
}

This is how it looks like without 1=1.

var firstCondition = true;
...
if (v != null) {
   if (!firstCondition) {
      stmt += " AND ";
   }
   else {
       stmt += " WHERE ";
       firstCondition = false;
   }
   stmt += "col = " + v.ToString());
}

Angular HTML binding

_x000D_
_x000D_
 <div [innerHTML]="HtmlPrint"></div><br>
_x000D_
_x000D_
_x000D_

The innerHtml is a property of HTML-Elements, which allows you to set it’s html-content programatically. There is also a innerText property which defines the content as plain text.

The [attributeName]="value" box bracket , surrounding the attribute defines an Angular input-binding. That means, that the value of the property (in your case innerHtml) is bound to the given expression, when the expression-result changes, the property value changes too.

So basically [innerHtml] allows you to bind and dynamically change the html-conent of the given HTML-Element.

What is the difference between LATERAL and a subquery in PostgreSQL?

One thing no one has pointed out is that you can use LATERAL queries to apply a user-defined function on every selected row.

For instance:

CREATE OR REPLACE FUNCTION delete_company(companyId varchar(255))
RETURNS void AS $$
    BEGIN
        DELETE FROM company_settings WHERE "company_id"=company_id;
        DELETE FROM users WHERE "company_id"=companyId;
        DELETE FROM companies WHERE id=companyId;
    END; 
$$ LANGUAGE plpgsql;

SELECT * FROM (
    SELECT id, name, created_at FROM companies WHERE created_at < '2018-01-01'
) c, LATERAL delete_company(c.id);

That's the only way I know how to do this sort of thing in PostgreSQL.

Generics/templates in python?

Look at how the built-in containers do it. dict and list and so on contain heterogeneous elements of whatever types you like. If you define, say, an insert(val) function for your tree, it will at some point do something like node.value = val and Python will take care of the rest.

mkdir -p functionality in Python

mkdir -p gives you an error if the file already exists:

$ touch /tmp/foo
$ mkdir -p /tmp/foo
mkdir: cannot create directory `/tmp/foo': File exists

So a refinement to the previous suggestions would be to re-raise the exception if os.path.isdir returns False (when checking for errno.EEXIST).

(Update) See also this highly similar question; I agree with the accepted answer (and caveats) except I would recommend os.path.isdir instead of os.path.exists.

(Update) Per a suggestion in the comments, the full function would look like:

import os
def mkdirp(directory):
    if not os.path.isdir(directory):
        os.makedirs(directory) 

How to leave space in HTML

Either use literal non-breaking space symbol (yes, you can copy/paste it), HTML entity, or, if you're dealing with big pre-formatted block, use white-space CSS property.

How do I create a sequence in MySQL?

Check out this article. I believe it should help you get what you are wanting. If your table already exists, and it has data in it already, the error you are getting may be due to the auto_increment trying to assign a value that already exists for other records.

In short, as others have already mentioned in comments, sequences, as they are thought of and handled in Oracle, do not exist in MySQL. However, you can likely use auto_increment to accomplish what you want.

Without additional details on the specific error, it is difficult to provide more specific help.

UPDATE

CREATE TABLE ORD (
  ORDID INT NOT NULL AUTO_INCREMENT,
  //Rest of table code
  PRIMARY KEY (ordid)
)
AUTO_INCREMENT = 622;

This link is also helpful for describing usage of auto_increment. Setting the AUTO_INCREMENT value appears to be a table option, and not something that is specified as a column attribute specifically.

Also, per one of the links from above, you can alternatively set the auto increment start value via an alter to your table.

ALTER TABLE ORD AUTO_INCREMENT = 622;

UPDATE 2 Here is a link to a working sqlfiddle example, using auto increment.
I hope this info helps.

How to add a fragment to a programmatically generated layout?

At some point, I suppose you will add your programatically created LinearLayout to some root layout that you defined in .xml. This is just a suggestion of mine and probably one of many solutions, but it works: Simply set an ID for the programatically created layout, and add it to the root layout that you defined in .xml, and then use the set ID to add the Fragment.

It could look like this:

LinearLayout rowLayout = new LinearLayout();
rowLayout.setId(whateveryouwantasid);
// add rowLayout to the root layout somewhere here

FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTransaction = fragMan.beginTransaction();   

Fragment myFrag = new ImageFragment();
fragTransaction.add(rowLayout.getId(), myFrag , "fragment" + fragCount);
fragTransaction.commit();

Simply choose whatever Integer value you want for the ID:

rowLayout.setId(12345);

If you are using the above line of code not just once, it would probably be smart to figure out a way to create unique-IDs, in order to avoid duplicates.

UPDATE:

Here is the full code of how it should be done: (this code is tested and works) I am adding two Fragments to a LinearLayout with horizontal orientation, resulting in the Fragments being aligned next to each other. Please also be aware, that I used a fixed height and width of 200dp, so that one Fragment does not use the full screen as it would with "match_parent".

MainActivity.java:

public class MainActivity extends Activity {

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);     

        LinearLayout fragContainer = (LinearLayout) findViewById(R.id.llFragmentContainer);

        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.HORIZONTAL);

        ll.setId(12345);

        getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 1"), "someTag1").commit();
        getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 2"), "someTag2").commit();

        fragContainer.addView(ll);
    }
}

TestFragment.java:

public class TestFragment extends Fragment {

    public static TestFragment newInstance(String text) {

        TestFragment f = new TestFragment();

        Bundle b = new Bundle();
        b.putString("text", text);
        f.setArguments(b);
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View v =  inflater.inflate(R.layout.fragment, container, false);

        ((TextView) v.findViewById(R.id.tvFragText)).setText(getArguments().getString("text"));     
        return v;
    }
}

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rlMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <LinearLayout
        android:id="@+id/llFragmentContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="19dp"
        android:orientation="vertical" >
    </LinearLayout>
</RelativeLayout>

fragment.xml:

  <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="200dp"
    android:layout_height="200dp" >

    <TextView
        android:id="@+id/tvFragText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="" />

</RelativeLayout>

And this is the result of the above code: (the two Fragments are aligned next to each other) result

Convert alphabet letters to number in Python

You can map the alphabet to a list and return the index of each one as per the below :

import string

alphabet=string.ascii_lowercase
#alphabet='abcdefghijklmnopqrstuvwxyz'

#Get the character index , ex: e  
print(chars.find('e'))
#This will return 4

How do I create a file at a specific path?

The file is created wherever the root of the python interpreter was started.

Eg, you start python in /home/user/program, then the file "test.py" would be located at /home/user/program/test.py

Why em instead of px?

example:

Code: body{font-size:10px;} //keep at 10 all sizes below correct, change this value and the rest change to be e.g. 1.4 of this value

1{font-size:1.2em;} //12px

2{font-size:1.4em;} //14px

3{font-size:1.6em;} //16px

4{font-size:1.8em;} //18px

5{font-size:2em;} //20px

body

1

2

3

4

5

by changing the value in body the rest change automatically to be a kind of times the base value…

10×2=20 10×1.6=16 etc

you could have the base value as 8px… so 8×2=16 8×1.6=12.8 //may be rounded by browser

POST request via RestTemplate in JSON

As specified here I guess you need to add a messageConverter for MappingJacksonHttpMessageConverter

What should a Multipart HTTP request with multiple files look like?

EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245

To see exactly what is happening, use nc -l and an user agent like a browser or cURL.

Save the form to an .html file:

<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
  <p><input type="text" name="text" value="text default">
  <p><input type="file" name="file1">
  <p><input type="file" name="file2">
  <p><button type="submit">Submit</button>
</form>

Create files to upload:

echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html

Run:

nc -l localhost 8000

Open the HTML on your browser, select the files and click on submit and check the terminal.

nc prints the request received. Firefox sent:

POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"

text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain

Content of a.txt.

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html

<!DOCTYPE html><title>Content of a.html.</title>

-----------------------------9051914041544843365972754266--

Aternativelly, cURL should send the same POST request as your a browser form:

nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000

You can do multiple tests with:

while true; do printf '' | nc -l localhost 8000; done

How to center align the ActionBar title in Android?

It works nicely.

activity = (AppCompatActivity) getActivity();

activity.getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);

LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.custom_actionbar, null);

ActionBar.LayoutParams p = new ActionBar.LayoutParams(
        ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.MATCH_PARENT,
        Gravity.CENTER);

((TextView) v.findViewById(R.id.title)).setText(FRAGMENT_TITLE);

activity.getSupportActionBar().setCustomView(v, p);
activity.getSupportActionBar().setDisplayShowTitleEnabled(true);
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Below layout of custom_actionbar:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:text="Example"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:ellipsize="end"
        android:maxLines="1"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@color/colorBlack" />

</RelativeLayout>

Difference between Static and final?

The two really aren't similar. static fields are fields that do not belong to any particular instance of a class.

class C {
    public static int n = 42;
}

Here, the static field n isn't associated with any particular instance of C but with the entire class in general (which is why C.n can be used to access it). Can you still use an instance of C to access n? Yes - but it isn't considered particularly good practice.

final on the other hand indicates that a particular variable cannot change after it is initialized.

class C {
    public final int n = 42;
}

Here, n cannot be re-assigned because it is final. One other difference is that any variable can be declared final, while not every variable can be declared static.

Also, classes can be declared final which indicates that they cannot be extended:

final class C {}

class B extends C {}  // error!

Similarly, methods can be declared final to indicate that they cannot be overriden by an extending class:

class C {
    public final void foo() {}
}

class B extends C {
    public void foo() {}  // error!
}

Tell Ruby Program to Wait some amount of time

Use sleep like so:

sleep 2

That'll sleep for 2 seconds.

Be careful to give an argument. If you just run sleep, the process will sleep forever. (This is useful when you want a thread to sleep until it's woken.)

Change the background color of CardView programmatically

You can use this in XML

card_view:cardBackgroundColor="@android:color/white"

or this in Java

cardView.setCardBackgroundColor(Color.WHITE);

How do I remove the non-numeric character from a string in java?

Simple way without using Regex:

public static String getOnlyNumerics(String str) {
    if (str == null) {
        return null;
    }
    StringBuffer strBuff = new StringBuffer();
    char c;
    for (int i = 0; i < str.length() ; i++) {
        c = str.charAt(i);
        if (Character.isDigit(c)) {
            strBuff.append(c);
        }
    }
    return strBuff.toString();
}

ExecuteNonQuery doesn't return results

Because the SET NOCOUNT option is set to on. Remove the line "SET NOCOUNT ON;" in your query or stored procedure.

See more at SqlCommand.ExecuteNonQuery() returns -1 when doing Insert / Update / Delete.

Use jquery to set value of div tag

When using the .html() method, a htmlString must be the parameter. (source) Put your string inside a HTML tag and it should work or use .text() as suggested by farzad.

Example:

<div class="demo-container">
    <div class="demo-box">Demonstration Box</div>
</div>

<script type="text/javascript">
$("div.demo-container").html( "<p>All new content. <em>You bet!</em></p>" );
</script>

How to install a previous exact version of a NPM package?

On Ubuntu you can try this command.

sudo npm cache clean -f
sudo npm install -g n
sudo n stable 

Specific version : sudo n 8.11.3 instead of sudo n stable

How should I read a file line-by-line in Python?

There is exactly one reason why the following is preferred:

with open('filename.txt') as fp:
    for line in fp:
        print line

We are all spoiled by CPython's relatively deterministic reference-counting scheme for garbage collection. Other, hypothetical implementations of Python will not necessarily close the file "quickly enough" without the with block if they use some other scheme to reclaim memory.

In such an implementation, you might get a "too many files open" error from the OS if your code opens files faster than the garbage collector calls finalizers on orphaned file handles. The usual workaround is to trigger the GC immediately, but this is a nasty hack and it has to be done by every function that could encounter the error, including those in libraries. What a nightmare.

Or you could just use the with block.

Bonus Question

(Stop reading now if are only interested in the objective aspects of the question.)

Why isn't that included in the iterator protocol for file objects?

This is a subjective question about API design, so I have a subjective answer in two parts.

On a gut level, this feels wrong, because it makes iterator protocol do two separate things—iterate over lines and close the file handle—and it's often a bad idea to make a simple-looking function do two actions. In this case, it feels especially bad because iterators relate in a quasi-functional, value-based way to the contents of a file, but managing file handles is a completely separate task. Squashing both, invisibly, into one action, is surprising to humans who read the code and makes it more difficult to reason about program behavior.

Other languages have essentially come to the same conclusion. Haskell briefly flirted with so-called "lazy IO" which allows you to iterate over a file and have it automatically closed when you get to the end of the stream, but it's almost universally discouraged to use lazy IO in Haskell these days, and Haskell users have mostly moved to more explicit resource management like Conduit which behaves more like the with block in Python.

On a technical level, there are some things you may want to do with a file handle in Python which would not work as well if iteration closed the file handle. For example, suppose I need to iterate over the file twice:

with open('filename.txt') as fp:
    for line in fp:
        ...
    fp.seek(0)
    for line in fp:
        ...

While this is a less common use case, consider the fact that I might have just added the three lines of code at the bottom to an existing code base which originally had the top three lines. If iteration closed the file, I wouldn't be able to do that. So keeping iteration and resource management separate makes it easier to compose chunks of code into a larger, working Python program.

Composability is one of the most important usability features of a language or API.

How to set the custom border color of UIView programmatically?

swift 3.0

self.uiTextView.layer.borderWidth = 0.5
    self.txtItemShortDes.layer.borderColor = UIColor(red:205.0/255.0, green:205.0/255.0, blue:205.0/255.0, alpha: 1.0).cgColor

right click context menu for datagridview

For the position for the context menu, y found the problem that I needed a it to be relative to the DataGridView, and the event I needed to use gives the poistion relative to the cell clicked. I haven't found a better solution so I implemented this function in the commons class, so I call it from wherever I need.

It's quite tested and works well. I Hope you find it useful.

    /// <summary>
    /// When DataGridView_CellMouseClick ocurs, it gives the position relative to the cell clicked, but for context menus you need the position relative to the DataGridView
    /// </summary>
    /// <param name="dgv">DataGridView that produces the event</param>
    /// <param name="e">Event arguments produced</param>
    /// <returns>The Location of the click, relative to the DataGridView</returns>
    public static Point PositionRelativeToDataGridViewFromDataGridViewCellMouseEventArgs(DataGridView dgv, DataGridViewCellMouseEventArgs e)
    {
        int x = e.X;
        int y = e.Y;
        if (dgv.RowHeadersVisible)
            x += dgv.RowHeadersWidth;
        if (dgv.ColumnHeadersVisible)
            y += dgv.ColumnHeadersHeight;
        for (int j = 0; j < e.ColumnIndex; j++)
            if (dgv.Columns[j].Visible)
                x += dgv.Columns[j].Width;
        for (int i = 0; i < e.RowIndex; i++)
            if (dgv.Rows[i].Visible)
                y += dgv.Rows[i].Height;
        return new Point(x, y);
    }

How to output something in PowerShell

I think in this case you will need Write-Output.

If you have a script like

Write-Output "test1";
Write-Host "test2";
"test3";

then, if you call the script with redirected output, something like yourscript.ps1 > out.txt, you will get test2 on the screen test1\ntest3\n in the "out.txt".

Note that "test3" and the Write-Output line will always append a new line to your text and there is no way in PowerShell to stop this (that is, echo -n is impossible in PowerShell with the native commands). If you want (the somewhat basic and easy in Bash) functionality of echo -n then see samthebest's answer.

If a batch file runs a PowerShell command, it will most likely capture the Write-Output command. I have had "long discussions" with system administrators about what should be written to the console and what should not. We have now agreed that the only information if the script executed successfully or died has to be Write-Host'ed, and everything that is the script's author might need to know about the execution (what items were updated, what fields were set, et cetera) goes to Write-Output. This way, when you submit a script to the system administrator, he can easily runthescript.ps1 >someredirectedoutput.txt and see on the screen, if everything is OK. Then send the "someredirectedoutput.txt" back to the developers.

How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?

Easily readable and customisable way to get a timestamp in your desired format, without use of any library:

function timestamp(){
  function pad(n) {return n<10 ? "0"+n : n}
  d=new Date()
  dash="-"
  colon=":"
  return d.getFullYear()+dash+
  pad(d.getMonth()+1)+dash+
  pad(d.getDate())+" "+
  pad(d.getHours())+colon+
  pad(d.getMinutes())+colon+
  pad(d.getSeconds())
}

(If you require time in UTC format, then just change the function calls. For example "getMonth" becomes "getUTCMonth")

How to use Python requests to fake a browser visit a.k.a and generate User Agent?

I had a similar issue but I was unable to use the UserAgent class inside the fake_useragent module. I was running the code inside a docker container

import requests
import ujson
import random

response = requests.get('https://fake-useragent.herokuapp.com/browsers/0.1.11')
agents_dictionary = ujson.loads(response.text)
random_browser_number = str(random.randint(0, len(agents_dictionary['randomize'])))
random_browser = agents_dictionary['randomize'][random_browser_number]
user_agents_list = agents_dictionary['browsers'][random_browser]
user_agent = user_agents_list[random.randint(0, len(user_agents_list)-1)]

I targeted the endpoint used in the module. This solution still gave me a random user agent however there is the possibility that the data structure at the endpoint could change.

In PHP, how do you change the key of an array element?

Hmm, I'm not test before, but I think this code working

function replace_array_key($data) {
    $mapping = [
        'old_key_1' => 'new_key_1',
        'old_key_2' => 'new_key_2',
    ];

    $data = json_encode($data);
    foreach ($mapping as $needed => $replace) {
        $data = str_replace('"'.$needed.'":', '"'.$replace.'":', $data);
    }

    return json_decode($data, true);
}

How do I space out the child elements of a StackPanel?

Another nice approach can be seen here: http://blogs.microsoft.co.il/blogs/eladkatz/archive/2011/05/29/what-is-the-easiest-way-to-set-spacing-between-items-in-stackpanel.aspx Link is broken -> this is webarchive of this link.

It shows how to create an attached behavior, so that syntax like this would work:

<StackPanel local:MarginSetter.Margin="5">
   <TextBox Text="hello" />
   <Button Content="hello" />
   <Button Content="hello" />
</StackPanel>

This is the easiest & fastest way to set Margin to several children of a panel, even if they are not of the same type. (I.e. Buttons, TextBoxes, ComboBoxes, etc.)

How to modify existing XML file with XmlDocument and XmlNode in C#

You need to do something like this:

// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");

// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");

// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
   // grab the "id" attribute
   XmlAttribute idAttribute = aNode.Attributes["id"];

   // check if that attribute even exists...
   if (idAttribute != null)
   {
      // if yes - read its current value
      string currentValue = idAttribute.Value;

      // here, you can now decide what to do - for demo purposes,
      // I just set the ID value to a fixed value if it was empty before
      if (string.IsNullOrEmpty(currentValue))
      {
         idAttribute.Value = "515";
      }
   }
}

// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");

install beautiful soup using pip

import os

os.system("pip install beautifulsoup4")

or

import subprocess

exe = subprocess.Popen("pip install beautifulsoup4")

exe_out = exe.communicate()

print(exe_out)

HTML: Image won't display?

Here are the most common reasons

  • Incorrect file paths

  • File names are misspelled

  • Wrong file extension

  • Files are missing

  • The read permission has not been set for the image(s)

Note: On *nix systems, consider using the following command to add read permission for an image:

chmod o+r imagedirectoryAddress/imageName.extension

or this command to add read permission for all images:

chmod o+r imagedirectoryAddress/*.extension

If you need more information, refer to this post.

Form onSubmit determine which submit button was pressed

OP stated he didn't want to modify the code for the buttons. This is the least-intrusive answer I could come up with using the other answers as a guide. It doesn't require additional hidden fields, allows you to leave the button code intact (sometimes you don't have access to what generates it), and gives you the info you were looking for from anywhere in your code...which button was used to submit the form. I haven't evaluated what happens if the user uses the Enter key to submit the form, rather than clicking.

<script language="javascript" type="text/javascript">

    var initiator = '';
    $(document).ready(function() {
        $(":submit").click(function() { initiator = this.name });
    });

</script>

Then you have access to the 'initiator' variable anywhere that might need to do the checking. Hope this helps.

~Spanky

AngularJS routing without the hash '#'

try

$locationProvider.html5Mode(true)

More info at $locationProvider
Using $location

How to read a CSV file from a URL with Python?

I am also using this approach for csv files (Python 3.6.9):

import csv
import io
import requests

r = requests.get(url)
buff = io.StringIO(r.text)
dr = csv.DictReader(buff)
for row in dr:
    print(row)

case in sql stored procedure on SQL Server

CASE isn't used for flow control... for this, you would need to use IF...

But, there's a set-based solution to this problem instead of the procedural approach:

UPDATE tblEmployee
SET 
  InOffice = CASE WHEN @NewStatus = 'InOffice' THEN -1 ELSE InOffice END,
  OutOffice = CASE WHEN @NewStatus = 'OutOffice' THEN -1 ELSE OutOffice END,
  Home = CASE WHEN @NewStatus = 'Home' THEN -1 ELSE Home END
WHERE EmpID = @EmpID

Note that the ELSE will preserves the original value if the @NewStatus condition isn't met.

Get remote registry value

If you have Powershell remoting and CredSSP setup then you can update your code to the following:

$Session = New-PSSession -ComputerName $Computer1 -Authentication CredSSP
$NetbackupVersion1 = Invoke-Command -Session $Session -ScriptBlock { $(Get-ItemProperty hklm:\SOFTWARE\Veritas\NetBackup\CurrentVersion).PackageVersion}
Remove-PSSession $Session

How to disable scrolling temporarily?

My take on this issue also includes a concern with the body width, as the page seems to dance a little when we hide the scroll bar with overflow = "hidden". The following code works perfectly for me, and is based on an Angular approach.

element.bind('mouseenter', function() {
    var w = document.body.offsetWidth;
    document.body.style.overflow = 'hidden';
    document.body.style.width = w + 'px';
});

element.bind('mouseleave', function() {
    document.body.style.overflow = 'initial';
    document.body.style.width = 'auto';
});

How to print environment variables to the console in PowerShell?

Prefix the variable name with env:

$env:path

For example, if you want to print the value of environment value "MINISHIFT_USERNAME", then command will be:

$env:MINISHIFT_USERNAME

You can also enumerate all variables via the env drive:

Get-ChildItem env:

Merge unequal dataframes and replace missing rows with 0

I used the answer given by Chase (answered May 11 '11 at 14:21), but I added a bit of code to apply that solution to my particular problem.

I had a frame of rates (user, download) and a frame of totals (user, download) to be merged by user, and I wanted to include every rate, even if there were no corresponding total. However, there could be no missing totals, in which case the selection of rows for replacement of NA by zero would fail.

The first line of code does the merge. The next two lines change the column names in the merged frame. The if statement replaces NA by zero, but only if there are rows with NA.

# merge rates and totals, replacing absent totals by zero
graphdata <- merge(rates, totals, by=c("user"),all.x=T)
colnames(graphdata)[colnames(graphdata)=="download.x"] = "download.rate"
colnames(graphdata)[colnames(graphdata)=="download.y"] = "download.total"
if(any(is.na(graphdata$download.total))) {
    graphdata[is.na(graphdata$download.total),]$download.total <- 0
}

How to check if a string is a valid JSON string in JavaScript without using Try/Catch

Here is the typescript version too:

JSONTryParse(input: any) {
    try {
        //check if the string exists
        if (input) {
            var o = JSON.parse(input);

            //validate the result too
            if (o && o.constructor === Object) {
                return o;
            }
        }
    }
    catch (e: any) {
    }

    return false;
};

jquery: animate scrollLeft

You'll want something like this:


$("#next").click(function(){
      var currentElement = currentElement.next();
      $('html, body').animate({scrollLeft: $(currentElement).offset().left}, 800);
      return false;
   }); 
I believe this should work, it's adopted from a scrollTop function.

How to set alignment center in TextBox in ASP.NET?

You can use:

<asp:textbox id="textBox1" style="text-align:center"></asp:textbox>

Or this:

textbox.Style["text-align"] = "center"; //right, left

What's the difference between unit tests and integration tests?

A unit test should have no dependencies on code outside the unit tested. You decide what the unit is by looking for the smallest testable part. Where there are dependencies they should be replaced by false objects. Mocks, stubs .. The tests execution thread starts and ends within the smallest testable unit.

When false objects are replaced by real objects and tests execution thread crosses into other testable units, you have an integration test

'Access denied for user 'root'@'localhost' (using password: NO)'

for this kind of error; you just have to set new password to the root user as an admin. follow the steps as follows:

[root ~]# mysql -u root
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password:NO)
  1. Stop the service/daemon of mysql running

    [root ~]# service mysql stop   
    mysql stop/waiting
    
  2. Start mysql without any privileges using the following option; This option is used to boot up and do not use the privilege system of MySQL.

    [root ~]# mysqld_safe --skip-grant-tables &
    

At this moment, the terminal will seem to halt. Let that be, and use new terminal for next steps.

  1. enter the mysql command prompt

    [root ~]# mysql -u root
    mysql> 
    
  2. Fix the permission setting of the root user ;

    mysql> use mysql;
    Database changed
    mysql> select * from  user;
    Empty set (0.00 sec)
    mysql> truncate table user;
    Query OK, 0 rows affected (0.00 sec)
    mysql> flush privileges;
    Query OK, 0 rows affected (0.01 sec)
    mysql> grant all privileges on *.* to root@localhost identified by 'YourNewPassword' with grant option;
    Query OK, 0 rows affected (0.01 sec)
    

*if you don`t want any password or rather an empty password

    mysql> grant all privileges on *.* to root@localhost identified by '' with grant option;
    Query OK, 0 rows affected (0.01 sec)*
    mysql> flush privileges;
    Query OK, 0 rows affected (0.00 sec)

Confirm the results:

    mysql> select host, user from user;
+-----------+------+
| host      | user |
+-----------+------+
| localhost | root |
+-----------+------+
1 row in set (0.00 sec)
  1. Exit the shell and restart mysql in normal mode.

    mysql> quit;
    [root ~]# kill -KILL [PID of mysqld_safe]
    [root ~]# kill -KILL [PID of mysqld]
    [root ~]# service mysql start
    
  2. Now you can successfully login as root user with the password you set

     [root ~]# mysql -u root -pYourNewPassword 
     mysql> 
    

Static method in a generic class?

Something like the following would get you closer

class Clazz
{
   public static <U extends Clazz> void doIt(U thing)
   {
   }
}

EDIT: Updated example with more detail

public abstract class Thingo 
{

    public static <U extends Thingo> void doIt(U p_thingo)
    {
        p_thingo.thing();
    }

    protected abstract void thing();

}

class SubThingoOne extends Thingo
{
    @Override
    protected void thing() 
    {
        System.out.println("SubThingoOne");
    }
}

class SubThingoTwo extends Thingo
{

    @Override
    protected void thing() 
    {
        System.out.println("SuThingoTwo");
    }

}

public class ThingoTest 
{

    @Test
    public void test() 
    {
        Thingo t1 = new SubThingoOne();
        Thingo t2 = new SubThingoTwo();

        Thingo.doIt(t1);
        Thingo.doIt(t2);

        // compile error -->  Thingo.doIt(new Object());
    }
}

What is a "method" in Python?

If you think of an object as being similar to a noun, then a method is similar to a verb. Use a method right after an object (i.e. a string or a list) to apply a method's action to it.

How to convert date to timestamp?

Try this function, it uses the Date.parse() method and doesn't require any custom logic:

function toTimestamp(strDate){
   var datum = Date.parse(strDate);
   return datum/1000;
}
alert(toTimestamp('02/13/2009 23:31:30'));

Any reason not to use '+' to concatenate two strings?

There is nothing wrong in concatenating two strings with +. Indeed it's easier to read than ''.join([a, b]).

You are right though that concatenating more than 2 strings with + is an O(n^2) operation (compared to O(n) for join) and thus becomes inefficient. However this has not to do with using a loop. Even a + b + c + ... is O(n^2), the reason being that each concatenation produces a new string.

CPython2.4 and above try to mitigate that, but it's still advisable to use join when concatenating more than 2 strings.

Behaviour of increment and decrement operators in Python

TL;DR

Python does not have unary increment/decrement operators (--/++). Instead, to increment a value, use

a += 1

More detail and gotchas

But be careful here. If you're coming from C, even this is different in python. Python doesn't have "variables" in the sense that C does, instead python uses names and objects, and in python ints are immutable.

so lets say you do

a = 1

What this means in python is: create an object of type int having value 1 and bind the name a to it. The object is an instance of int having value 1, and the name a refers to it. The name a and the object to which it refers are distinct.

Now lets say you do

a += 1

Since ints are immutable, what happens here is as follows:

  1. look up the object that a refers to (it is an int with id 0x559239eeb380)
  2. look up the value of object 0x559239eeb380 (it is 1)
  3. add 1 to that value (1 + 1 = 2)
  4. create a new int object with value 2 (it has object id 0x559239eeb3a0)
  5. rebind the name a to this new object
  6. Now a refers to object 0x559239eeb3a0 and the original object (0x559239eeb380) is no longer refered to by the name a. If there aren't any other names refering to the original object it will be garbage collected later.

Give it a try yourself:

a = 1
print(hex(id(a)))
a += 1
print(hex(id(a)))

How to create a numpy array of arbitrary length strings?

You can do so by creating an array of dtype=object. If you try to assign a long string to a normal numpy array, it truncates the string:

>>> a = numpy.array(['apples', 'foobar', 'cowboy'])
>>> a[2] = 'bananas'
>>> a
array(['apples', 'foobar', 'banana'], 
      dtype='|S6')

But when you use dtype=object, you get an array of python object references. So you can have all the behaviors of python strings:

>>> a = numpy.array(['apples', 'foobar', 'cowboy'], dtype=object)
>>> a
array([apples, foobar, cowboy], dtype=object)
>>> a[2] = 'bananas'
>>> a
array([apples, foobar, bananas], dtype=object)

Indeed, because it's an array of objects, you can assign any kind of python object to the array:

>>> a[2] = {1:2, 3:4}
>>> a
array([apples, foobar, {1: 2, 3: 4}], dtype=object)

However, this undoes a lot of the benefits of using numpy, which is so fast because it works on large contiguous blocks of raw memory. Working with python objects adds a lot of overhead. A simple example:

>>> a = numpy.array(['abba' for _ in range(10000)])
>>> b = numpy.array(['abba' for _ in range(10000)], dtype=object)
>>> %timeit a.copy()
100000 loops, best of 3: 2.51 us per loop
>>> %timeit b.copy()
10000 loops, best of 3: 48.4 us per loop

How to make the main content div fill height of screen with css

Using top: 40px and bottom: 40px (assuming your footer is also 40px) with no defined height, you can get this to work.

.header {
    width: 100%;
    height: 40px;
    position: absolute;
    top: 0;
    background-color:red;
}
.mainBody {
    width: 100%;
    top: 40px;
    bottom: 40px;
    position: absolute;
    background-color: gray;
}
.footer {
    width: 100%;
    height: 40px;
    position: absolute;
    bottom: 0;
    background-color: blue;
}

JSFiddle

Html helper for <input type="file" />

You can also use:

@using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ 
    <p>
        <input type="file" id="fileUpload" name="fileUpload" size="23" />
    </p>
    <p>
        <input type="submit" value="Upload file" /></p> 
}

Breaking out of a for loop in Java

public class Test {

public static void main(String args[]) {

  for(int x = 10; x < 20; x = x+1) {
     if(x==15)
         break;
     System.out.print("value of x : " + x );
     System.out.print("\n");
  }
}
}

WPF Datagrid Get Selected Cell Value

I was in such situation .. and found This:

int ColumnIndex = DataGrid.CurrentColumn.DisplayIndex;
TextBlock CellContent = DataGrid.SelectedCells[ColumnIndex].Column.GetCellContent(DataGrid.SelectedItem);

And make sure to treat custom columns' templates

Interfaces vs. abstract classes

Another thing to consider is that, since there is no multiple inheritance, if you want a class to be able to implement/inherit from your interface/abstract class, but inherit from another base class, use an interface.

How to get JSON data from the URL (REST API) to UI using jQuery or plain JavaScript?

 jquery.ajax({
            url: `//your api url`
            type: "GET",
            dataType: "json",
            success: function(data) {
                jQuery.each(data, function(index, value) {
                        console.log(data);
                        `All you API data is here`
                    }
                }
            });     

Current Subversion revision command

Just used @badcat's answer in a modified version, using subprocess.check_output():

import subprocess
revision = subprocess.check_output("svn info | awk '/^Revision:/ {print $2}'", shell=True).strip()

I believe you can also, install and use pysvn if you want to use python to interface with svn.

Open files always in a new tab

Open in new Tab Solution:

  1. Open the command palette by: Cmd + Shift + K
  2. Open settings file by: Preferences: Open Settings (JSON)
  3. Under user setting, enable Tabs by: "workbench.editor.showTabs": true

Vector erase iterator

Because the method erase in vector return the next iterator of the passed iterator.

I will give example of how to remove element in vector when iterating.

void test_del_vector(){
    std::vector<int> vecInt{0, 1, 2, 3, 4, 5};

    //method 1
    for(auto it = vecInt.begin();it != vecInt.end();){
        if(*it % 2){// remove all the odds
            it = vecInt.erase(it); // note it will = next(it) after erase
        } else{
            ++it;
        }
    }

    // output all the remaining elements
    for(auto const& it:vecInt)std::cout<<it;
    std::cout<<std::endl;

    // recreate vecInt, and use method 2
    vecInt = {0, 1, 2, 3, 4, 5};
    //method 2
    for(auto it=std::begin(vecInt);it!=std::end(vecInt);){
        if (*it % 2){
            it = vecInt.erase(it);
        }else{
            ++it;
        }
    }

    // output all the remaining elements
    for(auto const& it:vecInt)std::cout<<it;
    std::cout<<std::endl;

    // recreate vecInt, and use method 3
    vecInt = {0, 1, 2, 3, 4, 5};
    //method 3
    vecInt.erase(std::remove_if(vecInt.begin(), vecInt.end(),
                 [](const int a){return a % 2;}),
                 vecInt.end());

    // output all the remaining elements
    for(auto const& it:vecInt)std::cout<<it;
    std::cout<<std::endl;

}

output aw below:

024
024
024

A more generate method:

template<class Container, class F>
void erase_where(Container& c, F&& f)
{
    c.erase(std::remove_if(c.begin(), c.end(),std::forward<F>(f)),
            c.end());
}

void test_del_vector(){
    std::vector<int> vecInt{0, 1, 2, 3, 4, 5};
    //method 4
    auto is_odd = [](int x){return x % 2;};
    erase_where(vecInt, is_odd);

    // output all the remaining elements
    for(auto const& it:vecInt)std::cout<<it;
    std::cout<<std::endl;    
}

jQuery Dialog Box

I had the same problem and was looking for a way to solve it which brought me here. After reviewing the suggestion made from RaeLehman it led me to the solution. Here's my implementation.

In my $(document).ready event I initialize my dialog with the autoOpen set to false. I also chose to bind a click event to an element, like a button, which will open my dialog.

$(document).ready(function(){

    // Initialize my dialog
    $("#dialog").dialog({
        autoOpen: false,
        modal: true,
        buttons: {
        "OK":function() { // do something },
        "Cancel": function() { $(this).dialog("close"); }
    }
    });

    // Bind to the click event for my button and execute my function
    $("#x-button").click(function(){
        Foo.DoSomething();
    });
});

Next, I make sure that the function is defined and that is where I implement the dialog open method.

var Foo = {
    DoSomething: function(){
        $("#dialog").dialog("open");
    }
}

By the way, I tested this in IE7 and Firefox and it works fine. Hope this helps!

How to generate random number in Bash?

There is $RANDOM. I don't know exactly how it works. But it works. For testing, you can do :

echo $RANDOM

How to run Maven from another directory (without cd to project dir)?

You can use the parameter -f (or --file) and specify the path to your pom file, e.g. mvn -f /path/to/pom.xml

This runs maven "as if" it were in /path/to for the working directory.

How to host google web fonts on my own server?

It is legally allowed as long as you stick to the terms of the font's license - usually the OFL.

You'll need a set of web font formats, and the Font Squirrel Webfont Generator can produce these.

But the OFL required the fonts be renamed if they are modified, and using the generator means modifying them.

Maximum Length of Command Line String

Sorry for digging out an old thread, but I think sunetos' answer isn't correct (or isn't the full answer). I've done some experiments (using ProcessStartInfo in c#) and it seems that the 'arguments' string for a commandline command is limited to 2048 characters in XP and 32768 characters in Win7. I'm not sure what the 8191 limit refers to, but I haven't found any evidence of it yet.

Mips how to store user input string

Ok. I found a program buried deep in other files from the beginning of the year that does what I want. I can't really comment on the suggestions offered because I'm not an experienced spim or low level programmer.Here it is:

         .text
         .globl __start
    __start:
         la $a0,str1 #Load and print string asking for string
         li $v0,4
         syscall

         li $v0,8 #take in input
         la $a0, buffer #load byte space into address
         li $a1, 20 # allot the byte space for string
         move $t0,$a0 #save string to t0
         syscall

         la $a0,str2 #load and print "you wrote" string
         li $v0,4
         syscall

         la $a0, buffer #reload byte space to primary address
         move $a0,$t0 # primary address = t0 address (load pointer)
         li $v0,4 # print string
         syscall

         li $v0,10 #end program
         syscall


               .data
             buffer: .space 20
             str1:  .asciiz "Enter string(max 20 chars): "
             str2:  .asciiz "You wrote:\n"
             ###############################
             #Output:
             #Enter string(max 20 chars): qwerty 123
             #You wrote:
             #qwerty 123
             #Enter string(max 20 chars):   new world oreddeYou wrote:
             #  new world oredde //lol special character
             ###############################

Delete keychain items when an app is uninstalled

Files will be deleted from your app's document directory when the user uninstalls the app. Knowing this, all you have to do is check whether a file exists as the first thing that happens in application:didFinishLaunchingWithOptions:. Afterwards, unconditionally create the file (even if it's just a dummy file).

If the file did not exist at time of check, you know this is the first run since the latest install. If you need to know later in the app, save the boolean result to your app delegate member.

How do I invert BooleanToVisibilityConverter?

Implement your own implementation of IValueConverter. A sample implementation is at

http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx

In your Convert method, have it return the values you'd like instead of the defaults.

Understanding checked vs unchecked exceptions in Java

I just want to add some reasoning for not using checked exceptions at all. This is not a full answer, but I feel it does answer part of your question, and complements many other answers.

Whenever checked exceptions are involved, there's a throws CheckedException somewhere in a method signature (CheckedException could be any checked exception). A signature does NOT throw an Exception, throwing Exceptions is an aspect of implementation. Interfaces, method signatures, parent classes, all these things should NOT depend on their implementations. The usage of checked Exceptions here (actually the fact that you have to declare the throws in the method signature) is binding your higher-level interfaces with your implementations of these interfaces.

Let me show you an example.

Let's have a nice and clean interface like this

public interface IFoo {
    public void foo();
}

Now we can write many implementations of method foo(), like these

public class Foo implements IFoo {
    @Override
    public void foo() {
        System.out.println("I don't throw and exception");
    }
}

Class Foo is perfectly fine. Now let's make a first attempt at class Bar

public class Bar implements IFoo {
    @Override
    public void foo() {
        //I'm using InterruptedExcepton because you probably heard about it somewhere. It's a checked exception. Any checked exception will work the same.
        throw new InterruptedException();
    }
}

This class Bar won't compile. As InterruptedException is a checked exception, you must either capture it (with a try-catch inside method foo()) or declare that you're throwing it (adding throws InterruptedException to the method signature). As I don't want to capture this exception here (I want it to propagate upwards so I can properly deal with it somewhere else), let's alter the signature.

public class Bar implements IFoo {
    @Override
    public void foo() throws InterruptedException {
        throw new InterruptedException();
    }
}

This class Bar won't compile either! Bar's method foo() does NOT override IFoo's method foo() since their signatures are different. I could remove the @Override annotation, but I want to program against interface IFoo like IFoo foo; and later on decide on which implementation I want to use, like foo = new Bar();. If Bar's method foo() doesn't override IFoo's method foo, when I do foo.foo(); it won't call Bar's implementation of foo().

To make Bar's public void foo() throws InterruptedException override IFoo's public void foo() I MUST add throws InterruptedException to IFoo's method signature. This, however, will cause problems with my Foo class, since it's foo() method's signature differs from IFoo's method signature. Furthermore, if I added throws InterruptedException to Foo's method foo() I would get another error stating that Foo's method foo() declares that it throws an InterruptedException yet it never throws an InterruptedException.

As you can see (if I did a decent job at explaining this stuff), the fact that I'm throwing a checked exception like InterruptedException is forcing me to tie my interface IFoo to one of it's implementations, which in turn causes havoc on IFoo's other implementations!

This is one big reason why checked exceptions are BAD. In caps.

One solution is to capture the checked exception, wrap it in an unchecked exception and throw the unchecked exception.

C# nullable string error

System.String is a reference type and already "nullable".

Nullable<T> and the ? suffix are for value types such as Int32, Double, DateTime, etc.

Removing all script tags from html with JS Regular Expression

Regexes are beatable, but if you have a string version of HTML that you don't want to inject into a DOM, they may be the best approach. You may want to put it in a loop to handle something like:

<scr<script>Ha!</script>ipt> alert(document.cookie);</script>

Here's what I did, using the jquery regex from above:

var SCRIPT_REGEX = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi;
while (SCRIPT_REGEX.test(text)) {
    text = text.replace(SCRIPT_REGEX, "");
}

Show a PDF files in users browser via PHP/Perl

The safest way to have a PDF display instead of download seems to be embedding it using an object or iframe element. There are also 3rd party solutions like Google's PDF viewer.

See Best Way to Embed PDF in HTML for an overview.

There's also DoPDF, a Java based In-browser PDF viewer. I can't speak to its quality but it looks interesting.

shift a std_logic_vector of n bit to right or left

Personally, I think the concatenation is the better solution. The generic implementation would be

entity shifter is
    generic (
        REGSIZE  : integer := 8);
    port(
        clk      : in  str_logic;
        Data_in  : in  std_logic;
        Data_out : out std_logic(REGSIZE-1 downto 0);
end shifter ;

architecture bhv of shifter is
    signal shift_reg : std_logic_vector(REGSIZE-1 downto 0) := (others<='0');
begin
    process (clk) begin
        if rising_edge(clk) then
            shift_reg <= shift_reg(REGSIZE-2 downto 0) & Data_in;
        end if;
    end process;
end bhv;
Data_out <= shift_reg;

Both will implement as shift registers. If you find yourself in need of more shift registers than you are willing to spend resources on (EG dividing 1000 numbers by 4) you might consider using a BRAM to store the values and a single shift register to contain "indices" that result in the correct shift of all the numbers.

Checkout one file from Subversion

You can do it in two steps:

  1. Checkout an empty SVN repository with meta information only:

    $ cd /tmp
    
    $ svn co --depth empty http://svn.your.company.ca/training/trunk/sql
    
  2. Run svn up to update specified file:

    $ svn up http://svn.your.company.ca/training/trunk/sql/showSID.sql
    

How to check if spark dataframe is empty?

I found that on some cases:

>>>print(type(df))
<class 'pyspark.sql.dataframe.DataFrame'>

>>>df.take(1).isEmpty
'list' object has no attribute 'isEmpty'

this is same for "length" or replace take() by head()

[Solution] for the issue we can use.

>>>df.limit(2).count() > 1
False

HTML: can I display button text in multiple lines?

one other way to improve and style the multi-line text is

 <button>Click here to<br/> 
     <span style="color:red;">start playing</span>

   </button>

How to respond to clicks on a checkbox in an AngularJS directive?

This is the way I've been doing this sort of stuff. Angular tends to favor declarative manipulation of the dom rather than a imperative one(at least that's the way I've been playing with it).

The markup

<table class="table">
  <thead>
    <tr>
      <th>
        <input type="checkbox" 
          ng-click="selectAll($event)"
          ng-checked="isSelectedAll()">
      </th>
      <th>Title</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="e in entities" ng-class="getSelectedClass(e)">
      <td>
        <input type="checkbox" name="selected"
          ng-checked="isSelected(e.id)"
          ng-click="updateSelection($event, e.id)">
      </td>
      <td>{{e.title}}</td>
    </tr>
  </tbody>
</table>

And in the controller

var updateSelected = function(action, id) {
  if (action === 'add' && $scope.selected.indexOf(id) === -1) {
    $scope.selected.push(id);
  }
  if (action === 'remove' && $scope.selected.indexOf(id) !== -1) {
    $scope.selected.splice($scope.selected.indexOf(id), 1);
  }
};

$scope.updateSelection = function($event, id) {
  var checkbox = $event.target;
  var action = (checkbox.checked ? 'add' : 'remove');
  updateSelected(action, id);
};

$scope.selectAll = function($event) {
  var checkbox = $event.target;
  var action = (checkbox.checked ? 'add' : 'remove');
  for ( var i = 0; i < $scope.entities.length; i++) {
    var entity = $scope.entities[i];
    updateSelected(action, entity.id);
  }
};

$scope.getSelectedClass = function(entity) {
  return $scope.isSelected(entity.id) ? 'selected' : '';
};

$scope.isSelected = function(id) {
  return $scope.selected.indexOf(id) >= 0;
};

//something extra I couldn't resist adding :)
$scope.isSelectedAll = function() {
  return $scope.selected.length === $scope.entities.length;
};

EDIT: getSelectedClass() expects the entire entity but it was being called with the id of the entity only, which is now corrected

Getting the source HTML of the current page from chrome extension

Inject a script into the page you want to get the source from and message it back to the popup....

manifest.json

{
  "name": "Get pages source",
  "version": "1.0",
  "manifest_version": 2,
  "description": "Get pages source from a popup",
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": ["tabs", "<all_urls>"]
}

popup.html

<!DOCTYPE html>
<html style=''>
<head>
<script src='popup.js'></script>
</head>
<body style="width:400px;">
<div id='message'>Injecting Script....</div>
</body>
</html>

popup.js

chrome.runtime.onMessage.addListener(function(request, sender) {
  if (request.action == "getSource") {
    message.innerText = request.source;
  }
});

function onWindowLoad() {

  var message = document.querySelector('#message');

  chrome.tabs.executeScript(null, {
    file: "getPagesSource.js"
  }, function() {
    // If you try and inject into an extensions page or the webstore/NTP you'll get an error
    if (chrome.runtime.lastError) {
      message.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
    }
  });

}

window.onload = onWindowLoad;

getPagesSource.js

// @author Rob W <http://stackoverflow.com/users/938089/rob-w>
// Demo: var serialized_html = DOMtoString(document);

function DOMtoString(document_root) {
    var html = '',
        node = document_root.firstChild;
    while (node) {
        switch (node.nodeType) {
        case Node.ELEMENT_NODE:
            html += node.outerHTML;
            break;
        case Node.TEXT_NODE:
            html += node.nodeValue;
            break;
        case Node.CDATA_SECTION_NODE:
            html += '<![CDATA[' + node.nodeValue + ']]>';
            break;
        case Node.COMMENT_NODE:
            html += '<!--' + node.nodeValue + '-->';
            break;
        case Node.DOCUMENT_TYPE_NODE:
            // (X)HTML documents are identified by public identifiers
            html += "<!DOCTYPE " + node.name + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' "' + node.systemId + '"' : '') + '>\n';
            break;
        }
        node = node.nextSibling;
    }
    return html;
}

chrome.runtime.sendMessage({
    action: "getSource",
    source: DOMtoString(document)
});

Using JQuery to check if no radio button in a group has been checked

You could do something like this:

var radio_buttons = $("input[name='html_elements']");
if( radio_buttons.filter(':checked').length == 0){
  // None checked
} else {
  // If you need to use the result you can do so without
  // another (costly) jQuery selector call:
  var val = radio_buttons.val();
}

How / can I display a console window in Intellij IDEA?

IntelliJ IDEA 2018.3.6

Using macOS Mojave Version 10.14.4 and pressing ?F12(Alt+F12) will open Sound preferences.

A solution without changing the current keymap is to use the command above with the key fn.

fn ? F12(fn+Alt+F12) will open the Terminal. And you can use ShiftEsc to close it.

javascript regular expression to check for IP addresses

A less stringent when testing the type not the validity. For example when sorting columns use this check to see which sort to use.

export const isIpAddress = (ipAddress) => 
    /^((\d){1,3}\.){3}(\d){1,3}$/.test(ipAddress)

When checking for validity use this test. An even more stringent test checking that the IP 8-bit numbers are in the range 0-255:

export const isValidIpAddress = (ipAddress) => 
    /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipAddress)

force browsers to get latest js and css files in asp.net application

The main problem with doing it this way is mainly that you will need to remember to update your version number in your code every time you make any change to your css or js files.

A possibly better way to do it is to set a guaranteed unique parameter with each of your css or js files, like so:

<script src="scripts/myjavascript.js?_=<%=DateTime.Now.Ticks%>" type="text/javascript"></script>
<link href="styles/mystyle.css?_=<%=DateTime.Now.Ticks%>" rel="stylesheet" type="text/css" />

This forces the files to be requested from the server every single time, which also means that your site will not be as performant upon page load, since those files will never be cached, and will use unneeded bandwidth each time.

Essentially, if you can remember to update the version number every time a change is made, you can get away with how you're doing it.

Remove non-utf8 characters from string

Slightly different to the question, but what I am doing is to use HtmlEncode(string),

pseudo code here

var encoded = HtmlEncode(string);
encoded = Regex.Replace(encoded, "&#\d+?;", "");
var result = HtmlDecode(encoded);

input and output

"Headlight\x007E Bracket, &#123; Cafe Racer<> Style, Stainless Steel ????"
"Headlight~ Bracket, &#123; Cafe Racer<> Style, Stainless Steel ????"

I know it's not perfect, but does the job for me.

Capturing Groups From a Grep RegEx

I realize that an answer was already accepted for this, but from a "strictly *nix purist angle" it seems like the right tool for the job is pcregrep, which doesn't seem to have been mentioned yet. Try changing the lines:

    echo $f | grep -oEi '[0-9]+_([a-z]+)_[0-9a-z]*'
    name=$?

to the following:

    name=$(echo $f | pcregrep -o1 -Ei '[0-9]+_([a-z]+)_[0-9a-z]*')

to get only the contents of the capturing group 1.

The pcregrep tool utilizes all of the same syntax you've already used with grep, but implements the functionality that you need.

The parameter -o works just like the grep version if it is bare, but it also accepts a numeric parameter in pcregrep, which indicates which capturing group you want to show.

With this solution there is a bare minimum of change required in the script. You simply replace one modular utility with another and tweak the parameters.

Interesting Note: You can use multiple -o arguments to return multiple capture groups in the order in which they appear on the line.

When should I use mmap for file access?

In addition to other nice answers, a quote from Linux system programming written by Google's expert Robert Love:

Advantages of mmap( )

Manipulating files via mmap( ) has a handful of advantages over the standard read( ) and write( ) system calls. Among them are:

  • Reading from and writing to a memory-mapped file avoids the extraneous copy that occurs when using the read( ) or write( ) system calls, where the data must be copied to and from a user-space buffer.

  • Aside from any potential page faults, reading from and writing to a memory-mapped file does not incur any system call or context switch overhead. It is as simple as accessing memory.

  • When multiple processes map the same object into memory, the data is shared among all the processes. Read-only and shared writable mappings are shared in their entirety; private writable mappings have their not-yet-COW (copy-on-write) pages shared.

  • Seeking around the mapping involves trivial pointer manipulations. There is no need for the lseek( ) system call.

For these reasons, mmap( ) is a smart choice for many applications.

Disadvantages of mmap( )

There are a few points to keep in mind when using mmap( ):

  • Memory mappings are always an integer number of pages in size. Thus, the difference between the size of the backing file and an integer number of pages is "wasted" as slack space. For small files, a significant percentage of the mapping may be wasted. For example, with 4 KB pages, a 7 byte mapping wastes 4,089 bytes.

  • The memory mappings must fit into the process' address space. With a 32-bit address space, a very large number of various-sized mappings can result in fragmentation of the address space, making it hard to find large free contiguous regions. This problem, of course, is much less apparent with a 64-bit address space.

  • There is overhead in creating and maintaining the memory mappings and associated data structures inside the kernel. This overhead is generally obviated by the elimination of the double copy mentioned in the previous section, particularly for larger and frequently accessed files.

For these reasons, the benefits of mmap( ) are most greatly realized when the mapped file is large (and thus any wasted space is a small percentage of the total mapping), or when the total size of the mapped file is evenly divisible by the page size (and thus there is no wasted space).

How to pass text in a textbox to JavaScript function?

You could either access the element’s value by its name:

document.getElementsByName("textbox1"); // returns a list of elements with name="textbox1"
document.getElementsByName("textbox1")[0] // returns the first element in DOM with name="textbox1"

So:

<input name="buttonExecute" onclick="execute(document.getElementsByName('textbox1')[0].value)" type="button" value="Execute" />

Or you assign an ID to the element that then identifies it and you can access it with getElementById:

<input name="textbox1" id="textbox1" type="text" />
<input name="buttonExecute" onclick="execute(document.getElementById('textbox1').value)" type="button" value="Execute" />

ios app maximum memory budget

In my app, user experience is better if more memory is used, so I have to decide if I really should free all the memory I can in didReceiveMemoryWarning. Based on Split's and Jasper Pol's answer, using a maximum of 45% of the total device memory appears to be a safe threshold (thanks guys).

In case someone wants to look at my actual implementation:

#import "mach/mach.h"

- (void)didReceiveMemoryWarning
{
    // Remember to call super
    [super didReceiveMemoryWarning];

    // If we are using more than 45% of the memory, free even important resources,
    // because the app might be killed by the OS if we don't
    if ([self __getMemoryUsedPer1] > 0.45)
    {
        // Free important resources here
    }

    // Free regular unimportant resources always here
}

- (float)__getMemoryUsedPer1
{
    struct mach_task_basic_info info;
    mach_msg_type_number_t size = sizeof(info);
    kern_return_t kerr = task_info(mach_task_self(), MACH_TASK_BASIC_INFO, (task_info_t)&info, &size);
    if (kerr == KERN_SUCCESS)
    {
        float used_bytes = info.resident_size;
        float total_bytes = [NSProcessInfo processInfo].physicalMemory;
        //NSLog(@"Used: %f MB out of %f MB (%f%%)", used_bytes / 1024.0f / 1024.0f, total_bytes / 1024.0f / 1024.0f, used_bytes * 100.0f / total_bytes);
        return used_bytes / total_bytes;
    }
    return 1;
}

Swift (based on this answer):

func __getMemoryUsedPer1() -> Float
{
    let MACH_TASK_BASIC_INFO_COUNT = (sizeof(mach_task_basic_info_data_t) / sizeof(natural_t))
    let name = mach_task_self_
    let flavor = task_flavor_t(MACH_TASK_BASIC_INFO)
    var size = mach_msg_type_number_t(MACH_TASK_BASIC_INFO_COUNT)
    var infoPointer = UnsafeMutablePointer<mach_task_basic_info>.alloc(1)
    let kerr = task_info(name, flavor, UnsafeMutablePointer(infoPointer), &size)
    let info = infoPointer.move()
    infoPointer.dealloc(1)
    if kerr == KERN_SUCCESS
    {
        var used_bytes: Float = Float(info.resident_size)
        var total_bytes: Float = Float(NSProcessInfo.processInfo().physicalMemory)
        println("Used: \(used_bytes / 1024.0 / 1024.0) MB out of \(total_bytes / 1024.0 / 1024.0) MB (\(used_bytes * 100.0 / total_bytes)%%)")
        return used_bytes / total_bytes
    }
    return 1
}

HTTP POST with URL query parameters -- good idea or not?

I agree - it's probably safer to use a GET request if you're just passing data in the URL and not in the body. See this similar question for some additional views on the whole POST+GET concept.

Git fatal: protocol 'https' is not supported

Just use double quotes with URL, like: git clone "https://yourRepoUrl"

(It somehow sees that you are using 2 quote marks on start, don't know why).

I was getting the same error => fatal: protocol ''https' is not supported (you can see 2 quote marks on https).

$date + 1 year?

Try This

$nextyear  = date("M d,Y",mktime(0, 0, 0, date("m",strtotime($startDate)),   date("d",strtotime($startDate)),   date("Y",strtotime($startDate))+1));

Multiple Updates in MySQL

And now the easy way

update my_table m, -- let create a temp table with populated values
    (select 1 as id, 20 as value union -- this part will be generated
     select 2 as id, 30 as value union -- using a backend code
     -- for loop 
     select N as id, X as value
        ) t
set m.value = t.value where t.id=m.id -- now update by join - quick

Fancybox doesn't work with jQuery v1.9.0 [ f.browser is undefined / Cannot read property 'msie' ]

Hi this is due to new version of the jQuery => 1.9.0

you can check the update : http://blog.jquery.com/2013/01/15/jquery-1-9-final-jquery-2-0-beta-migrate-final-released/

jQuery.Browser is deprecated. you can keep latest version by adding a migration script : http://code.jquery.com/jquery-migrate-1.0.0.js

replace :

<script src="http://code.jquery.com/jquery-latest.js"></script>

by :

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.0.0.js"></script>

in your page and its working.

.aspx vs .ashx MAIN difference

Page is a special case handler.

Generic Web handler (*.ashx, extension based processor) is the default HTTP handler for all Web handlers that do not have a UI and that include the @WebHandler directive.

ASP.NET page handler (*.aspx) is the default HTTP handler for all ASP.NET pages.

Among the built-in HTTP handlers there are also Web service handler (*.asmx) and Trace handler (trace.axd)

MSDN says:

An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler.

The image below illustrates this: request pipe line

As to your second question:

Does ashx handle more connections than aspx?

Don't think so (but for sure, at least not less than).

Can I give a default value to parameters or optional parameters in C# functions?

That is exactly how you do it in C#, but the feature was first added in .NET 4.0

Start / Stop a Windows Service from a non-Administrator user account

subinacl.exe command-line tool is probably the only viable and very easy to use from anything in this post. You cant use a GPO with non-system services and the other option is just way way way too complicated.

Is Python interpreted, or compiled, or both?

According to the official Python site, it's interpreted.

https://www.python.org/doc/essays/blurb/

Python is an interpreted, object-oriented, high-level programming language...

...

Since there is no compilation step ...

...

The Python interpreter and the extensive standard library are available...

...

Instead, when the interpreter discovers an error, it raises an exception. When the program doesn't catch the exception, the interpreter prints a stack trace.

How to set the context path of a web application in Tomcat 7.0

The below trick worked for me.

1) Comment/delete the below configuration from server.xml file (inside conf folder) of tomcat.

2) Delete the existing ROOT folder (If any) residing inside tomcat webapps folder. And rename your war (e.g: test.war ) file to ROOT.war.

Remember that while renaming war file to ROOT.war "ROOT" should be in caps.

Limitation: You can deploy only one application inside one tomcat instance.

How to pass parameters to a Script tag?

Got it. Kind of a hack, but it works pretty nice:

var params = document.body.getElementsByTagName('script');
query = params[0].classList;
var param_a = query[0];
var param_b = query[1];
var param_c = query[2];

I pass the params in the script tag as classes:

<script src="http://path.to/widget.js" class="2 5 4"></script>

This article helped a lot.

How to run docker-compose up -d at system start up?

As an addition to user39544's answer, one more type of syntax for crontab -e:

@reboot sleep 60 && /usr/local/bin/docker-compose -f /path_to_your_project/docker-compose.yml up -d

Error message "Strict standards: Only variables should be passed by reference"

Well, in obvious cases like that, you can always tell PHP to suppress messages by using "@" in front of the function.

$monthly_index = @array_shift(unpack('H*', date('m/Y')));

It may not be one of the best programming practices to suppress all errors this way, but in certain cases (like this one) it comes handy and is acceptable.

As result, I am sure your friend 'system administrator' will be pleased with a less polluted error.log.

PHP Multiple Checkbox Array

if (isset($_POST['submit'])) {

for($i = 0; $i<= 3; $i++){

    if(isset($_POST['books'][$i]))

        $book .= ' '.$_POST['books'][$i];
}

How to get the current working directory using python 3?

Using pathlib you can get the folder in which the current file is located. __file__ is the pathname of the file from which the module was loaded. Ref: docs

import pathlib

current_dir = pathlib.Path(__file__).parent
current_file = pathlib.Path(__file__)

Doc ref: link

ExecutorService, how to wait for all tasks to finish

You could wait jobs to finish on a certain interval:

int maxSecondsPerComputeDTask = 20;
try {
    while (!es.awaitTermination(uniquePhrases.size() * maxSecondsPerComputeDTask, TimeUnit.SECONDS)) {
        // consider giving up with a 'break' statement under certain conditions
    }
} catch (InterruptedException e) {
    throw new RuntimeException(e);    
}

Or you could use ExecutorService.submit(Runnable) and collect the Future objects that it returns and call get() on each in turn to wait for them to finish.

ExecutorService es = Executors.newFixedThreadPool(2);
Collection<Future<?>> futures = new LinkedList<<Future<?>>();
for (DataTable singleTable : uniquePhrases) {
    futures.add(es.submit(new ComputeDTask(singleTable)));
}
for (Future<?> future : futures) {
   try {
       future.get();
   } catch (InterruptedException e) {
       throw new RuntimeException(e);
   } catch (ExecutionException e) {
       throw new RuntimeException(e);
   }
}

InterruptedException is extremely important to handle properly. It is what lets you or the users of your library terminate a long process safely.

Loop through all the files with a specific extension

as @chepner says in his comment you are comparing $i to a fixed string.

To expand and rectify the situation you should use [[ ]] with the regex operator =~

eg:

for i in $(ls);do
    if [[ $i =~ .*\.java$ ]];then
        echo "I want to do something with the file $i"
    fi
done

the regex to the right of =~ is tested against the value of the left hand operator and should not be quoted, ( quoted will not error but will compare against a fixed string and so will most likely fail"

but @chepner 's answer above using glob is a much more efficient mechanism.

R dates "origin" must be supplied

by the way, the zoo package, if it is loaded, overrides the base as.Date() with its own which, by default, provides origin="1970-01-01".

(i mention this in case you find that sometimes you need to add the origin, and sometimes you don't.)

How can I pass data from Flask to JavaScript in a template?

Alternatively you could add an endpoint to return your variable:

@app.route("/api/geocode")
def geo_code():
    return jsonify(geocode)

Then do an XHR to retrieve it:

fetch('/api/geocode')
  .then((res)=>{ console.log(res) })

Is there a way to take the first 1000 rows of a Spark Dataframe?

Limit is very simple, example limit first 50 rows

val df_subset = data.limit(50)

Parsing XML in Python using ElementTree example

If I understand your question correctly:

for elem in doc.findall('timeSeries/values/value'):
    print elem.get('dateTime'), elem.text

or if you prefer (and if there is only one occurrence of timeSeries/values:

values = doc.find('timeSeries/values')
for value in values:
    print value.get('dateTime'), elem.text

The findall() method returns a list of all matching elements, whereas find() returns only the first matching element. The first example loops over all the found elements, the second loops over the child elements of the values element, in this case leading to the same result.

I don't see where the problem with not finding timeSeries comes from however. Maybe you just forgot the getroot() call? (note that you don't really need it because you can work from the elementtree itself too, if you change the path expression to for example /timeSeriesResponse/timeSeries/values or //timeSeries/values)

Drawing circles with System.Drawing

You'll need to use DrawEllipse if you want to draw a circle using GDI+.

An example is here: http://www.websupergoo.com/helpig6net/source/3-examples/9-drawgdi.htm

Commenting in a Bash script inside a multiline command

The backslash escapes the #, interpreting it as its literal character instead of a comment character.

Disable single warning error

#pragma push/pop are often a solution for this kind of problems, but in this case why don't you just remove the unreferenced variable?

try
{
    // ...
}
catch(const your_exception_type &) // type specified but no variable declared
{
    // ...
}

What does value & 0xff do in Java?

In 32 bit format system the hexadecimal value 0xff represents 00000000000000000000000011111111 that is 255(15*16^1+15*16^0) in decimal. and the bitwise & operator masks the same 8 right most bits as in first operand.

JWT (JSON Web Token) automatic prolongation of expiration

I actually implemented this in PHP using the Guzzle client to make a client library for the api, but the concept should work for other platforms.

Basically, I issue two tokens, a short (5 minute) one and a long one that expires after a week. The client library uses middleware to attempt one refresh of the short token if it receives a 401 response to some request. It will then try the original request again and if it was able to refresh gets the correct response, transparently to the user. If it failed, it will just send the 401 up to the user.

If the short token is expired, but still authentic and the long token is valid and authentic, it will refresh the short token using a special endpoint on the service that the long token authenticates (this is the only thing it can be used for). It will then use the short token to get a new long token, thereby extending it another week every time it refreshes the short token.

This approach also allows us to revoke access within at most 5 minutes, which is acceptable for our use without having to store a blacklist of tokens.

Late edit: Re-reading this months after it was fresh in my head, I should point out that you can revoke access when refreshing the short token because it gives an opportunity for more expensive calls (e.g. call to the database to see if the user has been banned) without paying for it on every single call to your service.

How to convert PDF files to images

There is a free nuget package (Pdf2Image), which allows the extraction of pdf pages to jpg files or to a collection of images (List ) in just one line

        string file = "c:\\tmp\\test.pdf";

        List<System.Drawing.Image> images = PdfSplitter.GetImages(file, PdfSplitter.Scale.High);

        PdfSplitter.WriteImages(file, "c:\\tmp", PdfSplitter.Scale.High, PdfSplitter.CompressionLevel.Medium);

All source is also available on github Pdf2Image

Rename a file in C#

I couldn't find an approach which suits me, so I propose my version. Of course, it needs input and error handling.

public void Rename(string filePath, string newFileName)
{
    var newFilePath = Path.Combine(Path.GetDirectoryName(filePath), newFileName + Path.GetExtension(filePath));
    System.IO.File.Move(filePath, newFilePath);
}

When should one use a spinlock instead of mutex?

The rule for using spinlocks is simple: use a spinlock if and only if the real time the lock is held is bounded and sufficiently small.

Note that usually user implemented spinlocks DO NOT satisfy this requirement because they do not disable interrupts. Unless pre-emptions are disabled, a pre-emption whilst a spinlock is held violates the bounded time requirement.

Sufficiently small is a judgement call and depends on the context.

Exception: some kernel programming must use a spinlock even when the time is not bounded. In particular if a CPU has no work to do, it has no choice but to spin until some more work turns up.

Special danger: in low level programming take great care when multiple interrupt priorities exist (usually there is at least one non-maskable interrupt). In this higher priority pre-emptions can run even if interrupts at the thread priority are disabled (such as priority hardware services, often related to the virtual memory management). Provided a strict priority separation is maintained, the condition for bounded real time must be relaxed and replaced with bounded system time at that priority level. Note in this case not only can the lock holder be pre-empted but the spinner can also be interrupted; this is generally not a problem because there's nothing you can do about it.

How do I create a pause/wait function using Qt?

@kshark27's answer didn't work for me for some reason (because I use Qt 5.7?) so I ended up doing this:

while (someCondition) {

   // do something

   QApplication::processEvents();
   QThread::sleep(1); // 1 second

};

If this is done in the GUI thread, it obviously introduces a 1 second GUI lag before responding to user events. But if you can live with it, this solution is probably an easiest to implement and even Qt endorses it in their Threading Basics article (see When to Use Alternatives to Threads section).

Eclipse shows errors but I can't find them

I just removed all the private libraries in JavaBuildPath and added the jars again.. It worked

Jquery/Ajax call with timer

If you want to set something on a timer, you can use JavaScript's setTimeout or setInterval methods:

setTimeout ( expression, timeout );
setInterval ( expression, interval );

Where expression is a function and timeout and interval are integers in milliseconds. setTimeout runs the timer once and runs the expression once whereas setInterval will run the expression every time the interval passes.

So in your case it would work something like this:

setInterval(function() {
    //call $.ajax here
}, 5000); //5 seconds

As far as the Ajax goes, see jQuery's ajax() method. If you run an interval, there is nothing stopping you from calling the same ajax() from other places in your code.


If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:

setInterval() returns an integer which is the ID of the interval.

var id = setInterval(function() {
    //call $.ajax here
}, 30000); // 30 seconds

If you store that ID in a variable, you can then call clearInterval(id) which will stop the progression.

Then you can reinstantiate the setInterval() call after you've completed your ajax form submission.

How to set height property for SPAN

Use

.title{
  display: inline-block;
  height: 25px;
}

The only trick is browser support. Check if your list of supported browsers handles inline-block here.

Excel formula to reference 'CELL TO THE LEFT'

Make a named formula "LeftCell"

For those looking for a non-volatile answer, you can accomplish this by using the INDEX function in a named formula.

  1. Select Cell A2

  2. Open Name Manager (Ctrl+F3)

  3. Click New

  4. Name it 'LeftCell' (or whatever you prefer)

  5. For Scope:, select Workbook

  6. In Refers to:, enter the formula:

    =INDEX(!A1:!A2, 1)

  7. Click OK and close Name Manager

This tells Excel to always look at the value immediately to the left of the current cell, and will change dynamically as different cells are selected. If the name is used alone it provides the cell's value, but in a range it uses the reference. Credit to this answer about cell references for the idea.

How to copy a file to multiple directories using the gnu cp command

You can't do this with cp alone but you can combine cp with xargs:

echo dir1 dir2 dir3 | xargs -n 1 cp file1

Will copy file1 to dir1, dir2, and dir3. xargs will call cp 3 times to do this, see the man page for xargs for details.

Angularjs - simple form submit

I think the reason AngularJS does not say much about form submission because it depends more on 'two-way data binding'. In traditional html development you had one way data binding, i.e. once DOM rendered any changes you make to DOM element did not reflect in JS Object, however in AngularJS it works both way. Hence there's in fact no need to form submission. I have done a mid sized application using AngularJS without the need to form submission. If you are keen to submit form you can write a directive wrapping up your form which handles ENTER keydown and SUBMIT button click events and call form.submit().

If you want the sample source code of such a directive, please let me know by commenting on this. I figured out it would a simple directive that you can write yourself.

How to read pdf file and write it to outputStream

You can use PdfBox from Apache which is simple to use and has good performance.

Here is an example of extracting text from a PDF file (you can read more here) :

import java.io.*;
import org.apache.pdfbox.pdmodel.*;
import org.apache.pdfbox.util.*;

public class PDFTest {

 public static void main(String[] args){
 PDDocument pd;
 BufferedWriter wr;
 try {
         File input = new File("C:\\Invoice.pdf");  // The PDF file from where you would like to extract
         File output = new File("C:\\SampleText.txt"); // The text file where you are going to store the extracted data
         pd = PDDocument.load(input);
         System.out.println(pd.getNumberOfPages());
         System.out.println(pd.isEncrypted());
         pd.save("CopyOfInvoice.pdf"); // Creates a copy called "CopyOfInvoice.pdf"
         PDFTextStripper stripper = new PDFTextStripper();
         wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output)));
         stripper.writeText(pd, wr);
         if (pd != null) {
             pd.close();
         }
        // I use close() to flush the stream.
        wr.close();
 } catch (Exception e){
         e.printStackTrace();
        } 
     }
}

UPDATE:

You can get the text using PDFTextStripper:

PDFTextStripper reader = new PDFTextStripper();
String pageText = reader.getText(pd); // PDDocument object created

A regular expression to exclude a word/string

As you want to exclude both words, you need a conjuction:

^/(?!ignoreme$)(?!ignoreme2$)[a-z0-9]+$

Now both conditions must be true (neither ignoreme nor ignoreme2 is allowed) to have a match.

How are echo and print different in PHP?

They are:

  • print only takes one parameter, while echo can have multiple parameters.
  • print returns a value (1), so can be used as an expression.
  • echo is slightly faster.

Is it possible to override / remove background: none!important with jQuery?

div { background: none !important }
div { background: red; }

Is transparent.

div { background: none !important }
div { background: red !important; }

Is red.

An !important can override another !important.

If you can't edit the CSS file you can still add another one, or a style tag in the head tag.

Android Fragment no view found for ID?

I had this problem (when building my UI in code) and it was caused by my ViewPager (that showed Fragments) not having an ID set, so I simply used pager.setID(id) and then it worked.

This page helped me figure that out.

Two models in one view in ASP MVC 3

I hope you find it helpfull !!

i use ViewBag For Project and Model for task so in this way i am using two model in single view and in controller i defined viewbag's value or data

_x000D_
_x000D_
List<tblproject> Plist = new List<tblproject>();_x000D_
            Plist = ps.getmanagerproject(c, id);_x000D_
_x000D_
            ViewBag.projectList = Plist.Select(x => new SelectListItem_x000D_
            {_x000D_
                Value = x.ProjectId.ToString(),_x000D_
                Text = x.Title_x000D_
            });
_x000D_
_x000D_
_x000D_

and in view tbltask and projectlist are my two diff models

@{

IEnumerable<SelectListItem> plist = ViewBag.projectList;

} @model List

How can I save an image with PIL?

The error regarding the file extension has been handled, you either use BMP (without the dot) or pass the output name with the extension already. Now to handle the error you need to properly modify your data in the frequency domain to be saved as an integer image, PIL is telling you that it doesn't accept float data to save as BMP.

Here is a suggestion (with other minor modifications, like using fftshift and numpy.array instead of numpy.asarray) for doing the conversion for proper visualization:

import sys
import numpy
from PIL import Image

img = Image.open(sys.argv[1]).convert('L')

im = numpy.array(img)
fft_mag = numpy.abs(numpy.fft.fftshift(numpy.fft.fft2(im)))

visual = numpy.log(fft_mag)
visual = (visual - visual.min()) / (visual.max() - visual.min())

result = Image.fromarray((visual * 255).astype(numpy.uint8))
result.save('out.bmp')

Plotting images side by side using matplotlib

One thing that I found quite helpful to use to print all images :

_, axs = plt.subplots(n_row, n_col, figsize=(12, 12))
axs = axs.flatten()
for img, ax in zip(imgs, axs):
    ax.imshow(img)
plt.show()

How to share my Docker-Image without using the Docker-Hub?

[Update]

More recently, there is Amazon AWS ECR (Elastic Container Registry), which provides a Docker image registry to which you can control access by means of the AWS IAM access management service. ECR can also run a CVE (vulnerabilities) check on your image when you push it.

Once you create your ECR, and obtain the "URL" you can push and pull as required, subject to the permissions you create: hence making it private or public as you wish.

Pricing is by amount of data stored, and data transfer costs.

https://aws.amazon.com/ecr/

[Original answer]

If you do not want to use the Docker Hub itself, you can host your own Docker repository under Artifactory by JFrog:

https://www.jfrog.com/confluence/display/RTF/Docker+Repositories

which will then run on your own server(s).

Other hosting suppliers are available, eg CoreOS:

http://www.theregister.co.uk/2014/10/30/coreos_enterprise_registry/

which bought quay.io

Tomcat: How to find out running tomcat version

In Unix-like environments, I also recommend checking the actual running process command line:

$ ps aux | grep java

...
/usr/lib/jvm/java-8-openjdk-amd64/bin/java -Djava.util.logging.config.file=/srv/tomcat-instances/bla/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.awt.headless=true -Xmx4096M -XX:+UseConcMarkSweepGC -Djdk.tls.ephemeralDHKeySize=2048 -Djava.protocol.handler.pkgs=org.apache.catalina.webresources -agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n -Xmx4096m -Xms4096m -XX:MaxPermSize=2048m -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.port=8090 -Dcom.sun.management.jmxremote.rmi.port=8090 -Djava.rmi.server.hostname=localhost -Djava.endorsed.dirs=/opt/apache-tomcat-8.0.47/endorsed -classpath /opt/apache-tomcat-8.0.47/bin/bootstrap.jar:/opt/apache-tomcat-8.0.47/bin/tomcat-juli.jar -Dcatalina.base=/srv/tomcat-instances/bla -Dcatalina.home=/opt/apache-tomcat-8.0.47 -Djava.io.tmpdir=/tmp/tomcat8-bla-tmp org.apache.catalina.startup.Bootstrap start
...

One can run on subtle weird behaviors due to (operating system) environment variables and (Java) system properties being set to unexpected values. I had a situation where due to an outdated Tomcat setenv.sh, A Tomcat 8 started with classes from a Tomcat 7 on the classpath. Make sure that in the process command line options such as -Dcatalina.base, -Dcatalina.home and -classpath make sense.

How to convert array into comma separated string in javascript

You can simply use JavaScripts join() function for that. This would simply look like a.value.join(','). The output would be a string though.

How to increase the max connections in postgres?

Just increasing max_connections is bad idea. You need to increase shared_buffers and kernel.shmmax as well.


Considerations

max_connections determines the maximum number of concurrent connections to the database server. The default is typically 100 connections.

Before increasing your connection count you might need to scale up your deployment. But before that, you should consider whether you really need an increased connection limit.

Each PostgreSQL connection consumes RAM for managing the connection or the client using it. The more connections you have, the more RAM you will be using that could instead be used to run the database.

A well-written app typically doesn't need a large number of connections. If you have an app that does need a large number of connections then consider using a tool such as pg_bouncer which can pool connections for you. As each connection consumes RAM, you should be looking to minimize their use.


How to increase max connections

1. Increase max_connection and shared_buffers

in /var/lib/pgsql/{version_number}/data/postgresql.conf

change

max_connections = 100
shared_buffers = 24MB

to

max_connections = 300
shared_buffers = 80MB

The shared_buffers configuration parameter determines how much memory is dedicated to PostgreSQL to use for caching data.

  • If you have a system with 1GB or more of RAM, a reasonable starting value for shared_buffers is 1/4 of the memory in your system.
  • it's unlikely you'll find using more than 40% of RAM to work better than a smaller amount (like 25%)
  • Be aware that if your system or PostgreSQL build is 32-bit, it might not be practical to set shared_buffers above 2 ~ 2.5GB.
  • Note that on Windows, large values for shared_buffers aren't as effective, and you may find better results keeping it relatively low and using the OS cache more instead. On Windows the useful range is 64MB to 512MB.

2. Change kernel.shmmax

You would need to increase kernel max segment size to be slightly larger than the shared_buffers.

In file /etc/sysctl.conf set the parameter as shown below. It will take effect when postgresql reboots (The following line makes the kernel max to 96Mb)

kernel.shmmax=100663296

References

Postgres Max Connections And Shared Buffers

Tuning Your PostgreSQL Server

Laravel Redirect Back with() Message

I stopped writing this myself for laravel in favor of the Laracasts package that handles it all for you. It is really easy to use and keeps your code clean. There is even a laracast that covers how to use it. All you have to do:

Pull in the package through Composer.

"require": {
  "laracasts/flash": "~1.0"
}

Include the service provider within app/config/app.php.

'providers' => [
  'Laracasts\Flash\FlashServiceProvider'
];

Add a facade alias to this same file at the bottom:

'aliases' => [
  'Flash' => 'Laracasts\Flash\Flash'
];

Pull the HTML into the view:

@include('flash::message') 

There is a close button on the right of the message. This relies on jQuery so make sure that is added before your bootstrap.

optional changes:

If you aren't using bootstrap or want to skip the include of the flash message and write the code yourself:

@if (Session::has('flash_notification.message'))
  <div class="{{ Session::get('flash_notification.level') }}">
    {{ Session::get('flash_notification.message') }}
  </div>
@endif

If you would like to view the HTML pulled in by @include('flash::message'), you can find it in vendor/laracasts/flash/src/views/message.blade.php.

If you need to modify the partials do:

php artisan view:publish laracasts/flash

The two package views will now be located in the `app/views/packages/laracasts/flash/' directory.

Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

this is what i used:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];

NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:@"HH:mm:ss"];

NSDate *now = [[NSDate alloc] init];

NSString *theDate = [dateFormat stringFromDate:now];
NSString *theTime = [timeFormat stringFromDate:now];

NSLog(@"\n"
      "theDate: |%@| \n"
      "theTime: |%@| \n"
      , theDate, theTime);

[dateFormat release];
[timeFormat release];
[now release];

Regex that matches integers in between whitespace or start/end of string only

This worked in my case where I needed positive and negative integers that should NOT include zero-starting numbers like 01258 but should of course include 0

^(-?[1-9]+\d*)$|^0$

Example of valid values: "3", "-3", "0", "-555", "945465464654"

Example of not valid values: "0.0", "1.0", "0.7", "690.7", "0.0001", "a", "", " ", ".", "-", "001", "00.2", "000.5", ".3", "3.", " -1", "+100", "--1", "-.1", "-0", "00099", "099"

Sublime Text 2 Code Formatting

Maybe this answer is not quite what you're looking for, but it will fomat any language with the same keyboard shortcut. The solution are language specific keyboard shortcuts.

For every language you want to format, you must find and download a plugin for that, for example a html formatter and a C# formatter. And then you map the command for every plugin to the same key, but with a differnt context (see the link).

Greets

Git resolve conflict using --ours/--theirs for all files

function gitcheckoutall() {
    git diff --name-only --diff-filter=U | sed 's/^/"/;s/$/"/' | xargs git checkout --$1
}

I've added this function in .zshrc file.

Use them this way: gitcheckoutall theirs or gitcheckoutall ours

Difference between null and empty ("") Java String

String s = "";
s.length();

String s = null;
s.length();

A reference to an empty string "" points to an object in the heap - so you can call methods on it.

But a reference pointing to null has no object to point in the heap and thus you'll get a NullPointerException.

How do I put the image on the right side of the text in a UIButton?

Do Yourself. Xcode10, swift4,

For programmatically UI design

enter image description here

 lazy var buttonFilter : ButtonRightImageLeftTitle = {
    var button = ButtonRightImageLeftTitle()
    button.setTitle("Playfir", for: UIControl.State.normal)
    button.setImage(UIImage(named: "filter"), for: UIControl.State.normal)
    button.backgroundColor = UIColor.red
    button.contentHorizontalAlignment = .left
    button.titleLabel?.font = UIFont.systemFont(ofSize: 16)
    return button
}()

Edge inset values are applied to a rectangle to shrink or expand the area represented by that rectangle. Typically, edge insets are used during view layout to modify the view’s frame. Positive values cause the frame to be inset (or shrunk) by the specified amount. Negative values cause the frame to be outset (or expanded) by the specified amount.

class ButtonRightImageLeftTitle: UIButton {

    override func layoutSubviews() {
        super.layoutSubviews()

        guard imageView != nil else { return }

        imageEdgeInsets = UIEdgeInsets(top: 5, left: (bounds.width - 35), bottom: 5, right: 5)
        titleEdgeInsets = UIEdgeInsets(top: 0, left: -((imageView?.bounds.width)! + 10), bottom: 0, right: 0 )

    }
}

for StoryBoard UI design

enter image description here enter image description here