Programs & Examples On #Select insert

How can I INSERT data into two tables simultaneously in SQL Server?

I was also struggling with this problem, and find that the best way is to use a CURSOR.

I have tried Denis solution with OUTPUT, but as he mentiond, it's impossible to output external columns in an insert statement, and the MERGE can't work when insert multiple rows by select.

So, i've used a CURSOR, for each row in the outer table, i've done a INSERT, then use the @@IDENTITY for another INSERT.

DECLARE @OuterID int

DECLARE MY_CURSOR CURSOR 
  LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR 
SELECT  ID FROM   [external_Table]

OPEN MY_CURSOR
FETCH NEXT FROM MY_CURSOR INTO @OuterID

WHILE @@FETCH_STATUS = 0
BEGIN 
INSERT INTO [Table]   (data)
    SELECT data
    FROM     [external_Table] where ID = @OuterID 

    INSERT INTO [second_table] (FK,OuterID)
    VALUES(@OuterID,@@identity)

    FETCH NEXT FROM MY_CURSOR INTO @OuterID
END
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR

How do you send an HTTP Get Web Request in Python?

You can use urllib2

import urllib2
content = urllib2.urlopen(some_url).read()
print content

Also you can use httplib

import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
print res.status, res.reason
# Result:
200 OK

or the requests library

import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
# Result:
200

System.Net.WebException HTTP status code

By using the null-conditional operator (?.) you can get the HTTP status code with a single line of code:

 HttpStatusCode? status = (ex.Response as HttpWebResponse)?.StatusCode;

The variable status will contain the HttpStatusCode. When the there is a more general failure like a network error where no HTTP status code is ever sent then status will be null. In that case you can inspect ex.Status to get the WebExceptionStatus.

If you just want a descriptive string to log in case of a failure you can use the null-coalescing operator (??) to get the relevant error:

string status = (ex.Response as HttpWebResponse)?.StatusCode.ToString()
    ?? ex.Status.ToString();

If the exception is thrown as a result of a 404 HTTP status code the string will contain "NotFound". On the other hand, if the server is offline the string will contain "ConnectFailure" and so on.

(And for anybody that wants to know how to get the HTTP substatus code. That is not possible. It is a Microsoft IIS concept that is only logged on the server and never sent to the client.)

Convert a Unicode string to an escaped ASCII string

class Program
{
        static void Main(string[] args)
        {
            char[] originalString = "This string contains the unicode character Pi(p)".ToCharArray();
            StringBuilder asAscii = new StringBuilder(); // store final ascii string and Unicode points
            foreach (char c in originalString)
            {
                // test if char is ascii, otherwise convert to Unicode Code Point
                int cint = Convert.ToInt32(c);
                if (cint <= 127 && cint >= 0)
                    asAscii.Append(c);
                else
                    asAscii.Append(String.Format("\\u{0:x4} ", cint).Trim());
            }
            Console.WriteLine("Final string: {0}", asAscii);
            Console.ReadKey();
        }
}

All non-ASCII chars are converted to their Unicode Code Point representation and appended to the final string.

How to play CSS3 transitions in a loop?

If you want to take advantage of the 60FPS smoothness that the "transform" property offers, you can combine the two:

@keyframes changewidth {
  from {
    transform: scaleX(1);
  }

  to {
    transform: scaleX(2);
  }
}

div {
  animation-duration: 0.1s;
  animation-name: changewidth;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

More explanation on why transform offers smoother transitions here: https://medium.com/outsystems-experts/how-to-achieve-60-fps-animations-with-css3-db7b98610108

How to check if my string is equal to null?

If your string is null, calls like this should throw a NullReferenceException:

myString.equals(null)

But anyway, I think a method like this is what you want:

public static class StringUtils
{
    public static bool isNullOrEmpty(String myString)
    {
         return myString == null || "".equals(myString);
    }
}

Then in your code, you can do things like this:

if (!StringUtils.isNullOrEmpty(myString))
{
    doSomething();
}

Trigger a button click with JavaScript on the Enter key in a text box

In plain JavaScript,

if (document.layers) {
  document.captureEvents(Event.KEYDOWN);
}

document.onkeydown = function (evt) {
  var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
  if (keyCode == 13) {
    // For Enter.
    // Your function here.
  }
  if (keyCode == 27) {
    // For Escape.
    // Your function here.
  } else {
    return true;
  }
};

I noticed that the reply is given in jQuery only, so I thought of giving something in plain JavaScript as well.

Can jQuery provide the tag name?

Instead simply do:

$(function() {
  $(".rnd").each(function(i) {
    var id = $(this).attr("id");
    if (id === undefined || id.length === 0) {
      // this is the line that's giving me problems.
      // .attr("tag") returns undefined
      // change the below line...
      $(this).attr("id", "rnd" + this.tagName.toLowerCase() + "_" + i.toString()); 
  });
});

Disable back button in android

Just using this code: If you want backpressed disable, you dont use super.OnBackPressed();

@Override
public void onBackPressed() {

}

Git fatal: protocol 'https' is not supported

I have tried a lot of ways to solve this. But I am failed again and again. Then I did this:

Open Git Bash > go to your directory > paste the git clone https://[email protected]/*******.git after that a command prompt will be shown to give the login credentials. Give the credentials and clone your project.

cannot import name patterns

Pattern module in not available from django 1.8. So you need to remove pattern from your import and do something similar to the following:

from django.conf.urls import include, url
from django.contrib import admin

admin.autodiscover()

urlpatterns = [                 
    # here we are not using pattern module like in previous django versions
    url(r'^admin/', include(admin.site.urls)),
]

How to convert list of key-value tuples into dictionary?

Another way using dictionary comprehensions,

>>> t = [('A', 1), ('B', 2), ('C', 3)]
>>> d = { i:j for i,j in t }
>>> d
{'A': 1, 'B': 2, 'C': 3}

forcing web-site to show in landscape mode only

While I myself would be waiting here for an answer, I wonder if it can be done via CSS:

@media only screen and (orientation:portrait){
#wrapper {width:1024px}
}

@media only screen and (orientation:landscape){
#wrapper {width:1024px}
}

Clicking URLs opens default browser

The method boolean shouldOverrideUrlLoading(WebView view, String url) was deprecated in API 24. If you are supporting new devices you should use boolean shouldOverrideUrlLoading (WebView view, WebResourceRequest request).

You can use both by doing something like this:

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    newsItem.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            view.loadUrl(request.getUrl().toString());
            return true;
        }
    });
} else {
    newsItem.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    });
}

Can the Android layout folder contain subfolders?

If you are developing on a linux or a mac box, a workaround would be, to create subfolders which include symbolic links to your layoutfiles. Just use the ln command with -s

ln -s PATH_TO_YOUR_FILE

The Problem with this is, that your Layout folder still contains all the .xml files. But you could although select them by using the sub-folders. It's the closest thing, to what you would like to have.

I just read, that this might work with Windows, too if you are using Vista or later. There is this mklink command. Just google it, have never used it myself.

Another problem is, if you have the file opened and try to open it again out the plugin throws a NULL Pointer Exception. But it does not hang up.

Stylesheet not loaded because of MIME-type

I met this issue.

I refused to apply the style from 'http://m.b2b-v2-pre1.jcloudec.com/mobile-dynamic-load-component-view/resource/js/resource/js/need/layer.css?2.0' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

Changing the path could solve this issue.

Angular 2 declaring an array of objects

Datatype: array_name:datatype[]=[]; Example string: users:string[]=[];

For array of objects:

Objecttype: object_name:objecttype[]=[{}]; Example user: Users:user[]=[{}];

And if in some cases it's coming undefined in binding, make sure to initialize it on Oninit().

git push rejected: error: failed to push some refs

'remote: error: denying non-fast-forward refs/heads/master (you should pull first)'

That message suggests that there is a hook on the server that is rejecting fast forward pushes. Yes, it is usually not recommended and is a good guard, but since you are the only person using it and you want to do the force push, contact the administrator of the repo to allow to do the non-fastforward push by temporarily removing the hook or giving you the permission in the hook to do so.

How do I skip an iteration of a `foreach` loop?

You want:

foreach (int number in numbers) //   <--- go back to here --------+
{                               //                                |
    if (number < 0)             //                                |
    {                           //                                |
        continue;   // Skip the remainder of this iteration. -----+
    }

    // do work
}

Here's more about the continue keyword.


Update: In response to Brian's follow-up question in the comments:

Could you further clarify what I would do if I had nested for loops, and wanted to skip the iteration of one of the extended ones?

for (int[] numbers in numberarrays) {
  for (int number in numbers) { // What to do if I want to
                                // jump the (numbers/numberarrays)?
  }
}

A continue always applies to the nearest enclosing scope, so you couldn't use it to break out of the outermost loop. If a condition like that arises, you'd need to do something more complicated depending on exactly what you want, like break from the inner loop, then continue on the outer loop. See here for the documentation on the break keyword. The break C# keyword is similar to the Perl last keyword.

Also, consider taking Dustin's suggestion to just filter out values you don't want to process beforehand:

foreach (var basket in baskets.Where(b => b.IsOpen())) {
  foreach (var fruit in basket.Where(f => f.IsTasty())) {
    cuteAnimal.Eat(fruit); // Om nom nom. You don't need to break/continue
                           // since all the fruits that reach this point are
                           // in available baskets and tasty.
  }
}

How to uninstall Ruby from /usr/local?

Edit: As suggested in comments. This solution is for Linux OS. That too if you have installed ruby manually from package-manager.

If you want to have multiple ruby versions, better to have RVM. In that case you don't need to remove ruby older version.

Still if want to remove then follow the steps below:

First you should find where Ruby is:

whereis ruby

will list all the places where it exists on your system, then you can remove all them explicitly. Or you can use something like this:

rm -rf /usr/local/lib/ruby
rm -rf /usr/lib/ruby
rm -f /usr/local/bin/ruby
rm -f /usr/bin/ruby
rm -f /usr/local/bin/irb
rm -f /usr/bin/irb
rm -f /usr/local/bin/gem
rm -f /usr/bin/gem

How to convert a string from uppercase to lowercase in Bash?

I'm on Ubuntu 14.04, with Bash version 4.3.11. However, I still don't have the fun built in string manipulation ${y,,}

This is what I used in my script to force capitalization:

CAPITALIZED=`echo "${y}" | tr '[a-z]' '[A-Z]'`

When should I use the new keyword in C++?

If your variable is used only within the context of a single function, you're better off using a stack variable, i.e., Option 2. As others have said, you do not have to manage the lifetime of stack variables - they are constructed and destructed automatically. Also, allocating/deallocating a variable on the heap is slow by comparison. If your function is called often enough, you'll see a tremendous performance improvement if use stack variables versus heap variables.

That said, there are a couple of obvious instances where stack variables are insufficient.

If the stack variable has a large memory footprint, then you run the risk of overflowing the stack. By default, the stack size of each thread is 1 MB on Windows. It is unlikely that you'll create a stack variable that is 1 MB in size, but you have to keep in mind that stack utilization is cumulative. If your function calls a function which calls another function which calls another function which..., the stack variables in all of these functions take up space on the same stack. Recursive functions can run into this problem quickly, depending on how deep the recursion is. If this is a problem, you can increase the size of the stack (not recommended) or allocate the variable on the heap using the new operator (recommended).

The other, more likely condition is that your variable needs to "live" beyond the scope of your function. In this case, you'd allocate the variable on the heap so that it can be reached outside the scope of any given function.

Creating a Plot Window of a Particular Size

A convenient function for saving plots is ggsave(), which can automatically guess the device type based on the file extension, and smooths over differences between devices. You save with a certain size and units like this:

ggsave("mtcars.png", width = 20, height = 20, units = "cm")

In R markdown, figure size can be specified by chunk:

```{r, fig.width=6, fig.height=4}  
plot(1:5)
```

Reset local repository branch to be just like remote repository HEAD

Provided that the remote repository is origin, and that you're interested in branch_name:

git fetch origin
git reset --hard origin/<branch_name>

Also, you go for reset the current branch of origin to HEAD.

git fetch origin
git reset --hard origin/HEAD

How it works:

git fetch origin downloads the latest from remote without trying to merge or rebase anything.

Then the git reset resets the <branch_name> branch to what you just fetched. The --hard option changes all the files in your working tree to match the files in origin/branch_name.

SQLite table constraint - unique on multiple columns

Put the UNIQUE declaration within the column definition section; working example:

CREATE TABLE a (
    i INT,
    j INT,
    UNIQUE(i, j) ON CONFLICT REPLACE
);

Android error: Failed to install *.apk on device *: timeout

I know it sounds silly, but after trying everything recomended for this timeout issue on when running on a device, I decided to try changing the cable and it worked. It's a Coby Kyros MID7015.

Trying another cable is a good and simple option to take a chance on.

Grant Select on a view not base table when base table is in a different database

I tried this in one of my databases.

To get it to work, the user had to be added to the database housing the actual data. No rights were needed, just access.

Have you considered keeping the view in the database it references? Re usability and all if its benefits could follow.

jQuery find() method not working in AngularJS directive

You can do it like this:

 var myApp = angular.module('myApp', [])
  .controller('Ctrl', ['$scope', function($scope) {
     $scope.aaa = 3432
 }])
 .directive('test', function () {
    return {
       link: function (scope, elm, attr) {
           var look = elm.children('#findme').addClass("addedclass");
           console.log(look);
        }
   };
});

<div ng-app="myApp" ng-controller="Ctrl">
   <div test>TEST Div
      <div id="findme">{{aaa}}</div>
   </div>
</div>

http://jsfiddle.net/FZGKA/133/

Background color in input and text fields

input[type="text"], textarea {

  background-color : #d1d1d1; 

}

Hope that helps :)

Edit: working example, http://jsfiddle.net/C5WxK/

How to load a resource from WEB-INF directory of a web archive

Here is how it works for me with no Servlet use.

Let's say I am trying to access web.xml in project/WebContent/WEB-INF/web.xml

  1. In project property Source-tab add source folder by pointing to the parent container for WEB-INF folder (in my case WebContent )

  2. Now let's use class loader:

    InputStream inStream = class.getClass().getClassLoader().getResourceAsStream("Web-INF/web.xml")
    

change image opacity using javascript

You could use Jquery indeed or plain good old javascript:

var opacityPercent=30;
document.getElementById("id").style.cssText="opacity:0."+opacityPercent+"; filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity="+opacityPercent+");";

You put this in a function that you call on a setTimeout until the desired opacity is reached

Showing all session data at once?

For print session data you do not need to use print_r() function every time .

If you use it then it will be non-readable format.Data will be looks very dirty.

But if you use my function all you have to do is to use p()-Funtion and pass data into it. //create new file into application/cms_helper.php and load helper cms into //autoload or on controller

/*Copy Code for p function from here and paste into cms_helper.php in application/helpers folder */

   //@parram $data-array,$d-if true then die by default it is false
   //@author Your name

    function p($data,$d = false){

          echo "<pre>"; 
             print_r($data);
          echo "</pre>"; 

        if($d == TRUE){
             die();
          } 
      }

Just remember to load cms_helper into your project or controller using $this->load->helper('cms'); use bellow code into your controller or model it will works just GREAT.

 p($this->session->all_userdata()); // it will apply pre to your sesison data and other array as  well

Excel: Use a cell value as a parameter for a SQL query

I had the same problem as you, Noboby can understand me, But I solved it in this way.

SELECT NAME, TELEFONE, DATA
FROM   [sheet1$a1:q633]
WHERE  NAME IN (SELECT * FROM  [sheet2$a1:a2])

you need insert a parameter in other sheet, the SQL will consider that information like as database, then you can select the information and compare them into parameter you like.

Link vs compile vs controller

I wanted to add also what the O'Reily AngularJS book by the Google Team has to say:

Controller - Create a controller which publishes an API for communicating across directives. A good example is Directive to Directive Communication

Link - Programmatically modify resulting DOM element instances, add event listeners, and set up data binding.

Compile - Programmatically modify the DOM template for features across copies of a directive, as when used in ng-repeat. Your compile function can also return link functions to modify the resulting element instances.

Hash function that produces short hashes?

You could use an existing hash algorithm that produces something short, like MD5 (128 bits) or SHA1 (160). Then you can shorten that further by XORing sections of the digest with other sections. This will increase the chance of collisions, but not as bad as simply truncating the digest.

Also, you could include the length of the original data as part of the result to make it more unique. For example, XORing the first half of an MD5 digest with the second half would result in 64 bits. Add 32 bits for the length of the data (or lower if you know that length will always fit into fewer bits). That would result in a 96-bit (12-byte) result that you could then turn into a 24-character hex string. Alternately, you could use base 64 encoding to make it even shorter.

How can I make my own event in C#?

to do it we have to know the three components

  1. the place responsible for firing the Event
  2. the place responsible for responding to the Event
  3. the Event itself

    a. Event

    b .EventArgs

    c. EventArgs enumeration

now lets create Event that fired when a function is called

but I my order of solving this problem like this: I'm using the class before I create it

  1. the place responsible for responding to the Event

    NetLog.OnMessageFired += delegate(object o, MessageEventArgs args) 
    {
            // when the Event Happened I want to Update the UI
            // this is WPF Window (WPF Project)  
            this.Dispatcher.Invoke(() =>
            {
                LabelFileName.Content = args.ItemUri;
                LabelOperation.Content = args.Operation;
                LabelStatus.Content = args.Status;
            });
    };
    

NetLog is a static class I will Explain it later

the next step is

  1. the place responsible for firing the Event

    //this is the sender object, MessageEventArgs Is a class I want to create it  and Operation and Status are Event enums
    NetLog.FireMessage(this, new MessageEventArgs("File1.txt", Operation.Download, Status.Started));
    downloadFile = service.DownloadFile(item.Uri);
    NetLog.FireMessage(this, new MessageEventArgs("File1.txt", Operation.Download, Status.Finished));
    

the third step

  1. the Event itself

I warped The Event within a class called NetLog

public sealed class NetLog
{
    public delegate void MessageEventHandler(object sender, MessageEventArgs args);

    public static event MessageEventHandler OnMessageFired;
    public static void FireMessage(Object obj,MessageEventArgs eventArgs)
    {
        if (OnMessageFired != null)
        {
            OnMessageFired(obj, eventArgs);
        }
    }
}

public class MessageEventArgs : EventArgs
{
    public string ItemUri { get; private set; }
    public Operation Operation { get; private set; }
    public Status Status { get; private set; }

    public MessageEventArgs(string itemUri, Operation operation, Status status)
    {
        ItemUri = itemUri;
        Operation = operation;
        Status = status;
    }
}

public enum Operation
{
    Upload,Download
}

public enum Status
{
    Started,Finished
}

this class now contain the Event, EventArgs and EventArgs Enums and the function responsible for firing the event

sorry for this long answer

Understanding unique keys for array children in React.js

I was running into this error message because of <></> being returned for some items in the array when instead null needs to be returned.

Why do you need to put #!/bin/bash at the beginning of a script file?

To be more precise the shebang #!, when it is the first two bytes of an executable (x mode) file, is interpreted by the execve(2) system call (which execute programs). But POSIX specification for execve don't mention the shebang.

It must be followed by a file path of an interpreter executable (which BTW could even be relative, but most often is absolute).

A nice trick (or perhaps not so nice one) to find an interpreter (e.g. python) in the user's $PATH is to use the env program (always at /usr/bin/env on all Linux) like e.g.

 #!/usr/bin/env python

Any ELF executable can be an interpreter. You could even use #!/bin/cat or #!/bin/true if you wanted to! (but that would be often useless)

How to parse string into date?

CONVERT(datetime, '24.04.2012', 104)

Should do the trick. See here for more info: CAST and CONVERT (Transact-SQL)

Does java.util.List.isEmpty() check if the list itself is null?

Invoking any method on any null reference will always result in an exception. Test if the object is null first:

List<Object> test = null;
if (test != null && !test.isEmpty()) {
    // ...
}

Alternatively, write a method to encapsulate this logic:

public static <T> boolean IsNullOrEmpty(Collection<T> list) {
    return list == null || list.isEmpty();
}

Then you can do:

List<Object> test = null;
if (!IsNullOrEmpty(test)) {
    // ...
}

How to remove trailing whitespace in code, using another script?

Save as fix_whitespace.py:

#!/usr/bin/env python
"""
Fix trailing whitespace and line endings (to Unix) in a file.
Usage: python fix_whitespace.py foo.py
"""

import os
import sys


def main():
    """ Parse arguments, then fix whitespace in the given file """
    if len(sys.argv) == 2:
        fname = sys.argv[1]
        if not os.path.exists(fname):
            print("Python file not found: %s" % sys.argv[1])
            sys.exit(1)
    else:
        print("Invalid arguments. Usage: python fix_whitespace.py foo.py")
        sys.exit(1)
    fix_whitespace(fname)


def fix_whitespace(fname):
    """ Fix whitespace in a file """
    with open(fname, "rb") as fo:
        original_contents = fo.read()
    # "rU" Universal line endings to Unix
    with open(fname, "rU") as fo:
        contents = fo.read()
    lines = contents.split("\n")
    fixed = 0
    for k, line in enumerate(lines):
        new_line = line.rstrip()
        if len(line) != len(new_line):
            lines[k] = new_line
            fixed += 1
    with open(fname, "wb") as fo:
        fo.write("\n".join(lines))
    if fixed or contents != original_contents:
        print("************* %s" % os.path.basename(fname))
    if fixed:
        slines = "lines" if fixed > 1 else "line"
        print("Fixed trailing whitespace on %d %s" \
              % (fixed, slines))
    if contents != original_contents:
        print("Fixed line endings to Unix (\\n)")


if __name__ == "__main__":
    main()

How to set value of input text using jQuery

Using jQuery, we can use the following code:

Select by input name:

$('input[name="textboxname"]').val('some value')

Select by input class:

$('input[type=text].textboxclass').val('some value')

Select by input id:

$('#textboxid').val('some value')

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)

Try this:

sudo xcode-select --reset 
sudo xcodebuild -license

or this:

xcode-select --install

Removing the textarea border in HTML

Add this to your <head>:

<style type="text/css">
    textarea { border: none; }
</style>

Or do it directly on the textarea:

<textarea style="border: none"></textarea>

Creating a daemon in Linux

A daemon is just a process in the background. If you want to start your program when the OS boots, on linux, you add your start command to /etc/rc.d/rc.local (run after all other scripts) or /etc/startup.sh

On windows, you make a service, register the service, and then set it to start automatically at boot in administration -> services panel.

Getting "Skipping JaCoCo execution due to missing execution data file" upon executing JaCoCo

My response is very late but for others users In your case you have to configure failsafe pluging to use the command line agent configuration saved in itCoverageAgent variable. For exemple

<configuration>
    <argLine>${itCoverageAgent}</argLine>
</configuration>

In your maven configuration, jacoco prepare the command line arguments in prepare-agent phase, but failsafe plugin doesn't use it so there is no execution data file.

How to change the color of an image on hover

Ok, try this:

Get the image with the transparent circle - http://i39.tinypic.com/15s97vd.png Put that image in a html element and change that element's background color via css. This way you get the logo with the circle in the color defined in the stylesheet.

The html

<div class="badassColorChangingLogo">
    <img src="http://i39.tinypic.com/15s97vd.png" /> 
    Or download the image and change the path to the downloaded image in your machine
</div>

The css

div.badassColorChangingLogo{
    background-color:white;
}
div.badassColorChangingLogo:hover{
    background-color:blue;
}

Keep in mind that this wont work on non-alpha capable browsers like ie6, and ie7. for ie you can use a js fix. Google ddbelated png fix and you can get the script.

Need to find a max of three numbers in java

Two things: Change the variables x, y, z as int and call the method as Math.max(Math.max(x,y),z) as it accepts two parameters only.

In Summary, change below:

    String x = keyboard.nextLine();
    String y = keyboard.nextLine();
    String z = keyboard.nextLine();
    int max = Math.max(x,y,z);

to

    int x = keyboard.nextInt();
    int y = keyboard.nextInt();
    int z = keyboard.nextInt();
    int max =  Math.max(Math.max(x,y),z);

How do I compare version numbers in Python?

Posting my full function based on Kindall's solution. I was able to support any alphanumeric characters mixed in with the numbers by padding each version section with leading zeros.

While certainly not as pretty as his one-liner function, it seems to work well with alpha-numeric version numbers. (Just be sure to set the zfill(#) value appropriately if you have long strings in your versioning system.)

def versiontuple(v):
   filled = []
   for point in v.split("."):
      filled.append(point.zfill(8))
   return tuple(filled)

.

>>> versiontuple("10a.4.5.23-alpha") > versiontuple("2a.4.5.23-alpha")
True


>>> "10a.4.5.23-alpha" > "2a.4.5.23-alpha"
False

ASP.NET 2.0 - How to use app_offline.htm

Note that this behaves the same on IIS 6 and 7.x, and .NET 2, 3, and 4.x.

Also note that when app_offline.htm is present, IIS will return this http status code:

HTTP/1.1 503 Service Unavailable

This is all by design. This allows your load balancer (or whatever) to see that the server is off line.

Getting the ID of the element that fired an event

this.element.attr("id") works fine in IE8.

Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null

Your code is in the <head> => runs before the elements are rendered, so document.getElementById('compute'); returns null, as MDN promise...

element = document.getElementById(id);
element is a reference to an Element object, or null if an element with the specified ID is not in the document.

MDN

Solutions:

  1. Put the scripts in the bottom of the page.
  2. Call the attach code in the load event.
  3. Use jQuery library and it's DOM ready event.

What is the jQuery ready event and why is it needed?
(why no just JavaScript's load event):

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers...
...

ready docs

How to make Java 6, which fails SSL connection with "SSL peer shut down incorrectly", succeed like Java 7?

It seems that in the debug log for Java 6 the request is send in SSLv2 format.

main, WRITE: SSLv2 client hello message, length = 110

This is not mentioned as enabled by default in Java 7.
Change the client to use SSLv3 and above to avoid such interoperability issues.

Look for differences in JSSE providers in Java 7 and Java 6

support FragmentPagerAdapter holds reference to old fragments

I solved the problem by saving the fragments in SparceArray:

public abstract class SaveFragmentsPagerAdapter extends FragmentPagerAdapter {

    SparseArray<Fragment> fragments = new SparseArray<>();

    public SaveFragmentsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Fragment fragment = (Fragment) super.instantiateItem(container, position);
        fragments.append(position, fragment);
        return fragment;
    }

    @Nullable
    public Fragment getFragmentByPosition(int position){
        return fragments.get(position);
    }

}

htaccess redirect to https://www

There are a lot of solutions out there. Here is a link to the apache wiki which deals with this issue directly.

http://wiki.apache.org/httpd/RewriteHTTPToHTTPS

RewriteEngine On
# This will enable the Rewrite capabilities

RewriteCond %{HTTPS} !=on
# This checks to make sure the connection is not already HTTPS

RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
# This rule will redirect users from their original location, to the same location but using HTTPS.
# i.e.  http://www.example.com/foo/ to https://www.example.com/foo/
# The leading slash is made optional so that this will work either in httpd.conf
# or .htaccess context

PHP Configuration: It is not safe to rely on the system's timezone settings

Open your .htaccess file , add this line to the file, save, and try again :

php_value date.timezone "America/Sao_Paulo"

This works for me.

dismissModalViewControllerAnimated deprecated

Here is the corresponding presentViewController version that I used if it helps other newbies like myself:

if ([self respondsToSelector:@selector(presentModalViewController:animated:)]) {
    [self performSelector:@selector(presentModalViewController:animated:) withObject:testView afterDelay:0];
} else {
    [self presentViewController:configView animated:YES completion:nil];
}
[testView.testFrame setImage:info]; //this doesn't work for performSelector
[testView.testText setHidden:YES];

I had used a ViewController 'generically' and was able to get the modal View to appear differently depending what it was called to do (using setHidden and setImage). and things were working nicely before, but performSelector ignores 'set' stuff, so in the end it seems to be a poor solution if you try to be efficient like I tried to be...

How to keep one variable constant with other one changing with row in excel

There are two kinds of cell reference, and it's really valuable to understand them well.

One is relative reference, which is what you get when you just type the cell: A5. This reference will be adjusted when you paste or fill the formula into other cells.

The other is absolute reference, and you get this by adding dollar signs to the cell reference: $A$5. This cell reference will not change when pasted or filled.

A cool but rarely used feature is that row and column within a single cell reference may be independent: $A5 and A$5. This comes in handy for producing things like multiplication tables from a single formula.

Create a hexadecimal colour based on a string with JavaScript

Here's a solution I came up with to generate aesthetically pleasing pastel colours based on an input string. It uses the first two chars of the string as a random seed, then generates R/G/B based on that seed.

It could be easily extended so that the seed is the XOR of all chars in the string, rather than just the first two.

Inspired by David Crow's answer here: Algorithm to randomly generate an aesthetically-pleasing color palette

//magic to convert strings to a nice pastel colour based on first two chars
//
// every string with the same first two chars will generate the same pastel colour
function pastel_colour(input_str) {

    //TODO: adjust base colour values below based on theme
    var baseRed = 128;
    var baseGreen = 128;
    var baseBlue = 128;

    //lazy seeded random hack to get values from 0 - 256
    //for seed just take bitwise XOR of first two chars
    var seed = input_str.charCodeAt(0) ^ input_str.charCodeAt(1);
    var rand_1 = Math.abs((Math.sin(seed++) * 10000)) % 256;
    var rand_2 = Math.abs((Math.sin(seed++) * 10000)) % 256;
    var rand_3 = Math.abs((Math.sin(seed++) * 10000)) % 256;

    //build colour
    var red = Math.round((rand_1 + baseRed) / 2);
    var green = Math.round((rand_2 + baseGreen) / 2);
    var blue = Math.round((rand_3 + baseBlue) / 2);

    return { red: red, green: green, blue: blue };
}

GIST is here: https://gist.github.com/ro-sharp/49fd46a071a267d9e5dd

How to change the output color of echo in Linux

Here is the simplest and readable solution. With bashj (https://sourceforge.net/projects/bashj/), you would simply choose one of these lines:

#!/usr/bin/bash

W="Hello world!"
echo $W

R=130
G=60
B=190

echo u.colored($R,$G,$B,$W)

echo u.colored(255,127,0,$W)
echo u.red($W)
echo u.bold($W)
echo u.italic($W)

Y=u.yellow($W)
echo $Y
echo u.bold($Y)

256x256x256 colors are available if you have the color support in your terminal application.

How to include static library in makefile

The -L merely gives the path where to find the .a or .so file. What you're looking for is to add -lmine to the LIBS variable.

Make that -static -lmine to force it to pick the static library (in case both static and dynamic library exist).

Addition: Suppose the path to the file has been conveyed to the linker (or compiler driver) via -L you can also specifically tell it to link libfoo.a by giving -l:libfoo.a. Note that in this case the name includes the conventional lib-prefix. You can also give a full path this way. Sometimes this is the better method to "guide" the linker to the right location.

How do I update pip itself from inside my virtual environment?

pip version 10 has an issue. It will manifest as the error:

ubuntu@mymachine-:~/mydir$ sudo pip install --upgrade pip
Traceback (most recent call last):
  File "/usr/bin/pip", line 9, in <module>
    from pip import main
ImportError: cannot import name main

The solution is to be in the venv you want to upgrade and then run:

sudo myvenv/bin/pip install --upgrade pip

rather than just

sudo pip install --upgrade pip

Check table exist or not before create it in Oracle

Well there are lot of answeres already provided and lot are making sense too.

Some mentioned it is just warning and some giving a temp way to disable warnings. All that will work but add risk when number of transactions in your DB is high.

I came across similar situation today and here is very simple query I came up with...

declare
begin
  execute immediate '
    create table "TBL" ("ID" number not null)';
  exception when others then
    if SQLCODE = -955 then null; else raise; end if;
end;
/

955 is failure code.

This is simple, if exception come while running query it will be suppressed. and you can use same for SQL or Oracle.

Range of values in C Int and Long 32 - 64 bits

A 32-bit unsigned int has a range from 0 to 4,294,967,295. 0 to 65535 would be a 16-bit unsigned.

An unsigned long long (and, on a 64-bit implementation, possibly also ulong and possibly uint as well) have a range (at least) from 0 to 18,446,744,073,709,551,615 (264-1). In theory it could be greater than that, but at least for now that's rare to nonexistent.

C/C++ macro string concatenation

If they're both strings you can just do:

#define STR3 STR1 STR2

This then expands to:

#define STR3 "s" "1"

and in the C language, separating two strings with space as in "s" "1" is exactly equivalent to having a single string "s1".

Why I am Getting Error 'Channel is unrecoverably broken and will be disposed!'

I was having the same problem too. In my case was caused when trying to reproduce videos with a poor codification (demanded too much memory). This helped me to catch the error and request another version of the same video. https://stackoverflow.com/a/11986400/2508527

How can I overwrite file contents with new content in PHP?

MY PREFERRED METHOD is using fopen,fwrite and fclose [it will cost less CPU]

$f=fopen('myfile.txt','w');
fwrite($f,'new content');
fclose($f);

Warning for those using file_put_contents

It'll affect a lot in performance, for example [on the same class/situation] file_get_contents too: if you have a BIG FILE, it'll read the whole content in one shot and that operation could take a long waiting time

How can I use std::maps with user-defined types as key?

The right solution is to Specialize std::less for your class/Struct.

• Basically maps in cpp are implemented as Binary Search Trees.

  1. BSTs compare elements of nodes to determine the organization of the tree.
  2. Nodes who's element compares less than that of the parent node are placed on the left of the parent and nodes whose elements compare greater than the parent nodes element are placed on the right. i.e.

For each node, node.left.key < node.key < node.right.key

Every node in the BST contains Elements and in case of maps its KEY and a value, And keys are supposed to be ordered. More About Map implementation : The Map data Type.

In case of cpp maps , keys are the elements of the nodes and values does not take part in the organization of the tree its just a supplementary data .

So It means keys should be compatible with std::less or operator< so that they can be organized. Please check map parameters.

Else if you are using user defined data type as keys then need to give meaning full comparison semantics for that data type.

Solution : Specialize std::less:

The third parameter in map template is optional and it is std::less which will delegate to operator< ,

So create a new std::less for your user defined data type. Now this new std::less will be picked by std::map by default.

namespace std
{
    template<> struct  less<MyClass>
    {
        bool operator() (const MyClass& lhs, const MyClass& rhs) const
        {
            return lhs.anyMemen < rhs.age;
        }
    };

}

Note: You need to create specialized std::less for every user defined data type(if you want to use that data type as key for cpp maps).

Bad Solution: Overloading operator< for your user defined data type. This solution will also work but its very bad as operator < will be overloaded universally for your data type/class. which is undesirable in client scenarios.

Please check answer Pavel Minaev's answer

when I try to open an HTML file through `http://localhost/xampp/htdocs/index.html` it says unable to connect to localhost

You need to start your Apache Server normally you should have an xampp icon in the info-section from the taskbar, with this tool you can start the apache server as wel as the mysql database (if you need it)

How should I make my VBA code compatible with 64-bit Windows?

To write for all versions of Office use a combination of the newer VBA7 and Win64 conditional Compiler Constants.

VBA7 determines if code is running in version 7 of the VB editor (VBA version shipped in Office 2010+).

Win64 determines which version (32-bit or 64-bit) of Office is running.

#If VBA7 Then
'Code is running VBA7 (2010 or later).

     #If Win64 Then
     'Code is running in 64-bit version of Microsoft Office.
     #Else
     'Code is running in 32-bit version of Microsoft Office.
     #End If

#Else
'Code is running VBA6 (2007 or earlier).

#End If

See Microsoft Support Article for more details.

Removing element from array in component state

As mentioned in a comment to ephrion's answer above, filter() can be slow, especially with large arrays, as it loops to look for an index that appears to have been determined already. This is a clean, but inefficient solution.

As an alternative one can simply 'slice' out the desired element and concatenate the fragments.

var dummyArray = [];    
this.setState({data: dummyArray.concat(this.state.data.slice(0, index), this.state.data.slice(index))})

Hope this helps!

PHP preg_replace special characters

do this in two steps:

  1. replace not letter characters with this regex:

    [\/\&%#\$]

  2. replace quotes with this regex:

    [\"\']

and use preg_replace:

$stringWithoutNonLetterCharacters = preg_replace("/[\/\&%#\$]/", "_", $yourString);
$stringWithQuotesReplacedWithSpaces = preg_replace("/[\"\']/", " ", $stringWithoutNonLetterCharacters);

Array of PHP Objects

Yes, its possible to have array of objects in PHP.

class MyObject {
  private $property;

  public function  __construct($property) {
    $this->Property = $property;
  }
}
$ListOfObjects[] = new myObject(1); 
$ListOfObjects[] = new myObject(2); 
$ListOfObjects[] = new myObject(3); 
$ListOfObjects[] = new myObject(4); 

print "<pre>";
print_r($ListOfObjects);
print "</pre>";

Array as session variable

First change the array to a string by using implode() function. E.g $number=array(1,2,3,4,5,...); $stringofnumber=implode("|",$number); then pass the string to a session. e.g $_SESSION['string']=$stringofnumber; so when you go to the page where you want to use the array, just explode your string. e.g $number=explode("|", $_SESSION['string']); finally number is your array but remember to start array on the of each page.

Simple prime number generator in Python

  • The continue statement looks wrong.

  • You want to start at 2 because 2 is the first prime number.

  • You can write "while True:" to get an infinite loop.

Spring,Request method 'POST' not supported

I had csrf enabled in my sprint security xml file, so I just added one line in the form:

<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" /> 

This way I was able to submit the form having the model attribute.

How to print the values of slices

You could use a for loop to print the []Project as shown in @VonC excellent answer.

package main

import "fmt"

type Project struct{ name string }

func main() {
    projects := []Project{{"p1"}, {"p2"}}
    for i := range projects {
        p := projects[i]
        fmt.Println(p.name) //p1, p2
    }
}

CSS3 transition on click using pure CSS

As jeremyjjbrow said, :active pseudo won't persist. But there's a hack for doing it on pure css. You can wrap it on a <a> tag, and apply the :active on it, like this:

<a class="test">
    <img class="crossRotate" src="images/cross.png" alt="Cross Menu button" />
 </a>

And the css:

.test:active .crossRotate {
    transform: rotate(45deg);
    -webkit-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    }

Try it out... It works (at least on Chrome)!

Rounding integer division (instead of truncating)

try using math ceil function that makes rounding up. Math Ceil !

How to view changes made to files on a certain revision in Subversion

Call this in the project:

svn diff -r REVNO:HEAD --summarize

REVNO is the start revision number and HEAD is the end revision number. If HEAD is equal to the last revision number, it can skip it.

The command returns a list with all files that are changed/added/deleted in this revision period.

The command can be called with the URL revision parameter to check changes like this:

svn diff -r REVNO:HEAD --summarize SVN_URL

How to output JavaScript with PHP

You need to escape your quotes.

You can do this:

echo "<script type=\"text/javascript\">";

or this:

echo "<script type='text/javascript'>";

or this:

echo '<script type="text/javascript">';

Or just stay out of php

<script type="text/javascript">

How to find memory leak in a C++ code/project?

In addition to the tools and methodes provided in the other anwers, static code analysis tools can be used to detect memory leaks (and other issues as well). A free an robust tool is Cppcheck. But there are a lot of other tools available. Wikipedia has a list of static code analysis tools.

How to get the Android Emulator's IP address?

Within the code of my app I can get the running device IP andress easily like beolow:

WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());

In Perl, how do I create a hash whose keys come from a given array?

There is a presupposition here, that the most efficient way to do a lot of "Does the array contain X?" checks is to convert the array to a hash. Efficiency depends on the scarce resource, often time but sometimes space and sometimes programmer effort. You are at least doubling the memory consumed by keeping a list and a hash of the list around simultaneously. Plus you're writing more original code that you'll need to test, document, etc.

As an alternative, look at the List::MoreUtils module, specifically the functions any(), none(), true() and false(). They all take a block as the conditional and a list as the argument, similar to map() and grep():

print "At least one value undefined" if any { !defined($_) } @list;

I ran a quick test, loading in half of /usr/share/dict/words to an array (25000 words), then looking for eleven words selected from across the whole dictionary (every 5000th word) in the array, using both the array-to-hash method and the any() function from List::MoreUtils.

On Perl 5.8.8 built from source, the array-to-hash method runs almost 1100x faster than the any() method (1300x faster under Ubuntu 6.06's packaged Perl 5.8.7.)

That's not the full story however - the array-to-hash conversion takes about 0.04 seconds which in this case kills the time efficiency of array-to-hash method to 1.5x-2x faster than the any() method. Still good, but not nearly as stellar.

My gut feeling is that the array-to-hash method is going to beat any() in most cases, but I'd feel a whole lot better if I had some more solid metrics (lots of test cases, decent statistical analyses, maybe some big-O algorithmic analysis of each method, etc.) Depending on your needs, List::MoreUtils may be a better solution; it's certainly more flexible and requires less coding. Remember, premature optimization is a sin... :)

Should I put input elements inside a label element?

Personally I like to keep the label outside, like in your second example. That's why the FOR attribute is there. The reason being I'll often apply styles to the label, like a width, to get the form to look nice (shorthand below):

<style>
label {
  width: 120px;
  margin-right: 10px;
}
</style>

<label for="myinput">My Text</label>
<input type="text" id="myinput" /><br />
<label for="myinput2">My Text2</label>
<input type="text" id="myinput2" />

Makes it so I can avoid tables and all that junk in my forms.

Calling a user defined function in jQuery

If you want to call a normal function via a jQuery event, you can do it like this:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#btnSun').click(myFunction);_x000D_
});_x000D_
_x000D_
function myFunction() {_x000D_
  alert('hi');_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id="btnSun">Say hello!</button>
_x000D_
_x000D_
_x000D_

Get Selected value of a Combobox

You can use the below change event to which will trigger when the combobox value will change.

Private Sub ComboBox1_Change()
'your code here
End Sub

Also you can get the selected value using below

ComboBox1.Value

Use of for_each on map elements

C++14 brings generic lambdas. Meaning we can use std::for_each very easily:

std::map<int, int> myMap{{1, 2}, {3, 4}, {5, 6}, {7, 8}};

std::for_each(myMap.begin(), myMap.end(), [](const auto &myMapPair) {
    std::cout << "first " << myMapPair.first << " second "
              << myMapPair.second << std::endl;
});

I think std::for_each is sometimes better suited than a simple range based for loop. For example when you only want to loop through a subset of a map.

The activity must be exported or contain an intent-filter

Just Select App from dropdown menu with Run(green play icon). it will run the whole the App not the specific Activity. if it doesn't help try to use in that activity in ManiFest.xml file. thankyou

Paritition array into N chunks with Numpy

Try numpy.array_split.

From the documentation:

>>> x = np.arange(8.0)
>>> np.array_split(x, 3)
    [array([ 0.,  1.,  2.]), array([ 3.,  4.,  5.]), array([ 6.,  7.])]

Identical to numpy.split, but won't raise an exception if the groups aren't equal length.

If number of chunks > len(array) you get blank arrays nested inside, to address that - if your split array is saved in a, then you can remove empty arrays by:

[x for x in a if x.size > 0]

Just save that back in a if you wish.

How to install mechanize for Python 2.7?

Here's what I did which worked:

yum install python-pip
pip install -U multi-mechanize

How to simulate POST request?

Postman is the best application to test your APIs !

You can import or export your routes and let him remember all your body requests ! :)

EDIT : This comment is 5 yea's old and deprecated :D

Here's the new Postman App : https://www.postman.com/

Replace NA with 0 in a data frame column

First, here's some sample data:

set.seed(1)
dat <- data.frame(one = rnorm(15),
                 two = sample(LETTERS, 15),
                 three = rnorm(15),
                 four = runif(15))
dat <- data.frame(lapply(dat, function(x) { x[sample(15, 5)] <- NA; x }))
head(dat)
#          one  two       three      four
# 1         NA    M  0.80418951 0.8921983
# 2  0.1836433    O -0.05710677        NA
# 3 -0.8356286    L  0.50360797 0.3899895
# 4         NA    E          NA        NA
# 5  0.3295078    S          NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595

Here's our replacement:

dat[["four"]][is.na(dat[["four"]])] <- 0
head(dat)
#          one  two       three      four
# 1         NA    M  0.80418951 0.8921983
# 2  0.1836433    O -0.05710677 0.0000000
# 3 -0.8356286    L  0.50360797 0.3899895
# 4         NA    E          NA 0.0000000
# 5  0.3295078    S          NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595

Alternatively, you can, of course, write dat$four[is.na(dat$four)] <- 0

Android M Permissions: onRequestPermissionsResult() not being called

I also met a problem that even if you call correct requestPermissions, you still can have this problem. The issue is that parent activity may override this method without calling super. Add super and it will be fixed.

how can I enable PHP Extension intl?

For Megento Installation you Need to

  1. Stop Apache Service
  2. uncomment the extension=php_intl.dll in php.ini file.
  3. copy all 6 files icudt57.dll,icuin57.dll,icuio57.dll,icule57.dll,iculx57.dll,icuuc57.dll From php folder to apache\bin Now Restart you apache service

What is a Windows Handle?

A handle is a unique identifier for an object managed by Windows. It's like a pointer, but not a pointer in the sence that it's not an address that could be dereferenced by user code to gain access to some data. Instead a handle is to be passed to a set of functions that can perform actions on the object the handle identifies.

Error Handler - Exit Sub vs. End Sub

Your ProcExit label is your place where you release all the resources whether an error happened or not. For instance:

Public Sub SubA()
  On Error Goto ProcError

  Connection.Open
  Open File for Writing
  SomePreciousResource.GrabIt

ProcExit:  
  Connection.Close
  Connection = Nothing
  Close File
  SomePreciousResource.Release

  Exit Sub

ProcError:  
  MsgBox Err.Description  
  Resume ProcExit
End Sub

Update Rows in SSIS OLEDB Destination

Use Lookupstage to decide whether to insert or update. Check this link for more info - http://beingoyen.blogspot.com/2010/03/ssis-how-to-update-instead-of-insert.html

Steps to do update:

  1. Drag OLEDB Command [instead of oledb destination]
  2. Go to properties window
  3. Under Custom properties select SQLCOMMAND and insert update command ex:

    UPDATE table1 SET col1 = ?, col2 = ? where id = ?

  4. map columns in exact order from source to output as in update command

How can I echo a newline in a batch file?

Here you go, create a .bat file with the following in it :

@echo off
REM Creating a Newline variable (the two blank lines are required!)
set NLM=^


set NL=^^^%NLM%%NLM%^%NLM%%NLM%
REM Example Usage:
echo There should be a newline%NL%inserted here.

echo.
pause

You should see output like the following:

There should be a newline
inserted here.

Press any key to continue . . .

You only need the code between the REM statements, obviously.

jQuery UI dialog positioning

After reading all replies, this finally worked for me:

$(".mytext").mouseover(function() {
    var x = jQuery(this).position().left + jQuery(this).outerWidth();
    var y = jQuery(this).position().top - jQuery(document).scrollTop();
    jQuery("#dialog").dialog('option', 'position', [x,y]);
});

How to pass the values from one jsp page to another jsp without submit button?

I am trying to Understand your Question and it seems that you want the values in the first JSP to be available in the Second JSP.

  1. It is very bad Habit to Place Java Code snippets Inside JSP file, so that code snippet should go to a servlet.

  2. Pick the values in a servlet ie.

    String username = request.getParameter("username");
    String password = request.getParameter("password");
    
  3. Then Store the Values inside the Session:

    HttpSession sess = request.getSession(); 
    sess.setAttribute("username", username);
    sess.setAttribute("password", password);
    
  4. These values Will be available anywhere in the Application as long as the session is valid.

    HttpSession sess = request.getSession(false); //use false to use the existing session
    sess.getAttribute("username");//this will return username anytime in the session
    sess.getAttribute("password");//this will return password Any time in the session
    

I hope this is what you wanted to know, but please do not use code snippets in the JSP. You can always get the values into the JSP using jstl in the JSPs:

 ${username}//this will give you the username in the JSP
 ${password}// this will give you the password in the JSP

How to know if a Fragment is Visible?

Just in case you use a Fragment layout with a ViewPager (TabLayout), you can easily ask for the current (in front) fragment by ViewPager.getCurrentItem() method. It will give you the page index.

Mapping from page index to fragment[class] should be easy as you did the mapping in your FragmentPagerAdapter derived Adapter already.

int i = pager.getCurrentItem();

You may register for page change notifications by

ViewPager pager = (ViewPager) findViewById(R.id.container);
pager.addOnPageChangeListener(this);

Of course you must implement interface ViewPager.OnPageChangeListener

public class MainActivity 
    extends AppCompatActivity
    implements ViewPager.OnPageChangeListener
{
    public void onPageSelected (int position)
    {
        // we get notified here when user scrolls/switches Fragment in ViewPager -- so
        // we know which one is in front.
        Toast toast = Toast.makeText(this, "current page " + String.valueOf(position), Toast.LENGTH_LONG);
        toast.show();
    }

    public void onPageScrolled (int position, float positionOffset, int positionOffsetPixels) {
    }

    public void onPageScrollStateChanged (int state) {
    }
}

My answer here might be a little off the question. But as a newbie to Android Apps I was just facing exactly this problem and did not find an answer anywhere. So worked out above solution and posting it here -- perhaps someone finds it useful.

Edit: You might combine this method with LiveData on which the fragments subscribe. Further on, if you give your Fragments a page index as constructor argument, you can make a simple amIvisible() function in your fragment class.

In MainActivity:

private final MutableLiveData<Integer> current_page_ld = new MutableLiveData<>();
public LiveData<Integer> getCurrentPageIdx() { return current_page_ld; }

public void onPageSelected(int position) {
    current_page_ld.setValue(position);
}

public class MyPagerAdapter extends FragmentPagerAdapter
{
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page: But only on first
        // creation -- not on restore state !!!
        // see: https://stackoverflow.com/a/35677363/3290848
        switch (position) {
            case 0:
                return MyFragment.newInstance(0);
            case 1:
                return OtherFragment.newInstance(1);
            case 2:
                return XYFragment.newInstance(2);
        }
        return null;
    }
}

In Fragment:

    public static MyFragment newInstance(int index) {
        MyFragment fragment = new MyFragment();
        Bundle args = new Bundle();
        args.putInt("idx", index);
        fragment.setArguments(args);
        return fragment;
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mPageIndex = getArguments().getInt(ARG_PARAM1);
        }
        ...
    }
    
    public void onAttach(Context context)
    {
        super.onAttach(context);
        MyActivity mActivity = (MyActivity)context;

        mActivity.getCurrentPageIdx().observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer data) {
                if (data == mPageIndex) {
                    // have focus
                } else {
                    // not in front
                }
            }
        });
    }

Javascript: console.log to html

Create an ouput

<div id="output"></div>

Write to it using JavaScript

var output = document.getElementById("output");
output.innerHTML = "hello world";

If you would like it to handle more complex output values, you can use JSON.stringify

var myObj = {foo: "bar"};
output.innerHTML = JSON.stringify(myObj);

How to check whether a int is not null or empty?

int variables can't be null

If a null is to be converted to int, then it is the converter which decides whether to set 0, throw exception, or set another value (like Integer.MIN_VALUE). Try to plug your own converter.

Hex-encoded String to Byte Array

Use:

str.getBytes("UTF-16LE");

Youtube - downloading a playlist - youtube-dl

Your link is not a playlist.

A proper playlist URL looks like this:

https://www.youtube.com/playlist?list=PLHSdFJ8BDqEyvUUzm6R0HxawSWniP2c9K

Your URL is just the first video OF a certain playlist. It contains https://www.youtube.com/watch? instead of https://www.youtube.com/playlist?.

Pick the playlist by clicking on the title of the playlist on the right side in the list of videos and use this URL.

Convert Map<String,Object> to Map<String,String>

As you are casting from Object to String I recommend you catch and report (in some way, here I just print a message, which is generally bad) the exception.

    Map<String,Object> map = new HashMap<String,Object>(); //Object is containing String
    Map<String,String> newMap =new HashMap<String,String>();

    for (Map.Entry<String, Object> entry : map.entrySet()) {
        try{
            newMap.put(entry.getKey(), (String) entry.getValue());
        }
        catch(ClassCastException e){
            System.out.println("ERROR: "+entry.getKey()+" -> "+entry.getValue()+
                               " not added, as "+entry.getValue()+" is not a String");
        }
    }

Can Flask have optional URL parameters?

@user.route('/<user_id>', defaults={'username': default_value})
@user.route('/<user_id>/<username>')
def show(user_id, username):
   #
   pass

The "backspace" escape character '\b': unexpected behavior?

..........
^ <= pointer to "print head"
            /* part1 */
            printf("hello worl");
hello worl
          ^ <= pointer to "print head"
            /* part2 */
            printf("\b");
hello worl
         ^ <= pointer to "print head"
            /* part3 */
            printf("\b");
hello worl
        ^ <= pointer to "print head"
            /* part4 */
            printf("d\n");
hello wodl

^ <= pointer to "print head" on the next line

what is the difference between const_iterator and iterator?

There is no performance difference.

A const_iterator is an iterator that points to const value (like a const T* pointer); dereferencing it returns a reference to a constant value (const T&) and prevents modification of the referenced value: it enforces const-correctness.

When you have a const reference to the container, you can only get a const_iterator.

Edited: I mentionned “The const_iterator returns constant pointers” which is not accurate, thanks to Brandon for pointing it out.

Edit: For COW objects, getting a non-const iterator (or dereferencing it) will probably trigger the copy. (Some obsolete and now disallowed implementations of std::string use COW.)

How to encode URL to avoid special characters in Java?

URL construction is tricky because different parts of the URL have different rules for what characters are allowed: for example, the plus sign is reserved in the query component of a URL because it represents a space, but in the path component of the URL, a plus sign has no special meaning and spaces are encoded as "%20".

RFC 2396 explains (in section 2.4.2) that a complete URL is always in its encoded form: you take the strings for the individual components (scheme, authority, path, etc.), encode each according to its own rules, and then combine them into the complete URL string. Trying to build a complete unencoded URL string and then encode it separately leads to subtle bugs, like spaces in the path being incorrectly changed to plus signs (which an RFC-compliant server will interpret as real plus signs, not encoded spaces).

In Java, the correct way to build a URL is with the URI class. Use one of the multi-argument constructors that takes the URL components as separate strings, and it'll escape each component correctly according to that component's rules. The toASCIIString() method gives you a properly-escaped and encoded string that you can send to a server. To decode a URL, construct a URI object using the single-string constructor and then use the accessor methods (such as getPath()) to retrieve the decoded components.

Don't use the URLEncoder class! Despite the name, that class actually does HTML form encoding, not URL encoding. It's not correct to concatenate unencoded strings to make an "unencoded" URL and then pass it through a URLEncoder. Doing so will result in problems (particularly the aforementioned one regarding spaces and plus signs in the path).

SyntaxError: expected expression, got '<'

I had a similar problem using Angular js. i had a rewrite all to index.html in my .htaccess. The solution was to add the correct path slashes in . Each situation is unique, but hope this helps someone.

How to generate .json file with PHP?

Use this:

$json_data = json_encode($posts);
file_put_contents('myfile.json', $json_data);

You have to create the myfile.json before you run the script.

Permanently adding a file path to sys.path in Python

This way worked for me:

adding the path that you like:

export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add

checking: you can run 'export' cmd and check the output or you can check it using this cmd:

python -c "import sys; print(sys.path)"

How do I enumerate through a JObject?

For people like me, linq addicts, and based on svick's answer, here a linq approach:

using System.Linq;
//...
//make it linq iterable. 
var obj_linq = Response.Cast<KeyValuePair<string, JToken>>();

Now you can make linq expressions like:

JToken x = obj_linq
          .Where( d => d.Key == "my_key")
          .Select(v => v)
          .FirstOrDefault()
          .Value;
string y = ((JValue)x).Value;

Or just:

var y = obj_linq
       .Where(d => d.Key == "my_key")
       .Select(v => ((JValue)v.Value).Value)
       .FirstOrDefault();

Or this one to iterate over all data:

obj_linq.ToList().ForEach( x => { do stuff } ); 

How to remove the querystring and get only the url?

You can try:

<?php
$this_page = basename($_SERVER['REQUEST_URI']);
if (strpos($this_page, "?") !== false) $this_page = reset(explode("?", $this_page));
?>

The transaction log for database is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases

As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:

WHILE EXISTS (SELECT 1 
              FROM   YourTable 
              WHERE  <yourCondition>) 
  DELETE TOP(10000) FROM YourTable 
  WHERE  <yourCondition>

ERROR:'keytool' is not recognized as an internal or external command, operable program or batch file

This worked for me !! :

Go to this path or where ever you have your keytool.exe file

C:\Program Files\Java\jre7\bin

Hold shift and right click -> then press Open command window here

terminal will pop up, paste this in:

keytool -list -v -keystore "C:\Users\"Your-User-Name(no quotes)"\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

gives you both MD5 and SHA1

How to use font-awesome icons from node-modules

You could add it between your <head></head> tag like so:

<head>
  <link href="./node_modules/font-awesome/css/font-awesome.css" rel="stylesheet" type="text/css">
</head>

Or whatever your path to your node_modules is.

Edit (2017-06-26) - Disclaimer: THERE ARE BETTER ANSWERS. PLEASE DO NOT USE THIS METHOD. At the time of this original answer, good tools weren't as prevalent. With current build tools such as webpack or browserify, it probably doesn't make sense to use this answer. I can delete it, but I think it's important to highlight the various options one has and the possible dos and do nots.

Reduce size of legend area in barplot

The cex parameter will do that for you.

a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
        col = 1:6, space = c(0, 2))
legend("topright", 
       legend = c("a", "b", "c", "d", "e", "f"), 
       fill = 1:6, ncol = 2,
       cex = 0.75)

The plot

"Keep Me Logged In" - the best approach

I would recommend the approach mentioned by Stefan (i.e. follow the guidelines in Improved Persistent Login Cookie Best Practice) and also recommend that you make sure your cookies are HttpOnly cookies so they are not accessible to, potentially malicious, JavaScript.

Is there a color code for transparent in HTML?

When you have a 6 digit color code e.g. #ffffff, replace it with #ffffff00. Just add 2 zeros at the end to make the color transparent.

Here is an article describing the new standard in more depth: https://css-tricks.com/8-digit-hex-codes/

MongoDB: How to update multiple documents with a single command?

The following command can update multiple records of a collection

db.collection.update({}, 
{$set:{"field" : "value"}}, 
{ multi: true, upsert: false}
)

PHPMyAdmin Default login password

If it was installed with plesk (not sure if it's just that, or on the phpmyadmin side: It changes the root user to admin.

Does static constexpr variable inside a function make sense?

The short answer is that not only is static useful, it is pretty well always going to be desired.

First, note that static and constexpr are completely independent of each other. static defines the object's lifetime during execution; constexpr specifies that the object should be available during compilation. Compilation and execution are disjoint and discontiguous, both in time and space. So once the program is compiled, constexpr is no longer relevant.

Every variable declared constexpr is implicitly const but const and static are almost orthogonal (except for the interaction with static const integers.)

The C++ object model (§1.9) requires that all objects other than bit-fields occupy at least one byte of memory and have addresses; furthermore all such objects observable in a program at a given moment must have distinct addresses (paragraph 6). This does not quite require the compiler to create a new array on the stack for every invocation of a function with a local non-static const array, because the compiler could take refuge in the as-if principle provided it can prove that no other such object can be observed.

That's not going to be easy to prove, unfortunately, unless the function is trivial (for example, it does not call any other function whose body is not visible within the translation unit) because arrays, more or less by definition, are addresses. So in most cases, the non-static const(expr) array will have to be recreated on the stack at every invocation, which defeats the point of being able to compute it at compile time.

On the other hand, a local static const object is shared by all observers, and furthermore may be initialized even if the function it is defined in is never called. So none of the above applies, and a compiler is free not only to generate only a single instance of it; it is free to generate a single instance of it in read-only storage.

So you should definitely use static constexpr in your example.

However, there is one case where you wouldn't want to use static constexpr. Unless a constexpr declared object is either ODR-used or declared static, the compiler is free to not include it at all. That's pretty useful, because it allows the use of compile-time temporary constexpr arrays without polluting the compiled program with unnecessary bytes. In that case, you would clearly not want to use static, since static is likely to force the object to exist at runtime.

Get unicode value of a character

I found this nice code on web.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Unicode {

public static void main(String[] args) {
System.out.println("Use CTRL+C to quite to program.");

// Create the reader for reading in the text typed in the console. 
InputStreamReader inputStreamReader = new InputStreamReader(System.in);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

try {
  String line = null;
  while ((line = bufferedReader.readLine()).length() > 0) {
    for (int index = 0; index < line.length(); index++) {

      // Convert the integer to a hexadecimal code.
      String hexCode = Integer.toHexString(line.codePointAt(index)).toUpperCase();


      // but the it must be a four number value.
      String hexCodeWithAllLeadingZeros = "0000" + hexCode;
      String hexCodeWithLeadingZeros = hexCodeWithAllLeadingZeros.substring(hexCodeWithAllLeadingZeros.length()-4);

      System.out.println("\\u" + hexCodeWithLeadingZeros);
    }

  }
} catch (IOException ioException) {
       ioException.printStackTrace();
  }
 }
}

Original Article

Rotation of 3D vector?

I made a fairly complete library of 3D mathematics for Python{2,3}. It still does not use Cython, but relies heavily on the efficiency of numpy. You can find it here with pip:

python[3] -m pip install math3d

Or have a look at my gitweb http://git.automatics.dyndns.dk/?p=pymath3d.git and now also on github: https://github.com/mortlind/pymath3d .

Once installed, in python you may create the orientation object which can rotate vectors, or be part of transform objects. E.g. the following code snippet composes an orientation that represents a rotation of 1 rad around the axis [1,2,3], applies it to the vector [4,5,6], and prints the result:

import math3d as m3d
r = m3d.Orientation.new_axis_angle([1,2,3], 1)
v = m3d.Vector(4,5,6)
print(r * v)

The output would be

<Vector: (2.53727, 6.15234, 5.71935)>

This is more efficient, by a factor of approximately four, as far as I can time it, than the oneliner using scipy posted by B. M. above. However, it requires installation of my math3d package.

How is TeamViewer so fast?

The most fundamental thing here probably is that you don't want to transmit static images but only changes to the images, which essentially is analogous to video stream.

My best guess is some very efficient (and heavily specialized and optimized) motion compensation algorithm, because most of the actual change in generic desktop usage is linear movement of elements (scrolling text, moving windows, etc. opposed to transformation of elements).

The DirectX 3D performance of 1 FPS seems to confirm my guess to some extent.

How to change color of SVG image using CSS (jQuery SVG image replacement)?

You can now use the CSS filter property in most modern browsers (including Edge, but not IE11). It works on SVG images as well as other elements. You can use hue-rotate or invert to modify colors, although they don't let you modify different colors independently. I use the following CSS class to show a "disabled" version of an icon (where the original is an SVG picture with saturated color):

.disabled {
    opacity: 0.4;
    filter: grayscale(100%);
    -webkit-filter: grayscale(100%);
}

This makes it light grey in most browsers. In IE (and probably Opera Mini, which I haven't tested) it is noticeably faded by the opacity property, which still looks pretty good, although it's not grey.

Here's an example with four different CSS classes for the Twemoji bell icon: original (yellow), the above "disabled" class, hue-rotate (green), and invert (blue).

_x000D_
_x000D_
.twa-bell {_x000D_
  background-image: url("https://twemoji.maxcdn.com/svg/1f514.svg");_x000D_
  display: inline-block;_x000D_
  background-repeat: no-repeat;_x000D_
  background-position: center center;_x000D_
  height: 3em;_x000D_
  width: 3em;_x000D_
  margin: 0 0.15em 0 0.3em;_x000D_
  vertical-align: -0.3em;_x000D_
  background-size: 3em 3em;_x000D_
}_x000D_
.grey-out {_x000D_
  opacity: 0.4;_x000D_
  filter: grayscale(100%);_x000D_
  -webkit-filter: grayscale(100%);_x000D_
}_x000D_
.hue-rotate {_x000D_
  filter: hue-rotate(90deg);_x000D_
  -webkit-filter: hue-rotate(90deg);_x000D_
}_x000D_
.invert {_x000D_
  filter: invert(100%);_x000D_
  -webkit-filter: invert(100%);_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <span class="twa-bell"></span>_x000D_
  <span class="twa-bell grey-out"></span>_x000D_
  <span class="twa-bell hue-rotate"></span>_x000D_
  <span class="twa-bell invert"></span>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Modify table: How to change 'Allow Nulls' attribute from not null to allow null

ALTER TABLE public.contract_termination_requests
ALTER COLUMN management_company_id DROP NOT NULL;

VBA module that runs other modules

I just learned something new thanks to Artiso. I gave each module a name in the properties box. These names were also what I declared in the module. When I tried to call my second module, I kept getting an error: Compile error: Expected variable or procedure, not module

After reading Artiso's comment above about not having the same names, I renamed my second module, called it from the first, and problem solved. Interesting stuff! Thanks for the info Artiso!

In case my experience is unclear:

Module Name: AllFSGroupsCY Public Sub AllFSGroupsCY()

Module Name: AllFSGroupsPY Public Sub AllFSGroupsPY()

From AllFSGroupsCY()

Public Sub FSGroupsCY()

    AllFSGroupsPY 'will error each time until the properties name is changed

End Sub

CAST DECIMAL to INT

your can try this :

SELECT columnName1, CAST(columnName2 AS  SIGNED ) FROM tableName 

clear cache of browser by command line

You can run Rundll32.exe for IE Options control panel applet and achieve following tasks.


Deletes ALL History - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255

Deletes History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1

Deletes Cookies Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2

Deletes Temporary Internet Files Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8

Deletes Form Data Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16

Deletes Password History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32

What's the function like sum() but for multiplication? product()?

Perhaps not a "builtin", but I consider it builtin. anyways just use numpy

import numpy 
prod_sum = numpy.prod(some_list)

How to make rounded percentages add up to 100%

I'm not sure what level of accuracy you need, but what I would do is simply add 1 the first n numbers, n being the ceil of the total sum of decimals. In this case that is 3, so I would add 1 to the first 3 items and floor the rest. Of course this is not super accurate, some numbers might be rounded up or down when it shouldn't but it works okay and will always result in 100%.

So [ 13.626332, 47.989636, 9.596008, 28.788024 ] would be [14, 48, 10, 28] because Math.ceil(.626332+.989636+.596008+.788024) == 3

function evenRound( arr ) {
  var decimal = -~arr.map(function( a ){ return a % 1 })
    .reduce(function( a,b ){ return a + b }); // Ceil of total sum of decimals
  for ( var i = 0; i < decimal; ++i ) {
    arr[ i ] = ++arr[ i ]; // compensate error by adding 1 the the first n items
  }
  return arr.map(function( a ){ return ~~a }); // floor all other numbers
}

var nums = evenRound( [ 13.626332, 47.989636, 9.596008, 28.788024 ] );
var total = nums.reduce(function( a,b ){ return a + b }); //=> 100

You can always inform users that the numbers are rounded and may not be super-accurate...

What is the use of the %n format specifier in C?

The argument associated with the %n will be treated as an int* and is filled with the number of total characters printed at that point in the printf.

Set value of textbox using JQuery

$(document).ready(function() {
 $('#main_search').val('hi');
});

List and kill at jobs on UNIX

First

ps -ef

to list all processes. Note the the process number of the one you want to kill. Then

kill 1234

were you replace 1234 with the process number that you want.

Alternatively, if you are absolutely certain that there is only one process with a particular name, or you want to kill multiple processes which share the same name

killall processname

Image scaling causes poor quality in firefox/internet explorer but not chrome

It seems that you are right. No option scales the image better:
http://www.maxrev.de/html/image-scaling.html

I've tested FF14, IE9, OP12 and GC21. Only GC has a better scaling that can be deactivated through image-rendering: -webkit-optimize-contrast. All other browsers have no/poor scaling.

Screenshot of the different output: http://www.maxrev.de/files/2012/08/screenshot_interpolation_jquery_animate.png

Update 2017

Meanwhile some more browsers support smooth scaling:

  • ME38 (Microsoft Edge) has good scaling. It can't be disabled and it works for JPEG and PNG, but not for GIF.

  • FF51 (Regarding @karthik 's comment since FF21) has good scaling that can be disabled through the following settings:

    image-rendering: optimizeQuality
    image-rendering: optimizeSpeed
    image-rendering: -moz-crisp-edges
    

    Note: Regarding MDN the optimizeQuality setting is a synonym for auto (but auto does not disable smooth scaling):

    The values optimizeQuality and optimizeSpeed present in early draft (and coming from its SVG counterpart) are defined as synonyms for the auto value.

  • OP43 behaves like GC (not suprising as it is based on Chromium since 2013) and its still this option that disables smooth scaling:

    image-rendering: -webkit-optimize-contrast
    

No support in IE9-IE11. The -ms-interpolation-mode setting worked only in IE6-IE8, but was removed in IE9.

P.S. Smooth scaling is done by default. This means no image-rendering option is needed!

Zooming MKMapView to fit annotation pins?

@jowie's solution works great. One catch, if a map has only one annotation you'll end up with a fully zoomed out map. I added 0.1 to the rect make size to make sure setVisibleMapRect has something to zoom to.

MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.1, 0.1);

How to identify all stored procedures referring a particular table

In management studio you can just right click to table and click to 'View Dependencies' enter image description here

than you can see a list of Objects that have dependencies with your table :enter image description here

Set cURL to use local virtual hosts

It seems that this is not an uncommon problem.

Check this first.

If that doesn't help, you can install a local DNS server on Windows, such as this. Configure Windows to use localhost as the DNS server. This server can be configured to be authoritative for whatever fake domains you need, and to forward requests on to the real DNS servers for all other requests.

I personally think this is a bit over the top, and can't see why the hosts file wouldn't work. But it should solve the problem you're having. Make sure you set up your normal DNS servers as forwarders as well.

How to run 'sudo' command in windows

I've created wsudo, an open-source sudo-like CLI tool for Windows to run programs or commands with elevated right, in the context of the current directory. It's available as a Chocolatey package.

I use it a lot for stuff like configuring build agents, admin things like sfc /scannow, dism /online /cleanup-image /restorehealth or simply for installing/updating my local Chocolatey packages. Use at your own risk.

Installation

choco install wsudo

Chocolatey must be already installed.

Purpose

wsudo is a Linux sudo-like tool for Windows to invoke a program with elevated rights (as Administrator) from a non-admin shell command prompt and keeping its current directory.

This implementation doesn't depend on the legacy Windows Script Host (CScript). Instead, it uses a helper PowerShell 5.1 script that invokes "Start-Process -Wait -Verb runAs ..." cmdlet. Your system most likely already has PowerShell 5.x installed, otherwise you'll be offered to install it as a dependency.

Usage

wsudo runs a program or an inline command with elevated rights in the current directory. Examples:

wsudo .\myAdminScript.bat 
wsudox "del C:\Windows\Temp\*.* && pause"
wasudo cup all -y
wasudox start notepad C:\Windows\System32\drivers\etc\hosts 

For more details, visit the GitHub repro.

What does "for" attribute do in HTML <label> tag?

The for attribute associates the label with a control element, as defined in the description of label in the HTML 4.01 spec. This implies, among other things, that when the label element receives focus (e.g. by being clicked on), it passes the focus on to its associated control. The association between a label and a control may also be used by speech-based user agents, which may give the user a way to ask what the associated label is, when dealing with a control. (The association may not be as obvious as in visual rendering.)

In the first example in the question (without the for), the use of label markup has no logical or functional implication – it’s useless, unless you do something with it in CSS or JavaScript.

HTML specifications do not make it mandatory to associate labels with controls, but Web Content Accessibility Guidelines (WCAG) 2.0 do. This is described in the technical document H44: Using label elements to associate text labels with form controls, which also explains that the implicit association (by nesting e.g. input inside label) is not as widely supported as the explicit association via for and id attributes,

Static method in a generic class?

@BD at Rivenhill: Since this old question has gotten renewed attention last year, let us go on a bit, just for the sake of discussion. The body of your doIt method does not do anything T-specific at all. Here it is:

public class Clazz<T> {
  static <T> void doIt(T object) {
    System.out.println("shake that booty '" + object.getClass().toString()
                       + "' !!!");
  }
// ...
}

So you can entirely drop all type variables and just code

public class Clazz {
  static void doIt(Object object) {
    System.out.println("shake that booty '" + object.getClass().toString()
                       + "' !!!");
  }
// ...
}

Ok. But let's get back closer to the original problem. The first type variable on the class declaration is redundant. Only the second one on the method is needed. Here we go again, but it is not the final answer, yet:

public class Clazz  {
  static <T extends Saying> void doIt(T object) {
    System.out.println("shake that booty "+ object.say());
  }

  public static void main(String args[]) {
    Clazz.doIt(new KC());
    Clazz.doIt(new SunshineBand());
  }
}
// Output:
// KC
// Sunshine

interface Saying {
      public String say();
}

class KC implements Saying {
      public String say() {
          return "KC";
      }
}

class SunshineBand implements Saying {
      public String say() {
          return "Sunshine";
      }
}

However, it's all too much fuss about nothing, since the following version works just the same way. All it needs is the interface type on the method parameter. No type variables in sight anywhere. Was that really the original problem?

public class Clazz  {
  static void doIt(Saying object) {
    System.out.println("shake that booty "+ object.say());
  }

  public static void main(String args[]) {
    Clazz.doIt(new KC());
    Clazz.doIt(new SunshineBand());
  }
}

interface Saying {
      public String say();
}

class KC implements Saying {
      public String say() {
          return "KC";
      }
}

class SunshineBand implements Saying {
      public String say() {
          return "Sunshine";
      }
}

Generating Random Number In Each Row In Oracle Query

If you just use round then the two end numbers (1 and 9) will occur less frequently, to get an even distribution of integers between 1 and 9 then:

SELECT MOD(Round(DBMS_RANDOM.Value(1, 99)), 9) + 1 FROM DUAL

Getting time difference between two times in PHP

You can also use DateTime class:

$time1 = new DateTime('09:00:59');
$time2 = new DateTime('09:01:00');
$interval = $time1->diff($time2);
echo $interval->format('%s second(s)');

Result:

1 second(s)

What is the purpose of the : (colon) GNU Bash builtin?

Two more uses not mentioned in other answers:

Logging

Take this example script:

set -x
: Logging message here
example_command

The first line, set -x, makes the shell print out the command before running it. It's quite a useful construct. The downside is that the usual echo Log message type of statement now prints the message twice. The colon method gets round that. Note that you'll still have to escape special characters just like you would for echo.

Cron job titles

I've seen it being used in cron jobs, like this:

45 10 * * * : Backup for database ; /opt/backup.sh

This is a cron job that runs the script /opt/backup.sh every day at 10:45. The advantage of this technique is that it makes for better looking email subjects when the /opt/backup.sh prints some output.

OpenCV - Apply mask to a color image

Answer given by Abid Rahman K is not completely correct. I also tried it and found very helpful but got stuck.

This is how I copy image with a given mask.

x, y = np.where(mask!=0)
pts = zip(x, y)
# Assuming dst and src are of same sizes
for pt in pts:
   dst[pt] = src[pt]

This is a bit slow but gives correct results.

EDIT:

Pythonic way.

idx = (mask!=0)
dst[idx] = src[idx]

Convert Python ElementTree to string

How do I convert ElementTree.Element to a String?

For Python 3:

xml_str = ElementTree.tostring(xml, encoding='unicode')

For Python 2:

xml_str = ElementTree.tostring(xml, encoding='utf-8')

The following is compatible with both Python 2 & 3, but only works for Latin characters:

xml_str = ElementTree.tostring(xml).decode()

Example usage

from xml.etree import ElementTree

xml = ElementTree.Element("Person", Name="John")
xml_str = ElementTree.tostring(xml).decode()
print(xml_str)

Output:

<Person Name="John" />

Explanation

Despite what the name implies, ElementTree.tostring() returns a bytestring by default in Python 2 & 3. This is an issue in Python 3, which uses Unicode for strings.

In Python 2 you could use the str type for both text and binary data. Unfortunately this confluence of two different concepts could lead to brittle code which sometimes worked for either kind of data, sometimes not. [...]

To make the distinction between text and binary data clearer and more pronounced, [Python 3] made text and binary data distinct types that cannot blindly be mixed together.

Source: Porting Python 2 Code to Python 3

If we know what version of Python is being used, we can specify the encoding as unicode or utf-8. Otherwise, if we need compatibility with both Python 2 & 3, we can use decode() to convert into the correct type.

For reference, I've included a comparison of .tostring() results between Python 2 and Python 3.

ElementTree.tostring(xml)
# Python 3: b'<Person Name="John" />'
# Python 2: <Person Name="John" />

ElementTree.tostring(xml, encoding='unicode')
# Python 3: <Person Name="John" />
# Python 2: LookupError: unknown encoding: unicode

ElementTree.tostring(xml, encoding='utf-8')
# Python 3: b'<Person Name="John" />'
# Python 2: <Person Name="John" />

ElementTree.tostring(xml).decode()
# Python 3: <Person Name="John" />
# Python 2: <Person Name="John" />

Thanks to Martijn Peters for pointing out that the str datatype changed between Python 2 and 3.


Why not use str()?

In most scenarios, using str() would be the "cannonical" way to convert an object to a string. Unfortunately, using this with Element returns the object's location in memory as a hexstring, rather than a string representation of the object's data.

from xml.etree import ElementTree

xml = ElementTree.Element("Person", Name="John")
print(str(xml))  # <Element 'Person' at 0x00497A80>

How to serialize an Object into a list of URL query parameters?

This one-liner also handles nested objects and JSON.stringify them as needed:

let qs = Object.entries(obj).map(([k, v]) => `${k}=${encodeURIComponent(typeof (v) === "object" ? JSON.stringify(v) : v)}`).join('&')

WPF global exception handler

You can trap unhandled exceptions at different levels:

  1. AppDomain.CurrentDomain.UnhandledException From all threads in the AppDomain.
  2. Dispatcher.UnhandledException From a single specific UI dispatcher thread.
  3. Application.Current.DispatcherUnhandledException From the main UI dispatcher thread in your WPF application.
  4. TaskScheduler.UnobservedTaskException from within each AppDomain that uses a task scheduler for asynchronous operations.

You should consider what level you need to trap unhandled exceptions at.

Deciding between #2 and #3 depends upon whether you're using more than one WPF thread. This is quite an exotic situation and if you're unsure whether you are or not, then it's most likely that you're not.

android start activity from service

I had the same problem, and want to let you know that none of the above worked for me. What worked for me was:

 Intent dialogIntent = new Intent(this, myActivity.class);
 dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 this.startActivity(dialogIntent);

and in one my subclasses, stored in a separate file I had to:

public static Service myService;

myService = this;

new SubService(myService);

Intent dialogIntent = new Intent(myService, myActivity.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
myService.startActivity(dialogIntent);

All the other answers gave me a nullpointerexception.

error: passing xxx as 'this' argument of xxx discards qualifiers

Let's me give a more detail example. As to the below struct:

struct Count{
    uint32_t c;

    Count(uint32_t i=0):c(i){}

    uint32_t getCount(){
        return c;
    }

    uint32_t add(const Count& count){
        uint32_t total = c + count.getCount();
        return total;
    }
};

enter image description here

As you see the above, the IDE(CLion), will give tips Non-const function 'getCount' is called on the const object. In the method add count is declared as const object, but the method getCount is not const method, so count.getCount() may change the members in count.

Compile error as below(core message in my compiler):

error: passing 'const xy_stl::Count' as 'this' argument discards qualifiers [-fpermissive]

To solve the above problem, you can:

  1. change the method uint32_t getCount(){...} to uint32_t getCount() const {...}. So count.getCount() won't change the members in count.

or

  1. change uint32_t add(const Count& count){...} to uint32_t add(Count& count){...}. So count don't care about changing members in it.

As to you problem, objects in the std::set are stored as const StudentT, but the method getId and getName are not const, so you give the above error.

You can also see this question Meaning of 'const' last in a function declaration of a class? for more detail.

C compiler for Windows?

You may try Code::Blocks, which is better IDE and comes with MinGW GCC! I have used it and its just too good a freeware IDE for C/C++.

document.getElementById vs jQuery $()

One other difference: getElementById returns the first match, while $('#...') returns a collection of matches - yes, the same ID can be repeated in an HTML doc.

Further, getElementId is called from the document, while $('#...') can be called from a selector. So, in the code below, document.getElementById('content') will return the entire body but $('form #content')[0] will return inside of the form.

<body id="content">
   <h1>Header!</h1>
   <form>
      <div id="content"> My Form </div>
   </form>
</body>

It might seem odd to use duplicate IDs, but if you are using something like Wordpress, a template or plugin might use the same id as you use in the content. The selectivity of jQuery could help you out there.

SQL - Create view from multiple tables

This works too and you dont have to use join or anything:

DROP VIEW IF EXISTS yourview;

CREATE VIEW yourview AS
    SELECT table1.column1, 
    table2.column2
FROM 
table1, table2 
WHERE table1.column1 = table2.column1;

How to deserialize a list using GSON or another JSON library in Java?

With Gson, you'd just need to do something like:

List<Video> videos = gson.fromJson(json, new TypeToken<List<Video>>(){}.getType());

You might also need to provide a no-arg constructor on the Video class you're deserializing to.

check / uncheck checkbox using jquery?

For jQuery 1.6+ :

.attr() is deprecated for properties; use the new .prop() function instead as:

$('#myCheckbox').prop('checked', true); // Checks it
$('#myCheckbox').prop('checked', false); // Unchecks it

For jQuery < 1.6:

To check/uncheck a checkbox, use the attribute checked and alter that. With jQuery you can do:

$('#myCheckbox').attr('checked', true); // Checks it
$('#myCheckbox').attr('checked', false); // Unchecks it

Cause you know, in HTML, it would look something like:

<input type="checkbox" id="myCheckbox" checked="checked" /> <!-- Checked -->
<input type="checkbox" id="myCheckbox" /> <!-- Unchecked -->

However, you cannot trust the .attr() method to get the value of the checkbox (if you need to). You will have to rely in the .prop() method.

Python calling method in class

The first argument of all methods is usually called self. It refers to the instance for which the method is being called.

Let's say you have:

class A(object):
    def foo(self):
        print 'Foo'

    def bar(self, an_argument):
        print 'Bar', an_argument

Then, doing:

a = A()
a.foo() #prints 'Foo'
a.bar('Arg!') #prints 'Bar Arg!'

There's nothing special about this being called self, you could do the following:

class B(object):
    def foo(self):
        print 'Foo'

    def bar(this_object):
        this_object.foo()

Then, doing:

b = B()
b.bar() # prints 'Foo'

In your specific case:

dangerous_device = MissileDevice(some_battery)
dangerous_device.move(dangerous_device.RIGHT) 

(As suggested in comments MissileDevice.RIGHT could be more appropriate here!)

You could declare all your constants at module level though, so you could do:

dangerous_device.move(RIGHT)

This, however, is going to depend on how you want your code to be organized!

Is there any way to set environment variables in Visual Studio Code?

As it does not answer your question but searching vm arguments I stumbled on this page and there seem to be no other. So if you want to pass vm arguments its like so

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "java",
      "name": "ddtBatch",
      "request": "launch",
      "mainClass": "com.something.MyApplication",
      "projectName": "MyProject",
      "args": "Hello",
      "vmArgs": "-Dspring.config.location=./application.properties"
    }
  ]
}

What is tail recursion?

There are two basic kinds of recursions: head recursion and tail recursion.

In head recursion, a function makes its recursive call and then performs some more calculations, maybe using the result of the recursive call, for example.

In a tail recursive function, all calculations happen first and the recursive call is the last thing that happens.

Taken from this super awesome post. Please consider reading it.

Python Variable Declaration

This might be 6 years late, but in Python 3.5 and above, you declare a variable type like this:

variable_name: type_name

or this:

variable_name # type: shinyType

So in your case(if you have a CustomObject class defined), you can do:

customObj: CustomObject

See this or that for more info.

What is the difference between x86 and x64

If you download Java Development Kit(JDK) then there is a difference as it contains native libraries which differ for different architectures:

  • x86 is for 32-bit OS
  • x64 is for 64-bit OS

In addition you can use 32-bit JDK(x86) on 64-bit OS. But you can not use 64-bit JDK on 32-bit OS.

At the same time you can run compiled Java classes on any JVM. It does not matter whether it 32 or 64-bit.

ERROR in Cannot find module 'node-sass'

One of the cases is the post-install process fails. Right after node-sass is installed, the post-install script will be executed. It requires Python and a C++ builder for that process. The log 'gyp: No Xcode or CLT version detected!' maybe because it couldn't find any C++ builder. So try installing Python and any C++ builder then put their directories in environment variables so that npm can find them. (I come from Windows)

Can I pass a JavaScript variable to another browser window?

Putting code to the matter, you can do this from the parent window:

var thisIsAnObject = {foo:'bar'};
var w = window.open("http://example.com");
w.myVariable = thisIsAnObject;

or this from the new window:

var myVariable = window.opener.thisIsAnObject;

I prefer the latter, because you will probably need to wait for the new page to load anyway, so that you can access its elements, or whatever you want.

How to fix corrupt HDFS FIles

start all daemons and run the command as "hadoop namenode -recover -force" stop the daemons and start again.. wait some time to recover data.

Why rgb and not cmy?

There's a difference between additive colors (http://en.wikipedia.org/wiki/Additive_color) and subtractive colors (http://en.wikipedia.org/wiki/Subtractive_color).

With additive colors, the more you add, the brighter the colors become. This is because they are emitting light. This is why the day light is (more or less) white, since the Sun is emitting in almost all the visible wavelength spectrum.

On the other hand, with subtractive colors the more colors you mix, the darker the resulting color. This is because they are reflecting light. This is also why the black colors get hotter quickly, because it absorbs (almost) all light energy and reflects (almost) none.

Specifically to your question, it depends what medium you are working on. Traditionally, additive colors (RGB) are used because the canon for computer graphics was the computer monitor, and since it's emitting light, it makes sense to use the same structure for the graphic card (the colors are shown without conversions). However, if you are used to graphic arts and press, subtractive color model is used (CMYK). In programs such as Photoshop, you can choose to work in CMYK space although it doesn't matter what color model you use: the primary colors of one group are the secondary colors of the second one and viceversa.

P.D.: my father worked at graphic arts, this is why i know this... :-P

Convert String to double in Java

String s = "12.34";
double num = Double.valueOf(s);

How To Set A JS object property name from a variable

It does not matter where the variable comes from. Main thing we have one ... Set the variable name between square brackets "[ .. ]".

var optionName = 'nameA';
var JsonVar = {
[optionName] : 'some value'
}

Is there a Java API that can create rich Word documents?

There's a tool called JODConverter which hooks into open office to expose it's file format converters, there's versions available as a webapp (sits in tomcat) which you post to and a command line tool. I've been firing html at it and converting to .doc and pdf succesfully it's in a fairly big project, haven't gone live yet but I think I'm going to be using it. http://sourceforge.net/projects/jodconverter/

java get file size efficiently

All the test cases in this post are flawed as they access the same file for each method tested. So disk caching kicks in which tests 2 and 3 benefit from. To prove my point I took test case provided by GHAD and changed the order of enumeration and below are the results.

Looking at result I think File.length() is the winner really.

Order of test is the order of output. You can even see the time taken on my machine varied between executions but File.Length() when not first, and incurring first disk access won.

---
LENGTH sum: 1163351, per Iteration: 4653.404
CHANNEL sum: 1094598, per Iteration: 4378.392
URL sum: 739691, per Iteration: 2958.764

---
CHANNEL sum: 845804, per Iteration: 3383.216
URL sum: 531334, per Iteration: 2125.336
LENGTH sum: 318413, per Iteration: 1273.652

--- 
URL sum: 137368, per Iteration: 549.472
LENGTH sum: 18677, per Iteration: 74.708
CHANNEL sum: 142125, per Iteration: 568.5

Missing Push Notification Entitlement

Yes, that's the cause of the App Store rejection. If your ad-hoc provisioning profile has the aps-environment key, it means your app is configured correctly in the Apple Provisioning Portal. All you need to do is delete the App Store distribution profile on your local machine, then re-download and install the distribution profile from the Provisioning Portal. This new one should contain the aps-environment key.

How to have PHP display errors? (I've added ini_set and error_reporting, but just gives 500 on errors)

Adding to what deceze said above. This is a parse error, so in order to debug a parse error, create a new file in the root named debugSyntax.php. Put this in it:

<?php

///////    SYNTAX ERROR CHECK    ////////////
error_reporting(E_ALL);
ini_set('display_errors','On');

//replace "pageToTest.php" with the file path that you want to test. 
include('pageToTest.php'); 

?>

Run the debugSyntax.php page and it will display parse errors from the page that you chose to test.

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country

If you were using DropDownListFor like this:

@Html.DropDownListFor(m => m.SelectedItemId, Model.MySelectList)

where MySelectList in the model was a property of type SelectList, this error could be thrown if the property was null.

Avoid this by simple initializing it in constructor, like this:

public MyModel()
{
    MySelectList = new SelectList(new List<string>()); // empty list of anything...
}

I know it's not the OP's case, but this might help someone like me which had the same error due to this.

Windows batch file file download from a URL

This question has very good answer in here. My code is purely based on that answer with some modifications.

Save below snippet as wget.bat and put it in your system path (e.g. Put it in a directory and add this directory to system path.)

You can use it in your cli as follows:

wget url/to/file [?custom_name]

where url_to_file is compulsory and custom_name is optional

  1. If name is not provided, then downloaded file will be saved by its own name from the url.
  2. If the name is supplied, then the file will be saved by the new name.

The file url and saved filenames are displayed in ansi colored text. If that is causing problem for you, then check this github project.

@echo OFF
setLocal EnableDelayedExpansion
set Url=%1
set Url=!Url:http://=!
set Url=!Url:/=,!
set Url=!Url:%%20=?!
set Url=!Url: =?!

call :LOOP !Url!

set FileName=%2
if "%2"=="" set FileName=!FN!

echo.
echo.Downloading: [1;33m%1[0m to [1;33m\!FileName![0m

powershell.exe -Command wget %1 -OutFile !FileName!

goto :EOF
:LOOP
if "%1"=="" goto :EOF
set FN=%1
set FN=!FN:?= !
shift
goto :LOOP

P.S. This code requires you to have PowerShell installed.

Which is the best library for XML parsing in java

If you want a DOM-like API - that is, one where the XML parser turns the document into a tree of Element and Attribute nodes - then there are at least four to choose from: DOM itself, JDOM, DOM4J, and XOM. The only possible reason to use DOM is because it's perceived as a standard and is supplied in the JDK: in all other respects, the others are all superior. My own preference, for its combination of simplicity, power, and performance, is XOM.

And of course, there are other styles of processing: low-level parser interfaces (SAX and StAX), data-object binding interfaces (JAXB), and high-level declarative languages (XSLT, XQuery, XPath). Which is best for you depends on your project requirements and your personal taste.

How to Create a real one-to-one relationship in SQL Server

I'm pretty sure it is technically impossible in SQL Server to have a True 1 to 1 relationship, as that would mean you would have to insert both records at the same time (otherwise you'd get a constraint error on insert), in both tables, with both tables having a foreign key relationship to each other.

That being said, your database design described with a foreign key is a 1 to 0..1 relationship. There is no constrain possible that would require a record in tableB. You can have a pseudo-relationship with a trigger that creates the record in tableB.

So there are a few pseudo-solutions

First, store all the data in a single table. Then you'll have no issues in EF.

Or Secondly, your entity must be smart enough to not allow an insert unless it has an associated record.

Or thirdly, and most likely, you have a problem you are trying to solve, and you are asking us why your solution doesn't work instead of the actual problem you are trying to solve (an XY Problem).

UPDATE

To explain in REALITY how 1 to 1 relationships don't work, I'll use the analogy of the Chicken or the egg dilemma. I don't intend to solve this dilemma, but if you were to have a constraint that says in order to add a an Egg to the Egg table, the relationship of the Chicken must exist, and the chicken must exist in the table, then you couldn't add an Egg to the Egg table. The opposite is also true. You cannot add a Chicken to the Chicken table without both the relationship to the Egg and the Egg existing in the Egg table. Thus no records can be every made, in a database without breaking one of the rules/constraints.

Database nomenclature of a one-to-one relationship is misleading. All relationships I've seen (there-fore my experience) would be more descriptive as one-to-(zero or one) relationships.

Can I change the Android startActivity() transition animation?

For fadeIn and fadeOut, only add this after super.onCreate(savedInstanceState) in your new Activity class. You don't need to create something else (No XML, no anim folder, no extra function).

overridePendingTransition(R.anim.abc_fade_in,R.anim.abc_fade_out);

How can I embed a YouTube video on GitHub wiki pages?

Complete Example

Expanding on @MGA's Answer

While it's not possible to embed a video in Markdown you can "fake it" by including a valid linked image in your markup file, using this format:

[![IMAGE ALT TEXT](http://img.youtube.com/vi/YOUTUBE_VIDEO_ID_HERE/0.jpg)](http://www.youtube.com/watch?v=YOUTUBE_VIDEO_ID_HERE "Video Title")

Explanation of the Markdown

If this markup snippet looks complicated, break it down into two parts:

an image
![image alt text](https://example.com/link-to-image)
wrapped in a link
[link text](https://example.com/my-link "link title")

Example using Valid Markdown and YouTube Thumbnail:

Everything Is AWESOME

We are sourcing the thumbnail image directly from YouTube and linking to the actual video, so when the person clicks the image/thumbnail they will be taken to the video.

Code:

[![Everything Is AWESOME](https://img.youtube.com/vi/StTqXEQ2l-Y/0.jpg)](https://www.youtube.com/watch?v=StTqXEQ2l-Y "Everything Is AWESOME")

OR If you want to give readers a visual cue that the image/thumbnail is actually a playable video, take your own screenshot of the video in YouTube and use that as the thumbnail instead.

Example using Screenshot with Video Controls as Visual Cue:

Everything Is AWESOME

Code:

[![Everything Is AWESOME](http://i.imgur.com/Ot5DWAW.png)](https://youtu.be/StTqXEQ2l-Y?t=35s "Everything Is AWESOME")

 Clear Advantages

While this requires a couple of extra steps (a) taking the screenshot of the video and (b) uploading it so you can use the image as your thumbnail it does have 3 clear advantages:

  1. The person reading your markdown (or resulting html page) has a visual cue telling them they can watch the video (video controls encourage clicking)
  2. You can chose a specific frame in the video to use as the thumbnail (thus making your content more engaging)
  3. You can link to a specific time in the video from which play will start when the linked-image is clicked. (in our case from 35 seconds)

Taking and uploading a screenshot takes a few seconds but has a big payoff.

Works Everywhere!

Since this is standard markdown, it works everywhere. try it on GitHub, Reddit, Ghost, and here on Stack Overflow.

Vimeo

This approach also works with Vimeo videos

Example

Little red riding hood

Code

[![Little red riding hood](http://i.imgur.com/7YTMFQp.png)](https://vimeo.com/3514904 "Little red riding hood - Click to Watch!")

Notes:

Copy data from one column to other column (which is in a different table)

In SQL Server 2008 you can use a multi-table update as follows:

UPDATE tblindiantime 
SET tblindiantime.CountryName = contacts.BusinessCountry
FROM tblindiantime 
JOIN contacts
ON -- join condition here

You need a join condition to specify which row should be updated.

If the target table is currently empty then you should use an INSERT instead:

INSERT INTO tblindiantime (CountryName)
SELECT BusinessCountry FROM contacts

How to update RecyclerView Adapter Data?

I found out that a really simple way to reload the RecyclerView is to just call

recyclerView.removeAllViews();

This will first remove all content of the RecyclerView and then add it again with the updated values.

Output in a table format in Java's System.out

I may be very late for the Answer but here a simple and generic solution

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class TableGenerator {

    private int PADDING_SIZE = 2;
    private String NEW_LINE = "\n";
    private String TABLE_JOINT_SYMBOL = "+";
    private String TABLE_V_SPLIT_SYMBOL = "|";
    private String TABLE_H_SPLIT_SYMBOL = "-";

    public String generateTable(List<String> headersList, List<List<String>> rowsList,int... overRiddenHeaderHeight)
    {
        StringBuilder stringBuilder = new StringBuilder();

        int rowHeight = overRiddenHeaderHeight.length > 0 ? overRiddenHeaderHeight[0] : 1; 

        Map<Integer,Integer> columnMaxWidthMapping = getMaximumWidhtofTable(headersList, rowsList);

        stringBuilder.append(NEW_LINE);
        stringBuilder.append(NEW_LINE);
        createRowLine(stringBuilder, headersList.size(), columnMaxWidthMapping);
        stringBuilder.append(NEW_LINE);


        for (int headerIndex = 0; headerIndex < headersList.size(); headerIndex++) {
            fillCell(stringBuilder, headersList.get(headerIndex), headerIndex, columnMaxWidthMapping);
        }

        stringBuilder.append(NEW_LINE);

        createRowLine(stringBuilder, headersList.size(), columnMaxWidthMapping);


        for (List<String> row : rowsList) {

            for (int i = 0; i < rowHeight; i++) {
                stringBuilder.append(NEW_LINE);
            }

            for (int cellIndex = 0; cellIndex < row.size(); cellIndex++) {
                fillCell(stringBuilder, row.get(cellIndex), cellIndex, columnMaxWidthMapping);
            }

        }

        stringBuilder.append(NEW_LINE);
        createRowLine(stringBuilder, headersList.size(), columnMaxWidthMapping);
        stringBuilder.append(NEW_LINE);
        stringBuilder.append(NEW_LINE);

        return stringBuilder.toString();
    }

    private void fillSpace(StringBuilder stringBuilder, int length)
    {
        for (int i = 0; i < length; i++) {
            stringBuilder.append(" ");
        }
    }

    private void createRowLine(StringBuilder stringBuilder,int headersListSize, Map<Integer,Integer> columnMaxWidthMapping)
    {
        for (int i = 0; i < headersListSize; i++) {
            if(i == 0)
            {
                stringBuilder.append(TABLE_JOINT_SYMBOL);   
            }

            for (int j = 0; j < columnMaxWidthMapping.get(i) + PADDING_SIZE * 2 ; j++) {
                stringBuilder.append(TABLE_H_SPLIT_SYMBOL);
            }
            stringBuilder.append(TABLE_JOINT_SYMBOL);
        }
    }


    private Map<Integer,Integer> getMaximumWidhtofTable(List<String> headersList, List<List<String>> rowsList)
    {
        Map<Integer,Integer> columnMaxWidthMapping = new HashMap<>();

        for (int columnIndex = 0; columnIndex < headersList.size(); columnIndex++) {
            columnMaxWidthMapping.put(columnIndex, 0);
        }

        for (int columnIndex = 0; columnIndex < headersList.size(); columnIndex++) {

            if(headersList.get(columnIndex).length() > columnMaxWidthMapping.get(columnIndex))
            {
                columnMaxWidthMapping.put(columnIndex, headersList.get(columnIndex).length());
            }
        }


        for (List<String> row : rowsList) {

            for (int columnIndex = 0; columnIndex < row.size(); columnIndex++) {

                if(row.get(columnIndex).length() > columnMaxWidthMapping.get(columnIndex))
                {
                    columnMaxWidthMapping.put(columnIndex, row.get(columnIndex).length());
                }
            }
        }

        for (int columnIndex = 0; columnIndex < headersList.size(); columnIndex++) {

            if(columnMaxWidthMapping.get(columnIndex) % 2 != 0)
            {
                columnMaxWidthMapping.put(columnIndex, columnMaxWidthMapping.get(columnIndex) + 1);
            }
        }


        return columnMaxWidthMapping;
    }

    private int getOptimumCellPadding(int cellIndex,int datalength,Map<Integer,Integer> columnMaxWidthMapping,int cellPaddingSize)
    {
        if(datalength % 2 != 0)
        {
            datalength++;
        }

        if(datalength < columnMaxWidthMapping.get(cellIndex))
        {
            cellPaddingSize = cellPaddingSize + (columnMaxWidthMapping.get(cellIndex) - datalength) / 2;
        }

        return cellPaddingSize;
    }

    private void fillCell(StringBuilder stringBuilder,String cell,int cellIndex,Map<Integer,Integer> columnMaxWidthMapping)
    {

        int cellPaddingSize = getOptimumCellPadding(cellIndex, cell.length(), columnMaxWidthMapping, PADDING_SIZE);

        if(cellIndex == 0)
        {
            stringBuilder.append(TABLE_V_SPLIT_SYMBOL); 
        }

        fillSpace(stringBuilder, cellPaddingSize);
        stringBuilder.append(cell);
        if(cell.length() % 2 != 0)
        {
            stringBuilder.append(" ");
        }

        fillSpace(stringBuilder, cellPaddingSize);

        stringBuilder.append(TABLE_V_SPLIT_SYMBOL); 

    }

    public static void main(String[] args) {
        TableGenerator tableGenerator = new TableGenerator();

        List<String> headersList = new ArrayList<>(); 
        headersList.add("Id");
        headersList.add("F-Name");
        headersList.add("L-Name");
        headersList.add("Email");

        List<List<String>> rowsList = new ArrayList<>();

        for (int i = 0; i < 5; i++) {
            List<String> row = new ArrayList<>(); 
            row.add(UUID.randomUUID().toString());
            row.add(UUID.randomUUID().toString());
            row.add(UUID.randomUUID().toString());
            row.add(UUID.randomUUID().toString());

            rowsList.add(row);
        }

        System.out.println(tableGenerator.generateTable(headersList, rowsList));
    }
}

With this kind of Output

+----------------------------------------+----------------------------------------+----------------------------------------+----------------------------------------+
|                   Id                   |                F-Name                  |                 L-Name                 |                  Email                 |
+----------------------------------------+----------------------------------------+----------------------------------------+----------------------------------------+
|  70a56f25-d42a-499c-83ac-50188c45a0ac  |  aa04285e-c135-46e2-9f90-988bf7796cd0  |  ac495ba7-d3c7-463c-8c24-9ffde67324bc  |  f6b5851b-41e0-4a4e-a237-74f8e0bff9ab  |
|  6de181ca-919a-4425-a753-78d2de1038ef  |  c4ba5771-ccee-416e-aebd-ef94b07f4fa2  |  365980cb-e23a-4513-a895-77658f130135  |  69e01da1-078e-4934-afb0-5afd6ee166ac  |
|  f3285f33-5083-4881-a8b4-c8ae10372a6c  |  46df25ed-fa0f-42a4-9181-a0528bc593f6  |  d24016bf-a03f-424d-9a8f-9a7b7388fd85  |  4b976794-aac1-441e-8bd2-78f5ccbbd653  |
|  ab799acb-a582-45e7-ba2f-806948967e6c  |  d019438d-0a75-48bc-977b-9560de4e033e  |  8cb2ad11-978b-4a67-a87e-439d0a21ef99  |  2f2d9a39-9d95-4a5a-993f-ceedd5ff9953  |
|  78a68c0a-a824-42e8-b8a8-3bdd8a89e773  |  0f030c1b-2069-4c1a-bf7d-f23d1e291d2a  |  7f647cb4-a22e-46d2-8c96-0c09981773b1  |  0bc944ef-c1a7-4dd1-9eef-915712035a74  |
+----------------------------------------+----------------------------------------+----------------------------------------+----------------------------------------+

How do I make the scrollbar on a div only visible when necessary?

You can try with below one:

  <div style="width: 100%; height: 100%; overflow-x: visible; overflow-y: scroll;">Text</div>

How to show all privileges from a user in oracle?

You can use below code to get all the privileges list from all users.

select * from dba_sys_privs 

How to add some non-standard font to a website?

I did a bit of research and dug up Dynamic Text Replacement (published 2004-06-15).

This technique uses images, but it appears to be "hands free". You write your text, and you let a few automated scripts do automated find-and-replace on the page for you on the fly.

It has some limitations, but it is probably one of the easier choices (and more browser compatible) than all the rest I've seen.

How to Convert double to int in C?

I suspect you don't actually have that problem - I suspect you've really got:

double a = callSomeFunction();
// Examine a in the debugger or via logging, and decide it's 3669.0

// Now cast
int b = (int) a;
// Now a is 3668

What makes me say that is that although it's true that many decimal values cannot be stored exactly in float or double, that doesn't hold for integers of this kind of magnitude. They can very easily be exactly represented in binary floating point form. (Very large integers can't always be exactly represented, but we're not dealing with a very large integer here.)

I strongly suspect that your double value is actually slightly less than 3669.0, but it's being displayed to you as 3669.0 by whatever diagnostic device you're using. The conversion to an integer value just performs truncation, not rounding - hence the issue.

Assuming your double type is an IEEE-754 64-bit type, the largest value which is less than 3669.0 is exactly

3668.99999999999954525264911353588104248046875

So if you're using any diagnostic approach where that value would be shown as 3669.0, then it's quite possible (probable, I'd say) that this is what's happening.

How can I rename column in laravel using migration?

Follow these steps, respectively for rename column migration file.

1- Is there Doctrine/dbal library in your project. If you don't have run the command first

composer require doctrine/dbal

2- create update migration file for update old migration file. Warning (need to have the same name)

php artisan make:migration update_oldFileName_table

for example my old migration file name: create_users_table update file name should : update_users_table

3- update_oldNameFile_table.php

Schema::table('users', function (Blueprint $table) {
$table->renameColumn('from', 'to');
});

'from' my old column name and 'to' my new column name

4- Finally run the migrate command

php artisan migrate

Source link: laravel document

Remove all padding and margin table HTML and CSS

Try to use this CSS:

/* Apply this to your `table` element. */
#page {
   border-collapse: collapse;
}

/* And this to your table's `td` elements. */
#page td {
   padding: 0; 
   margin: 0;
}

How to center and crop an image to always appear in square shape with CSS?

object-fit property does the magic. On JsFiddle.

CSS

.image {
  width: 160px;
  height: 160px;
}

.object-fit_fill {
  object-fit: fill
}

.object-fit_contain {
  object-fit: contain
}

.object-fit_cover {
  object-fit: cover
}

.object-fit_none {
  object-fit: none
}

.object-fit_scale-down {
  object-fit: scale-down
}

HTML

<div class="original-image">
  <p>original image</p>
  <img src="http://lorempixel.com/500/200">
</div>

<div class="image">
  <p>object-fit: fill</p>
  <img class="object-fit_fill" src="http://lorempixel.com/500/200">
</div>

<div class="image">
  <p>object-fit: contain</p>
  <img class="object-fit_contain" src="http://lorempixel.com/500/200">
</div>

<div class="image">
  <p>object-fit: cover</p>
  <img class="object-fit_cover" src="http://lorempixel.com/500/200">
</div>

<div class="image">
  <p>object-fit: none</p>
  <img class="object-fit_none" src="http://lorempixel.com/500/200">
</div>

<div class="image">
  <p>object-fit: scale-down</p>
  <img class="object-fit_scale-down" src="http://lorempixel.com/500/200">
</div>

Result

How the rendered images look (in a browser that supports <code>object-fit</code>)

How to show soft-keyboard when edittext is focused

To hide keyboard, use this one:

getActivity().getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

and to show keyboard:

getActivity().getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

How can I set a cookie in react?

Little update. There is a hook available for react-cookie

1) First of all, install the dependency (just for a note)

yarn add react-cookie

or

npm install react-cookie

2) My usage example:

// SignInComponent.js
import { useCookies } from 'react-cookie'

const SignInComponent = () => {

// ...

const [cookies, setCookie] = useCookies(['access_token', 'refresh_token'])

async function onSubmit(values) {
    const response = await getOauthResponse(values);

    let expires = new Date()
    expires.setTime(expires.getTime() + (response.data.expires_in * 1000))
    setCookie('access_token', response.data.access_token, { path: '/',  expires})
    setCookie('refresh_token', response.data.refresh_token, {path: '/', expires})

    // ...
}

// next goes my sign-in form

}

Hope it is helpful.

Suggestions to improve the example above are very appreciated!

IIS7 - The request filtering module is configured to deny a request that exceeds the request content length

<configuration>
    <system.web>
        <httpRuntime maxRequestLength="1048576" />
    </system.web>
</configuration>

From here.

For IIS7 and above, you also need to add the lines below:

 <system.webServer>
   <security>
      <requestFiltering>
         <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
   </security>
 </system.webServer>

How can I detect if this dictionary key exists in C#?

What is the type of c.PhysicalAddresses? If it's Dictionary<TKey,TValue>, then you can use the ContainsKey method.

How to change the remote a branch is tracking?

I've found @critikaster's post helpful, except that I had to perform these commands with GIT 2.21:

$ git remote set-url origin https://some_url/some_repo
$ git push --set-upstream origin master

Spring jUnit Testing properties file

As for the testing, you should use from Spring 4.1 which will overwrite the properties defined in other places:

@TestPropertySource("classpath:application-test.properties")

Test property sources have higher precedence than those loaded from the operating system's environment or Java system properties as well as property sources added by the application like @PropertySource

URL rewriting with PHP

If you only want to change the route for picture.php then adding rewrite rule in .htaccess will serve your needs, but, if you want the URL rewriting as in Wordpress then PHP is the way. Here is simple example to begin with.

Folder structure

There are two files that are needed in the root folder, .htaccess and index.php, and it would be good to place the rest of the .php files in separate folder, like inc/.

root/
  inc/
  .htaccess
  index.php

.htaccess

RewriteEngine On
RewriteRule ^inc/.*$ index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]

This file has four directives:

  1. RewriteEngine - enable the rewriting engine
  2. RewriteRule - deny access to all files in inc/ folder, redirect any call to that folder to index.php
  3. RewriteCond - allow direct access to all other files ( like images, css or scripts )
  4. RewriteRule - redirect anything else to index.php

index.php

Because everything is now redirected to index.php, there will be determined if the url is correct, all parameters are present, and if the type of parameters are correct.

To test the url we need to have a set of rules, and the best tool for that is a regular expression. By using regular expressions we will kill two flies with one blow. Url, to pass this test must have all the required parameters that are tested on allowed characters. Here are some examples of rules.

$rules = array( 
    'picture'   => "/picture/(?'text'[^/]+)/(?'id'\d+)",    // '/picture/some-text/51'
    'album'     => "/album/(?'album'[\w\-]+)",              // '/album/album-slug'
    'category'  => "/category/(?'category'[\w\-]+)",        // '/category/category-slug'
    'page'      => "/page/(?'page'about|contact)",          // '/page/about', '/page/contact'
    'post'      => "/(?'post'[\w\-]+)",                     // '/post-slug'
    'home'      => "/"                                      // '/'
);

Next is to prepare the request uri.

$uri = rtrim( dirname($_SERVER["SCRIPT_NAME"]), '/' );
$uri = '/' . trim( str_replace( $uri, '', $_SERVER['REQUEST_URI'] ), '/' );
$uri = urldecode( $uri );

Now that we have the request uri, the final step is to test uri on regular expression rules.

foreach ( $rules as $action => $rule ) {
    if ( preg_match( '~^'.$rule.'$~i', $uri, $params ) ) {
        /* now you know the action and parameters so you can 
         * include appropriate template file ( or proceed in some other way )
         */
    }
}

Successful match will, since we use named subpatterns in regex, fill the $params array almost the same as PHP fills the $_GET array. However, when using a dynamic url, $_GET array is populated without any checks of the parameters.

    /picture/some+text/51

    Array
    (
        [0] => /picture/some text/51
        [text] => some text
        [1] => some text
        [id] => 51
        [2] => 51
    )

    picture.php?text=some+text&id=51

    Array
    (
        [text] => some text
        [id] => 51
    )

These few lines of code and a basic knowing of regular expressions is enough to start building a solid routing system.

Complete source

define( 'INCLUDE_DIR', dirname( __FILE__ ) . '/inc/' );

$rules = array( 
    'picture'   => "/picture/(?'text'[^/]+)/(?'id'\d+)",    // '/picture/some-text/51'
    'album'     => "/album/(?'album'[\w\-]+)",              // '/album/album-slug'
    'category'  => "/category/(?'category'[\w\-]+)",        // '/category/category-slug'
    'page'      => "/page/(?'page'about|contact)",          // '/page/about', '/page/contact'
    'post'      => "/(?'post'[\w\-]+)",                     // '/post-slug'
    'home'      => "/"                                      // '/'
);

$uri = rtrim( dirname($_SERVER["SCRIPT_NAME"]), '/' );
$uri = '/' . trim( str_replace( $uri, '', $_SERVER['REQUEST_URI'] ), '/' );
$uri = urldecode( $uri );

foreach ( $rules as $action => $rule ) {
    if ( preg_match( '~^'.$rule.'$~i', $uri, $params ) ) {
        /* now you know the action and parameters so you can 
         * include appropriate template file ( or proceed in some other way )
         */
        include( INCLUDE_DIR . $action . '.php' );

        // exit to avoid the 404 message 
        exit();
    }
}

// nothing is found so handle the 404 error
include( INCLUDE_DIR . '404.php' );

How to make an alert dialog fill 90% of screen size?

public static WindowManager.LayoutParams setDialogLayoutParams(Activity activity, Dialog dialog)
    {
        try 
        {
            Display display = activity.getWindowManager().getDefaultDisplay();
            Point screenSize = new Point();
            display.getSize(screenSize);
            int width = screenSize.x;

            WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
            layoutParams.copyFrom(dialog.getWindow().getAttributes());
            layoutParams.width = (int) (width - (width * 0.07) ); 
            layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
            return layoutParams;
        } 
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }

What is the most efficient/elegant way to parse a flat table into a tree?

There are really good solutions which exploit the internal btree representation of sql indices. This is based on some great research done back around 1998.

Here is an example table (in mysql).

CREATE TABLE `node` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `tw` int(10) unsigned NOT NULL,
  `pa` int(10) unsigned DEFAULT NULL,
  `sz` int(10) unsigned DEFAULT NULL,
  `nc` int(11) GENERATED ALWAYS AS (tw+sz) STORED,
  PRIMARY KEY (`id`),
  KEY `node_tw_index` (`tw`),
  KEY `node_pa_index` (`pa`),
  KEY `node_nc_index` (`nc`),
  CONSTRAINT `node_pa_fk` FOREIGN KEY (`pa`) REFERENCES `node` (`tw`) ON DELETE CASCADE
)

The only fields necessary for the tree representation are:

  • tw: The Left to Right DFS Pre-order index, where root = 1.
  • pa: The reference (using tw) to the parent node, root has null.
  • sz: The size of the node's branch including itself.
  • nc: is used as syntactic sugar. it is tw+nc and represents the tw of the node's "next child".

Here is an example 24 node population, ordered by tw:

+-----+---------+----+------+------+------+
| id  | name    | tw | pa   | sz   | nc   |
+-----+---------+----+------+------+------+
|   1 | Root    |  1 | NULL |   24 |   25 |
|   2 | A       |  2 |    1 |   14 |   16 |
|   3 | AA      |  3 |    2 |    1 |    4 |
|   4 | AB      |  4 |    2 |    7 |   11 |
|   5 | ABA     |  5 |    4 |    1 |    6 |
|   6 | ABB     |  6 |    4 |    3 |    9 |
|   7 | ABBA    |  7 |    6 |    1 |    8 |
|   8 | ABBB    |  8 |    6 |    1 |    9 |
|   9 | ABC     |  9 |    4 |    2 |   11 |
|  10 | ABCD    | 10 |    9 |    1 |   11 |
|  11 | AC      | 11 |    2 |    4 |   15 |
|  12 | ACA     | 12 |   11 |    2 |   14 |
|  13 | ACAA    | 13 |   12 |    1 |   14 |
|  14 | ACB     | 14 |   11 |    1 |   15 |
|  15 | AD      | 15 |    2 |    1 |   16 |
|  16 | B       | 16 |    1 |    1 |   17 |
|  17 | C       | 17 |    1 |    6 |   23 |
| 359 | C0      | 18 |   17 |    5 |   23 |
| 360 | C1      | 19 |   18 |    4 |   23 |
| 361 | C2(res) | 20 |   19 |    3 |   23 |
| 362 | C3      | 21 |   20 |    2 |   23 |
| 363 | C4      | 22 |   21 |    1 |   23 |
|  18 | D       | 23 |    1 |    1 |   24 |
|  19 | E       | 24 |    1 |    1 |   25 |
+-----+---------+----+------+------+------+

Every tree result can be done non-recursively. For instance, to get a list of ancestors of node at tw='22'

Ancestors

select anc.* from node me,node anc 
where me.tw=22 and anc.nc >= me.tw and anc.tw <= me.tw 
order by anc.tw;
+-----+---------+----+------+------+------+
| id  | name    | tw | pa   | sz   | nc   |
+-----+---------+----+------+------+------+
|   1 | Root    |  1 | NULL |   24 |   25 |
|  17 | C       | 17 |    1 |    6 |   23 |
| 359 | C0      | 18 |   17 |    5 |   23 |
| 360 | C1      | 19 |   18 |    4 |   23 |
| 361 | C2(res) | 20 |   19 |    3 |   23 |
| 362 | C3      | 21 |   20 |    2 |   23 |
| 363 | C4      | 22 |   21 |    1 |   23 |
+-----+---------+----+------+------+------+

Siblings and children are trivial - just use pa field ordering by tw.

Descendants

For example the set (branch) of nodes that are rooted at tw = 17.

select des.* from node me,node des 
where me.tw=17 and des.tw < me.nc and des.tw >= me.tw 
order by des.tw;
+-----+---------+----+------+------+------+
| id  | name    | tw | pa   | sz   | nc   |
+-----+---------+----+------+------+------+
|  17 | C       | 17 |    1 |    6 |   23 |
| 359 | C0      | 18 |   17 |    5 |   23 |
| 360 | C1      | 19 |   18 |    4 |   23 |
| 361 | C2(res) | 20 |   19 |    3 |   23 |
| 362 | C3      | 21 |   20 |    2 |   23 |
| 363 | C4      | 22 |   21 |    1 |   23 |
+-----+---------+----+------+------+------+

Additional Notes

This methodology is extremely useful for when there are a far greater number of reads than there are inserts or updates.

Because the insertion, movement, or updating of a node in the tree requires the tree to be adjusted, it is necessary to lock the table before commencing with the action.

The insertion/deletion cost is high because the tw index and sz (branch size) values will need to be updated on all the nodes after the insertion point, and for all ancestors respectively.

Branch moving involves moving the tw value of the branch out of range, so it is also necessary to disable foreign key constraints when moving a branch. There are, essentially four queries required to move a branch:

  • Move the branch out of range.
  • Close the gap that it left. (the remaining tree is now normalised).
  • Open the gap where it will go to.
  • Move the branch into it's new position.

Adjust Tree Queries

The opening/closing of gaps in the tree is an important sub-function used by create/update/delete methods, so I include it here.

We need two parameters - a flag representing whether or not we are downsizing or upsizing, and the node's tw index. So, for example tw=18 (which has a branch size of 5). Let's assume that we are downsizing (removing tw) - this means that we are using '-' instead of '+' in the updates of the following example.

We first use a (slightly altered) ancestor function to update the sz value.

update node me, node anc set anc.sz = anc.sz - me.sz from 
node me, node anc where me.tw=18 
and ((anc.nc >= me.tw and anc.tw < me.pa) or (anc.tw=me.pa));

Then we need to adjust the tw for those whose tw is higher than the branch to be removed.

update node me, node anc set anc.tw = anc.tw - me.sz from 
node me, node anc where me.tw=18 and anc.tw >= me.tw;

Then we need to adjust the parent for those whose pa's tw is higher than the branch to be removed.

update node me, node anc set anc.pa = anc.pa - me.sz from 
node me, node anc where me.tw=18 and anc.pa >= me.tw;

Using Google Text-To-Speech in Javascript

Here is the code snippet I found:

var audio = new Audio();
audio.src ='http://translate.google.com/translate_tts?ie=utf-8&tl=en&q=Hello%20World.';
audio.play();