Programs & Examples On #Ftell

ftell is a standard C library function which returns the current offset in a file or stream in relation to the first byte.

How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption

Errors: "Bad encrypt / decrypt" "gitencrypt_smudge: FAILURE: openssl error decrypting file"

There are various error strings that are thrown from openssl, depending on respective versions, and scenarios. Below is the checklist I use in case of openssl related issues:

  1. Ideally, openssl is able to encrypt/decrypt using same key (+ salt) & enc algo only.
  2. Ensure that openssl versions (used to encrypt/decrypt), are compatible. For eg. the hash used in openssl changed at version 1.1.0 from MD5 to SHA256. This produces a different key from the same password. Fix: add "-md md5" in 1.1.0 to decrypt data from lower versions, and add "-md sha256 in lower versions to decrypt data from 1.1.0

  3. Ensure that there is a single openssl version installed in your machine. In case there are multiple versions installed simultaneously (in my machine, these were installed :- 'LibreSSL 2.6.5' and 'openssl 1.1.1d'), make the sure that only the desired one appears in your PATH variable.

Read from file or stdin

Just testing for end of file with feof would do, I think.

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6

What I did in my case was to update

"lib": [
      "es2020",
      "dom"
    ]

with

"lib": [
  "es2016",
  "dom"
]

in my tsconfig.json file

Testing web application on Mac/Safari when I don't own a Mac

A) Install VirtualBox and download free MacOS High Sierra image

See tutorial here: https://www.wikigain.com/install-macos-high-sierra-virtualbox-windows/

You will get the latest Safari.

You don't need to pay for those online services!!!

Use these vbox settings to increase resolution and memory, but it is still very laggy and slow:

cd "C:\Program Files\Oracle\VirtualBox\"
VBoxManage setextradata "macOS" VBoxInternal2/EfiGraphicsResolution 1920x1080
VBoxManage modifyvm "macOS" --vram 256

B) Alternatively try VMware

which seems to be much faster: youtube.com/watch?v=K7E_UqgCFbQ (video taken down) - use google ( you need VMware + MacOs ISO image)

@edit: It is significantly faster!!!

How to find lines containing a string in linux

Write the queue job information in long format to text file

qstat -f > queue.txt

Grep job names

grep 'Job_Name' queue.txt

What is href="#" and why is it used?

The href attribute defines the URL of the resource of a link. If the anchor tag does not have href tag then it will not become hyperlink. The href attribute have the following values:

1. Absolute path: move to another site like href="http://www.google.com"
2. Relative path: move to another page within the site like herf ="defaultpage.aspx"
3. Move to an element with a specified id within the page like href="#bottom"
4. href="javascript:void(0)", it does not move anywhere.
5. href="#" , it does not move anywhere but scroll on the top of the current page.
6. href= "" , it will load the current page but some browsers causes forbidden errors.

Note: When we do not need to specified any url inside a anchor tag then use 
<a href="javascript:void(0)">Test1</a>

Creating a div element in jQuery

$(HTMLelement) can success it. If you want an epmty div use it as $('<div></div>');. Also you can set the other elements by the same method. If you want to change inner HTML after created you can use html() method. For get outerHTML as string you can use is like this :

var element = $('<div/>');
var innerHTML = element.html(); // if you want set new HTML use it like this element.html('<b>new HTML</b>');
var outerHTML = element[0].outerHTML;

Reading and displaying data from a .txt file

In Java 8, you can read a whole file, simply with:

public String read(String file) throws IOException {
  return new String(Files.readAllBytes(Paths.get(file)));
}

or if its a Resource:

public String read(String file) throws IOException {
  URL url = Resources.getResource(file);
  return Resources.toString(url, Charsets.UTF_8);
}

Java 8: merge lists with stream API

Alternative: Stream.concat()

Stream.concat(map.values().stream(), listContainer.lst.stream())
                             .collect(Collectors.toList()

java create date object using a value string

try this, it worked for me.

 String inputString = "01-01-1900";
    Date inputDate= null;
    try {
        inputDate = new SimpleDateFormat("dd-MM-yyyy").parse(inputString);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    dp.getDatePicker().setMinDate(inputDate.getTime());

Get value of a string after last slash in JavaScript

var str = "foo/bar/test.html";
var lastSlash = str.lastIndexOf("/");
alert(str.substring(lastSlash+1));

How to capture the browser window close event?

My Issue: The 'onbeforeunload' event would only be triggered if there were odd number of submits(clicks). I had a combination of solutions from similar threads in SO to have my solution work. well my code will speak.

<!--The definition of event and initializing the trigger flag--->


$(document).ready(function() {
  updatefgallowPrompt(true);
  window.onbeforeunload = WarnUser; 
}

function WarnUser() {
  var allowPrompt = getfgallowPrompt();
  if(allowPrompt) {
    saveIndexedDataAlert();
    return null;
  } else {
    updatefgallowPrompt(true);
    event.stopPropagation
  }
}

<!--The method responsible for deciding weather the unload event is triggered from submit or not--->
function saveIndexedDataAlert() {
  var allowPrompt = getfgallowPrompt();
  var lenIndexedDocs = parseInt($('#sortable3 > li').size()) + parseInt($('#sortable3 > ul').size());

  if(allowPrompt && $.trim(lenIndexedDocs) > 0) {
    event.returnValue = "Your message";
  } else {
    event.returnValue = "   ";
    updatefgallowPrompt(true);
  }
}

<!---Function responsible to reset the trigger flag---->
$(document).click(function(event) {  
  $('a').live('click', function() { updatefgallowPrompt(false); });
});

<!--getter and setter for the flag---->
function updatefgallowPrompt (allowPrompt){ //exit msg dfds
  $('body').data('allowPrompt', allowPrompt);   
}   

function getfgallowPrompt(){        
  return $('body').data('allowPrompt'); 
}

How to use filesaver.js

wll it looks like I found the answer, although I havent tested it yet

var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");

from this page https://github.com/eligrey/FileSaver.js

WebAPI Multiple Put/Post parameters

If attribute routing is being used, you can use the [FromUri] and [FromBody] attributes.

Example:

[HttpPost()]
[Route("api/products/{id:int}")]
public HttpResponseMessage AddProduct([FromUri()] int id,  [FromBody()] Product product)
{
  // Add product
}

counting the number of lines in a text file

Your hack of decrementing the count at the end is exactly that -- a hack.

Far better to write your loop correctly in the first place, so it doesn't count the last line twice.

int main() { 
    int number_of_lines = 0;
    std::string line;
    std::ifstream myfile("textexample.txt");

    while (std::getline(myfile, line))
        ++number_of_lines;
    std::cout << "Number of lines in text file: " << number_of_lines;
    return 0;
}

Personally, I think in this case, C-style code is perfectly acceptable:

int main() {
    unsigned int number_of_lines = 0;
    FILE *infile = fopen("textexample.txt", "r");
    int ch;

    while (EOF != (ch=getc(infile)))
        if ('\n' == ch)
            ++number_of_lines;
    printf("%u\n", number_of_lines);
    return 0;
}

Edit: Of course, C++ will also let you do something a bit similar:

int main() {
    std::ifstream myfile("textexample.txt");

    // new lines will be skipped unless we stop it from happening:    
    myfile.unsetf(std::ios_base::skipws);

    // count the newlines with an algorithm specialized for counting:
    unsigned line_count = std::count(
        std::istream_iterator<char>(myfile),
        std::istream_iterator<char>(), 
        '\n');

    std::cout << "Lines: " << line_count << "\n";
    return 0;
}

Replace \n with actual new line in Sublime Text

Fool proof method (no RegEx and Ctrl+Enter didn't work for me as it was just jumping to next Find):

First, select an occurrence of \n and hit Ctrl+H (brings up the Replace... dialogue, also accessible through Find -> Replace... menu). This populates the Find what field.

Go to the end of any line of your file (press End if your keyboard has it) and select the end of line by holding down Shift and pressing ? (right arrow) EXACTLY once. Then copy-paste this into the Replace with field.

(the animation is for finding true new lines; works the same for replacing them)

enter image description here

int array to string

I realize my opinion is probably not the popular one, but I guess I have a hard time jumping on the Linq-y band wagon. It's nifty. It's condensed. I get that and I'm not opposed to using it where it's appropriate. Maybe it's just me, but I feel like people have stopped thinking about creating utility functions to accomplish what they want and instead prefer to litter their code with (sometimes) excessively long lines of Linq code for the sake of creating a dense 1-liner.

I'm not saying that any of the Linq answers that people have provided here are bad, but I guess I feel like there is the potential that these single lines of code can start to grow longer and more obscure as you need to handle various situations. What if your array is null? What if you want a delimited string instead of just purely concatenated? What if some of the integers in your array are double-digit and you want to pad each value with leading zeros so that the string for each element is the same length as the rest?

Taking one of the provided answers as an example:

        result = arr.Aggregate(string.Empty, (s, i) => s + i.ToString());

If I need to worry about the array being null, now it becomes this:

        result = (arr == null) ? null : arr.Aggregate(string.Empty, (s, i) => s + i.ToString());

If I want a comma-delimited string, now it becomes this:

        result = (arr == null) ? null : arr.Skip(1).Aggregate(arr[0].ToString(), (s, i) => s + "," + i.ToString());

This is still not too bad, but I think it's not obvious at a glance what this line of code is doing.

Of course, there's nothing stopping you from throwing this line of code into your own utility function so that you don't have that long mess mixed in with your application logic, especially if you're doing it in multiple places:

    public static string ToStringLinqy<T>(this T[] array, string delimiter)
    {
        // edit: let's replace this with a "better" version using a StringBuilder
        //return (array == null) ? null : (array.Length == 0) ? string.Empty : array.Skip(1).Aggregate(array[0].ToString(), (s, i) => s + "," + i.ToString());
        return (array == null) ? null : (array.Length == 0) ? string.Empty : array.Skip(1).Aggregate(new StringBuilder(array[0].ToString()), (s, i) => s.Append(delimiter).Append(i), s => s.ToString());
    }

But if you're going to put it into a utility function anyway, do you really need it to be condensed down into a 1-liner? In that case why not throw in a few extra lines for clarity and take advantage of a StringBuilder so that you're not doing repeated concatenation operations:

    public static string ToStringNonLinqy<T>(this T[] array, string delimiter)
    {
        if (array != null)
        {
            // edit: replaced my previous implementation to use StringBuilder
            if (array.Length > 0)
            {
                StringBuilder builder = new StringBuilder();

                builder.Append(array[0]);
                for (int i = 1; i < array.Length; i++)
                {
                    builder.Append(delimiter);
                    builder.Append(array[i]);
                }

                return builder.ToString()
            }
            else
            {
                return string.Empty;
            }
        }
        else
        {
            return null;
        }
    }

And if you're really so concerned about performance, you could even turn it into a hybrid function that decides whether to do string.Join or to use a StringBuilder depending on how many elements are in the array (this is a micro-optimization, not worth doing in my opinion and possibly more harmful than beneficial, but I'm using it as an example for this problem):

    public static string ToString<T>(this T[] array, string delimiter)
    {
        if (array != null)
        {
            // determine if the length of the array is greater than the performance threshold for using a stringbuilder
            // 10 is just an arbitrary threshold value I've chosen
            if (array.Length < 10)
            {
                // assumption is that for arrays of less than 10 elements
                // this code would be more efficient than a StringBuilder.
                // Note: this is a crazy/pointless micro-optimization.  Don't do this.
                string[] values = new string[array.Length];

                for (int i = 0; i < values.Length; i++)
                    values[i] = array[i].ToString();

                return string.Join(delimiter, values);
            }
            else
            {
                // for arrays of length 10 or longer, use a StringBuilder
                StringBuilder sb = new StringBuilder();

                sb.Append(array[0]);
                for (int i = 1; i < array.Length; i++)
                {
                    sb.Append(delimiter);
                    sb.Append(array[i]);
                }

                return sb.ToString();
            }
        }
        else
        {
            return null;
        }
    }

For this example, the performance impact is probably not worth caring about, but the point is that if you are in a situation where you actually do need to be concerned with the performance of your operations, whatever they are, then it will most likely be easier and more readable to handle that within a utility function than using a complex Linq expression.

That utility function still looks kind of clunky. Now let's ditch the hybrid stuff and do this:

    // convert an enumeration of one type into an enumeration of another type
    public static IEnumerable<TOut> Convert<TIn, TOut>(this IEnumerable<TIn> input, Func<TIn, TOut> conversion)
    {
        foreach (TIn value in input)
        {
            yield return conversion(value);
        }
    }

    // concatenate the strings in an enumeration separated by the specified delimiter
    public static string Delimit<T>(this IEnumerable<T> input, string delimiter)
    {
        IEnumerator<T> enumerator = input.GetEnumerator();

        if (enumerator.MoveNext())
        {
            StringBuilder builder = new StringBuilder();

            // start off with the first element
            builder.Append(enumerator.Current);

            // append the remaining elements separated by the delimiter
            while (enumerator.MoveNext())
            {
                builder.Append(delimiter);
                builder.Append(enumerator.Current);
            }

            return builder.ToString();
        }
        else
        {
            return string.Empty;
        }
    }

    // concatenate all elements
    public static string ToString<T>(this IEnumerable<T> input)
    {
        return ToString(input, string.Empty);
    }

    // concatenate all elements separated by a delimiter
    public static string ToString<T>(this IEnumerable<T> input, string delimiter)
    {
        return input.Delimit(delimiter);
    }

    // concatenate all elements, each one left-padded to a minimum length
    public static string ToString<T>(this IEnumerable<T> input, int minLength, char paddingChar)
    {
        return input.Convert(i => i.ToString().PadLeft(minLength, paddingChar)).Delimit(string.Empty);
    }

Now we have separate and fairly compact utility functions, each of which are arguable useful on their own.

Ultimately, my point is not that you shouldn't use Linq, but rather just to say don't forget about the benefits of creating your own utility functions, even if they are small and perhaps only contain a single line that returns the result from a line of Linq code. If nothing else, you'll be able to keep your application code even more condensed than you could achieve with a line of Linq code, and if you are using it in multiple places, then using a utility function makes it easier to adjust your output in case you need to change it later.

For this problem, I'd rather just write something like this in my application code:

        int[] arr = { 0, 1, 2, 3, 0, 1 };

        // 012301
        result = arr.ToString<int>();

        // comma-separated values
        // 0,1,2,3,0,1
        result = arr.ToString(",");

        // left-padded to 2 digits
        // 000102030001
        result = arr.ToString(2, '0');

MySQL Foreign Key Error 1005 errno 150 primary key as foreign key

For me, I was trying to match up a regular indexed field in a child table, to a primary key in the parent table, and by default some MySQL frontend GUIs like Sequel Pro set the primary key as unsigned, so you have to make sure that the child table field is unsigned too (unless these fields might contain negative ints, then make sure they're both signed).

Registry key for global proxy settings for Internet Explorer 10 on Windows 8

Create a .reg file containing your proxy settings for your users. Create a batch file setting it to setting it to run the .reg file with the extension /s

On a server using a logon script, tell the logon to run the batch file. Jason

Access restriction: Is not accessible due to restriction on required library ..\jre\lib\rt.jar

In Eclipse:
Project -> properties -> java Build Path -> libraries

Remove existing JRE System Library, then Add Library -> JRE System library -> next -> ok

Error will be removed.

How can I install packages using pip according to the requirements.txt file from a local directory?

Use:

pip install -r requirements.txt

For further details, please check the help option:

pip install --help

We can find the option '-r' -

-r, --requirement Install from the given requirements file. This option can be used multiple times.

Further information on some commonly used pip install options (this is the help option on the pip install command):

Enter image description here

Also the above is the complete set of options. Please use pip install --help for the complete list of options.

How do I remove time part from JavaScript date?

Parse that string into a Date object:

var myDate = new Date('10/11/1955 10:40:50 AM');

Then use the usual methods to get the date's day of month (getDate) / month (getMonth) / year (getFullYear).

var noTime = new Date(myDate.getFullYear(), myDate.getMonth(), myDate.getDate());

React.js: How to append a component on click?

As @Alex McMillan mentioned, use state to dictate what should be rendered in the dom.

In the example below I have an input field and I want to add a second one when the user clicks the button, the onClick event handler calls handleAddSecondInput( ) which changes inputLinkClicked to true. I am using a ternary operator to check for the truthy state, which renders the second input field

class HealthConditions extends React.Component {
  constructor(props) {
    super(props);


    this.state = {
      inputLinkClicked: false
    }
  }

  handleAddSecondInput() {
    this.setState({
      inputLinkClicked: true
    })
  }


  render() {
    return(
      <main id="wrapper" className="" data-reset-cookie-tab>
        <div id="content" role="main">
          <div className="inner-block">

            <H1Heading title="Tell us about any disabilities, illnesses or ongoing conditions"/>

            <InputField label="Name of condition"
              InputType="text"
              InputId="id-condition"
              InputName="condition"
            />

            {
              this.state.inputLinkClicked?

              <InputField label=""
                InputType="text"
                InputId="id-condition2"
                InputName="condition2"
              />

              :

              <div></div>
            }

            <button
              type="button"
              className="make-button-link"
              data-add-button=""
              href="#"
              onClick={this.handleAddSecondInput}
            >
              Add a condition
            </button>

            <FormButton buttonLabel="Next"
              handleSubmit={this.handleSubmit}
              linkto={
                this.state.illnessOrDisability === 'true' ?
                "/404"
                :
                "/add-your-details"
              }
            />

            <BackLink backLink="/add-your-details" />

          </div>
         </div>
      </main>
    );
  }
}

Unsupported major.minor version 52.0 in my app

The Simplest solution is you have to update your JDK to latest, version . Because Cordova supports only latest JDK .

1. First of all you have to update your Android SDK. Then,

2. If you are not able to update through your terminal , Got to your Software center of Linux destro and search the Latest (which one you want to install) and install that one .

Then again run Cordova build .

It will solve the problem .

In ,my case it worked.

In Go's http package, how do I get the query string on a POST request?

Below words come from the official document.

Form contains the parsed form data, including both the URL field's query parameters and the POST or PUT form data. This field is only available after ParseForm is called.

So, sample codes as below would work.

func parseRequest(req *http.Request) error {
    var err error

    if err = req.ParseForm(); err != nil {
        log.Error("Error parsing form: %s", err)
        return err
    }

    _ = req.Form.Get("xxx")

    return nil
}

Oracle SQL escape character (for a '&')

insert into AGREGADORES_AGREGADORES (IDAGREGADOR,NOMBRE,URL)
values (2,'Netvibes',
'http://www.netvibes.com/subscribe.php?type=rss' || chr(38) || 'amp;url=');

How do I fix a "Expected Primary-expression before ')' token" error?

showInventory(player);     // I get the error here.

void showInventory(player& obj) {   // By Johnny :D

this means that player is an datatype and showInventory expect an referance to an variable of type player.

so the correct code will be

  void showInventory(player& obj) {   // By Johnny :D
    for(int i = 0; i < 20; i++) {
        std::cout << "\nINVENTORY:\n" + obj.getItem(i);
        i++;
        std::cout << "\t\t\t" + obj.getItem(i) + "\n";
        i++;
    }
    }

players myPlayers[10];

    std::string toDo() //BY KEATON
    {
    std::string commands[5] =   // This is the valid list of commands.
        {"help", "inv"};

    std::string ans;
    std::cout << "\nWhat do you wish to do?\n>> ";
    std::cin >> ans;

    if(ans == commands[0]) {
        helpMenu();
        return NULL;
    }
    else if(ans == commands[1]) {
        showInventory(myPlayers[0]);     // or any other index,also is not necessary to have an array
        return NULL;
    }

}

Adding Only Untracked Files

If you have thousands of untracked files (ugh, don't ask) then git add -i will not work when adding *. You will get an error stating Argument list too long.

If you then also are on Windows (don't ask #2 :-) and need to use PowerShell for adding all untracked files, you can use this command:

git ls-files -o --exclude-standard | select | foreach { git add $_ }

How to remove close button on the jQuery UI dialog?

Since I found I was doing this in several places in my app, I wrapped it in a plugin:

(function ($) {
   $.fn.dialogNoClose = function () {
      return this.each(function () {
         // hide the close button and prevent ESC key from closing
         $(this).closest(".ui-dialog").find(".ui-dialog-titlebar-close").hide();
         $(this).dialog("option", "closeOnEscape", false);
      });
   };
})(jQuery)

Usage Example:

$("#dialog").dialog({ /* lots of options */ }).dialogNoClose();

Python Linked List

When using immutable linked lists, consider using Python's tuple directly.

ls = (1, 2, 3, 4, 5)

def first(ls): return ls[0]
def rest(ls): return ls[1:]

Its really that ease, and you get to keep the additional funcitons like len(ls), x in ls, etc.

MIPS: Integer Multiplication and Division

To multiply, use mult for signed multiplication and multu for unsigned multiplication. Note that the result of the multiplication of two 32-bit numbers yields a 64-number. If you want the result back in $v0 that means that you assume the result will fit in 32 bits.

The 32 most significant bits will be held in the HI special register (accessible by mfhi instruction) and the 32 least significant bits will be held in the LO special register (accessible by the mflo instruction):

E.g.:

li $a0, 5
li $a1, 3
mult $a0, $a1
mfhi $a2 # 32 most significant bits of multiplication to $a2
mflo $v0 # 32 least significant bits of multiplication to $v0

To divide, use div for signed division and divu for unsigned division. In this case, the HI special register will hold the remainder and the LO special register will hold the quotient of the division.

E.g.:

div $a0, $a1
mfhi $a2 # remainder to $a2
mflo $v0 # quotient to $v0

What algorithm for a tic-tac-toe game can I use to determine the "best move" for the AI?

An attempt without using a play field.

  1. to win(your double)
  2. if not, not to lose(opponent's double)
  3. if not, do you already have a fork(have a double double)
  4. if not, if opponent has a fork
    1. search in blocking points for possible double and fork(ultimate win)
    2. if not search forks in blocking points(which gives the opponent the most losing possibilities )
    3. if not only blocking points(not to lose)
  5. if not search for double and fork(ultimate win)
  6. if not search only for forks which gives opponent the most losing possibilities
  7. if not search only for a double
  8. if not dead end, tie, random.
  9. if not(it means your first move)
    1. if it's the first move of the game;
      1. give the opponent the most losing possibility(the algorithm results in only corners which gives 7 losing point possibility to opponent)
      2. or for breaking boredom just random.
    2. if it's second move of the game;
      1. find only the not losing points(gives a little more options)
      2. or find the points in this list which has the best winning chance(it can be boring,cause it results in only all corners or adjacent corners or center)

Note: When you have double and forks, check if your double gives the opponent a double.if it gives, check if that your new mandatory point is included in your fork list.

git recover deleted file where no commit was made after the delete

You've staged the deletion so you need to do:

git checkout HEAD cc.properties store/README store/cc.properties

git checkout . only checks out from the index where the deletion has already been staged.

bootstrap jquery show.bs.modal event won't fire

Sometimes this doesn't work if:

1) you have an error in the java script code before your line with $('#myModal').on('show.bs.modal'...). To troubleshoot put an alert message before the line to see if it comes up when you load the page. To resolve eliminate JSs above to see which one is the problem

2) Another problem is if you load up the JS in wrong order. For example you can have the $('#myModal').on('show.bs.modal'...) part before you actually load JQuery.js. In that case your call will be ignored, so first in the HTML (view page source to be sure) check if the script link to JQuery is above your modal onShow call, otherwise it will be ignored. To troubleshoot put an alert inside the on show an one before. If you see the one before and not the one inside the onShow function it is clear that the function cannot execute. If the spelling is right more than likely your call to JQuery.js is not made or it is made after the onShow part

Use '=' or LIKE to compare strings in SQL?

There is another reason for using "like" even if the performance is slower: Character values are implicitly converted to integer when compared, so:

declare @transid varchar(15)

if @transid != 0

will give you a "The conversion of the varchar value '123456789012345' overflowed an int column" error.

Re-assign host access permission to MySQL user

The more general answer is

UPDATE mysql.user SET host = {newhost} WHERE user = {youruser}

How to get row index number in R?

I'm interpreting your question to be about getting row numbers.

  • You can try as.numeric(rownames(df)) if you haven't set the rownames. Otherwise use a sequence of 1:nrow(df).
  • The which() function converts a TRUE/FALSE row index into row numbers.

How to read a file line-by-line into a list?

You could simply do the following, as has been suggested:

with open('/your/path/file') as f:
    my_lines = f.readlines()

Note that this approach has 2 downsides:

1) You store all the lines in memory. In the general case, this is a very bad idea. The file could be very large, and you could run out of memory. Even if it's not large, it is simply a waste of memory.

2) This does not allow processing of each line as you read them. So if you process your lines after this, it is not efficient (requires two passes rather than one).

A better approach for the general case would be the following:

with open('/your/path/file') as f:
    for line in f:
        process(line)

Where you define your process function any way you want. For example:

def process(line):
    if 'save the world' in line.lower():
         superman.save_the_world()

(The implementation of the Superman class is left as an exercise for you).

This will work nicely for any file size and you go through your file in just 1 pass. This is typically how generic parsers will work.

How to get all of the IDs with jQuery?

My suggestion?

var arr = $.map($("#mydiv [id]"), function(n, i) {
  return n.id;
});

you could also do this as:

var arr = $.map($("#mydiv span"), function(n, i) {

or

var arr = $.map($("#mydiv span[id]"), function(n, i) {

or even just:

var arr = $("#mydiv [id]").map(function() {
  return this.id;
});

Lots of ways basically.

PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND)

Try this function : mltiple queries and multiple values insertion.

function employmentStatus($Status) {
$pdo = PDO2::getInstance();

$sql_parts = array(); 
for($i=0; $i<count($Status); $i++){
    $sql_parts[] = "(:userID, :val$i)";
}

$requete = $pdo->dbh->prepare("DELETE FROM employment_status WHERE userid = :userID; INSERT INTO employment_status (userid, status) VALUES ".implode(",", $sql_parts));
$requete->bindParam(":userID", $_SESSION['userID'],PDO::PARAM_INT);
for($i=0; $i<count($Status); $i++){
    $requete->bindParam(":val$i", $Status[$i],PDO::PARAM_STR);
}
if ($requete->execute()) {
    return true;
}
return $requete->errorInfo();
}

Retrieving the text of the selected <option> in <select> element

Easy, simple way:

const select = document.getElementById('selectID');
const selectedOption = [...select.options].find(option => option.selected).text;

What does %~dp0 mean, and how does it work?

Great example from Strawberry Perl's portable shell launcher:

set drive=%~dp0
set drivep=%drive%
if #%drive:~-1%# == #\# set drivep=%drive:~0,-1%

set PATH=%drivep%\perl\site\bin;%drivep%\perl\bin;%drivep%\c\bin;%PATH%

not sure what the negative 1's doing there myself, but it works a treat!

TypeError: 'int' object is not callable

In my case I changed:

return <variable>

with:

return str(<variable>)

try with the following and it must work:

str(round((a/b)*0.9*c))

How to check if $? is not equal to zero in unix shell scripting?

Try this after execution of your script :

if [ $? -ne 0 ];
then
//statements//
fi

How do I check if a SQL Server text column is empty?

Actually, you just have to use the LIKE operator.

SELECT * FROM mytable WHERE mytextfield LIKE ''

Function pointer as parameter

The correct way to do this is:

typedef void (*callback_function)(void); // type for conciseness

callback_function disconnectFunc; // variable to store function pointer type

void D::setDisconnectFunc(callback_function pFunc)
{
    disconnectFunc = pFunc; // store
}

void D::disconnected()
{
    disconnectFunc(); // call
    connected = false;
}

Get keys from HashMap in Java

To get Key and its value

e.g

private Map<String, Integer> team1 = new HashMap<String, Integer>();
  team1.put("United", 5);
  team1.put("Barcelona", 6);
    for (String key:team1.keySet()){
                     System.out.println("Key:" + key +" Value:" + team1.get(key)+" Count:"+Collections.frequency(team1, key));// Get Key and value and count
                }

Will print: Key: United Value:5 Key: Barcelona Value:6

Convert Year/Month/Day to Day of Year in Python

If you have reason to avoid the use of the datetime module, then these functions will work.

def is_leap_year(year):
    """ if year is a leap year return True
        else return False """
    if year % 100 == 0:
        return year % 400 == 0
    return year % 4 == 0

def doy(Y,M,D):
    """ given year, month, day return day of year
        Astronomical Algorithms, Jean Meeus, 2d ed, 1998, chap 7 """
    if is_leap_year(Y):
        K = 1
    else:
        K = 2
    N = int((275 * M) / 9.0) - K * int((M + 9) / 12.0) + D - 30
    return N

def ymd(Y,N):
    """ given year = Y and day of year = N, return year, month, day
        Astronomical Algorithms, Jean Meeus, 2d ed, 1998, chap 7 """    
    if is_leap_year(Y):
        K = 1
    else:
        K = 2
    M = int((9 * (K + N)) / 275.0 + 0.98)
    if N < 32:
        M = 1
    D = N - int((275 * M) / 9.0) + K * int((M + 9) / 12.0) + 30
    return Y, M, D

IE Driver download location Link for Selenium

You can download IE Driver (both 32 and 64-bit) from Selenium official site: http://docs.seleniumhq.org/download/

32 bit Windows IE

64 bit Windows IE

IE Driver is also available in the following site:

http://selenium-release.storage.googleapis.com/index.html

Why am I getting ImportError: No module named pip ' right after installing pip?

Just be sure that you have include python to windows PATH variable, then run python -m ensurepip

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

enter image description here

In my case, forgot to define Primary Key to Table. So assign like shown in Picture and Refresh your table from "Update model from Database" from .edmx file. Hope it will help !!!

Best Java obfuscator?

As said elsewhere on here, proguard is good, but what might not be known is that there is also a third-party maven plugin for it here http://pyx4me.com/pyx4me-maven-plugins/proguard-maven-plugin/...I've used them both together and they're very good.

Comma separated results in SQL

If you're stuck with SQL Server <2017, you can use GroupConcat. The syntax and the performance is far better than the FOR XML PATH sollution.

Installation:

-- https://codeplexarchive.blob.core.windows.net/archive/projects/groupconcat/groupconcat.zip
create assembly [GroupConcat] from 0x4D5A90000300000004000000FFFF0000B800000000000000400000000000000000000000000000000000000000000000000000000000000000000000800000000E1FBA0E00B409CD21B8014CCD21546869732070726F6772616D2063616E6E6F742062652072756E20696E20444F53206D6F64652E0D0D0A2400000000000000504500004C01030058898C510000000000000000E00002210B010B00001E000000080000000000007E3D0000002000000040000000000010002000000002000004000000000000000400000000000000008000000002000000000000030040850000100000100000000010000010000000000000100000000000000000000000243D000057000000004000003804000000000000000000000000000000000000006000000C00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000080000000000000000000000082000004800000000000000000000002E74657874000000841D000000200000001E000000020000000000000000000000000000200000602E7273726300000038040000004000000006000000200000000000000000000000000000400000402E72656C6F6300000C0000000060000000020000002600000000000000000000000000004000004200000000000000000000000000000000603D0000000000004800000002000500C02C00006410000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003202731100000A7D010000042A0000001330040047000000010000110F01281200000A2D3D0F01281300000A0A027B01000004066F1400000A2C1A027B01000004250B06250C07086F1500000A17586F1600000A2A027B0100000406176F1700000A2A001B30050089000000020000110F017B010000046F1800000A0C2B601202281900000A0A1200281A00000A0B027B01000004076F1400000A2C29027B01000004250D072513040911046F1500000A0F017B01000004076F1500000A586F1600000A2B19027B01000004070F017B01000004076F1500000A6F1700000A1202281B00000A2D97DE0E1202FE160300001B6F1C00000ADC2A0000000110000002000D006D7A000E000000001B3003009B00000003000011027B010000043989000000027B010000046F1D00000A16317B731E00000A0A027B010000046F1800000A0D2B341203281900000A0B160C2B1E061201281A00000A6F1F00000A260672010000706F1F00000A260817580C081201282000000A32D81203281B00000A2DC3DE0E1203FE160300001B6F1C00000ADC06066F2100000A1759176F2200000A6F2300000A282400000A2A14282400000A2A000110000002002B00416C000E00000000133003003900000004000011036F2500000A0A0206732600000A7D01000004160B2B1B027B01000004036F2700000A036F2500000A6F1700000A0717580B0706175931DF2A0000001B3002005B0000000500001103027B010000046F1D00000A6F2800000A027B010000046F1800000A0B2B221201281900000A0A031200281A00000A6F2900000A031200282000000A6F2800000A1201281B00000A2DD5DE0E1201FE160300001B6F1C00000ADC2A000110000002001D002F4C000E000000001330020024000000060000110F01FE16060000016F2300000A0A027B0300000406282A00000A2C0702067D030000042A5E02731100000A7D02000004027E2B00000A7D030000042A133004004F000000010000110F01281200000A2D450F01281300000A0A027B02000004066F1400000A2C1B027B02000004250B06250C07086F1500000A17586F1600000A2B0D027B0200000406176F1700000A020428070000062A001B300500A300000002000011027B03000004282C00000A2C0D020F017B030000047D030000040F017B020000046F1800000A0C2B601202281900000A0A1200281A00000A0B027B02000004076F1400000A2C29027B02000004250D072513040911046F1500000A0F017B02000004076F1500000A586F1600000A2B19027B02000004070F017B02000004076F1500000A6F1700000A1202281B00000A2D97DE0E1202FE160300001B6F1C00000ADC2A0001100000020027006D94000E000000001B300300B300000003000011027B0200000439A1000000027B020000046F1D00000A163E90000000731E00000A0A027B020000046F1800000A0D2B351203281900000A0B160C2B1F061201281A00000A6F1F00000A2606027B030000046F1F00000A260817580C081201282000000A32D71203281B00000A2DC2DE0E1203FE160300001B6F1C00000ADC06066F2100000A027B030000046F2D00000A59027B030000046F2D00000A6F2200000A6F2300000A282400000A2A14282400000A2A000110000002002E004270000E00000000133003004500000004000011036F2500000A0A0206732600000A7D02000004160B2B1B027B02000004036F2700000A036F2500000A6F1700000A0717580B0706175931DF02036F2700000A7D030000042A0000001B300200670000000500001103027B020000046F1D00000A6F2800000A027B020000046F1800000A0B2B221201281900000A0A031200281A00000A6F2900000A031200282000000A6F2800000A1201281B00000A2DD5DE0E1201FE160300001B6F1C00000ADC03027B030000046F2900000A2A000110000002001D002F4C000E000000001330020024000000060000110F01FE16060000016F2300000A0A027B0500000406282A00000A2C0702067D050000042AEA027B060000042D310F01282E00000A172E150F01282E00000A182E0B7205000070732F00000A7A020F01282E00000A283000000A7D060000042A7A02731100000A7D04000004027E2B00000A7D0500000402167D060000042A00001330040056000000010000110F01281200000A2D4C0F01281300000A0A027B04000004066F1400000A2C1B027B04000004250B06250C07086F1500000A17586F1600000A2B0D027B0400000406176F1700000A0204280E0000060205280F0000062A00001B300500B800000002000011027B05000004282C00000A2C0D020F017B050000047D05000004027B060000042D0D020F017B060000047D060000040F017B040000046F1800000A0C2B601202281900000A0A1200281A00000A0B027B04000004076F1400000A2C29027B04000004250D072513040911046F1500000A0F017B04000004076F1500000A586F1600000A2B19027B04000004070F017B04000004076F1500000A6F1700000A1202281B00000A2D97DE0E1202FE160300001B6F1C00000ADC2A0110000002003C006DA9000E000000001B300300D700000007000011027B0400000439C5000000027B040000046F1D00000A163EB4000000731E00000A0B027B06000004183313027B04000004731E000006733100000A0A2B0C027B04000004733200000A0A066F3300000A13042B351204283400000A0C160D2B1F071202281A00000A6F1F00000A2607027B050000046F1F00000A260917580D091202282000000A32D71204283500000A2DC2DE0E1204FE160600001B6F1C00000ADC07076F2100000A027B050000046F2D00000A59027B050000046F2D00000A6F2200000A6F2300000A282400000A2A14282400000A2A0001100000020052004294000E00000000133003005100000004000011036F2500000A0A0206732600000A7D04000004160B2B1B027B04000004036F2700000A036F2500000A6F1700000A0717580B0706175931DF02036F2700000A7D0500000402036F3600000A7D060000042A0000001B300200730000000500001103027B040000046F1D00000A6F2800000A027B040000046F1800000A0B2B221201281900000A0A031200281A00000A6F2900000A031200282000000A6F2800000A1201281B00000A2DD5DE0E1201FE160300001B6F1C00000ADC03027B050000046F2900000A03027B060000046F3700000A2A000110000002001D002F4C000E00000000EA027B080000042D310F01282E00000A172E150F01282E00000A182E0B7205000070732F00000A7A020F01282E00000A283000000A7D080000042A4E02731100000A7D0700000402167D080000042A00133004004F000000010000110F01281200000A2D450F01281300000A0A027B07000004066F1400000A2C1B027B07000004250B06250C07086F1500000A17586F1600000A2B0D027B0700000406176F1700000A020428160000062A001B3005009E00000002000011027B080000042D0D020F017B080000047D080000040F017B070000046F1800000A0C2B601202281900000A0A1200281A00000A0B027B07000004076F1400000A2C29027B07000004250D072513040911046F1500000A0F017B07000004076F1500000A586F1600000A2B19027B07000004070F017B07000004076F1500000A6F1700000A1202281B00000A2D97DE0E1202FE160300001B6F1C00000ADC2A000001100000020022006D8F000E000000001B300300C800000008000011027B0700000439B6000000027B070000046F1D00000A163EA5000000731E00000A0B027B08000004183313027B07000004731E000006733100000A0A2B0C027B07000004733200000A0A066F3300000A13052B3A1205283400000A0C1202281A00000A0D1613042B1A07096F1F00000A260772010000706F1F00000A2611041758130411041202282000000A32DB1205283500000A2DBDDE0E1205FE160600001B6F1C00000ADC07076F2100000A1759176F2200000A6F2300000A282400000A2A14282400000A2A01100000020052004799000E00000000133003004500000004000011036F2500000A0A0206732600000A7D07000004160B2B1B027B07000004036F2700000A036F2500000A6F1700000A0717580B0706175931DF02036F3600000A7D080000042A0000001B300200670000000500001103027B070000046F1D00000A6F2800000A027B070000046F1800000A0B2B221201281900000A0A031200281A00000A6F2900000A031200282000000A6F2800000A1201281B00000A2DD5DE0E1201FE160300001B6F1C00000ADC03027B080000046F3700000A2A000110000002001D002F4C000E000000002204036F3800000A2A1E02283900000A2A00000042534A4201000100000000000C00000076322E302E35303732370000000005006C000000C4060000237E0000300700006405000023537472696E677300000000940C00006C00000023555300000D0000100000002347554944000000100D00005403000023426C6F6200000000000000020000015717A2090900000000FA253300160000010000002500000006000000080000001E0000001E0000000500000039000000180000000800000003000000040000000400000006000000010000000300000000000A00010000000000060081007A000A00B20097000600C3007A000600E500CA000600F100CA000A001F010A0106004E0144010600600144010A009C010A010A00CA01970006001702050206002E02050206004B02050206006A02050206008302050206009C0205020600B70205020600D202050206000A03EB0206001E030502060057033703060077033703060095037A000A00AB0397000A00CC0397000600D303EB020600E903EB0217002B04000006004404CA00060070047A0006009A048E040600EB047A00060014057A0006001E057A000E002D05CA0006004005CA008F002B0400000000000001000000000001000100092110001A00270005000100010009211000330027000500020007000921100042002700050004000E00092110005200270005000700160001001000610027000D0009001D000100FE0010000100FE0010000100730139000100FE001000010073013900010095014F000100FE001000010095014F005020000000008600050118000100602000000000860029011C000100B4200000000086003401220002005C210000000086003A0128000300142200000000E6015B012D0004005C2200000000E6016D0133000500D4220000000081087D011C00060004230000000086000501180007001C2300000000860029013C000700782300000000860034014400090038240000000086003A0128000A00082500000000E6015B012D000B005C2500000000E6016D0133000C00E0250000000081087D011C000D001026000000008108A40152000E004B26000000008600050118000F006C26000000008600290158000F00D026000000008600340162001200A4270000000086003A0128001300982800000000E6015B012D001400F82800000000E6016D01330015008829000000008108A40152001600C329000000008600050118001700D82900000000860029016D001700342A000000008600340175001900F02A0000000086003A0128001A00D42B00000000E6015B012D001B00282C00000000E6016D0133001C00AC2C00000000E601B6017B001D00B52C000000008618BE0118001F0000000100C40100000100DC0100000000000000000100E20100000100E40100000100E60100000100C40100000200EC0100000100DC0100000000000000000100E20100000100E40100000100E60100000100E60100000100C40100000200EC0100000300F60100000100DC0100000000000000000100E20100000100E40100000100E60100000100C40100000200F60100000100DC0100000000000000000100E20100000100E40100000100010200000200030202000900030009000400090005000900060006005100BE0118005900BE01BA006100BE01BA006900BE01BA007100BE01BA007900BE01BA008100BE01BA008900BE01BA009100BE01BA009900BE01BF00A100BE01BA00A900BE01C400B100BE011800B900BE011800C100BE01C900D100BE0142011400BE0118003100F4034F013100FF035301140009045701140015045D0114001E0464011400270464011400360477011C005304890124005F049B011C0067044F01F1007C04180014008404B701F900BE011800F900A804BB012400FF03C101F900AF04B701F900BA04C6011900C10453013100CA04CD013900D604B7011400BE01C4003900E004530141006D01C40041006D01BA000101F204F9010101000539000101060503020101AF04B7014900FF0308020901BE01BA00110126050C022C00BE0119022C00BE012C022C0036043902340053048901340067044F0139004E05080241006D0167020101570587021900BE01180024000B0081002E006B0035032E002B000E032E0013008C022E001B009D022E0023000E032E003B0014032E0033008C022E0043000E032E0053000E032E0063002C0343007B00CF0063007B00CF0064000B00940083007B00CF00A3007B00CF00E4000B00810004010B00A70044010B009400E4010B00810004020B00A70064020B009400E4020B00810044030B0094006C01A001D301E501EA01FF014D026C0203000100040002000500040000008B014A0000008B014A000000AF0168000000AF01680001000700030001000E00050001000F0007000100160009000A004801820194011102450204800000010000000D13F49F00000000000027000000020000000000000000000000010071000000000002000000000000000000000001008B000000000002000000000000000000000001007A000000000000000000003C4D6F64756C653E0047726F7570436F6E6361742E646C6C0047524F55505F434F4E4341540047726F7570436F6E6361740047524F55505F434F4E4341545F440047524F55505F434F4E4341545F44530047524F55505F434F4E4341545F530052657665727365436F6D7061726572006D73636F726C69620053797374656D0056616C7565547970650053797374656D2E44617461004D6963726F736F66742E53716C5365727665722E536572766572004942696E61727953657269616C697A65004F626A6563740053797374656D2E436F6C6C656374696F6E732E47656E657269630049436F6D706172657260310044696374696F6E61727960320076616C75657300496E69740053797374656D2E446174612E53716C54797065730053716C537472696E6700416363756D756C617465004D65726765005465726D696E6174650053797374656D2E494F0042696E61727952656164657200526561640042696E6172795772697465720057726974650064656C696D69746572007365745F44656C696D697465720044656C696D6974657200736F727442790053716C42797465007365745F536F7274427900536F7274427900436F6D70617265002E63746F720056414C55450053716C46616365744174747269627574650047726F7570007200770076616C75650044454C494D4954455200534F52545F4F52444552007800790053797374656D2E5265666C656374696F6E00417373656D626C795469746C6541747472696275746500417373656D626C794465736372697074696F6E41747472696275746500417373656D626C79436F6E66696775726174696F6E41747472696275746500417373656D626C79436F6D70616E7941747472696275746500417373656D626C7950726F6475637441747472696275746500417373656D626C79436F7079726967687441747472696275746500417373656D626C7954726164656D61726B41747472696275746500417373656D626C7943756C747572654174747269627574650053797374656D2E52756E74696D652E496E7465726F70536572766963657300436F6D56697369626C6541747472696275746500417373656D626C7956657273696F6E4174747269627574650053797374656D2E52756E74696D652E436F6D70696C6572536572766963657300436F6D70696C6174696F6E52656C61786174696F6E734174747269627574650052756E74696D65436F6D7061746962696C6974794174747269627574650053657269616C697A61626C654174747269627574650053716C55736572446566696E656441676772656761746541747472696275746500466F726D6174005374727563744C61796F7574417474726962757465004C61796F75744B696E64006765745F49734E756C6C006765745F56616C756500436F6E7461696E734B6579006765745F4974656D007365745F4974656D0041646400456E756D657261746F7200476574456E756D657261746F72004B657956616C7565506169726032006765745F43757272656E74006765745F4B6579004D6F76654E6578740049446973706F7361626C6500446973706F7365006765745F436F756E740053797374656D2E5465787400537472696E674275696C64657200417070656E64006765745F4C656E6774680052656D6F766500546F537472696E67006F705F496D706C696369740052656164496E7433320052656164537472696E6700537472696E67006F705F496E657175616C69747900456D7074790049734E756C6C4F72456D70747900457863657074696F6E00436F6E7665727400546F4279746500536F7274656444696374696F6E6172796032004944696374696F6E617279603200526561644279746500436F6D70617265546F0000000000032C00006549006E00760061006C0069006400200053006F0072007400420079002000760061006C00750065003A00200075007300650020003100200066006F007200200041005300430020006F00720020003200200066006F007200200044004500530043002E0000008002D97266C26949A672EA780F71C8980008B77A5C561934E08905151211010E0706151215020E0803200001052001011119052001011108042000111905200101121D05200101122102060E072002011119111905200101110C04280011190206050520010111250920030111191119112505200101111004280011250720020111191125052001011114052002080E0E12010001005408074D617853697A65A00F000012010001005408074D617853697A65FFFFFFFF12010001005408074D617853697A6504000000042001010E0420010102042001010805200101116572010002000000050054080B4D61784279746553697A65FFFFFFFF5402124973496E76617269616E74546F4E756C6C73015402174973496E76617269616E74546F4475706C696361746573005402124973496E76617269616E74546F4F726465720154020D49734E756C6C4966456D7074790105200101116D06151215020E08032000020320000E0520010213000620011301130007200201130013010A07030E151215020E080E0A2000151171021300130106151171020E080A2000151175021300130106151175020E080420001300160705151175020E080E151171020E08151215020E080E03200008052001127D0E0420001301062002127D080805000111190E110704127D151175020E0808151171020E0804070208080E0702151175020E08151171020E08050002020E0E0307010E040001020E032000050400010505071512808D020E08122002011512809102130013011512110113000C2001011512809102130013010B20001511809502130013010715118095020E081907051512808D020E08127D151175020E080815118095020E0804200101051A07061512808D020E08127D151175020E080E0815118095020E08042001080E1001000B47726F7570436F6E63617400007001006B537472696E6720636F6E636174656E6174696F6E2061676772656761746520666F722053514C205365727665722E2044726F702D696E207265706C6163656D656E7420666F72206275696C742D696E204D7953514C2047524F55505F434F4E4341542066756E74696F6E2E000005010000000017010012436F7079726967687420C2A920203230313100000801000800000000001E01000100540216577261704E6F6E457863657074696F6E5468726F7773014C3D000000000000000000006E3D0000002000000000000000000000000000000000000000000000603D00000000000000000000000000000000000000005F436F72446C6C4D61696E006D73636F7265652E646C6C0000000000FF25002000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100100000001800008000000000000000000000000000000100010000003000008000000000000000000000000000000100000000004800000058400000E00300000000000000000000E00334000000560053005F00560045005200530049004F004E005F0049004E0046004F0000000000BD04EFFE0000010000000100F49F0D1300000100F49F0D133F000000000000000400000002000000000000000000000000000000440000000100560061007200460069006C00650049006E0066006F00000000002400040000005400720061006E0073006C006100740069006F006E00000000000000B00440030000010053007400720069006E006700460069006C00650049006E0066006F0000001C0300000100300030003000300030003400620030000000F0006C00010043006F006D006D0065006E0074007300000053007400720069006E006700200063006F006E0063006100740065006E006100740069006F006E002000610067006700720065006700610074006500200066006F0072002000530051004C0020005300650072007600650072002E002000440072006F0070002D0069006E0020007200650070006C006100630065006D0065006E007400200066006F00720020006200750069006C0074002D0069006E0020004D007900530051004C002000470052004F00550050005F0043004F004E004300410054002000660075006E00740069006F006E002E00000040000C000100460069006C0065004400650073006300720069007000740069006F006E0000000000470072006F007500700043006F006E00630061007400000040000F000100460069006C006500560065007200730069006F006E000000000031002E0030002E0034003800370037002E00340030003900340038000000000040001000010049006E007400650072006E0061006C004E0061006D0065000000470072006F007500700043006F006E006300610074002E0064006C006C0000004800120001004C006500670061006C0043006F007000790072006900670068007400000043006F0070007900720069006700680074002000A90020002000320030003100310000004800100001004F0072006900670069006E0061006C00460069006C0065006E0061006D0065000000470072006F007500700043006F006E006300610074002E0064006C006C00000038000C000100500072006F0064007500630074004E0061006D00650000000000470072006F007500700043006F006E00630061007400000044000F000100500072006F006400750063007400560065007200730069006F006E00000031002E0030002E0034003800370037002E00340030003900340038000000000048000F00010041007300730065006D0062006C0079002000560065007200730069006F006E00000031002E0030002E0034003800370037002E003400300039003400380000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000C000000803D00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 with permission_set = safe;
create aggregate [dbo].[GROUP_CONCAT]    (@VALUE [nvarchar](4000))                                                      returns[nvarchar](max) external name [GroupConcat].[GroupConcat.GROUP_CONCAT];
create aggregate [dbo].[GROUP_CONCAT_D]  (@VALUE [nvarchar](4000), @DELIMITER [nvarchar](4))                            returns[nvarchar](max) external name [GroupConcat].[GroupConcat.GROUP_CONCAT_D];
create aggregate [dbo].[GROUP_CONCAT_DS] (@VALUE [nvarchar](4000), @DELIMITER [nvarchar](4), @SORT_ORDER [tinyint])     returns[nvarchar](max) external name [GroupConcat].[GroupConcat.GROUP_CONCAT_DS];
create aggregate [dbo].[GROUP_CONCAT_S]  (@VALUE [nvarchar](4000), @SORT_ORDER [tinyint])                               returns[nvarchar](max) external name [GroupConcat].[GroupConcat.GROUP_CONCAT_S];

go

Usage:

declare @liststr varchar(max)
select @liststr = dbo.group_concat_d(institutionname, ',')
from education
where studentnumber = '111'
group by studentnumber;
select @liststr

GroupConcat does not support ordering, though. You could use PIVOT, CTE's and windows functions if you need ordering:

drop table if exists #students;
create table #students (
    name        varchar(20),
    institution varchar(20),
    year        int -- order by year
)
go

insert into #students(name, institution, year)
values
    ('Simon', 'INSTITUTION1', 2005),
    ('Simon', 'INSTITUTION2', 2008);

with cte as (
    select name,
           institution,
           rn = row_number() over (partition by name order by year)
    from #students
)
select name,
       [1] +
       isnull((',' + [2]), '') +
       isnull((',' + [3]), '') +
       isnull((',' + [4]), '') +
       isnull((',' + [5]), '') +
       isnull((',' + [6]), '') +
       isnull((',' + [7]), '') +
       isnull((',' + [8]), '') +
       isnull((',' + [9]), '') +
       isnull((',' + [10]), '') +
       isnull((',' + [11]), '') +
       isnull((',' + [12]), '') +
       isnull((',' + [13]), '') +
       isnull((',' + [14]), '') +
       isnull((',' + [15]), '') +
       isnull((',' + [16]), '') +
       isnull((',' + [17]), '') +
       isnull((',' + [18]), '') +
       isnull((',' + [19]), '') +
       isnull((',' + [20]), '')
from cte
    pivot (
    max(institution)
    for rn in ([1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20])
    ) as piv

Execute multiple command lines with the same process using .NET

A command-line process such cmd.exe or mysql.exe will usually read (and execute) whatever you (the user) type in (at the keyboard).

To mimic that, I think you want to use the RedirectStandardInput property: http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardinput.aspx

Undo git stash pop that results in merge conflict

As it turns out, Git is smart enough not to drop a stash if it doesn't apply cleanly. I was able to get to the desired state with the following steps:

  1. To unstage the merge conflicts: git reset HEAD . (note the trailing dot)
  2. To save the conflicted merge (just in case): git stash
  3. To return to master: git checkout master
  4. To pull latest changes: git fetch upstream; git merge upstream/master
  5. To correct my new branch: git checkout new-branch; git rebase master
  6. To apply the correct stashed changes (now 2nd on the stack): git stash apply stash@{1}

How can I move all the files from one folder to another using the command line?

Be sure to use quotes if there are spaces in the file path:

move "C:\Users\MyName\My Old Folder\*" "C:\Users\MyName\My New Folder"

That will move the contents of C:\Users\MyName\My Old Folder\ to C:\Users\MyName\My New Folder

Access Control Origin Header error using Axios in React Web throwing error in Chrome

try it proxy package.json add code:

"proxy":"https://localhost:port"

and restart npm enjoy

same code

const instance = axios.create({
  baseURL: "/api/list", 
 
});

is it possible to evenly distribute buttons across the width of an android linearlayout

Equally weighted children

To create a linear layout in which each child uses the same amount of space on the screen, set the android:layout_height of each view to "0dp" (for a vertical layout) or the android:layout_width of each view to "0dp" (for a horizontal layout). Then set the android:layout_weight of each view to "1".

In order for this to work in the LinearLayout view group the attribute values for android:layout_width and android:layout_height need to be equal to "match_parent"...

What steps are needed to stream RTSP from FFmpeg?

FWIW, I was able to setup a local RTSP server for testing purposes using simple-rtsp-server and ffmpeg following these steps:

  1. Create a configuration file for the RTSP server called rtsp-simple-server.yml with this single line:
    protocols: [tcp]
    
  2. Start the RTSP server as a Docker container:
    $ docker run --rm -it -v $PWD/rtsp-simple-server.yml:/rtsp-simple-server.yml -p 8554:8554 aler9/rtsp-simple-server
    
  3. Use ffmpeg to stream a video file (looping forever) to the server:
    $ ffmpeg -re -stream_loop -1 -i test.mp4 -f rtsp -rtsp_transport tcp rtsp://localhost:8554/live.stream
    

Once you have that running you can use ffplay to view the stream:

$ ffplay -rtsp_transport tcp rtsp://localhost:8554/live.stream

Note that simple-rtsp-server can also handle UDP streams (i.s.o. TCP) but that's tricky running the server as a Docker container.

Evaluating string "3*(4+2)" yield int 18

static double Evaluate(string expression) { 
  var loDataTable = new DataTable(); 
  var loDataColumn = new DataColumn("Eval", typeof (double), expression); 
  loDataTable.Columns.Add(loDataColumn); 
  loDataTable.Rows.Add(0); 
  return (double) (loDataTable.Rows[0]["Eval"]); 
} 

Explanation of how it works:

First, we make a table in the part var loDataTable = new DataTable();, just like in a Data Base Engine (MS SQL for example).

Then, a column, with some specific parameters (var loDataColumn = new DataColumn("Eval", typeof (double), expression);).

The "Eval" parameter is the name of the column (ColumnName attribute).

typeof (double) is the type of data to be stored in the column, which is equal to put System.Type.GetType("System.Double"); instead.

expression is the string that the Evaluate method receives, and is stored in the attribute Expression of the column. This attribute is for a really specific purpose (obvious), which is that every row that's put on the column will be fullfilled with the "Expression", and it accepts practically wathever can be put in a SQL Query. Refer to http://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression(v=vs.100).aspx to know what can be put in the Expression attribute, and how it's evaluated.

Then, loDataTable.Columns.Add(loDataColumn); adds the column loDataColumn to the loDataTable table.

Then, a row is added to the table with a personalized column with a Expression attribute, done via loDataTable.Rows.Add(0);. When we add this row, the cell of the column "Eval" of the table loDataTable is fullfilled automatically with its "Expression" attribute, and, if it has operators and SQL Queries, etc, it's evaluated and then stored to the cell, so, here happens the "magic", the string with operators is evaluated and stored to a cell...

Finally, just return the value stored to the cell of the column "Eval" in row 0 (it's an index, starts counting from zero), and making a conversion to a double with return (double) (loDataTable.Rows[0]["Eval"]);.

And that's all... job done!

And here a code eaiser to understand, which does the same... It's not inside a method, and it's explained too.

DataTable MyTable = new DataTable();
DataColumn MyColumn = new DataColumn();
MyColumn.ColumnName = "MyColumn";
MyColumn.Expression = "5+5/5"
MyColumn.DataType = typeof(double);
MyTable.Columns.Add(MyColumn);
DataRow MyRow = MyTable.NewRow();
MyTable.Rows.Add(MyRow);
return (double)(MyTable.Rows[0]["MyColumn"]);

First, create the table with DataTable MyTable = new DataTable();

Then, a column with DataColumn MyColumn = new DataColumn();

Next, we put a name to the column. This so we can search into it's contents when it's stored to the table. Done via MyColumn.ColumnName = "MyColumn";

Then, the Expression, here we can put a variable of type string, in this case there's a predefined string "5+5/5", which result is 6.

The type of data to be stored to the column MyColumn.DataType = typeof(double);

Add the column to the table... MyTable.Columns.Add(MyColumn);

Make a row to be inserted to the table, which copies the table structure DataRow MyRow = MyTable.NewRow();

Add the row to the table with MyTable.Rows.Add(MyRow);

And return the value of the cell in row 0 of the column MyColumn of the table MyTable with return (double)(MyTable.Rows[0]["MyColumn"]);

Lesson done!!!

Chart.js v2 - hiding grid lines

If you want to hide gridlines but want to show yAxes, you can set:

yAxes: [{...
         gridLines: {
                        drawBorder: true,
                        display: false
                    }
       }]

How to check if a file is empty in Bash?

Many of the answers are correct but I feel like they could be more complete / simplistic etc. for example :

Example 1 : Basic if statement

# BASH4+ example on Linux :

typeset read_file="/tmp/some-file.txt"
if [ ! -s "${read_file}" ]  || [ ! -f "${read_file}" ] ;then
    echo "Error: file (${read_file}) not found.. "
    exit 7
fi

if $read_file is empty or not there stop the show with exit. More than once I have had misread the top answer here to mean the opposite.

Example 2 : As a function

# -- Check if file is missing /or empty --
# Globals: None
# Arguments: file name
# Returns: Bool
# --
is_file_empty_or_missing() {
    [[ ! -f "${1}" || ! -s "${1}" ]] && return 0 || return 1
}

What is the facade design pattern?

It is basically single window clearance system.You assign any work it will delegate to particular method in another class.

Android Studio: Can't start Git

I had the same problem, this is how I fixed it:

I use windows...

Go to

C:\Users\<username>\AppData\Local\GitHub\PortableGit_c2ba306e536fdf878271f7fe636a147ff37326ad\bin

So in my Account I had this

C:\Users\victor\AppData\Local\GitHub\PortableGit_c2ba306e536fdf878271f7fe636a147ff37326ad\bin

Make sure you find the git.exe

Then go to the VCS window(Settings --> Version Control---> Git), and paste the PATH and append git.exe at the end

So you shall have this

C:\Users\<username>\AppData\Local\GitHub\PortableGit_c2ba306e536fdf878271f7fe636a147ff37326ad\bin\git.exe 

Then click test to verify if git is working well.

Java Generate Random Number Between Two Given Values

Assuming the upper is the upper bound and lower is the lower bound, then you can make a random number, r, between the two bounds with:

int r = (int) (Math.random() * (upper - lower)) + lower;

Angular2 router (@angular/router), how to set default route?

Suppose you want to load RegistrationComponent on load and then ConfirmationComponent on some event click on RegistrationComponent.

So in appModule.ts, you can write like this.

RouterModule.forRoot([
      { 
        path: '', 
        redirectTo: 'registration', 
        pathMatch: 'full'
       },
       { 
        path: 'registration', 
        component: RegistrationComponent
       },
      {
        path : 'confirmation',
        component: ConfirmationComponent
      }
    ]) 

OR

RouterModule.forRoot([
       { 
        path: '', 
        component: RegistrationComponent
       },
      {
        path : 'confirmation',
        component: ConfirmationComponent
      }
    ]) 

is also fine. Choose whatever you like.

Count Rows in Doctrine QueryBuilder

To count items after some number of items (offset), $qb->setFirstResults() cannot be applied in this case, as it works not as a condition of query, but as an offset of query result for a range of items selected (i. e. setFirstResult cannot be used togather with COUNT at all). So to count items, which are left I simply did the following:

   //in repository class:
   $count = $qb->select('count(p.id)')
      ->from('Products', 'p')
      ->getQuery()
      ->getSingleScalarResult();

    return $count;

    //in controller class:
    $count = $this->em->getRepository('RepositoryBundle')->...

    return $count-$offset;

Anybody knows more clean way to do it?

create table with sequence.nextval in oracle

I for myself prefer Lukas Edger's solution.

But you might want to know there is also a function SYS_GUID which can be applied as a default value to a column and generate unique ids.

you can read more about pros and cons here

How to include clean target in Makefile?

The best thing is probably to create a variable that holds your binaries:

binaries=code1 code2

Then use that in the all-target, to avoid repeating:

all: clean $(binaries)

Now, you can use this with the clean-target, too, and just add some globs to catch object files and stuff:

.PHONY: clean

clean:
    rm -f $(binaries) *.o

Note use of the .PHONY to make clean a pseudo-target. This is a GNU make feature, so if you need to be portable to other make implementations, don't use it.

Coerce multiple columns to factors at once

Here is another tidyverse approach using the modify_at() function from the purrr package.

library(purrr)

# Data frame with only integer columns
data <- data.frame(matrix(sample(1:40), 4, 10, dimnames = list(1:4, LETTERS[1:10])))

# Modify specified columns to a factor class
data_with_factors <- data %>%
    purrr::modify_at(c("A", "C", "E"), factor)


# Check the results:
str(data_with_factors)
# 'data.frame':   4 obs. of  10 variables:
#  $ A: Factor w/ 4 levels "8","12","33",..: 1 3 4 2
#  $ B: int  25 32 2 19
#  $ C: Factor w/ 4 levels "5","15","35",..: 1 3 4 2
#  $ D: int  11 7 27 6
#  $ E: Factor w/ 4 levels "1","4","16","20": 2 3 1 4
#  $ F: int  21 23 39 18
#  $ G: int  31 14 38 26
#  $ H: int  17 24 34 10
#  $ I: int  13 28 30 29
#  $ J: int  3 22 37 9

A failure occurred while executing com.android.build.gradle.internal.tasks

Clean Project -> Invalidate caches/restart. My problem resolved with this.

The most accurate way to check JS object's type?

var o = ...
var proto =  Object.getPrototypeOf(o);
proto === SomeThing;

Keep a handle on the prototype you expect the object to have, then compare against it.

for example

var o = "someString";
var proto =  Object.getPrototypeOf(o);
proto === String.prototype; // true

How can I extract substrings from a string in Perl?

Long time no Perl

while(<STDIN>) {
    next unless /:\s*(\S+)\s+\(([^\)]+)\)\s*(\*?)/;
    print "|$1|$2|$3|\n";
}

Filtering Sharepoint Lists on a "Now" or "Today"

Pass Today as value as mentioned below in $viewQuery property :

$web = Get-SPWeb "http://sitename"
$list = $web.Lists.TryGetList($listtitle)
write-host "Exporting '$($list.Title)' data from '$($web.Title)' site.."
$viewTitle = "Program Events" #Title property
#Add the column names from the ViewField property to a string collection
$viewFields = New-Object System.Collections.Specialized.StringCollection
$viewFields.Add("Event Date") > $null
$viewFields.Add("Title") > $null
#Query property
$viewQuery = "<Where><Geq><FieldRef Name='EventDate' /><Value IncludeTimeValue='TRUE' Type='DateTime'><Today/></Value></Geq></Where><OrderBy><FieldRef Name='EventDate' Ascending='True' /></OrderBy>"
#RowLimit property
$viewRowLimit = 30
#Paged property
$viewPaged = $true
#DefaultView property
$viewDefaultView = $false
#Create the view in the destination list
$newview = $list.Views.Add($viewTitle, $viewFields, $viewQuery, $viewRowLimit, $viewPaged, $viewDefaultView)
Write-Host ("View '" + $newview.Title + "' created in list '" + $list.Title + "' on site " + $web.Url)
$web.Dispose()

'Operation is not valid due to the current state of the object' error during postback

For ASP.NET 1.1, this is still due to someone posting more than 1000 form fields, but the setting must be changed in the registry rather than a config file. It should be added as a DWORD named MaxHttpCollectionKeys in the registry under

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ASP.NET\1.1.4322.0

for 32-bit editions of Windows, and

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\ASP.NET\1.1.4322.0

for 64-bit editions of Windows.

Role/Purpose of ContextLoaderListener in Spring?

Your understanding is correct. I wonder why you don't see any advantages in ContextLoaderListener. For example, you need to build a session factory (to manage database). This operation can take some time, so it's better to do it on startup. Of course you can do it with init servlets or something else, but the advantage of Spring's approach is that you make configuration without writing code.

Python loop for inside lambda

anon and chepner's answers are on the right track. Python 3.x has a print function and this is what you will need if you want to embed print within a function (and, a fortiori, lambdas).

However, you can get the print function very easily in python 2.x by importing from the standard library's future module. Check it out:

>>>from __future__ import print_function
>>>
>>>iterable = ["a","b","c"]
>>>map(print, iterable)
a
b
c
[None, None, None]
>>>

I guess that looks kind of weird, so feel free to assign the return to _ if you would like to suppress [None, None, None]'s output (you are interested in the side-effects only, I assume):

>>>_ = map(print, iterable)
a
b
c
>>>

How to set text color to a text view programmatically

Use,..

Color.parseColor("#bdbdbd");

like,

mTextView.setTextColor(Color.parseColor("#bdbdbd"));

Or if you have defined color code in resource's color.xml file than

(From API >= 23)

mTextView.setTextColor(ContextCompat.getColor(context, R.color.<name_of_color>));

(For API < 23)

mTextView.setTextColor(getResources().getColor(R.color.<name_of_color>));

INSERT ... ON DUPLICATE KEY (do nothing)

Yes, use INSERT ... ON DUPLICATE KEY UPDATE id=id (it won't trigger row update even though id is assigned to itself).

If you don't care about errors (conversion errors, foreign key errors) and autoincrement field exhaustion (it's incremented even if the row is not inserted due to duplicate key), then use INSERT IGNORE.

JavaScript click event listener on class

* This was edited to allow for children of the target class to trigger the events. See bottom of the answer for details. *

An alternative answer to add an event listener to a class where items are frequently being added and removed. This is inspired by jQuery's on function where you can pass in a selector for a child element that the event is listening on.

var base = document.querySelector('#base'); // the container for the variable content
var selector = '.card'; // any css selector for children

base.addEventListener('click', function(event) {
  // find the closest parent of the event target that
  // matches the selector
  var closest = event.target.closest(selector);
  if (closest && base.contains(closest)) {
    // handle class event
  }
});

Fiddle: https://jsfiddle.net/u6oje7af/94/

This will listen for clicks on children of the base element and if the target of a click has a parent matching the selector, the class event will be handled. You can add and remove elements as you like without having to add more click listeners to the individual elements. This will catch them all even for elements added after this listener was added, just like the jQuery functionality (which I imagine is somewhat similar under the hood).

This depends on the events propagating, so if you stopPropagation on the event somewhere else, this may not work. Also, the closest function has some compatibility issues with IE apparently (what doesn't?).

This could be made into a function if you need to do this type of action listening repeatedly, like

function addChildEventListener(base, eventName, selector, handler) {
  base.addEventListener(eventName, function(event) {
    var closest = event.target.closest(selector);
    if (closest && base.contains(closest)) {
      // passes the event to the handler and sets `this`
      // in the handler as the closest parent matching the
      // selector from the target element of the event
      handler.call(closest, event);
    }
  });
}

=========================================
EDIT: This post originally used the matches function for DOM elements on the event target, but this restricted the targets of events to the direct class only. It has been updated to use the closest function instead, allowing for events on children of the desired class to trigger the events as well. The original matches code can be found at the original fiddle: https://jsfiddle.net/u6oje7af/23/

How to get PID of process I've just started within java program?

If portability is not a concern, and you just want to get the pid on Windows without a lot of hassle while using code that is tested and known to work on all modern versions of Windows, you can use kohsuke's winp library. It is also available on Maven Central for easy consumption.

Process process = //...;
WinProcess wp = new WinProcess(process);
int pid = wp.getPid();

How to get the query string by javascript?

You need to simple use following function.

function GetQueryStringByParameter(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
        return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }

--- How to Use ---

var QueryString= GetQueryStringByParameter('QueryString');

How to delete $_POST variable upon pressing 'Refresh' button on browser with PHP?

Set an intermediate page where you change $_POST variables into $_SESSION. In your actual page, unset them after usage.

You may pass also the initial page URL to set the browser back button.

How can I work with command line on synology?

for my example:

Windows XP ---> Synology:DS218+

  • Step1:
        > DNS: Control Panel (???)
             > Terminal & SNMP(??? & SNMP)
  • Step2:
        Enable Telnet service (?? Telnet ??)
        or Enable SSH Service (?? SSH ??)


    enter image description here
    enter image description here


  • Step3: Launch the terminal on Windows (or via executing

        cmd
    to launch the terminal)
    enter image description here


  • Step4: type: telnet your_nas_ip_or_domain_name, like below

        telnet 192.168.1.104
    enter image description here



  • Step5:
    demo a terminal application, like compiling the Java code

    Fzz login: tsungjung411

    Password:

    # shows the current working directory (?????????)
    $ pwd
    /var/services/homes/tsungjung411


    # edit a Java file (via vi), then compile and run it 
    # (?? vi ?? Java ??,???????)
    $ vi Main.java

    # show the file content (??????)
    $ cat Main.java
    public class Main {
        public static void main(String [] args) {
            System.out.println("hello, World!");
        }
    }

    # compiles the Java file (?? Java ??)
    javac Main.java

    # executes the Java file (?? Java ??)
    $ java Main
    hello, World!

    # shows the file list (??????)
    $ ls
    CloudStation  Main.class  Main.java  www

enter image description here


    # shows the JRE version on this Synology Disk Station
    $ java -version
    openjdk version "1.8.0_151"
    OpenJDK Runtime Environment (IcedTea 3.6.0) (linux-gnu build 1.8.0_151-b12)
    OpenJDK 64-Bit Server VM (build 25.151-b12, mixed mode)




  • Step6:
    demo another terminal application, like running the Python code

    $ python
    Python 2.7.12 (default, Nov 10 2017, 20:30:30)
    [GCC 4.9.3 20150311 (prerelease)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
    >>> import sys
    >>>
    >>> # shows the the python version
    >>> print(sys.version)
    2.7.12 (default, Nov 10 2017, 20:30:30)
    [GCC 4.9.3 20150311 (prerelease)]
    >>>
    >>> import os
    >>>
    >>> # shows the current working directory
    >>> print(os.getcwd())
    /volume1/homes/tsungjung411

enter image description here


    $ # launch Python 3
    $ python3
    Python 3.5.1 (default, Dec  9 2016, 00:20:03)
    [GCC 4.9.3 20150311 (prerelease)] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>>




How to center buttons in Twitter Bootstrap 3?

Update for Bootstrap 4:

Wrap the button with a div set with the 'd-flex' and 'justify-content-center' utility classes to take advantage of flexbox.

<!-- Button -->
<div class="form-group">
  <div class="d-flex justify-content-center">
    <button id="singlebutton" name="singlebutton" class="btn btn-primary">
      Next Step!
    </button>
  </div>
</div>

The benefit of using flexbox is being able to add additional elements/buttons on the same axis, but with their own separate alignment. It also opens up the possibility of vertical alignment with the 'align-items-start/center/end' classes, too.

You could wrap the label and button with another div to keep them aligned with each other.

e.g. https://codepen.io/anon/pen/BJoeRY?editors=1000

How to create empty text file from a batch file?

copy NUL EmptyFile.txt

DOS has a few special files (devices, actually) that exist in every directory, NUL being the equivalent of UNIX's /dev/null: it's a magic file that's always empty and throws away anything you write to it. Here's a list of some others; CON is occasionally useful as well.

To avoid having any output at all, you can use

copy /y NUL EmptyFile.txt >NUL

/y prevents copy from asking a question you can't see when output goes to NUL.

How is using "<%=request.getContextPath()%>" better than "../"

request.getContextPath()- returns root path of your application, while ../ - returns parent directory of a file.

You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.

Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.

<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>

PS- This is the one reason I can figure out. Don't know if there is any more significance to it.

How to Troubleshoot Intermittent SQL Timeout Errors

The issue is because of a bad query the time to executing query is taking more than 60 seconds or a Lock on the Table

The issue looks like a deadlock is occurring; we have queries which are blocking the queries to complete in time. The default timeout for a query is 60 secs and beyond that we will have the SQLException for timeout.

Please check the SQL Server logs for deadlocks. The other way to solve the issue to to increase the Timeout on the Command Object (Temp Solution).

Target a css class inside another css class

I use div instead of tables and am able to target classes within the main class, as below:

CSS

.main {
    .width: 800px;
    .margin: 0 auto;
    .text-align: center;
}
.main .table {
    width: 80%;
}
.main .row {
   / ***something ***/
}
.main .column {
    font-size: 14px;
    display: inline-block;
}
.main .left {
    width: 140px;
    margin-right: 5px;
    font-size: 12px;
}
.main .right {
    width: auto;
    margin-right: 20px;
    color: #fff;
    font-size: 13px;
    font-weight: normal;
}

HTML

<div class="main">
    <div class="table">
        <div class="row">
            <div class="column left">Swing Over Bed</div>
            <div class="column right">650mm</div>
            <div class="column left">Swing In Gap</div>
            <div class="column right">800mm</div>
        </div>
    </div>
</div>

If you want to style a particular "cell" exclusively you can use another sub-class or the id of the div e.g:

.main #red { color: red; }

<div class="main">
    <div class="table">
        <div class="row">
            <div id="red" class="column left">Swing Over Bed</div>
            <div class="column right">650mm</div>
            <div class="column left">Swing In Gap</div>
            <div class="column right">800mm</div>
        </div>
    </div>
</div>

Get the ID of a drawable in ImageView

As of today, there is no support on this function. However, I found a little hack on this one.

 imageView.setImageResource(R.drawable.ic_star_black_48dp);
 imageView.setTag(R.drawable.ic_star_black_48dp);

So if you want to get the ID of the view, just get it's tag.

if (imageView.getTag() != null) {
   int resourceID = (int) imageView.getTag();

   //
   // drawable id.
   //   
}

In vb.net, how to get the column names from a datatable

This is how to retrieve a Column Name from a DataColumn:

MyDataTable.Columns(1).ColumnName 

To get the name of all DataColumns within your DataTable:

Dim name(DT.Columns.Count) As String
Dim i As Integer = 0
For Each column As DataColumn In DT.Columns
  name(i) = column.ColumnName
  i += 1
Next

References

NSRange to Range<String.Index>

In the accepted answer I find the optionals cumbersome. This works with Swift 3 and seems to have no problem with emojis.

func textField(_ textField: UITextField, 
      shouldChangeCharactersIn range: NSRange, 
      replacementString string: String) -> Bool {

  guard let value = textField.text else {return false} // there may be a reason for returning true in this case but I can't think of it
  // now value is a String, not an optional String

  let valueAfterChange = (value as NSString).replacingCharacters(in: range, with: string)
  // valueAfterChange is a String, not an optional String

  // now do whatever processing is required

  return true  // or false, as required
}

How to change progress bar's progress color in Android

simply use:

PorterDuff.Mode mode = PorterDuff.Mode.SRC_IN;
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
    mode = PorterDuff.Mode.MULTIPLY;
}

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    progressBar.setProgressTintList(ColorStateList.valueOf(Color.RED));
    progressBar.setProgressBackgroundTintList(ColorStateList.valueOf(Color.RED));
} else {
    Drawable progressDrawable;
    progressDrawable = (progressBar.isIndeterminate() ? progressBar.getIndeterminateDrawable() : progressBar.getProgressDrawable()).mutate();
    progressDrawable.setColorFilter(context.getResources().getColor(Color.RED), mode);
    progressBar.setProgressDrawable(progressDrawable);
}

How to allow <input type="file"> to accept only image files?

Using this:

<input type="file" accept="image/*">

works in both FF and Chrome.

How to style the UL list to a single line

HTML code:

<ul class="list">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

CSS code:

ul.list li{
  width: auto;
  float: left;
}

Get elements by attribute when querySelectorAll is not available without using libraries?

A little modification on @kevinfahy 's answer, to allow getting the attribute by value if needed:

function getElementsByAttributeValue(attribute, value){
  var matchingElements = [];
  var allElements = document.getElementsByTagName('*');
  for (var i = 0, n = allElements.length; i < n; i++) {
    if (allElements[i].getAttribute(attribute) !== null) {
      if (!value || allElements[i].getAttribute(attribute) == value)
        matchingElements.push(allElements[i]);
    }
  }
  return matchingElements;
}

How do I read all classes from a Java package in the classpath?

Here is another option, slight modification to another answer in above/below:

Reflections reflections = new Reflections("com.example.project.package", 
    new SubTypesScanner(false));
Set<Class<? extends Object>> allClasses = 
    reflections.getSubTypesOf(Object.class);

How to center a component in Material-UI and make it responsive?

Another option is:

<Grid container justify = "center">
  <Your centered component/>
</Grid>

How to stop tracking and ignore changes to a file in Git?

The problem may be caused by the order of operation. If you modified the .gitignore first, then git rm --cached xxx,you may have to continue to encounter this problem.

Correct solution:

  1. git rm --cached xxx
  2. modified the .gitignore

Order invariant!

The .gitignore reload after modification!

Error: [$injector:unpr] Unknown provider: $routeProvider

In angular 1.4 +, in addition to adding the dependency

angular.module('myApp', ['ngRoute'])

,we also need to reference the separate angular-route.js file

<script src="angular.js">
<script src="angular-route.js">

see https://docs.angularjs.org/api/ngRoute

How to reference a method in javadoc?

you can use @see to do that:

sample:

interface View {
        /**
         * @return true: have read contact and call log permissions, else otherwise
         * @see #requestReadContactAndCallLogPermissions()
         */
        boolean haveReadContactAndCallLogPermissions();

        /**
         * if not have permissions, request to user for allow
         * @see #haveReadContactAndCallLogPermissions()
         */
        void requestReadContactAndCallLogPermissions();
    }

How to execute an Oracle stored procedure via a database link

The syntax is

EXEC mySchema.myPackage.myProcedure@myRemoteDB( 'someParameter' );

How to trigger HTML button when you press Enter in textbox?

It works when input type="button" is replaced with input type="submit" for the default button which needs to be triggered.

C# error: Use of unassigned local variable

The compiler only knows that the code is or isn't reachable if you use "return". Think of Environment.Exit() as a function that you call, and the compiler don't know that it will close the application.

Proper way to renew distribution certificate for iOS

This was a really a helpful thread, I followed the same steps as @junjie mentioned but for me something weird happened, the below are the steps I did.

  1. Went to developer portal and revoked the certificate which was about to expire.
  2. Went to XCode6.4 and in the Account settings, the certificate still showed valid, I went crazy.
  3. Then I opened XCode7, there the certificate was shown with "Reset" button instead of create and I hit the reset button and later in the portal I was able to see an extended certificate present. This is what Apple says about Reset button

If Xcode detects an issue with a signing identity, it displays an appropriate action in Accounts preferences. If Xcode displays a Create button, the signing identity doesn’t exist in Member Center or on your Mac. If Xcode displays a Reset button, the signing identity is not usable on your Mac—for example, it is missing the private key. If you click the Reset button, Xcode revokes and requests the corresponding certificate.

  1. I tried creating an Appstore ipa with that, just to test and it worked fine so I am saved, but still not sure what has happened. May be I had multiple accounts configured in my Mac, dont know.

The controller for path was not found or does not implement IController

Also, for those who the solution above didn't work, here's is what worked for me:

I have a solution with multiple projects. All projects were in MVC3. I installed Visual Studio 2012 in my machine and it seems that some projects were automatically upgraded to MVC4.

I got this problem

The controller for path '/etc/etc' was not found or does not implement IController

because the project that handled that route was pointing to MVC4.

I had to manually update their references to use MVC3. You can also do that by opening the .csproj file with a text editor. Find the reference to MVC3 and remove this line:

<SpecificVersion>False</SpecificVersion>

Creating a JSON array in C#

You're close. This should do the trick:

new {items = new [] {
    new {name = "command" , index = "X", optional = "0"}, 
    new {name = "command" , index = "X", optional = "0"}
}}

If your source was an enumerable of some sort, you might want to do this:

new {items = source.Select(item => new 
{
    name = item.Name, index = item.Index, options = item.Optional
})};

design a stack such that getMinimum( ) should be O(1)

I used a different kind of stack. Here is the implementation.

//
//  main.cpp
//  Eighth
//
//  Created by chaitanya on 4/11/13.
//  Copyright (c) 2013 cbilgika. All rights reserved.
//

#include <iostream>
#include <limits>
using namespace std;
struct stack
{
    int num;
    int minnum;
}a[100];

void push(int n,int m,int &top)
{

    top++;
    if (top>=100) {
        cout<<"Stack Full";
        cout<<endl;
    }
    else{
        a[top].num = n;
        a[top].minnum = m;
    }


}

void pop(int &top)
{
    if (top<0) {
        cout<<"Stack Empty";
        cout<<endl;
    }
    else{
       top--; 
    }


}
void print(int &top)
{
    cout<<"Stack: "<<endl;
    for (int j = 0; j<=top ; j++) {
        cout<<"("<<a[j].num<<","<<a[j].minnum<<")"<<endl;
    }
}


void get_min(int &top)
{
    if (top < 0)
    {
        cout<<"Empty Stack";
    }
    else{
        cout<<"Minimum element is: "<<a[top].minnum;
    }
    cout<<endl;
}

int main()
{

    int top = -1,min = numeric_limits<int>::min(),num;
    cout<<"Enter the list to push (-1 to stop): ";
    cin>>num;
    while (num!=-1) {
        if (top == -1) {
            min = num;
            push(num, min, top);
        }
        else{
            if (num < min) {
                min = num;
            }
            push(num, min, top);
        }
        cin>>num;
    }
    print(top);
    get_min(top);
    return 0;
}

Output:

Enter the list to push (-1 to stop): 5
1
4
6
2
-1
Stack: 
(5,5)
(1,1)
(4,1)
(6,1)
(2,1)
Minimum element is: 1

Try it. I think it answers the question. The second element of every pair gives the minimum value seen when that element was inserted.

Applying Comic Sans Ms font style

You need to use quote marks.

font-family: "Comic Sans MS", cursive, sans-serif;

Although you really really shouldn't use comic sans. The font has massive stigma attached to it's use; it's not seen as professional at all.

How to embed a YouTube channel into a webpage

In order to embed your channel, all you need to do is copy then paste the following code in another web-page.

<script src="http://www.gmodules.com/ig/ifr?url=http://www.google.com/ig/modules/youtube.xml&up_channel=YourChannelName&synd=open&w=320&h=390&title=&border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>

Make sure to replace the YourChannelName with your actual channel name.

For example: if your channel name were CaliChick94066 your channel embed code would be:

<script src="http://www.gmodules.com/ig/ifr?url=http://www.google.com/ig/modules/youtube.xml&up_channel=CaliChick94066&synd=open&w=320&h=390&title=&border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>

Please look at the following links:

YouTube on your site

Embed YouTube Channel

You just have to name the URL to your channel name. Also you can play with the height and the border color and size. Hope it helps

How do I get class name in PHP?

This will return pure class name even when using namespace:

echo substr(strrchr(__CLASS__, "\\"), 1);    

Fixing the order of facets in ggplot

Here's a solution that keeps things within a dplyr pipe chain. You sort the data in advance, and then using mutate_at to convert to a factor. I've modified the data slightly to show how this solution can be applied generally, given data that can be sensibly sorted:

# the data
temp <- data.frame(type=rep(c("T", "F", "P"), 4),
                    size=rep(c("50%", "100%", "200%", "150%"), each=3), # cannot sort this
                    size_num = rep(c(.5, 1, 2, 1.5), each=3), # can sort this
                    amount=c(48.4, 48.1, 46.8, 
                             25.9, 26.0, 24.9,
                             20.8, 21.5, 16.5,
                             21.1, 21.4, 20.1))

temp %>% 
  arrange(size_num) %>% # sort
  mutate_at(vars(size), funs(factor(., levels=unique(.)))) %>% # convert to factor

  ggplot() + 
  geom_bar(aes(x = type, y=amount, fill=type), 
           position="dodge", stat="identity") + 
  facet_grid(~ size)

You can apply this solution to arrange the bars within facets, too, though you can only choose a single, preferred order:

    temp %>% 
  arrange(size_num) %>%
  mutate_at(vars(size), funs(factor(., levels=unique(.)))) %>%
  arrange(desc(amount)) %>%
  mutate_at(vars(type), funs(factor(., levels=unique(.)))) %>%
  ggplot() + 
  geom_bar(aes(x = type, y=amount, fill=type), 
           position="dodge", stat="identity") + 
  facet_grid(~ size)


  ggplot() + 
  geom_bar(aes(x = type, y=amount, fill=type), 
           position="dodge", stat="identity") + 
  facet_grid(~ size)

Return Index of an Element in an Array Excel VBA

The only (& even though cumbersome but yet expedient / relatively quick) way I can do this, is to concatenate the any-dimensional array, and reduce it to 1 dimension, with "/[column number]//\|" as the delimiter.

& use a single-cell result multiple lookupall macro function on the this 1-d column.

& then index match to pull out the positions. (usuing multiple find match)

That way you get all matching occurrences of the element/string your looking for, in the original any-dimension array, and their positions. In one cell.

Wish I could write a macro / function for this entire process. It would save me more fuss.

PostgreSQL 'NOT IN' and subquery

You could also use a LEFT JOIN and IS NULL condition:

SELECT 
  mac, 
  creation_date 
FROM 
  logs
    LEFT JOIN consols ON logs.mac = consols.mac
WHERE 
  logs_type_id=11
AND
  consols.mac IS NULL;

An index on the "mac" columns might improve performance.

Detect HTTP or HTTPS then force HTTPS in JavaScript

You can do:

  <script type="text/javascript">        
        if (window.location.protocol != "https:") {
           window.location.protocol = "https";
        }
    </script>

Display two fields side by side in a Bootstrap Form

Just put two inputs inside a div with class form-group and set display flex on the div style

<form method="post">
<div class="form-group" style="display: flex;"><input type="text" class="form-control" name="nome" placeholder="Nome e sobrenome" style="margin-right: 4px;" /><input type="text" class="form-control" style="margin-left: 4px;" name="cpf" placeholder="CPF" /></div>
<div class="form-group" style="display: flex;"><input type="email" class="form-control" name="email" placeholder="Email" style="margin-right: 4px;" /><input type="tel" class="form-control" style="margin-left: 4px;" name="telephone" placeholder="Telefone" /></div>
<div class="form-group"><input type="password" class="form-control" name="password" placeholder="Password" /></div>
<div class="form-group"><input type="password" class="form-control" name="password-repeat" placeholder="Password (repeat)" /></div>
<div class="form-group">
    <div class="form-check"><label class="form-check-label"><input type="checkbox" class="form-check-input" />I agree to the license terms.</label></div>
</div>
<div class="form-group"><button class="btn btn-primary btn-block" type="submit">Sign Up</button></div><a class="already" href="#">You already have an account? Login here.</a></form>

Splitting strings in PHP and get last part

As has been mentioned by others, if you don't assign the result of explode() to a variable, you get the message:

E_STRICT: Strict standards: Only variables should be passed by reference

The correct way is:

$words = explode('-', 'hello-world-123');
$id = array_pop($words); // 123
$slug = implode('-', $words); // hello-world

Dynamically adding HTML form field using jQuery

something like so might work:

<script type="text/javascript">
$(document).ready(function(){
    var $input = $("<input name='myField' type='text'>");
    $('#section2').append($input);
});
</script>

<form>
    <div id="section1"><!-- some controls--></div>
    <div id="section2"><!-- for dynamic controls--></div>
</form>

Difference between left join and right join in SQL Server

(INNER) JOIN: Returns records that have matching values in both tables.

LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the right table.

RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from the left table.

FULL (OUTER) JOIN: Return all records when there is a match in either left or right table

For example, lets suppose we have two table with following records:

Table A

id   firstname   lastname
___________________________
1     Ram         Thapa
2     sam         Koirala
3     abc         xyz
6    sruthy       abc

Table B

id2   place
_____________
1      Nepal
2      USA
3      Lumbini
5      Kathmandu

Inner Join

Note: It give the intersection of two table.

Inner Join

Syntax

SELECT column_name FROM table1 INNER JOIN table2 ON table1.column_name = table2.column_name;

Apply it in your sample table:

SELECT TableA.firstName,TableA.lastName,TableB.Place FROM TableA INNER JOIN TableB ON TableA.id = TableB.id2;

Result will be:

firstName       lastName       Place
_____________________________________
  Ram         Thapa             Nepal
  sam         Koirala            USA
  abc         xyz              Lumbini

Left Join

Note : will give all selected rows in TableA, plus any common selected rows in TableB.

Left join

SELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name;

Apply it in your sample table

SELECT TableA.firstName,TableA.lastName,TableB.Place FROM TableA LEFT JOIN TableB ON TableA.id = TableB.id2;

Result will be:

firstName   lastName    Place
______________________________
 Ram         Thapa      Nepal
 sam         Koirala    USA
 abc         xyz        Lumbini
sruthy       abc        Null

Right Join

Note:will give all selected rows in TableB, plus any common selected rows in TableA.

Right Join

Syntax:

SELECT column_name(s) FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name;

Apply it in your samole table:

SELECT TableA.firstName,TableA.lastName,TableB.Place FROM TableA RIGHT JOIN TableB ON TableA.id = TableB.id2;

Result will bw:

firstName   lastName     Place
______________________________
Ram         Thapa         Nepal
sam         Koirala       USA
abc         xyz           Lumbini
Null        Null          Kathmandu

Full Join

Note : It is same as union operation, it will return all selected values from both tables.

Full join

Syntax:

SELECT column_name(s) FROM table1 FULL OUTER JOIN table2 ON table1.column_name = table2.column_name;

Apply it in your samp[le table:

SELECT TableA.firstName,TableA.lastName,TableB.Place FROM TableA FULL JOIN TableB ON TableA.id = TableB.id2;

Result will be:

firstName   lastName    Place
______________________________
 Ram         Thapa      Nepal
 sam         Koirala    USA
 abc         xyz        Lumbini
sruthy       abc        Null
 Null         Null      Kathmandu

Some facts

For INNER joins the order doesn't matter

For (LEFT, RIGHT or FULL) OUTER joins,the order matter

Find More at w3schools

Is try-catch like error handling possible in ASP Classic?

Regarding Wolfwyrd's anwer: "On Error Resume Next" in fact turns error handling off! Not on. On Error Goto 0 turns error-handling back ON because at the least, we want the machine to catch it if we didn't write it in ourselves. Off = leaving it to you to handle it.

If you use On Error Resume Next, you need to be careful about how much code you include after it: remember, the phrase "If Err.Number <> 0 Then" only refers to the most previous error triggered.

If your block of code after "On Error Resume Next" has several places where you might reasonably expect it to fail, then you must place "If Err.number <> 0" after each and every one of those possible failure lines, to check execution.

Otherwise, after "on error resume next" means just what it says - your code can fail on as many lines as it likes and execution will continue merrily along. That's why it's a pain in the ass.

Python Function to test ping

Here is a simplified function that returns a boolean and has no output pushed to stdout:

import subprocess, platform
def pingOk(sHost):
    try:
        output = subprocess.check_output("ping -{} 1 {}".format('n' if platform.system().lower()=="windows" else 'c', sHost), shell=True)

    except Exception, e:
        return False

    return True

How do I bind to list of checkbox values with AngularJS?

Try my baby:

**

myApp.filter('inputSelected', function(){
  return function(formData){
    var keyArr = [];
    var word = [];
    Object.keys(formData).forEach(function(key){
    if (formData[key]){
        var keyCap = key.charAt(0).toUpperCase() + key.slice(1);
      for (var char = 0; char<keyCap.length; char++ ) {
        if (keyCap[char] == keyCap[char].toUpperCase()){
          var spacedLetter = ' '+ keyCap[char];
          word.push(spacedLetter);
        }
        else {
          word.push(keyCap[char]);
        }
      }
    }
    keyArr.push(word.join(''))
    word = [];
    })
    return keyArr.toString();
  }
})

**

Then for any ng-model with checkboxes, it will return a string of all the input you selected:

<label for="Heard about ITN">How did you hear about ITN?: *</label><br>
<label class="checkbox-inline"><input ng-model="formData.heardAboutItn.brotherOrSister" type="checkbox" >Brother or Sister</label>
<label class="checkbox-inline"><input ng-model="formData.heardAboutItn.friendOrAcquaintance" type="checkbox" >Friend or Acquaintance</label>


{{formData.heardAboutItn | inputSelected }}

//returns Brother or Sister, Friend or Acquaintance

In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?

For django 1.9+
You can use Fields disabled argument to make field disable. e.g. In following code snippet from forms.py file , I have made employee_code field disabled

class EmployeeForm(forms.ModelForm):
    employee_code = forms.CharField(disabled=True)
    class Meta:
        model = Employee
        fields = ('employee_code', 'designation', 'salary')

Reference https://docs.djangoproject.com/en/dev/ref/forms/fields/#disabled

Best Practice: Access form elements by HTML id or name attribute?

[1] document.forms[0].elements[0];

"No-omg-never!" comes to mind when I see this method of element access. The problem with this is that it assumes that the DOM is a normal data structure (e.g.: an array) wherein the element order is static, consistent or reliable in anyway. We know that 99.9999% of the time, that this is not the case. Reordering or input elements within the form, adding another form to the page before the form in question, or moving the form in question are all cases where this code breaks. Short story: this is very fragile. As soon as you add or move something, it's going to break.

[2] document.myForm.foo;

I'm with Sergey ILinsky on this:

  • Access arbitrary elements by referring to their id attribute: document.getElementById("myform");
  • Access named form elements by name, relative to their parent form element: document.getElementById("myform").foo;

My main issue with this method is that the name attribute is useless when applied to a form. The name is not passed to the server as part of the POST/GET and doesn't work for hash style bookmarks.

[3] document.getElementById('foo');

In my opinion, this is the most preferable method. Direct access is the most concise and clear method.

[4] document.getElementById('myForm').foo;

In my opinion, this is acceptable, but more verbose than necessary. Method #3 is preferable.


I just so happened to be watch a video from Douglas Crockford and he weighed in on this very subject. The point of interest is at -12:00. To summarize:

  • Document collections (document.anchor, document.form, etc) are obsolete and irrelevant (method 1).
  • The name attribute is used to name things, not to access them. It is for naming things like windows, input fields, and anchor tags.
  • "ID is the thing that you should use to uniquely identify an element so that you can get access to it. They (name and ID) used to be interchangeable, but they aren't anymore."

So there you have it. Semantically, this makes the most sense.

Linux bash script to extract IP address

May be not for all cases (especially if you have several NIC's), this will help:

hostname -I | awk '{ print $1 }'

How to convert String into Hashmap in java

This is one solution. If you want to make it more generic, you can use the StringUtils library.

String value = "{first_name = naresh,last_name = kumar,gender = male}";
value = value.substring(1, value.length()-1);           //remove curly brackets
String[] keyValuePairs = value.split(",");              //split the string to creat key-value pairs
Map<String,String> map = new HashMap<>();               

for(String pair : keyValuePairs)                        //iterate over the pairs
{
    String[] entry = pair.split("=");                   //split the pairs to get key and value 
    map.put(entry[0].trim(), entry[1].trim());          //add them to the hashmap and trim whitespaces
}

For example you can switch

 value = value.substring(1, value.length()-1);

to

 value = StringUtils.substringBetween(value, "{", "}");

if you are using StringUtils which is contained in apache.commons.lang package.

Ansible: how to get output to display

Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register parameter, independently of the module used.

Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:

---
- hosts: localhost
  tasks:
    - shell: ls
      register: shell_result

    - debug:
        var: shell_result.stdout_lines

Here register tells ansible to save the response of the module into the shell_result variable, and then we use the debug module to print the variable out.

An example run would look like the this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
changed: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "shell_result.stdout_lines": [
        "play.yml"
    ]
}

Responses can contain multiple fields. stdout_lines is one of the default fields you can expect from a module's response.

Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout or stdout_lines values, however the msg field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.

Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v, -vvv and -vvvv. For example when running the playbook with verbosity (-vvv) you get this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
(...)
changed: [localhost] => {
    "changed": true,
    "cmd": "ls",
    "delta": "0:00:00.007621",
    "end": "2017-02-17 23:04:41.912570",
    "invocation": {
        "module_args": {
            "_raw_params": "ls",
            "_uses_shell": true,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "warn": true
        },
        "module_name": "command"
    },
    "rc": 0,
    "start": "2017-02-17 23:04:41.904949",
    "stderr": "",
    "stdout": "play.retry\nplay.yml",
    "stdout_lines": [
        "play.retry",
        "play.yml"
    ],
    "warnings": []
}

As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines is available, and its contents are what we expect.

To answer your main question about the jenkins_script module, if you check its documentation, you can see that it returns the output in the output field, so you might want to try the following:

tasks:
  - jenkins_script:
      script: (...)
    register: jenkins_result

  - debug:
      var: jenkins_result.output

Looping through list items with jquery

To solve this without jQuery .each() you'd have to fix your code like this:

var listItems = $("#productList").find("li");
var ind, len, product;

for ( ind = 0, len = listItems.length; ind < len; ind++ ) {
    product = $(listItems[ind]);

    // ...
}

Bugs in your original code:

  1. for ... in will also loop through all inherited properties; i.e. you will also get a list of all functions that are defined by jQuery.

  2. The loop variable li is not the list item, but the index to the list item. In that case the index is a normal array index (i.e. an integer)

Basically you are save to use .each() as it is more comfortable, but espacially when you are looping bigger arrays the code in this answer will be much faster.

For other alternatives to .each() you can check out this performance comparison: http://jsperf.com/browser-diet-jquery-each-vs-for-loop

jQuery: go to URL with target="_blank"

Detect if a target attribute was used and contains "_blank". For mobile devices that don't like "_blank", this is a reliable alternative.

    $('.someSelector').bind('touchend click', function() {

        var url = $('a', this).prop('href');
        var target = $('a', this).prop('target');

        if(url) {
            // # open in new window if "_blank" used
            if(target == '_blank') { 
                window.open(url, target);
            } else {
                window.location = url;
            }
        }           
    });

Upload a file to Amazon S3 with NodeJS

var express = require('express')

app = module.exports = express();
var secureServer = require('http').createServer(app);
secureServer.listen(3001);

var aws = require('aws-sdk')
var multer = require('multer')
var multerS3 = require('multer-s3')

    aws.config.update({
    secretAccessKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    accessKeyId: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    region: 'us-east-1'
    });
    s3 = new aws.S3();

   var upload = multer({
   storage: multerS3({
    s3: s3,
    dirname: "uploads",
    bucket: "Your bucket name",
    key: function (req, file, cb) {
        console.log(file);
        cb(null, "uploads/profile_images/u_" + Date.now() + ".jpg"); //use  
     Date.now() for unique file keys
    }
  })
   });

 app.post('/upload', upload.single('photos'), function(req, res, next) {

 console.log('Successfully uploaded ', req.file)

 res.send('Successfully uploaded ' + req.file.length + ' files!')

})

Change icon-bar (?) color in bootstrap

The reason your CSS isn't working is because of specificity. The Bootstrap selector has a higher specificity than yours, so your style is completely ignored.

Bootstrap styles this with the selector: .navbar-default .navbar-toggle .icon-bar. This selector has a B specificity value of 3, whereas yours only has a B specificity value of 1.

Therefore, to override this, simply use the same selector in your CSS (assuming your CSS is included after Bootstrap's):

.navbar-default .navbar-toggle .icon-bar {
    background-color: black;
}

TypeError: document.getElementbyId is not a function

Case sensitive: document.getElementById (notice the capital B).

What is the difference between char * const and const char *?

Two rules

  1. If const is between char and *, it will affect the left one.
  2. If const is not between char and *, it will affect the nearest one.

e.g.

  1. char const *. This is a pointer points to a constant char.
  2. char * const. This is a constant pointer points to a char.

npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself

"A requires a peer of B but none was installed". Consider it as "A requires one of B's peers but that peer was not installed and we're not telling you which of B's peers you need."

The automatic installation of peer dependencies was explicitly removed with npm 3.

NPM Blog

Release notes of v3

So you cannot install peer dependencies automatically with npm 3 and upwards.

Updated Solution:

Use following for each peer dependency to install that and remove the error

npm install --save-dev xxxxx

Deprecated Solution:

  1. You can use npm-install-peers to find and install required peer dependencies.

    npm install -g npm-install-peers

    npm-install-peers

  2. If you are getting this error after updating any package's version then remove node_modules directory and reinstall packages by npm install or npm cache clean and npm install.

Use grep to report back only line numbers

You're going to want the second field after the colon, not the first.

grep -n "text to find" file.txt | cut -f2 -d:

fork: retry: Resource temporarily unavailable

This is commonly caused by running out of file descriptors.

There is the systems total file descriptor limit, what do you get from the command:

sysctl fs.file-nr

This returns counts of file descriptors:

<in_use> <unused_but_allocated> <maximum>

To find out what a users file descriptor limit is run the commands:

sudo su - <username>
ulimit -Hn

To find out how many file descriptors are in use by a user run the command:

sudo lsof -u <username> 2>/dev/null | wc -l

So now if you are having a system file descriptor limit issue you will need to edit your /etc/sysctl.conf file and add, or modify it it already exists, a line with fs.file-max and set it to a value large enough to deal with the number of file descriptors you need and reboot.

fs.file-max = 204708

Android Studio - How to Change Android SDK Path

Though many of the above answers serve the purpose, there is one straight forward thing we can do in project itself.

In Eclipse, go to Window->Preferences, select "Android" from left side menu. On the right panel you will see "SDK Location". Provide the path here.

Good luck.

Self-reference for cell, column and row in worksheet functions

My current Column is calculated by:

Method 1:

=LEFT(ADDRESS(ROW(),COLUMN(),4,1),LEN(ADDRESS(ROW(),COLUMN(),4,1))-LEN(ROW()))

Method 2:

=LEFT(ADDRESS(ROW(),COLUMN(),4,1),INT((COLUMN()-1)/26)+1)

My current Row is calculated by:

=RIGHT(ADDRESS(ROW(),COLUMN(),4,1),LEN(ROW()))

so an indirect link to Sheet2!My Column but a different row, specified in Column A on my row is:

Method 1:

=INDIRECT("Sheet2!"&LEFT(ADDRESS(ROW(),COLUMN(),4,1),LEN(ADDRESS(ROW(),COLUMN(),4,1))-LEN(ROW()))&INDIRECT(ADDRESS(ROW(),1,4,1)))

Method 2:

=INDIRECT("Sheet2!"&LEFT(ADDRESS(ROW(),COLUMN(),4,1),INT((COLUMN()-1)/26)+1)&INDIRECT(ADDRESS(ROW(),1,4,1)))

So if A6=3 and my row is 6 and my Col is C returns contents of "Sheet2!C3"

So if A7=1 and my row is 7 and my Col is D returns contents of "Sheet2!D1"

Error including image in Latex

If you have Gimp, I saw that exporting the image in .eps format would do the job.

What is the actual use of Class.forName("oracle.jdbc.driver.OracleDriver") while connecting to a database?

Pre Java 6 the DriverManager class wouldn't have known which JDBC driver you wanted to use. Class.forName("...") was a way on pre-loading the driver classes.

If you are using Java 6 you no longer need to do this.

How to make a website secured with https

Try making a boot directory in PHP, as in

<?PHP
$ip = $_SERVER['REMOTE_ADDR'];
$privacy = ['BOOTSTRAP_CONFIG'];
$shell   = ['BOOTSTRAP_OUTPUT'];
enter code here
if $ip == $privacy {
function $privacy int $ip = "https://";
} endif {
echo $shell
}
?>

Thats mainly it!

How can I pass a reference to a function, with parameters?

What you are after is called partial function application.

Don't be fooled by those that don't understand the subtle difference between that and currying, they are different.

Partial function application can be used to implement, but is not currying. Here is a quote from a blog post on the difference:

Where partial application takes a function and from it builds a function which takes fewer arguments, currying builds functions which take multiple arguments by composition of functions which each take a single argument.

This has already been answered, see this question for your answer: How can I pre-set arguments in JavaScript function call?

Example:

var fr = partial(f, 1, 2, 3);

// now, when you invoke fr() it will invoke f(1,2,3)
fr();

Again, see that question for the details.

Fade Effect on Link Hover?

Try this in your css:

.a {
    transition: color 0.3s ease-in-out;
}
.a {
    color:turquoise;
}
.a:hover {
    color: #454545;
}

What is special about /dev/tty?

/dev/tty is a synonym for the controlling terminal (if any) of the current process. As jtl999 says, it's a character special file; that's what the c in the ls -l output means.

man 4 tty or man -s 4 tty should give you more information, or you can read the man page online here.

Incidentally, pwd > /dev/tty doesn't necessarily print to the shell's stdout (though it is the pwd command's standard output). If the shell's standard output has been redirected to something other than the terminal, /dev/tty still refers to the terminal.

You can also read from /dev/tty, which will normally read from the keyboard.

Convert Base64 string to an image file?

This code worked for me.

_x000D_
_x000D_
<?php_x000D_
$decoded = base64_decode($base64);_x000D_
$file = 'invoice.pdf';_x000D_
file_put_contents($file, $decoded);_x000D_
_x000D_
if (file_exists($file)) {_x000D_
    header('Content-Description: File Transfer');_x000D_
    header('Content-Type: application/octet-stream');_x000D_
    header('Content-Disposition: attachment; filename="'.basename($file).'"');_x000D_
    header('Expires: 0');_x000D_
    header('Cache-Control: must-revalidate');_x000D_
    header('Pragma: public');_x000D_
    header('Content-Length: ' . filesize($file));_x000D_
    readfile($file);_x000D_
    exit;_x000D_
}_x000D_
?>
_x000D_
_x000D_
_x000D_

Converting between datetime, Timestamp and datetime64

Welcome to hell.

You can just pass a datetime64 object to pandas.Timestamp:

In [16]: Timestamp(numpy.datetime64('2012-05-01T01:00:00.000000'))
Out[16]: <Timestamp: 2012-05-01 01:00:00>

I noticed that this doesn't work right though in NumPy 1.6.1:

numpy.datetime64('2012-05-01T01:00:00.000000+0100')

Also, pandas.to_datetime can be used (this is off of the dev version, haven't checked v0.9.1):

In [24]: pandas.to_datetime('2012-05-01T01:00:00.000000+0100')
Out[24]: datetime.datetime(2012, 5, 1, 1, 0, tzinfo=tzoffset(None, 3600))

Printing long int value in C

Use printf("%ld",a);

Have a look at format specifiers for printf

Execute a stored procedure in another stored procedure in SQL server

Your sp_test: Return fullname

USE [MY_DB]
GO

IF (OBJECT_ID('[dbo].[sp_test]', 'P') IS NOT NULL)
DROP PROCEDURE [dbo].sp_test;
GO

CREATE PROCEDURE [dbo].sp_test 
@name VARCHAR(20),
@last_name VARCHAR(30),
@full_name VARCHAR(50) OUTPUT
AS

SET @full_name = @name + @last_name;

GO

In your sp_main

...
DECLARE @my_name VARCHAR(20);
DECLARE @my_last_name VARCHAR(30);
DECLARE @my_full_name VARCHAR(50);
...

EXEC sp_test @my_name, @my_last_name, @my_full_name OUTPUT;
...

Best lightweight web server (only static content) for Windows

You can use Python as a quick way to host static content. On Windows, there are many options for running Python, I've personally used CygWin and ActivePython.

To use Python as a simple HTTP server just change your working directory to the folder with your static content and type python -m SimpleHTTPServer 8000, everything in the directory will be available at http:/localhost:8000/

Python 3

To do this with Python, 3.4.1 (and probably other versions of Python 3), use the http.server module:

python -m http.server <PORT>
# or possibly:
python3 -m http.server <PORT>

# example:
python -m http.server 8080

On Windows:

py -m http.server <PORT>

ComboBox- SelectionChanged event has old value, not new value

Following event is fired for any change of the text in the ComboBox (when the selected index is changed and when the text is changed by editing too).

<ComboBox IsEditable="True" TextBoxBase.TextChanged="cbx_TextChanged" />

How to convert between bytes and strings in Python 3?

The 'mangler' in the above code sample was doing the equivalent of this:

bytesThing = stringThing.encode(encoding='UTF-8')

There are other ways to write this (notably using bytes(stringThing, encoding='UTF-8'), but the above syntax makes it obvious what is going on, and also what to do to recover the string:

newStringThing = bytesThing.decode(encoding='UTF-8')

When we do this, the original string is recovered.

Note, using str(bytesThing) just transcribes all the gobbledegook without converting it back into Unicode, unless you specifically request UTF-8, viz., str(bytesThing, encoding='UTF-8'). No error is reported if the encoding is not specified.

How to create folder with PHP code?

You can create it easily:

$structure = './depth1/depth2/depth3/';
if (!mkdir($structure, 0, true)) {
die('Failed to create folders...');
}

Basic Authentication Using JavaScript

Today we use Bearer token more often that Basic Authentication but if you want to have Basic Authentication first to get Bearer token then there is a couple ways:

const request = new XMLHttpRequest();
request.open('GET', url, false, username,password)
request.onreadystatechange = function() {
        // D some business logics here if you receive return
   if(request.readyState === 4 && request.status === 200) {
       console.log(request.responseText);
   }
}
request.send()

Full syntax is here

Second Approach using Ajax:

$.ajax
({
  type: "GET",
  url: "abc.xyz",
  dataType: 'json',
  async: false,
  username: "username",
  password: "password",
  data: '{ "key":"sample" }',
  success: function (){
    alert('Thanks for your up vote!');
  }
});

Hopefully, this provides you a hint where to start API calls with JS. In Frameworks like Angular, React, etc there are more powerful ways to make API call with Basic Authentication or Oauth Authentication. Just explore it.

Getting the name / key of a JToken with JSON.net

The default iterator for the JObject is as a dictionary iterating over key/value pairs.

JObject obj = JObject.Parse(response);
foreach (var pair in obj) {
    Console.WriteLine (pair.Key);
}

How can I encode a string to Base64 in Swift?

Swift 5.1, Xcode 11:

public extension String {

    /// Assuming the current string is base64 encoded, this property returns a String
    /// initialized by converting the current string into Unicode characters, encoded to
    /// utf8. If the current string is not base64 encoded, nil is returned instead.
    var base64Decoded: String? {
        guard let base64 = Data(base64Encoded: self) else { return nil }
        let utf8 = String(data: base64, encoding: .utf8)
        return utf8
    }

    /// Returns a base64 representation of the current string, or nil if the
    /// operation fails.
    var base64Encoded: String? {
        let utf8 = self.data(using: .utf8)
        let base64 = utf8?.base64EncodedString()
        return base64
    }

}

Check if a file exists with wildcard in shell script

Here is my answer -

files=(xorg-x11-fonts*)

if [ -e "${files[0]}" ];
then
    printf "BLAH"
fi

Hibernate Criteria for Dates

Why do you use Restrictions.like(...)?

You should use Restrictions.eq(...).

Note you can also use .le, .lt, .ge, .gt on date objects as comparison operators. LIKE operator is not appropriate for this case since LIKE is useful when you want to match results according to partial content of a column. Please see http://www.sql-tutorial.net/SQL-LIKE.asp for the reference.

For example if you have a name column with some people's full name, you can do where name like 'robert %' so that you will return all entries with name starting with 'robert ' (% can replace any character).

In your case you know the full content of the date you're trying to match so you shouldn't use LIKE but equality. I guess Hibernate doesn't give you any exception in this case, but anyway you will probably have the same problem with the Restrictions.eq(...).

Your date object you got with the code:

SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
String myDate = "17-04-2011";
Date date = formatter.parse(myDate);

This date object is equals to the 17-04-2011 at 0h, 0 minutes, 0 seconds and 0 nanoseconds.

This means that your entries in database must have exactly that date. What i mean is that if your database entry has a date "17-April-2011 19:20:23.707000000", then it won't be retrieved because you just ask for that date: "17-April-2011 00:00:00.0000000000".

If you want to retrieve all entries of your database from a given day, you will have to use the following code:

    SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
    String myDate = "17-04-2011";
    // Create date 17-04-2011 - 00h00
    Date minDate = formatter.parse(myDate);
    // Create date 18-04-2011 - 00h00 
    // -> We take the 1st date and add it 1 day in millisecond thanks to a useful and not so known class
    Date maxDate = new Date(minDate.getTime() + TimeUnit.DAYS.toMillis(1));
    Conjunction and = Restrictions.conjunction();
    // The order date must be >= 17-04-2011 - 00h00
    and.add( Restrictions.ge("orderDate", minDate) );
    // And the order date must be < 18-04-2011 - 00h00
    and.add( Restrictions.lt("orderDate", maxDate) ); 

How can I list ALL grants a user received?

The most comprehensive and reliable method I know is still by using DBMS_METADATA:

select dbms_metadata.get_granted_ddl( 'SYSTEM_GRANT', :username ) from dual;
select dbms_metadata.get_granted_ddl( 'OBJECT_GRANT', :username ) from dual;
select dbms_metadata.get_granted_ddl( 'ROLE_GRANT', :username ) from dual;

(username must be written all uppercase)

Interesting answers though.

Why compile Python code?

Beginners assume Python is compiled because of .pyc files. The .pyc file is the compiled bytecode, which is then interpreted. So if you've run your Python code before and have the .pyc file handy, it will run faster the second time, as it doesn't have to re-compile the bytecode

compiler: A compiler is a piece of code that translates the high level language into machine language

Interpreters: Interpreters also convert the high level language into machine readable binary equivalents. Each time when an interpreter gets a high level language code to be executed, it converts the code into an intermediate code before converting it into the machine code. Each part of the code is interpreted and then execute separately in a sequence and an error is found in a part of the code it will stop the interpretation of the code without translating the next set of the codes.

Sources: http://www.toptal.com/python/why-are-there-so-many-pythons http://www.engineersgarage.com/contribution/difference-between-compiler-and-interpreter

How to check for an empty struct?

Keep in mind that with pointers to struct you'd have to dereference the variable and not compare it with a pointer to empty struct:

session := &Session{}
if (Session{}) == *session {
    fmt.Println("session is empty")
}

Check this playground.

Also here you can see that a struct holding a property which is a slice of pointers cannot be compared the same way...

Deserialize Java 8 LocalDateTime with JacksonMapper

This worked for me:

 @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", shape = JsonFormat.Shape.STRING)
 private LocalDateTime startDate;

C# Example of AES256 encryption using System.Security.Cryptography.Aes

Maybe this example listed here can help you out. Statement from the author

about 24 lines of code to encrypt, 23 to decrypt

Due to the fact that the link in the original posting is dead - here the needed code parts (c&p without any change to the original source)

  /*
  Copyright (c) 2010 <a href="http://www.gutgames.com">James Craig</a>
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
  
  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.
  
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.*/
   
  #region Usings
  using System;
  using System.IO;
  using System.Security.Cryptography;
  using System.Text;
  #endregion
   
  namespace Utilities.Encryption
  {
      /// <summary>
      /// Utility class that handles encryption
      /// </summary>
      public static class AESEncryption
      {
          #region Static Functions
   
          /// <summary>
          /// Encrypts a string
          /// </summary>
          /// <param name="PlainText">Text to be encrypted</param>
          /// <param name="Password">Password to encrypt with</param>
          /// <param name="Salt">Salt to encrypt with</param>
          /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
          /// <param name="PasswordIterations">Number of iterations to do</param>
          /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
          /// <param name="KeySize">Can be 128, 192, or 256</param>
          /// <returns>An encrypted string</returns>
          public static string Encrypt(string PlainText, string Password,
              string Salt = "Kosher", string HashAlgorithm = "SHA1",
              int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
              int KeySize = 256)
          {
              if (string.IsNullOrEmpty(PlainText))
                  return "";
              byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
              byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
              byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);
              PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
              byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
              RijndaelManaged SymmetricKey = new RijndaelManaged();
              SymmetricKey.Mode = CipherMode.CBC;
              byte[] CipherTextBytes = null;
              using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
              {
                  using (MemoryStream MemStream = new MemoryStream())
                  {
                      using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
                      {
                          CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
                          CryptoStream.FlushFinalBlock();
                          CipherTextBytes = MemStream.ToArray();
                          MemStream.Close();
                          CryptoStream.Close();
                      }
                  }
              }
              SymmetricKey.Clear();
              return Convert.ToBase64String(CipherTextBytes);
          }
   
          /// <summary>
          /// Decrypts a string
          /// </summary>
          /// <param name="CipherText">Text to be decrypted</param>
          /// <param name="Password">Password to decrypt with</param>
          /// <param name="Salt">Salt to decrypt with</param>
          /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
          /// <param name="PasswordIterations">Number of iterations to do</param>
          /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
          /// <param name="KeySize">Can be 128, 192, or 256</param>
          /// <returns>A decrypted string</returns>
          public static string Decrypt(string CipherText, string Password,
              string Salt = "Kosher", string HashAlgorithm = "SHA1",
              int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
              int KeySize = 256)
          {
              if (string.IsNullOrEmpty(CipherText))
                  return "";
              byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
              byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
              byte[] CipherTextBytes = Convert.FromBase64String(CipherText);
              PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
              byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
              RijndaelManaged SymmetricKey = new RijndaelManaged();
              SymmetricKey.Mode = CipherMode.CBC;
              byte[] PlainTextBytes = new byte[CipherTextBytes.Length];
              int ByteCount = 0;
              using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes))
              {
                  using (MemoryStream MemStream = new MemoryStream(CipherTextBytes))
                  {
                      using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
                      {
   
                          ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
                          MemStream.Close();
                          CryptoStream.Close();
                      }
                  }
              }
              SymmetricKey.Clear();
              return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);
          }
   
          #endregion
      }
  }

Generate insert script for selected records?

If you are using Oracle SQL Developer then it would be

select /*insert*/ * from TABLE_NAME where COLUMN_NAME = 'VALUE';

Run this as a script

How to create cross-domain request?

Many long (and correct) answers here. But usually you won't do these things manually - at least not when you set up your first projects for development (this is where you usually stumble upon these things). If you use koa for the backend: use koa-cors. Install via npm...

npm install --save koa-cors

...and use it in the code:

const cors = require('koa-cors');
const Koa = require('koa');
const app = new Koa();
app.use(cors());

problem solved.

How do I record audio on iPhone with AVAudioRecorder?

Great Thanks to @Massimo Cafaro and Shaybc I was able achieve below tasks

in iOS 8 :

Record audio & Save

Play Saved Recording

1.Add "AVFoundation.framework" to your project

in .h file

2.Add below import statement 'AVFoundation/AVFoundation.h'.

3.Define "AVAudioRecorderDelegate"

4.Create a layout with Record, Play buttons and their action methids

5.Define Recorder and Player etc.

Here is the complete example code which may help you.

ViewController.h

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface ViewController : UIViewController <AVAudioRecorderDelegate>

@property(nonatomic,strong) AVAudioRecorder *recorder;
@property(nonatomic,strong) NSMutableDictionary *recorderSettings;
@property(nonatomic,strong) NSString *recorderFilePath;
@property(nonatomic,strong) AVAudioPlayer *audioPlayer;
@property(nonatomic,strong) NSString *audioFileName;

- (IBAction)startRecording:(id)sender;
- (IBAction)stopRecording:(id)sender;

- (IBAction)startPlaying:(id)sender;
- (IBAction)stopPlaying:(id)sender;

@end

Then do the job in

ViewController.m

#import "ViewController.h"

#define DOCUMENTS_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]

@interface ViewController ()
@end

@implementation ViewController

@synthesize recorder,recorderSettings,recorderFilePath;
@synthesize audioPlayer,audioFileName;


#pragma mark - View Controller Life cycle methods
- (void)viewDidLoad
{
    [super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


#pragma mark - Audio Recording
- (IBAction)startRecording:(id)sender
{
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *err = nil;
    [audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
    if(err)
    {
        NSLog(@"audioSession: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]);
        return;
    }
    [audioSession setActive:YES error:&err];
    err = nil;
    if(err)
    {
        NSLog(@"audioSession: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]);
        return;
    }
    
    recorderSettings = [[NSMutableDictionary alloc] init];
    [recorderSettings setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
    [recorderSettings setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
    [recorderSettings setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
    [recorderSettings setValue :[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
    [recorderSettings setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
    [recorderSettings setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
    
    // Create a new audio file
    audioFileName = @"recordingTestFile";
    recorderFilePath = [NSString stringWithFormat:@"%@/%@.caf", DOCUMENTS_FOLDER, audioFileName] ;
    
    NSURL *url = [NSURL fileURLWithPath:recorderFilePath];
    err = nil;
    recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recorderSettings error:&err];
    if(!recorder){
        NSLog(@"recorder: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]);
        UIAlertView *alert =
        [[UIAlertView alloc] initWithTitle: @"Warning" message: [err localizedDescription] delegate: nil
                         cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    //prepare to record
    [recorder setDelegate:self];
    [recorder prepareToRecord];
    recorder.meteringEnabled = YES;
    
    BOOL audioHWAvailable = audioSession.inputIsAvailable;
    if (! audioHWAvailable) {
        UIAlertView *cantRecordAlert =
        [[UIAlertView alloc] initWithTitle: @"Warning"message: @"Audio input hardware not available"
                                  delegate: nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [cantRecordAlert show];
        return;
    }
    
    // start recording
    [recorder recordForDuration:(NSTimeInterval) 60];//Maximum recording time : 60 seconds default
    NSLog(@"Recroding Started");
}

- (IBAction)stopRecording:(id)sender
{
    [recorder stop];
    NSLog(@"Recording Stopped");
}

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *) aRecorder successfully:(BOOL)flag
{
    NSLog (@"audioRecorderDidFinishRecording:successfully:");
}


#pragma mark - Audio Playing
- (IBAction)startPlaying:(id)sender
{
    NSLog(@"playRecording");
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    
     NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@.caf", DOCUMENTS_FOLDER, audioFileName]];
    NSError *error;
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    audioPlayer.numberOfLoops = 0;
    [audioPlayer play];
    NSLog(@"playing");
}
- (IBAction)stopPlaying:(id)sender
{
    [audioPlayer stop];
    NSLog(@"stopped");
}

@end

enter image description here

How to run a PowerShell script

Type:

powershell -executionpolicy bypass -File .\Test.ps1

NOTE: Here Test.ps1 is the PowerShell script.

Using the grep and cut delimiter command (in bash shell scripting UNIX) - and kind of "reversing" it?

You don't need to change the delimiter to display the right part of the string with cut.

The -f switch of the cut command is the n-TH element separated by your delimiter : :, so you can just type :

 grep puddle2_1557936 | cut -d ":" -f2

Another solutions (adapt it a bit) if you want fun :

Using :

grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                        
/home/rogers.williams/folderz/puddle2

or still with look around

grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                    
/home/rogers.williams/folderz/puddle2

or with :

perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                      
/home/rogers.williams/folderz/puddle2

or using (thanks to glenn jackman)

ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

awk -F'puddle2_1557936:' '{print $2}'  <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or using only :

IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2

or using in a :

js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2

or using in a :

php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2' 
/home/rogers.williams/folderz/puddle2

Python3 integer division

Try this:

a = 1
b = 2
int_div  = a // b

Looking to understand the iOS UIViewController lifecycle

The methods viewWillLayoutSubviews and viewDidLayoutSubviews aren't mentioned in the diagrams, but these are called between viewWillAppear and viewDidAppear. They can be called multiple times.

Django error - matching query does not exist

your line raising the error is here:

comment = Comment.objects.get(pk=comment_id)

you try to access a non-existing comment.

from django.shortcuts import get_object_or_404

comment = get_object_or_404(Comment, pk=comment_id)

Instead of having an error on your server, your user will get a 404 meaning that he tries to access a non existing resource.

Ok up to here I suppose you are aware of this.

Some users (and I'm part of them) let tabs running for long time, if users are authorized to delete data, it may happens. A 404 error may be a better error to handle a deleted resource error than sending an email to the admin.

Other users go to addresses from their history, (same if data have been deleted since it may happens).

Debugging the error "gcc: error: x86_64-linux-gnu-gcc: No such file or directory"

I was getting the error “gcc: error: x86_64-linux-gnu-gcc: No such file or directory” as I was trying to build a simple c-extension module to run in Python. I tried all the things above to no avail, and finally realized that I had an error in my module.c code! So I thought it would be helpful to add that, if you are getting this error message but you have python-dev and everything correctly installed, you should look for issues in your code.

Is it possible to declare a public variable in vba and assign a default value?

Just to offer you a different angle -

I find it's not a good idea to maintain public variables between function calls. Any variables you need to use should be stored in Subs and Functions and passed as parameters. Once the code is done running, you shouldn't expect the VBA Project to maintain the values of any variables.

The reason for this is that there is just a huge slew of things that can inadvertently reset the VBA Project while using the workbook. When this happens, any public variables get reset to 0.

If you need a value to be stored outside of your subs and functions, I highly recommend using a hidden worksheet with named ranges for any information that needs to persist.

how to clear JTable

This is the fastest and easiest way that I have found;

while (tableModel.getRowCount()>0)
          {
             tableModel.removeRow(0);
          }

This clears the table lickety split and leaves it ready for new data.

Limit length of characters in a regular expression?

Is there a way to limit a regex to 100 characters WITH regex?

Your example suggests that you'd like to grab a number from inside the regex and then use this number to place a maximum length on another part that is matched later in the regex. This usually isn't possible in a single pass. Your best bet is to have two separate regular expressions:

  • one to match the maximum length you'd like to use
  • one which uses the previously extracted value to verify that its own match does not exceed the specified length

If you just want to limit the number of characters matched by an expression, most regular expressions support bounds by using braces. For instance,

\d{3}-\d{3}-\d{4}

will match (US) phone numbers: exactly three digits, then a hyphen, then exactly three digits, then another hyphen, then exactly four digits.

Likewise, you can set upper or lower limits:

\d{5,10}

means "at least 5, but not more than 10 digits".


Update: The OP clarified that he's trying to limit the value, not the length. My new answer is don't use regular expressions for that. Extract the value, then compare it against the maximum you extracted from the size parameter. It's much less error-prone.

make: Nothing to be done for `all'

Make is behaving correctly. hello already exists and is not older than the .c files, and therefore there is no more work to be done. There are four scenarios in which make will need to (re)build:

  • If you modify one of your .c files, then it will be newer than hello, and then it will have to rebuild when you run make.
  • If you delete hello, then it will obviously have to rebuild it
  • You can force make to rebuild everything with the -B option. make -B all
  • make clean all will delete hello and require a rebuild. (I suggest you look at @Mat's comment about rm -f *.o hello

Where is Maven's settings.xml located on Mac OS?

After I have downloaded the binary from apache site I, have placed the extracted folder in /Library
So now the location of the settings.xml file is in:

/Library/apache_maven_3.6.3/conf

How to know user has clicked "X" or the "Close" button?

Assuming you're asking for WinForms, you may use the FormClosing() event. The event FormClosing() is triggered any time a form is to get closed.

To detect if the user clicked either X or your CloseButton, you may get it through the sender object. Try to cast sender as a Button control, and verify perhaps for its name "CloseButton", for instance.

private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
    if (string.Equals((sender as Button).Name, @"CloseButton"))
        // Do something proper to CloseButton.
    else
        // Then assume that X has been clicked and act accordingly.
}

Otherwise, I have never ever needed to differentiate whether X or CloseButton was clicked, as I wanted to perform something specific on the FormClosing event, like closing all MdiChildren before closing the MDIContainerForm, or event checking for unsaved changes. Under these circumstances, we don't need, according to me, to differentiate from either buttons.

Closing by ALT+F4 will also trigger the FormClosing() event, as it sends a message to the Form that says to close. You may cancel the event by setting the

FormClosingEventArgs.Cancel = true. 

In our example, this would translate to be

e.Cancel = true.

Notice the difference between the FormClosing() and the FormClosed() events.

FormClosing occurs when the form received the message to be closed, and verify whether it has something to do before it is closed.

FormClosed occurs when the form is actually closed, so after it is closed.

Does this help?

Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App

You can also do this in ASP.NET Core 2 by defining the connection string in your appSettings.json file. Then in your Startup.cs you specify which connection string to use.

appSettings.json

{
    "connectionStrings": {
        "YourDBConnectionString": "Server=(localdb)\\mssqllocaldb;Database=YourDB;Trusted_Connection=True"
    }
}

Startup.cs

public static IConfiguration Configuration { get; private set;}

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}
var connectionString = Configuration["connectionStrings:YourDBConnectionString"];
services.AddDbContext<YourDbContext>(x => x.UseSqlServer(connectionString));

Eclipse CDT: Symbol 'cout' could not be resolved

I am using Ubuntu 12.04 / Eclipse 4.2.1 / CDT 8.1.1 and I used to have the same problem for quite some time: importing a C++ project from SVN would cause these annoying "Unresolved inclusion" errors and I would instead have to create a new project and copy the files in there as a work-around (still partial, since SVN functionality would not be there!).

At last, I have just found a simple, satisfactory solution:

  • Go to Project -> Properties -> C/C++ General -> Preprocessor Include Paths, Macros etc. -> Providers and check Enable language settings providers for this project.

  • Restart Eclipse.

Hopefully that already does the trick.

How to call a method in another class of the same package?

By calling method

public class a 
{
    void sum(int i,int k)
    {
        System.out.println("THe sum of the number="+(i+k));
    }
}
class b
{
    public static void main(String[] args)
    {
        a vc=new a();
        vc.sum(10 , 20);
    }
}

Python: How to ignore an exception and proceed?

Try this:

try:
    blah()
except:
    pass

recursion versus iteration

Yes, as said by Thanakron Tandavas,

Recursion is good when you are solving a problem that can be solved by divide and conquer technique.

For example: Towers of Hanoi

  1. N rings in increasing size
  2. 3 poles
  3. Rings start stacked on pole 1. Goal is to move rings so that they are stacked on pole 3 ...But
    • Can only move one ring at a time.
    • Can’t put larger ring on top of smaller.
  4. Iterative solution is “powerful yet ugly”; recursive solution is “elegant”.

How to consume a webApi from asp.net Web API to store result in database?

public class EmployeeApiController : ApiController
{
    private readonly IEmployee _employeeRepositary;

    public EmployeeApiController()
    {
        _employeeRepositary = new EmployeeRepositary();
    }

    public async Task<HttpResponseMessage> Create(EmployeeModel Employee)
    {
        var returnStatus = await _employeeRepositary.Create(Employee);
        return Request.CreateResponse(HttpStatusCode.OK, returnStatus);
    }
} 

Persistance

public async Task<ResponseStatusViewModel> Create(EmployeeModel Employee)
{    
    var responseStatusViewModel = new ResponseStatusViewModel();
    var connection = new SqlConnection(EmployeeConfig.EmployeeConnectionString);
                var command = new SqlCommand("usp_CreateEmployee", connection);
                command.CommandType = CommandType.StoredProcedure;
                var pEmployeeName = new SqlParameter("@EmployeeName", SqlDbType.VarChar, 50);
                pEmployeeName.Value = Employee.EmployeeName;
                command.Parameters.Add(pEmployeeName);


                try
                {
                    await connection.OpenAsync();
                    await command.ExecuteNonQueryAsync();

                    command.Dispose();
                    connection.Dispose();

                }
                catch (Exception ex)
                {

                    throw ex;
                }
                return responseStatusViewModel;
            }

Repository

Task<ResponseStatusViewModel> Create(EmployeeModel Employee);

public class EmployeeConfig
{
    public static string EmployeeConnectionString;
    private const string EmployeeConnectionStringKey = "EmployeeConnectionString";
    public static void InitializeConfig()
    {
        EmployeeConnectionString = GetConnectionStringValue(EmployeeConnectionStringKey);
    }

    private static string GetConnectionStringValue(string connectionStringName)
    {
        return Convert.ToString(ConfigurationManager.ConnectionStrings[connectionStringName]);
    }
}

JQuery create a form and add elements to it programmatically

var form = $("<form/>", 
                 { action:'/myaction' }
            );
form.append( 
    $("<input>", 
         { type:'text', 
           placeholder:'Keywords', 
           name:'keyword', 
           style:'width:65%' }
     )
);

form.append( 
     $("<input>", 
          { type:'submit', 
            value:'Search', 
            style:'width:30%' }
       )
);

$("#someDivId").append(form);

Assign output of os.system to a variable and prevent it from being displayed on the screen

For python 3.5+ it is recommended that you use the run function from the subprocess module. This returns a CompletedProcess object, from which you can easily obtain the output as well as return code. Since you are only interested in the output, you can write a utility wrapper like this.

from subprocess import PIPE, run

def out(command):
    result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True, shell=True)
    return result.stdout

my_output = out("echo hello world")
# Or
my_output = out(["echo", "hello world"])

Can I update a component's props in React.js?

Much has changed with hooks, e.g. componentWillReceiveProps turned into useEffect+useRef (as shown in this other SO answer), but Props are still Read-Only, so only the caller method should update it.

INNER JOIN ON vs WHERE clause

They have a different human-readable meaning.

However, depending on the query optimizer, they may have the same meaning to the machine.

You should always code to be readable.

That is to say, if this is a built-in relationship, use the explicit join. if you are matching on weakly related data, use the where clause.

What is trunk, branch and tag in Subversion?

A great place to start learning about Subversion is http://svnbook.red-bean.com/.

As far as Visual Studio tools are concerned, I like AnkhSVN, but I haven't tried the VisualSVN plugin yet.

VisualSVN does rely on TortoiseSVN, but TortoiseSVN is also a nice complement to Ankh IMHO.

Is it better to use "is" or "==" for number comparison in Python?

Use ==.

Sometimes, on some python implementations, by coincidence, integers from -5 to 256 will work with is (in CPython implementations for instance). But don't rely on this or use it in real programs.

Android: how to make an activity return results to the activity which calls it?

UPDATE Feb. 2021

As in Activity v1.2.0 and Fragment v1.3.0, the new Activity Result APIs have been introduced.

The Activity Result APIs provide components for registering for a result, launching the result, and handling the result once it is dispatched by the system.

So there is no need of using startActivityForResult and onActivityResult anymore.

In order to use the new API, you need to create an ActivityResultLauncher in your origin Activity, specifying the callback that will be run when the destination Activity finishes and returns the desired data:

private val intentLauncher =
    registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->

        if (result.resultCode == Activity.RESULT_OK) {
            result.data?.getStringExtra("streetkey")
            result.data?.getStringExtra("citykey")
            result.data?.getStringExtra("homekey")
        }
    }

and then, launching your intent whenever you need to:

intentLauncher.launch(Intent(this, YourActivity::class.java))

And to return data from the destination Activity, you just have to add an intent with the values to return to the setResult() method:

val data = Intent()
data.putExtra("streetkey", "streetname")
data.putExtra("citykey", "cityname")
data.putExtra("homekey", "homename")

setResult(Activity.RESULT_OK, data)
finish()

For any additional information, please refer to Android Documentation

Producer/Consumer threads using a Queue

OK, as others note, the best thing to do is to use java.util.concurrent package. I highly recommend "Java Concurrency in Practice". It's a great book that covers almost everything you need to know.

As for your particular implementation, as I noted in the comments, don't start Threads from Constructors -- it can be unsafe.

Leaving that aside, the second implementation seem better. You don't want to put queues in static fields. You are probably just loosing flexibility for nothing.

If you want to go ahead with your own implementation (for learning purpose I guess?), supply a start() method at least. You should construct the object (you can instantiate the Thread object), and then call start() to start the thread.

Edit: ExecutorService have their own queue so this can be confusing.. Here's something to get you started.

public class Main {
    public static void main(String[] args) {
        //The numbers are just silly tune parameters. Refer to the API.
        //The important thing is, we are passing a bounded queue.
        ExecutorService consumer = new ThreadPoolExecutor(1,4,30,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(100));

        //No need to bound the queue for this executor.
        //Use utility method instead of the complicated Constructor.
        ExecutorService producer = Executors.newSingleThreadExecutor();

        Runnable produce = new Produce(consumer);
        producer.submit(produce);   
    }
}

class Produce implements Runnable {
    private final ExecutorService consumer;

    public Produce(ExecutorService consumer) {
        this.consumer = consumer;
    }

    @Override
    public void run() {
        Pancake cake = Pan.cook();
        Runnable consume = new Consume(cake);
        consumer.submit(consume);
    }
}

class Consume implements Runnable {
    private final Pancake cake;

    public Consume(Pancake cake){
        this.cake = cake;
    }

    @Override
    public void run() {
        cake.eat();
    }
}

Further EDIT: For producer, instead of while(true), you can do something like:

@Override
public void run(){
    while(!Thread.currentThread().isInterrupted()){
        //do stuff
    }
}

This way you can shutdown the executor by calling .shutdownNow(). If you'd use while(true), it won't shutdown.

Also note that the Producer is still vulnerable to RuntimeExceptions (i.e. one RuntimeException will halt the processing)

Get the full URL in PHP

I've made this class to handle my URI's

<?php
/** -------------------------------------------------------------------------------------------------------------------
 * URI CLASS
 * URI management class
 *
 * @author Sandu Liviu Catalin
 * @email slc(dot)universe(at)gmail(dot)com
 * @license Public Domain
**/
abstract class _URI
{
    /** ---------------------------------------------------------------------------------------------------------------
     *  - BASE PARAMETERS
     * $_Script_Hidden - Hide the script name from the returned URI
     * $_Public_Path - Location where public resources are stored
     * $_Public_Relative - Return the relative path version of public location
     * $_Public_Skin - Is the skin directory located in the public directory
     * $_Skin_Path - Location where skins are stored
     * $_Skin_Relative - Return the relative path version of skin location
     * $_Skin_Default - Use this as the default system skin
     * $_Fallback_Base - Use this base URL if you can't extract the current URL
     * $_Fallback_Scheme - Use this scheme if you can't find it automatically
     * $_Fallback_User - Use this user name if you can't find it automatically
     * $_Fallback_Passwd - Use this password if you can't find it automatically
     * $_Fallback_Host - Use this host if you can't find it automatically
     * $_Fallback_Port - Use this port number if you can't find it automatically
     * $_Fallback_Script - Use this script name if you can't find it automatically
     * $_Separator_Scheme - Use this to separate the scheme from the rest of the url
     * $_Separator_Credentials - Use this to separate the user name from the password
     * $_Separator_Auth - Use this to separate the user name and password from host
     * $_Separator_Port - Use this to separate the port number from host
     * $_Separator_Query - Use this to separate the query data from base URL
     * $_Separator_Fragment - Use this to separate the fragment data from query data
    */
    protected static $_Script_Hidden;
    protected static $_Public_Path;
    protected static $_Public_Relative;
    protected static $_Public_Skin;
    protected static $_Skin_Path;
    protected static $_Skin_Relative;
    protected static $_Skin_Default;
    protected static $_Fallback_Base;
    protected static $_Fallback_Scheme;
    protected static $_Fallback_User;
    protected static $_Fallback_Passwd;
    protected static $_Fallback_Host;
    protected static $_Fallback_Port;
    protected static $_Fallback_Script;
    protected static $_Separator_Scheme;
    protected static $_Separator_Credentials;
    protected static $_Separator_Auth;
    protected static $_Separator_Port;
    protected static $_Separator_Query;
    protected static $_Separator_Fragment;

    /** ----------------------------------------------------------------------------------------------------------------
     * CACHED BASES
     * Precompiled common URLs for quick retrieval
    */
    protected static $Base_Host;
    protected static $Base_App;
    protected static $Base_Script;
    protected static $Base_Current;
    protected static $Base_Public;
    protected static $Base_Skin;

    /** ----------------------------------------------------------------------------------------------------------------
     * DATA CONTAINERS
     * Raw URI segments saved from extracted data
    */
    protected static $__Segments = array(
        'SCHEME' => '',
        'USER' => '',
        'PASSWD' => '',
        'HOST' => '',
        'PORT' => '',
        'PATH' => '',
        'SCRIPT' => '',
        'INFO' => '',
        'QUERY' => '',
    );

    /** ----------------------------------------------------------------------------------------------------------------
     * PARSER KEYWORDS
     * URI data asigned to specific keywords.
    */
    protected static $__Parsers;

    /** ----------------------------------------------------------------------------------------------------------------
     * CLASS INITIALIZER
     * Initialize the class
     *
     * @access public
     * @param $Params [array] - An associative array of supported parrameters
     * @return void
    */
    public static function __Init($Params=array())
    {
        // Configure the class
        self::$_Script_Hidden = (isset($Params['Script_Hidden'])) ? $Params['Script_Hidden'] : FALSE;
        self::$_Public_Path = (isset($Params['Public_Path'])) ? $Params['Public_Path'] : 'public';
        self::$_Public_Relative = (isset($Params['Public_Relative'])) ? $Params['Public_Relative'] : TRUE;
        self::$_Public_Skin = (isset($Params['Public_Skin'])) ? $Params['Public_Skin'] : TRUE;
        self::$_Skin_Path = (isset($Params['Skin_Path'])) ? $Params['Skin_Path'] : 'themes';
        self::$_Skin_Relative = (isset($Params['Skin_Relative'])) ? $Params['Skin_Relative'] : TRUE;
        self::$_Skin_Default = (isset($Params['Skin_Default'])) ? $Params['Skin_Default'] : 'default';
        self::$_Fallback_Base = (isset($Params['Fallback_Base'])) ? $Params['Fallback_Base'] : '127.0.0.1';
        self::$_Fallback_Scheme = (isset($Params['Fallback_Scheme'])) ? $Params['Fallback_Scheme'] : 'http';
        self::$_Fallback_User = (isset($Params['Fallback_User'])) ? $Params['Fallback_User'] : '';
        self::$_Fallback_Passwd = (isset($Params['Fallback_Passwd'])) ? $Params['Fallback_Passwd'] : '';
        self::$_Fallback_Host = (isset($Params['Fallback_Host'])) ? $Params['Fallback_Host'] : '127.0.0.1';
        self::$_Fallback_Port = (isset($Params['Fallback_Port'])) ? $Params['Fallback_Port'] : '';
        self::$_Fallback_Script = (isset($Params['Fallback_Script'])) ? $Params['Fallback_Script'] : 'index.php';
        self::$_Separator_Scheme = (isset($Params['Separator_Scheme'])) ? $Params['Separator_Scheme'] : '://';
        self::$_Separator_Credentials = (isset($Params['Separator_Credentials'])) ? $Params['Separator_Credentials'] : ':';
        self::$_Separator_Auth = (isset($Params['Separator_Auth'])) ? $Params['Separator_Auth'] : '@';
        self::$_Separator_Port = (isset($Params['Separator_Port'])) ? $Params['Separator_Port'] : ':';
        self::$_Separator_Query = (isset($Params['Separator_Query'])) ? $Params['Separator_Query'] : '?';
        self::$_Separator_Fragment = (isset($Params['Separator_Fragment'])) ? $Params['Separator_Fragment'] : '#';
        // Do some clean up of the configurations
        self::$_Public_Path = implode('/', explode('/', str_replace(array('/', '\\'), '/', self::$_Public_Path)));
        self::$_Skin_Path = implode('/', explode('/', str_replace(array('/', '\\'), '/', self::$_Skin_Path)));
        // Extract the URL information
        self::Extract();
        // Precompile common bases
        self::$Base_Host = self::Compile('HOST');
        self::$Base_App = self::Compile('PATH');
        self::$Base_Script = self::$Base_App.(self::$_Script_Hidden ? '' : '/'.self::$__Segments['SCRIPT']);
        self::$Base_Current = self::$Base_Script.(empty(self::$__Segments['INFO']) ? '' : '/'.self::$__Segments['INFO']);
        self::$Base_Public = self::$_Public_Relative ? self::$_Public_Path : self::$Base_App.'/'.self::$_Public_Path;
        self::$Base_Skin = self::$_Skin_Relative ? self::$_Skin_Path : self::$Base_Public.'/'.self::$_Skin_Path;
        self::$Base_Skin .= '/'.self::$_Skin_Default;
        // Setup the parsers
        self::$__Parsers['SR_Key'][] = '%HostBase%';
        self::$__Parsers['SR_Data'][] =& self::$Base_Host;
        self::$__Parsers['SR_Key'][] = '%AppBase%';
        self::$__Parsers['SR_Data'][] =& self::$Base_App;
        self::$__Parsers['SR_Key'][] = '%ScriptBase%';
        self::$__Parsers['SR_Data'][] =& self::$Base_Script;
        self::$__Parsers['SR_Key'][] = '%CurrentBase%';
        self::$__Parsers['SR_Data'][] =& self::$Base_Current;
        self::$__Parsers['SR_Key'][] = '%PublicBase%';
        self::$__Parsers['SR_Data'][] =& self::$Base_Public;
        self::$__Parsers['SR_Key'][] = '%SkinBase%';
        self::$__Parsers['SR_Data'][] =& self::$Base_Skin;
        self::$__Parsers['SR_Data'][] =& self::$__Segments['SCHEME'];
        self::$__Parsers['SR_Key'][] = '%UserSegment%';
        self::$__Parsers['SR_Data'][] =& self::$__Segments['USER'];
        self::$__Parsers['SR_Key'][] = '%PasswdSegment%';
        self::$__Parsers['SR_Data'][] =& self::$__Segments['PASSWD'];
        self::$__Parsers['SR_Key'][] = '%HostSegment%';
        self::$__Parsers['SR_Data'][] =& self::$__Segments['HOST'];
        self::$__Parsers['SR_Key'][] = '%PortSegment%';
        self::$__Parsers['SR_Data'][] =& self::$__Segments['PORT'];
        self::$__Parsers['SR_Key'][] = '%PathSegment%';
        self::$__Parsers['SR_Data'][] =& self::$__Segments['PATH'];
        self::$__Parsers['SR_Key'][] = '%ScriptSegment%';
        self::$__Parsers['SR_Data'][] =& self::$__Segments['SCRIPT'];
        self::$__Parsers['SR_Key'][] = '%InfoSegment%';
        self::$__Parsers['SR_Data'][] =& self::$__Segments['INFO'];
        self::$__Parsers['SR_Key'][] = '%QuerySegment%';
        self::$__Parsers['SR_Data'][] =& self::$__Segments['QUERY'];
        self::$__Parsers['SR_Key'][] = '%PublicPath%';
        self::$__Parsers['SR_Data'][] =& self::$_Public_Path;
        self::$__Parsers['SR_Key'][] = '%SkinPath%';
        self::$__Parsers['SR_Data'][] =& self::$_Skin_Path;
        self::$__Parsers['SR_Key'][] = '%DefaultSkin%';
        self::$__Parsers['SR_Data'][] =& self::$_Skin_Default;
        // Everything OK so far
    }

    /** ----------------------------------------------------------------------------------------------------------------
     * URI EXTRACTOR
     * Try every posibility to obtain all the segments of the current URL
     *
     * @access public
     * @return array
    */
    public static function Extract()
    {
        // No point in executing twice to get the same result
        if (!empty(self::$__Segments['HOST'])) return self::$__Segments;
        // Let's try to have a falback for most basic data
        $Script_URI = (isset($_SERVER['SCRIPT_URI'])) ? parse_url($_SERVER['SCRIPT_URI']) : array();
        if (empty($Script_URI)) {
            $Script_URI = parse_url(self::$_Fallback_Base);
        }
        // Try ever possibility to obtain the data that surounds the script name
        if (isset($_SERVER['PHP_SELF'])) {
            $Script_Path = $_SERVER['PHP_SELF'];
        } elseif (isset($_SERVER['REQUEST_URI'])) {
            $Script_Path = preg_replace('/\?.*/', '', $_SERVER['REQUEST_URI']);
        } elseif (isset($Script_URI['path'])) {
            $Script_Path = $Script_URI['path'];
        } elseif (isset($_SERVER['SCRIPT_NAME'])) {
            $Script_Path = isset($_SERVER['SCRIPT_NAME']).(isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '');
        } elseif (isset($_SERVER['DOCUMENT_ROOT']) && isset($_SERVER['SCRIPT_FILENAME'])) {
            $Script_Path = substr($_SERVER['SCRIPT_FILENAME'], strlen($_SERVER['DOCUMENT_ROOT']),
                                    (strlen($_SERVER['SCRIPT_FILENAME'])-strlen($_SERVER['DOCUMENT_ROOT'])));
            $Script_Path .= (isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '');
        } else {
            $Script_Path = '';
        }
        // Explode the previously extracted data
        if (strlen($Script_Path) > 0) {
            $Script_Path = preg_split('/[\/]/', $Script_Path, -1, PREG_SPLIT_NO_EMPTY);
        } else {
            $Script_Path = array();
        }
        // Try to obtain the name of the currently executed script
        if (isset($_SERVER['SCRIPT_FILENAME'])) {
            $Script_Name = basename($_SERVER['SCRIPT_FILENAME']);
        } elseif (isset($_SERVER['SCRIPT_NAME'])) {
            $Script_Name = basename($_SERVER['SCRIPT_NAME']);
        } else {
            $Script_Name = self::$_Fallback_Script;
        }
        // Try to find the name of the script in the script path
        $Script_Split = (is_string($Script_Name)) ? array_search($Script_Name, $Script_Path, TRUE) : NULL;
        // Try to obtain the request scheme
        if (isset($_SERVER['REQUEST_SCHEME'])) {
            self::$__Segments['SCHEME'] = $_SERVER['REQUEST_SCHEME'];
        } elseif (isset($_SERVER['SERVER_PROTOCOL'])) {
            self::$__Segments['SCHEME'] = strtolower($_SERVER['SERVER_PROTOCOL']);
            self::$__Segments['SCHEME'] = substr(self::$__Segments['SCHEME'], 0, strpos(self::$__Segments['SCHEME'], '/'));
            self::$__Segments['SCHEME'] .= (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 's' : '';
        } elseif (isset($Script_URI['scheme'])) {
            self::$__Segments['SCHEME'] = $Script_URI['scheme'];
        } else {
            self::$__Segments['SCHEME'] = self::$_Fallback_Scheme;
        }
        // Try to obtain the user name (if one was used)
        if (isset($_SERVER['PHP_AUTH_USER'])) {
            self::$__Segments['USER'] = $_SERVER['PHP_AUTH_USER'];
        } elseif (isset($Script_URI['user'])) {
            self::$__Segments['USER'] = $Script_URI['user'];
        } else {
            self::$__Segments['USER'] = self::$_Fallback_User;
        }
        // Try to obtain the user password (if one was used)
        if (isset($_SERVER['PHP_AUTH_PW'])) {
            self::$__Segments['PASSWD'] = $_SERVER['PHP_AUTH_PW'];
        } elseif (isset($Script_URI['pass'])) {
            self::$__Segments['PASSWD'] = $Script_URI['pass'];
        } else {
            self::$__Segments['PASSWD'] = self::$_Fallback_Passwd;
        }
        // Try to obtai the host name
        if (isset($_SERVER['SERVER_NAME'])) {
            self::$__Segments['HOST'] = $_SERVER['SERVER_NAME'];
        } elseif (isset($_SERVER['HTTP_HOST'])) {
            self::$__Segments['HOST'] = $_SERVER['HTTP_HOST'];
        } elseif (isset($Script_URI['host'])) {
            self::$__Segments['HOST'] = $Script_URI['host'];
        } else {
            self::$__Segments['HOST'] = self::$_Fallback_Host;
        }
        // Try to obtain the port number (if one was used)
        if (isset($Script_URI['port'])) {
            self::$__Segments['PORT'] = $Script_URI['port'];
        } else {
            self::$__Segments['PORT'] = self::$_Fallback_Port;
        }
        // Try to obtain the path to the script
        if (is_numeric($Script_Split)) {
            self::$__Segments['PATH'] = implode('/', array_slice($Script_Path, 0, $Script_Split, TRUE));
        } else {
            self::$__Segments['PATH'] = '';
        }
        // Try to obtain the Script name
        if (is_string($Script_Name)) {
            self::$__Segments['SCRIPT'] = $Script_Name;
        } else {
            self::$__Segments['SCRIPT'] = '';
        }
        // Try to obtain any passed info
        if (isset($_SERVER['PATH_INFO'])) {
            self::$__Segments['INFO'] = implode('/', preg_split('/[\/]/', $_SERVER['PATH_INFO'], -1, PREG_SPLIT_NO_EMPTY));
        } elseif (is_numeric($Script_Split)) {
            self::$__Segments['INFO'] = implode('/', array_slice($Script_Path, $Script_Split+1));
        } else {
            self::$__Segments['INFO'] = '';
        }
        // -----Pending Feature: Try to also extract the query string

        // Return the extracted URI segments
        return self::$__Segments;

    }

    /** ----------------------------------------------------------------------------------------------------------------
     * URI COMPILER
     * Compile raw URI segments into a usable URL
     *
     * @access public
     * @param $Until [string] - The name of the segment where compilation should stop and return
     * @return string
    */
    public static function Compile($Until=NULL)
    {
        $URI= '';
        $Until = (is_string($Until)) ? strtoupper($Until) : $Until;
        if ($Until === 'SCHEME') {
            return $URI .= (self::$__Segments['SCHEME'] !== '') ? self::$__Segments['SCHEME'].self::$_Separator_Scheme : '';
        } else {
            $URI .= (self::$__Segments['SCHEME'] !== '') ? self::$__Segments['SCHEME'].self::$_Separator_Scheme : '';
        }
        if ($Until === 'USER') {
            return $URI .= (self::$__Segments['USER'] !== '') ? self::$__Segments['USER'].self::$_Separator_Credentials : '';
        } else {
            $URI .= (self::$__Segments['USER'] !== '') ? self::$__Segments['USER'] : '';
        }
        $URI .= (self::$__Segments['USER'] !== '' || self::$__Segments['PASSWD'] !== '') ? self::$_Separator_Credentials : '';
        if ($Until === 'PASSWD') {
            return $URI .= (self::$__Segments['PASSWD'] !== '') ? self::$__Segments['PASSWD'].self::$_Separator_Auth : '';
        } else {
            $URI .= (self::$__Segments['PASSWD'] !== '') ? self::$__Segments['PASSWD'] : '';
        }
        $URI .= (self::$__Segments['USER'] !== '' || self::$__Segments['PASSWD'] !== '') ? self::$_Separator_Auth : '';
        if ($Until === 'HOST') {
            return $URI .= (self::$__Segments['HOST'] !== '') ? self::$__Segments['HOST'] : '';
        } else {
            $URI .= (self::$__Segments['HOST'] !== '') ? self::$__Segments['HOST'] : '';
        }
        if ($Until === 'PORT') {
            return $URI .= (self::$__Segments['PORT'] !== '') ? self::$_Separator_Port.self::$__Segments['PORT'] : '';
        } else {
            $URI .= (self::$__Segments['PORT'] !== '') ? self::$_Separator_Port.self::$__Segments['PORT'] : '';
        }
        if ($Until === 'PATH') {
            return $URI .= (self::$__Segments['PATH'] !== '') ? '/'.self::$__Segments['PATH'] : '';
        } else {
            $URI .= (self::$__Segments['PATH'] !== '') ? '/'.self::$__Segments['PATH'] : '';
        }
        if ($Until === 'SCRIPT') {
            return $URI .= (self::$__Segments['SCRIPT'] !== '') ? '/'.self::$__Segments['SCRIPT'] : '';
        } else {
            $URI .= (self::$__Segments['SCRIPT'] !== '') ? '/'.self::$__Segments['SCRIPT'] : '';
        }
        if ($Until === 'INFO') {
            return $URI .= (self::$__Segments['INFO'] !== '') ? '/'.self::$__Segments['INFO'] : '';
        } else {
            $URI .= (self::$__Segments['INFO'] !== '') ? '/'.self::$__Segments['INFO'] : '';
        }
        return $URI;
    }

    /** ----------------------------------------------------------------------------------------------------------------
     * SEGMENT RETRIEVER
     * Return a specific URI segment
     *
     * @access public
     * @param $Name [string] - The name of the segment you want
     * @return string (on success) bool (on failure)
    */
    public static function Segment($Name)
    {
        if (isset(self::$__Segments[$Name])) {
            return self::$__Segments[$Name];
        } return FALSE;
    }

    /** ----------------------------------------------------------------------------------------------------------------
     * BASE RETRIEVER
     * Return a specific precompiled base
     *
     * @access public
     * @param $Name [string] - The name of the base you want
     * @return mixed (on success) boolean (on failure)
    */
    public static function Base($Name)
    {
        switch ($Name) {
            case 'Host':
            case 'Domain':
                return self::$Base_Host;
            break;
            case 'App':
            case 'Base':
                return self::$Base_App;
            break;
            case 'Script':
            case 'Index':
                return self::$Base_Script;
            break;
            case 'Current':
            case 'This':
                return self::$Base_Current;
            break;
            case 'Public':
            case 'Web':
                return self::$Base_Public;
            break;
            case 'Skin':
            case 'Theme':
                return self::$Base_Skin;
            break;
            case 'All':
                return array(
                    'Host'=>self::$Base_Host,
                    'App'=>self::$Base_App,
                    'Script'=>self::$Base_Script,
                    'Current'=>self::$Base_Current,
                    'Public'=>self::$Base_Public,
                    'Skin'=>self::$Base_Skin,
                );
            break;
        } return FALSE;
    }

    /** ----------------------------------------------------------------------------------------------------------------
     * STRING PARSER
     * Replace known keywords in the specified string with current URI data
     *
     * @access public
     * @param $String [string] - A string that you want to parse
     * @return void
    */
    public static function Parse($String)
    {
        if (is_string($String)) {
            return str_replace(self::$__Parsers['SR_Key'], self::$__Parsers['SR_Data'], $String);
        } elseif (is_array($String)) {
            foreach ($String as $K => $V) {
                $Parsed[$K] = self::$replace($V);
            } return $Parsed;
        } return FALSE;
    }
}
if (isset($_URI_Params)) {
    _URI::__Init($_URI_Params);
} else {
    _URI::__Init();
} 

Of course you have to adapt it to your needs and system !?!

<?php
// Change a few parameters before loading the class.
$_URI_Params = array(
    'Public_Relative' => FALSE,
    'Skin_Relative' => FALSE,
    'Skin_Default' => 'classic',
    // etc.
);
// Get the URI class
require('uri.php');
// Output all extracted URI segments
echo '<pre>';
var_dump(_URI::Extract());
echo '</pre>';
// Output extracted segments individually
echo 'Scheme: '._URI::Segment('SCHEME').'<br/>';
echo 'User: '._URI::Segment('USER').'<br/>';
echo 'Password: '._URI::Segment('PASSWD').'<br/>';
echo 'Host: '._URI::Segment('HOST').'<br/>';
echo 'Port: '._URI::Segment('PORT').'<br/>';
echo 'Path: '._URI::Segment('PATH').'<br/>';
echo 'Script: '._URI::Segment('SCRIPT').'<br/>';
echo 'Info: '._URI::Segment('INFO').'<br/>';
// Compile extracted segments into a usable URL
echo '<br/>';
echo 'Full Compiled URI: '._URI::Compile().'<br/>';
echo '<br/>';
// Output precompiled common bases for a faster result and better performance
echo 'Host Base: '._URI::Base('Host').'<br/>';
echo 'Application Base: '._URI::Base('App').'<br/>';
echo 'Running Script: '._URI::Base('Script').'<br/>';
echo 'Current URI Base: '._URI::Base('Current').'<br/>';
echo 'Public Folder Base: '._URI::Base('Public').'<br/>';
echo 'Skin Folder Base: '._URI::Base('Skin').'<br/>';
// Get all the precompiled bases in an associative array
echo '<pre>';
var_dump(_URI::Base('All'));
echo '</pre>';
// Parse an example string and replace known keys with actual URI data.
echo _URI::Parse('This is my current domain: %HostBase%
And the current application is here: %AppBase%
I load my skins form: %SkinBase%
etc.
'); 

It still needs to be perfected but it's a god solution for a centralized URI system :D

Can I specify maxlength in css?

No. This needs to be done in the HTML. You could set the value with Javascript if you need to though.

Calling an API from SQL Server stored procedure

I worked so much, I hope my effort might help you out.

Just paste this into your SSMS and press F5:

Declare @Object as Int;
DECLARE @hr  int
Declare @json as table(Json_Table nvarchar(max))

Exec @hr=sp_OACreate 'MSXML2.ServerXMLHTTP.6.0', @Object OUT;
IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object
Exec @hr=sp_OAMethod @Object, 'open', NULL, 'get',
                 'http://overpass-api.de/api/interpreter?data=[out:json];area[name=%22Auckland%22]-%3E.a;(node(area.a)[amenity=cinema];way(area.a)[amenity=cinema];rel(area.a)[amenity=cinema];);out;', --Your Web Service Url (invoked)
                 'false'
IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object
Exec @hr=sp_OAMethod @Object, 'send'
IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object
Exec @hr=sp_OAMethod @Object, 'responseText', @json OUTPUT
IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object

INSERT into @json (Json_Table) exec sp_OAGetProperty @Object, 'responseText'
-- select the JSON string
select * from @json
-- Parse the JSON string
SELECT * FROM OPENJSON((select * from @json), N'$.elements')
WITH (   
      [type] nvarchar(max) N'$.type'   ,
      [id]   nvarchar(max) N'$.id',
      [lat]   nvarchar(max) N'$.lat',
      [lon]   nvarchar(max) N'$.lon',
      [amenity]   nvarchar(max) N'$.tags.amenity',
      [name]   nvarchar(max) N'$.tags.name'     
)
EXEC sp_OADestroy @Object

This query will give you 3 results:

1. Catch the error in case something goes wrong (don't panic, it will always show you an error above 4000 characters because NVARCHAR(MAX) can only store till 4000 characters)

2. Put the JSON into a string (which is what we want)

3. BONUS: parse the JSON and nicely store the data into a table (how cool is that?)

enter image description here

How to configure socket connect timeout

Check this out on MSDN. It does not appear that you can do this with the implemented properties in the Socket class.

The poster on MSDN actually solved his problem using threading. He had a main thread which called out to other threads which run the connection code for a couple seconds and then check the Connected property of the socket:

I created another method wich actually connected the socket ... had the main thread sleep for 2 seconds and then check on the connecting method (wich is run in a separate thread) if the socket was connected good otherwise throw an exception "Timed out " and that;s all. Thanks again for the repleies.

What are you trying to do, and why can't it wait for 15-30 seconds before timing out?

Redirect form to different URL based on select option element

This can be archived by adding code on the onchange event of the select control.

For Example:

<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
    <option value="http://gmail.com">Gmail</option>
    <option value="http://youtube.com">Youtube</option>
</select>

Can't find the 'libpq-fe.h header when trying to install pg gem

I have tried all solutions but only works below command

pip install psycopg2-binary