Programs & Examples On #Ipconfig

A Windows command used to view and modify network IP-related settings.

What is Teredo Tunneling Pseudo-Interface?

Is to do with IPv6

All the gory details here: http://www.microsoft.com/technet/network/ipv6/teredo.mspx

Some people have had issues with it, and disabled it, but as a general rule, if it aint broke...

JPA COUNT with composite primary key query not working

Use count(d.ertek) or count(d.id) instead of count(d). This can be happen when you have composite primary key at your entity.

How to get first N elements of a list in C#?

To take first 5 elements better use expression like this one:

var firstFiveArrivals = myList.Where([EXPRESSION]).Take(5);

or

var firstFiveArrivals = myList.Where([EXPRESSION]).Take(5).OrderBy([ORDER EXPR]);

It will be faster than orderBy variant, because LINQ engine will not scan trough all list due to delayed execution, and will not sort all array.

class MyList : IEnumerable<int>
{

    int maxCount = 0;

    public int RequestCount
    {
        get;
        private set;
    }
    public MyList(int maxCount)
    {
        this.maxCount = maxCount;
    }
    public void Reset()
    {
        RequestCount = 0;
    }
    #region IEnumerable<int> Members

    public IEnumerator<int> GetEnumerator()
    {
        int i = 0;
        while (i < maxCount)
        {
            RequestCount++;
            yield return i++;
        }
    }

    #endregion

    #region IEnumerable Members

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException();
    }

    #endregion
}
class Program
{
    static void Main(string[] args)
    {
        var list = new MyList(15);
        list.Take(5).ToArray();
        Console.WriteLine(list.RequestCount); // 5;

        list.Reset();
        list.OrderBy(q => q).Take(5).ToArray();
        Console.WriteLine(list.RequestCount); // 15;

        list.Reset();
        list.Where(q => (q & 1) == 0).Take(5).ToArray();
        Console.WriteLine(list.RequestCount); // 9; (first 5 odd)

        list.Reset();
        list.Where(q => (q & 1) == 0).Take(5).OrderBy(q => q).ToArray();
        Console.WriteLine(list.RequestCount); // 9; (first 5 odd)
    }
}

Automatically create an Enum based on values in a database lookup table?

Does it have to be an actual enum? How about using a Dictionary<string,int> instead?

for example

Dictionary<string, int> MyEnum = new Dictionary(){{"One", 1}, {"Two", 2}};
Console.WriteLine(MyEnum["One"]);

Copying PostgreSQL database to another server

If you are looking to migrate between versions (eg you updated postgres and have 9.1 running on localhost:5432 and 9.3 running on localhost:5434) you can run:

pg_dumpall -p 5432 -U myuser91 | psql -U myuser94 -d postgres -p 5434

Check out the migration docs.

ios Upload Image and Text using HTTP POST

Here's code from my app to post an image to our web server:

// Dictionary that holds post parameters. You can set your post parameters that your server accepts or programmed to accept.
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:[NSString stringWithString:@"1.0"] forKey:[NSString stringWithString:@"ver"]];
[_params setObject:[NSString stringWithString:@"en"] forKey:[NSString stringWithString:@"lan"]];
[_params setObject:[NSString stringWithFormat:@"%d", userId] forKey:[NSString stringWithString:@"userId"]];
[_params setObject:[NSString stringWithFormat:@"%@",title] forKey:[NSString stringWithString:@"title"]];

// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
NSString *BoundaryConstant = [NSString stringWithString:@"----------V2ymHFg03ehbqgZCaKO6jy"];

// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ 
NSString* FileParamConstant = [NSString stringWithString:@"file"];

// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:@""]; 

// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];                                    
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:@"POST"];

// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];

// post body
NSMutableData *body = [NSMutableData data];

// add params (all params are strings)
for (NSString *param in _params) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}

// add image data
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0);
if (imageData) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:imageData];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}

[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];

// setting the body of the post to the reqeust
[request setHTTPBody:body];

// set the content-length
NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long) [body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

// set URL
[request setURL:requestURL];

Check if passed argument is file or directory in Bash

A more elegant solution

echo "Enter the file name"
read x
if [ -f $x ]
then
    echo "This is a regular file"
else
    echo "This is a directory"
fi

SyntaxError: missing ; before statement

too many ) parenthesis remove one of them.

Download a file with Android, and showing the progress in a ProgressDialog

Do not forget to replace "/sdcard..." by new File("/mnt/sdcard/...") otherwise you will get a FileNotFoundException

Bulk Insertion in Laravel using eloquent ORM

This is how you do it in more Eloquent way,

    $allintests = [];
    foreach($intersts as $item){ //$intersts array contains input data
        $intestcat = new User_Category();
        $intestcat->memberid = $item->memberid;
        $intestcat->catid= $item->catid;
        $allintests[] = $intestcat->attributesToArray();
    }
    User_Category::insert($allintests);

ASP.NET Core configuration for .NET Core console application

On .Net Core 3.1 we just need to do these:

static void Main(string[] args)
{
  var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
}

Using SeriLog will look like:

using Microsoft.Extensions.Configuration;
using Serilog;
using System;


namespace yournamespace
{
    class Program
    {

        static void Main(string[] args)
        {
            var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
            Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();

            try
            {
                Log.Information("Starting Program.");
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Program terminated unexpectedly.");
                return;
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
    }
}

And the Serilog appsetings.json section for generating one file daily will look like:

  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "C:\\Logs\\Program.json",
          "rollingInterval": "Day",
          "formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact"
        }
      }
    ]
  }

mysql stored-procedure: out parameter

SET out_number=SQRT(input_number); 

Instead of this write:

select SQRT(input_number); 

Please don't write SET out_number and your input parameter should be:

PROCEDURE `test`.`my_sqrt`(IN input_number INT, OUT out_number FLOAT) 

How can I see the specific value of the sql_mode?

You can also try this to determine the current global sql_mode value:

SELECT @@GLOBAL.sql_mode;

or session sql_mode value:

SELECT @@SESSION.sql_mode;

I also had the feeling that the SQL mode was indeed empty.

How do I check for vowels in JavaScript?

function isVowel(char)
{
  if (char.length == 1)
  {
    var vowels = "aeiou";
    var isVowel = vowels.indexOf(char) >= 0 ? true : false;

    return isVowel;
  }
}

Basically it checks for the index of the character in the string of vowels. If it is a consonant, and not in the string, indexOf will return -1.

TypeScript and array reduce function

Reduce() is..

  • The reduce() method reduces the array to a single value.
  • The reduce() method executes a provided function for each value of the array (from left-to-right).
  • The return value of the function is stored in an accumulator (result/total).

It was ..

let array=[1,2,3];
function sum(acc,val){ return acc+val;} // => can change to (acc,val)=>acc+val
let answer= array.reduce(sum); // answer is 6

Change to

let array=[1,2,3];
let answer=arrays.reduce((acc,val)=>acc+val);

Also you can use in

  1. find max
    let array=[5,4,19,2,7];
    function findMax(acc,val)
    {
     if(val>acc){
       acc=val; 
     }
    }

    let biggest=arrays.reduce(findMax); // 19
  1. find an element that not repeated.
    arr = [1, 2, 5, 4, 6, 8, 9, 2, 1, 4, 5, 8, 9]
    v = 0
    for i in range(len(arr)):
    v = v ^ arr[i]
    print(value)  //6

git diff file against its last change

One of the ways to use git diff is:

git diff <commit> <path>

And a common way to refer one commit of the last commit is as a relative path to the actual HEAD. You can reference previous commits as HEAD^ (in your example this will be 123abc) or HEAD^^ (456def in your example), etc ...

So the answer to your question is:

git diff HEAD^^ myfile

Input group - two inputs close to each other

To show more than one inputs inline without using "form-inline" class you can use the next code:

<div class="input-group">
    <input type="text" class="form-control" value="First input" />
    <span class="input-group-btn"></span>
    <input type="text" class="form-control" value="Second input" />
</div>

Then using CSS selectors:

/* To remove space between text inputs */
.input-group > .input-group-btn:empty {
    width: 0px;
}

Basically you have to insert an empty span tag with "input-group-btn" class between input tags.

If you want to see more examples of input groups and bootstrap-select groups take a look at this URL: http://jsfiddle.net/vkhusnulina/gze0Lcm0

How can I search sub-folders using glob.glob module?

configfiles = glob.glob('C:/Users/sam/Desktop/**/*.txt")

Doesn't works for all cases, instead use glob2

configfiles = glob2.glob('C:/Users/sam/Desktop/**/*.txt")

How can I make grep print the lines below and above each matching line?

Use -B, -A or -C option

grep --help
...
-B, --before-context=NUM  print NUM lines of leading context
-A, --after-context=NUM   print NUM lines of trailing context
-C, --context=NUM         print NUM lines of output context
-NUM                      same as --context=NUM
...

Understanding the basics of Git and GitHub

  1. What is the difference between Git and GitHub?

    Git is a version control system; think of it as a series of snapshots (commits) of your code. You see a path of these snapshots, in which order they where created. You can make branches to experiment and come back to snapshots you took.

    GitHub, is a web-page on which you can publish your Git repositories and collaborate with other people.

  2. Is Git saving every repository locally (in the user's machine) and in GitHub?

    No, it's only local. You can decide to push (publish) some branches on GitHub.

  3. Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?

    Yes, Git runs local if you don't use GitHub. An alternative to using GitHub could be running Git on files hosted on Dropbox, but GitHub is a more streamlined service as it was made especially for Git.

  4. How does Git compare to a backup system such as Time Machine?

    It's a different thing, Git lets you track changes and your development process. If you use Git with GitHub, it becomes effectively a backup. However usually you would not push all the time to GitHub, at which point you do not have a full backup if things go wrong. I use git in a folder that is synchronized with Dropbox.

  5. Is this a manual process, in other words if you don't commit you won't have a new version of the changes made?

    Yes, committing and pushing are both manual.

  6. If are not collaborating and you are already using a backup system why would you use Git?

    • If you encounter an error between commits you can use the command git diff to see the differences between the current code and the last working commit, helping you to locate your error.

    • You can also just go back to the last working commit.

    • If you want to try a change, but are not sure that it will work. You create a branch to test you code change. If it works fine, you merge it to the main branch. If it does not you just throw the branch away and go back to the main branch.

    • You did some debugging. Before you commit you always look at the changes from the last commit. You see your debug print statement that you forgot to delete.

Make sure you check gitimmersion.com.

How to manage a redirect request after a jQuery Ajax call

No browsers handle 301 and 302 responses correctly. And in fact the standard even says they should handle them "transparently" which is a MASSIVE headache for Ajax Library vendors. In Ra-Ajax we were forced into using HTTP response status code 278 (just some "unused" success code) to handle transparently redirects from the server...

This really annoys me, and if someone here have some "pull" in W3C I would appreciate that you could let W3C know that we really need to handle 301 and 302 codes ourselves...! ;)

Does Index of Array Exist

Assuming you also want to check if the item is not null

if (array.Length > 25 && array[25] != null)
{
    //it exists
}

Check if an element contains a class in JavaScript?

The easy and effective solution is trying .contains method.

test.classList.contains(testClass);

Error :- java runtime environment JRE or java development kit must be available in order to run eclipse

open /Users/you/eclipse/java-oxygen right click on eclipse, click on show package content

Then go to Contents/Eclipse and select file eclipse.ini, open in text file or in any editor.

search deleted java path and add newer java path till bin /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/bin

Use Awk to extract substring

I am asking in general, how to write a compatible awk script that performs the same functionality ...

To solve the problem in your quesiton is easy. (check others' answer).

If you want to write an awk script, which portable to any awk implementations and versions (gawk/nawk/mawk...) it is really hard, even if with --posix (gawk)

for example:

  • some awk works on string in terms of characters, some with bytes
  • some supports \x escape, some not
  • FS interpreter works differently
  • keywords/reserved words abbreviation restriction
  • some operator restriction e.g. **
  • even same awk impl. (gawk for example), the version 4.0 and 3.x have difference too.
  • the implementation of certain functions are also different. (your problem is one example, see below)

well all the points above are just spoken in general. Back to your problem, you problem is only related to fundamental feature of awk. awk '{print $x}' the line like that will work all awks.

There are two reasons why your awk line behaves differently on gawk and mawk:

  • your used substr() function wrongly. this is the main cause. you have substr($0, 0, RSTART - 1) the 0 should be 1, no matter which awk do you use. awk array, string idx etc are 1-based.

  • gawk and mawk implemented substr() differently.

Flexbox: how to get divs to fill up 100% of the container width without wrapping?

You can use the shorthand flex property and set it to

flex: 0 0 100%;

That's flex-grow, flex-shrink, and flex-basis in one line. Flex shrink was described above, flex grow is the opposite, and flex basis is the size of the container.

How to show uncommitted changes in Git and some Git diffs in detail

For me, the only thing which worked is

git diff HEAD

including the staged files, git diff --cached only shows staged files.

Byte Array to Hex String

If you have a numpy array, you can do the following:

>>> import numpy as np
>>> a = np.array([133, 53, 234, 241])
>>> a.astype(np.uint8).data.hex()
'8535eaf1'

how to open *.sdf files?

It can be opened using Visual Studio 2012.Follow the below path in VS after opening the project. View->Server Explorer->

enter image description here

Setting PHP tmp dir - PHP upload not working

The problem described here was solved by me quite a long time ago but I don't really remember what was the main reason that uploads weren't working. There were multiple things that needed fixing so the upload could work. I have created checklist that might help others having similar problems and I will edit it to make it as helpful as possible. As I said before on chat, I was working on embedded system, so some points may be skipped on non-embedded systems.

  • Check upload_tmp_dir in php.ini. This is directory where PHP stores temporary files while uploading.

  • Check open_basedir in php.ini. If defined it limits PHP read/write rights to specified path and its subdirectories. Ensure that upload_tmp_dir is inside this path.

  • Check post_max_size in php.ini. If you want to upload 20 Mbyte files, try something a little bigger, like post_max_size = 21M. This defines largest size of POST message which you are probably using during upload.

  • Check upload_max_filesize in php.ini. This specifies biggest file that can be uploaded.

  • Check memory_limit in php.ini. That's the maximum amount of memory a script may consume. It's quite obvious that it can't be lower than upload size (to be honest I'm not quite sure about it-PHP is probably buffering while copying temporary files).

  • Ensure that you're checking the right php.ini file that is one used by PHP on your webserver. The best solution is to execute script with directive described here http://php.net/manual/en/function.php-ini-loaded-file.php (php_ini_loaded_file function)

  • Check what user php runs as (See here how to do it: How to check what user php is running as? ). I have worked on different distros and servers. Sometimes it is apache, but sometimes it can be root. Anyway, check that this user has rights for reading and writing in the temporary directory and directory that you're uploading into. Check all directories in the path in case you're uploading into subdirectory (for example /dir1/dir2/-check both dir1 and dir2.

  • On embedded platforms you sometimes need to restrict writing to root filesystem because it is stored on flash card and this helps to extend life of this card. If you are using scripts to enable/disable file writes, ensure that you enable writing before uploading.

  • I had serious problems with PHP >5.4 upload monitoring based on sessions (as described here http://phpmaster.com/tracking-upload-progress-with-php-and-javascript/ ) on some platforms. Try something simple at first (like here: http://www.dzone.com/snippets/very-simple-php-file-upload ). If it works, you can try more sophisticated mechanisms.

  • If you make any changes in php.ini remember to restart server so the configuration will be reloaded.

How to use a link to call JavaScript?

Or, if you're using PrototypeJS

<script type="text/javascript>
  Event.observe( $('thelink'), 'click', function(event) {
      //do stuff

      Event.stop(event);
  }
</script>

<a href="#" id="thelink">This is the link</a>

How to find my Subversion server version number?

Try this:

ssh your_user@your_server svnserve --version

svnserve, version 1.3.1 (r19032)
   compiled May  8 2006, 07:38:44

I hope it helps.

Cannot get Kerberos service ticket: KrbException: Server not found in Kerberos database (7)

"Server not found in Kerberos database" error can happen if you have registered the SPN to multiple users/computers.

You can check that with:

$ SetSPN -Q ServicePrincipalName
( SetSPN -Q HTTP/my.server.local@MYDOMAIN )

how to put focus on TextBox when the form load?

Textbox.Focus() "Tries" to set focus on the textbox element. In case of the element visibility is hidden for example, Focus() will not work. So make sure that your element is visible before calling Focus().

Postgres: SQL to list table foreign keys

One another way:

WITH foreign_keys AS (
    SELECT
      conname,
      conrelid,
      confrelid,
      unnest(conkey)  AS conkey,
      unnest(confkey) AS confkey
    FROM pg_constraint
    WHERE contype = 'f' -- AND confrelid::regclass = 'your_table'::regclass
)
-- if confrelid, conname pair shows up more than once then it is multicolumn foreign key
SELECT fk.conname as constraint_name,
       fk.confrelid::regclass as referenced_table, af.attname as pkcol,
       fk.conrelid::regclass as referencing_table, a.attname as fkcol
FROM foreign_keys fk
JOIN pg_attribute af ON af.attnum = fk.confkey AND af.attrelid = fk.confrelid
JOIN pg_attribute a ON a.attnum = conkey AND a.attrelid = fk.conrelid
ORDER BY fk.confrelid, fk.conname
;

How to redirect siteA to siteB with A or CNAME records

I think several of the answers hit around the possible solution to your problem.

I agree the easiest (and best solution for SEO purposes) is the 301 redirect. In IIS this is fairly trivial, you'd create a site for subdomain.hostone.com, after creating the site, right-click on the site and go into properties. Click on the "Home Directory" tab of the site properties window that opens. Select the radio button "A redirection to a URL", enter the url for the new site (http://subdomain.hosttwo.com), and check the checkboxes for "The exact URL entered above", "A permanent redirection for this resource" (this second checkbox causes a 301 redirect, instead of a 302 redirect). Click OK, and you're done.

Or you could create a page on the site of http://subdomain.hostone.com, using one of the following methods (depending on what the hosting platform supports)

PHP Redirect:


<?
Header( "HTTP/1.1 301 Moved Permanently" ); 
Header( "Location: http://subdomain.hosttwo.com" ); 
?>

ASP Redirect:


<%@ Language=VBScript %>
<%
Response.Status="301 Moved Permanently"
Response.AddHeader "Location","http://subdomain.hosttwo.com"
%>

ASP .NET Redirect:


<script runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location","http://subdomain.hosttwo.com");
}
</script>

Now assuming your CNAME record is correctly created, then the only problem you are experiencing is that the site created for http://subdomain.hosttwo.com is using a shared IP, and host headers to determine which site should be displayed. To resolve this issue under IIS, in IIS Manager on the web server, you'd right-click on the site for subdomain.hosttwo.com, and click "Properties". On the displayed "Web Site" tab, you should see an "Advanced" button next to the IP address that you'll need to click. On the "Advanced Web Site Identification" window that appears, click "Add". Select the same IP address that is already being used by subdomain.hosttwo.com, enter 80 as the TCP port, and then enter subdomain.hosttwo.com as the Host Header value. Click OK until you are back to the main IIS Manager window, and you should be good to go. Open a browser, and browse to http://subdomain.hostone.com, and you'll see the site at http://subdomain.hosttwo.com appear, even though your URL shows http://subdomain.hostone.com

Hope that helps...

Sending command line arguments to npm script

I've found this question while I was trying to solve my issue with running sequelize seed:generate cli command:

node_modules/.bin/sequelize seed:generate --name=user

Let me get to the point. I wanted to have a short script command in my package.json file and to provide --name argument at the same time

The answer came after some experiments. Here is my command in package.json

"scripts: {
  "seed:generate":"NODE_ENV=development node_modules/.bin/sequelize seed:generate"
}

... and here is an example of running it in terminal to generate a seed file for a user

> yarn seed:generate --name=user

> npm run seed:generate -- --name=user

FYI

yarn -v
1.6.0

npm -v
5.6.0

Appropriate datatype for holding percent values?

Assuming two decimal places on your percentages, the data type you use depends on how you plan to store your percentages. If you are going to store their fractional equivalent (e.g. 100.00% stored as 1.0000), I would store the data in a decimal(5,4) data type with a CHECK constraint that ensures that the values never exceed 1.0000 (assuming that is the cap) and never go below 0 (assuming that is the floor). If you are going to store their face value (e.g. 100.00% is stored as 100.00), then you should use decimal(5,2) with an appropriate CHECK constraint. Combined with a good column name, it makes it clear to other developers what the data is and how the data is stored in the column.

What is the best way to return different types of ResponseEntity in Spring MVC or Spring-Boot

Using custom exception class you can return different HTTP status code and dto object.

@PostMapping("/save")
public ResponseEntity<UserDto> saveUser(@RequestBody UserDto userDto) {
    if(userDto.getId() != null) {
        throw new UserNotFoundException("A new user cannot already have an ID");
    }
    return ResponseEntity.ok(userService.saveUser(userDto));
}

Exception class

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "user not found")
public class UserNotFoundException extends RuntimeException {

    public UserNotFoundException(String message) {

        super(message);
    }
}

Sanitizing user input before adding it to the DOM in Javascript

You need to take extra precautions when using user supplied data in HTML attributes. Because attributes has many more attack vectors than output inside HTML tags.

The only way to avoid XSS attacks is to encode everything except alphanumeric characters. Escape all characters with ASCII values less than 256 with the &#xHH; format. Which unfortunately may cause problems in your scenario, if you are using CSS classes and javascript to fetch those elements.

OWASP has a good description of how to mitigate HTML attribute XSS:

http://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet#RULE_.233_-_JavaScript_Escape_Before_Inserting_Untrusted_Data_into_HTML_JavaScript_Data_Values

Jquery to change form action

Try this:

$('#button1').click(function(){
   $('#formId').attr('action', 'page1');
});


$('#button2').click(function(){
   $('#formId').attr('action', 'page2');
});

Check if one date is between two dates

I did the same thing that @Diode, the first answer, but i made the condition with a range of dates, i hope this example going to be useful for someone

e.g (the same code to example with array of dates)

_x000D_
_x000D_
var dateFrom = "02/06/2013";_x000D_
var dateTo = "02/09/2013";_x000D_
_x000D_
var d1 = dateFrom.split("/");_x000D_
var d2 = dateTo.split("/");_x000D_
_x000D_
var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]);  // -1 because months are from 0 to 11_x000D_
var to   = new Date(d2[2], parseInt(d2[1])-1, d2[0]); _x000D_
_x000D_
_x000D_
_x000D_
var dates= ["02/06/2013", "02/07/2013", "02/08/2013", "02/09/2013", "02/07/2013", "02/10/2013", "02/011/2013"];_x000D_
_x000D_
dates.forEach(element => {_x000D_
   let parts = element.split("/");_x000D_
   let date= new Date(parts[2], parseInt(parts[1]) - 1, parts[0]);_x000D_
        if (date >= from && date < to) {_x000D_
           console.log('dates in range', date);_x000D_
        }_x000D_
})
_x000D_
_x000D_
_x000D_

Alter Table Add Column Syntax

The correct syntax for adding column into table is:

ALTER TABLE table_name
  ADD column_name column-definition;

In your case it will be:

ALTER TABLE Employees
  ADD EmployeeID int NOT NULL IDENTITY (1, 1)

To add multiple columns use brackets:

ALTER TABLE table_name
  ADD (column_1 column-definition,
       column_2 column-definition,
       ...
       column_n column_definition);

COLUMN keyword in SQL SERVER is used only for altering:

ALTER TABLE table_name
  ALTER COLUMN column_name column_type;

Increase bootstrap dropdown menu width

Usually we have the need to control the width of the dropdown menu; specially that's essential when the dropdown menu holds a form, e.g. login form --- then the dropdown menu and its items should be wide enough for ease of inputing username/email and password.

Besides, when the screen is smaller than 768px or when the window (containing the dropdown menu) is zoomed down to smaller than 768px, Bootstrap 3 responsively scales the dropdown menu to the whole width of the screen/window. We need to keep this reponsive action.

Hence, the following css class could do that:

@media (min-width: 768px) {
    .dropdown-menu {
        width: 300px !important;  /* change the number to whatever that you need */
    }
}

(I had used it in my web app.)

Singular matrix issue with Numpy

By definition, by multiplying a 1D vector by its transpose, you've created a singular matrix.

Each row is a linear combination of the first row.

Notice that the second row is just 8x the first row.

Likewise, the third row is 50x the first row.

There's only one independent row in your matrix.

MSSQL Error 'The underlying provider failed on Open'

context.Connection.Open() didn't help solving my problem so I tried enabling "Allow Remote Clients" in DTC config, no more error.

In windows 7 you can open the DTC config by running dcomcnfg, Component Services -> Computers -> My Computer -> Distributed Transaction Coordinator -> Right click to Local DTC -> Security.

(How) can I count the items in an enum?

I like to use enums as arguments to my functions. It's an easy means to provide a fixed list of "options". The trouble with the top voted answer here is that using that, a client can specify an "invalid option". As a spin off, I recommend doing essentially the same thing, but use a constant int outside of the enum to define the count of them.

enum foobar { foo, bar, baz, quz };
const int FOOBAR_NR_ITEMS=4;

It's not pleasant, but it's a clean solution if you don't change the enum without updating the constant.

How to move the cursor word by word in the OS X Terminal

On Mac OS X - the following keyboard shortcuts work by default. Note that you have to make Option key act like Meta in Terminal preferences (under keyboard tab)

  • alt (?)+F to jump Forward by a word
  • alt (?)+B to jump Backward by a word

I have observed that default emacs key-bindings for simple text navigation seem to work on bash shells. You can use

  • alt (?)+D to delete a word starting from the current cursor position
  • ctrl+A to jump to start of the line
  • ctrl+E to jump to end of the line
  • ctrl+K to kill the line starting from the cursor position
  • ctrl+Y to paste text from the kill buffer
  • ctrl+R to reverse search for commands you typed in the past from your history
  • ctrl+S to forward search (works in zsh for me but not bash)
  • ctrl+F to move forward by a char
  • ctrl+B to move backward by a char
  • ctrl+W to remove the word backwards from cursor position

NSRange from Swift Range?

My solution is a string extension that first gets the swift range then get's the distance from the start of the string to the start and end of the substring.

These values are then used to calculate the start and length of the substring. We can then apply these values to the NSMakeRange constructor.

This solution works with substrings that consist of multiple words, which a lot of the solutions here using enumerateSubstrings let me down on.

extension String {

    func NSRange(of substring: String) -> NSRange? {
        // Get the swift range 
        guard let range = range(of: substring) else { return nil }

        // Get the distance to the start of the substring
        let start = distance(from: startIndex, to: range.lowerBound) as Int
        //Get the distance to the end of the substring
        let end = distance(from: startIndex, to: range.upperBound) as Int

        //length = endOfSubstring - startOfSubstring
        //start = startOfSubstring
        return NSMakeRange(start, end - start)
    }

}

What is the difference between json.load() and json.loads() functions

Just going to add a simple example to what everyone has explained,

json.load()

json.load can deserialize a file itself i.e. it accepts a file object, for example,

# open a json file for reading and print content using json.load
with open("/xyz/json_data.json", "r") as content:
  print(json.load(content))

will output,

{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}

If I use json.loads to open a file instead,

# you cannot use json.loads on file object
with open("json_data.json", "r") as content:
  print(json.loads(content))

I would get this error:

TypeError: expected string or buffer

json.loads()

json.loads() deserialize string.

So in order to use json.loads I will have to pass the content of the file using read() function, for example,

using content.read() with json.loads() return content of the file,

with open("json_data.json", "r") as content:
  print(json.loads(content.read()))

Output,

{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}

That's because type of content.read() is string, i.e. <type 'str'>

If I use json.load() with content.read(), I will get error,

with open("json_data.json", "r") as content:
  print(json.load(content.read()))

Gives,

AttributeError: 'str' object has no attribute 'read'

So, now you know json.load deserialze file and json.loads deserialize a string.

Another example,

sys.stdin return file object, so if i do print(json.load(sys.stdin)), I will get actual json data,

cat json_data.json | ./test.py

{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}

If I want to use json.loads(), I would do print(json.loads(sys.stdin.read())) instead.

Conda command not found

Maybe you should type add this to your .bashrc or .zshrc

export PATH="/anaconda3/bin":$PATH

It worked for me.

HTTP 1.0 vs 1.1

One of the first differences that I can recall from top of my head are multiple domains running in the same server, partial resource retrieval, this allows you to retrieve and speed up the download of a resource (it's what almost every download accelerator does).

If you want to develop an application like a website or similar, you don't need to worry too much about the differences but you should know the difference between GET and POST verbs at least.

Now if you want to develop a browser then yes, you will have to know the complete protocol as well as if you are trying to develop a HTTP server.

If you are only interested in knowing the HTTP protocol I would recommend you starting with HTTP/1.1 instead of 1.0.

Using a scanner to accept String input and storing in a String Array

//go through this code I have made several changes in it//

import java.util.Scanner;

public class addContact {
public static void main(String [] args){

//declare arrays
String [] contactName = new String [12];
String [] contactPhone = new String [12];
String [] contactAdd1 = new String [12];
String [] contactAdd2 = new String [12];
int i=0;
String name = "0";
String phone = "0";
String add1 = "0";
String add2 = "0";
//method of taken input
Scanner input = new Scanner(System.in);

//while name field is empty display prompt etc.
while (i<11)
{
    i++;
System.out.println("Enter contacts name: "+ i);
name = input.nextLine();
name += contactName[i];
}


while (i<12)
{
    i++;
System.out.println("Enter contacts addressline1:");
add1 = input.nextLine();
add1 += contactAdd1[i];
}

while (i<12)
{
    i++;
System.out.println("Enter contacts addressline2:");
add2 = input.nextLine();
add2 += contactAdd2[i];
}

while (i<12)
{
    i++;
System.out.println("Enter contact phone number: ");
phone = input.nextLine();
phone += contactPhone[i];
}

}   
}

What's the difference between ng-model and ng-bind

ng-bind has one-way data binding ($scope --> view). It has a shortcut {{ val }} which displays the scope value $scope.val inserted into html where val is a variable name.

ng-model is intended to be put inside of form elements and has two-way data binding ($scope --> view and view --> $scope) e.g. <input ng-model="val"/>.

What does --net=host option in Docker command really do?

After the docker installation you have 3 networks by default:

docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
f3be8b1ef7ce        bridge              bridge              local
fbff927877c1        host                host                local
023bb5940080        none                null                local

I'm trying to keep this simple. So if you start a container by default it will be created inside the bridge (docker0) network.

$ docker run -d jenkins
1498e581cdba        jenkins             "/bin/tini -- /usr..."   3 minutes ago       Up 3 minutes        8080/tcp, 50000/tcp   friendly_bell

In the dockerfile of jenkins the ports 8080 and 50000 are exposed. Those ports are opened for the container on its bridge network. So everything inside that bridge network can access the container on port 8080 and 50000. Everything in the bridge network is in the private range of "Subnet": "172.17.0.0/16", If you want to access them from the outside you have to map the ports with -p 8080:8080. This will map the port of your container to the port of your real server (the host network). So accessing your server on 8080 will route to your bridgenetwork on port 8080.

Now you also have your host network. Which does not containerize the containers networking. So if you start a container in the host network it will look like this (it's the first one):

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                 NAMES
1efd834949b2        jenkins             "/bin/tini -- /usr..."   6 minutes ago       Up 6 minutes                              eloquent_panini
1498e581cdba        jenkins             "/bin/tini -- /usr..."   10 minutes ago      Up 10 minutes       8080/tcp, 50000/tcp   friendly_bell

The difference is with the ports. Your container is now inside your host network. So if you open port 8080 on your host you will acces the container immediately.

$ sudo iptables -I INPUT 5 -p tcp -m tcp --dport 8080 -j ACCEPT

I've opened port 8080 in my firewall and when I'm now accesing my server on port 8080 I'm accessing my jenkins. I think this blog is also useful to understand it better.

Googlemaps API Key for Localhost

Guess I'm a bit late to the party, and although I agree that creating a seperate key for development (localhost) and product it is possible to do both in only 1 key.

When you use Application restrictions -> http referers -> Website restricitions you can enter wildcard urls.

However using a wildcard like .localhost/ or .localhost:{port}. (when already having .yourwebsite.com/* ) don't seem to work.

Just putting a single * does work but this basicly gives you an unlimited key which is not what you want either.

When you include the full path withhout using the wildcard * it also works, so in my case putting:

http://localhost{port}/
http://localhost:{port}/something-else/here

Makes the Google maps work both local as on www.yourwebsite.com using the same API key.

Anyway when having 2 seperate keys is also an option I would advise to do that.

How to uninstall pip on OSX?

In my case I ran the following command and it worked (not that I was expecting it to):

sudo pip uninstall pip

Which resulted in:

Uninstalling pip-6.1.1:
  /Library/Python/2.7/site-packages/pip-6.1.1.dist-info/DESCRIPTION.rst
  /Library/Python/2.7/site-packages/pip-6.1.1.dist-info/METADATA
  /Library/Python/2.7/site-packages/pip-6.1.1.dist-info/RECORD
  <and all the other stuff>
  ...

  /usr/local/bin/pip
  /usr/local/bin/pip2
  /usr/local/bin/pip2.7
Proceed (y/n)? y
  Successfully uninstalled pip-6.1.1

Python: How to get values of an array at certain index positions?

Although you ask about numpy arrays, you can get the same behavior for regular Python lists by using operator.itemgetter.

>>> from operator import itemgetter
>>> a = [0,88,26,3,48,85,65,16,97,83,91]
>>> ind_pos = [1, 5, 7]
>>> print itemgetter(*ind_pos)(a)
(88, 85, 16)

top align in html table?

Some CSS :

table td, table td * {
    vertical-align: top;
}

How do I hide certain files from the sidebar in Visual Studio Code?

This may not me a so good of a answer but if you first select all the files you want to access by pressing on them in the side bar, so that they pop up on top of your screen for example: script.js, index.html, style.css. Close all the files you don't need at the top.

When you're done with that you press Ctrl+B on windows and linux, i don't know what it is on mac.

But there you have it. please send no hate

Setting ANDROID_HOME enviromental variable on Mac OS X

Adding the following to my .bash_profile worked for me:

export ANDROID_HOME=/Users/$USER/Library/Android/sdk
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

Generic XSLT Search and Replace template

Here's one way in XSLT 2

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;','''')"/>   </xsl:template> </xsl:stylesheet> 

Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:variable name="apos">'</xsl:variable>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;',$apos)"/>   </xsl:template> </xsl:stylesheet> 

c# how to add byte to byte array

Simple, just use the code below, as I do:

        public void AppendSpecifiedBytes(ref byte[] dst, byte[] src)
    {
        // Get the starting length of dst
        int i = dst.Length;
        // Resize dst so it can hold the bytes in src
        Array.Resize(ref dst, dst.Length + src.Length);
        // For each element in src
        for (int j = 0; j < src.Length; j++)
        {
            // Add the element to dst
            dst[i] = src[j];
            // Increment dst index
            i++;
        }
    }

    // Appends src byte to the dst array
    public void AppendSpecifiedByte(ref byte[] dst, byte src)
    {
        // Resize dst so that it can hold src
        Array.Resize(ref dst, dst.Length + 1);
        // Add src to dst
        dst[dst.Length - 1] = src;
    }

How can change width of dropdown list?

Try this code:

<select name="wgtmsr" id="wgtmsr">
<option value="kg">Kg</option>
<option value="gm">Gm</option>
<option value="pound">Pound</option>
<option value="MetricTon">Metric ton</option>
<option value="litre">Litre</option>
<option value="ounce">Ounce</option>
</select>

CSS:

#wgtmsr{
 width:150px;   
}

If you want to change the width of the option you can do this in your css:

#wgtmsr option{
  width:150px;   
}

Maybe you have a conflict in your css rules that override the width of your select

DEMO

Declare variable MySQL trigger

Agree with neubert about the DECLARE statements, this will fix syntax error. But I would suggest you to avoid using openning cursors, they may be slow.

For your task: use INSERT...SELECT statement which will help you to copy data from one table to another using only one query.

INSERT ... SELECT Syntax.

How to input automatically when running a shell over SSH?

There definitely is... Use the spawn, expect, and send commands:

spawn test.sh
expect "Are you sure you want to continue connecting (yes/no)?"
send "yes"

There are more examples all over Stack Overflow, see: Help with Expect within a bash script

You may need to install these commands first, depending on your system.

What is the difference between null and System.DBNull.Value?

DBNull.Value is what the .NET Database providers return to represent a null entry in the database. DBNull.Value is not null and comparissons to null for column values retrieved from a database row will not work, you should always compare to DBNull.Value.

http://msdn.microsoft.com/en-us/library/system.dbnull.value.aspx

Return string without trailing slash

I know the question is about trailing slashes but I found this post during my search for trimming slashes (both at the tail and head of a string literal), as people would need this solution I am posting one here :

'///I am free///'.replace(/^\/+|\/+$/g, ''); // returns 'I am free'

UPDATE:

as @Stephen R mentioned in the comments, if you want to remove both slashes and backslashes both at the tail and the head of a string literal, you would write :

'\/\\/\/I am free\\///\\\\'.replace(/^[\\/]+|[\\/]+$/g, '') // returns 'I am free'

passing several arguments to FUN of lapply (and others *apply)

As suggested by Alan, function 'mapply' applies a function to multiple Multiple Lists or Vector Arguments:

mapply(myfun, arg1, arg2)

See man page: https://stat.ethz.ch/R-manual/R-devel/library/base/html/mapply.html

React Native TextInput that only accepts numeric characters

A kind reminder to those who encountered the problem that "onChangeText" cannot change the TextInput value as expected on iOS: that is actually a bug in ReactNative and had been fixed in version 0.57.1. Refer to: https://github.com/facebook/react-native/issues/18874

How to display .svg image using swift

As I know there are 2 different graphic formats:

  1. Raster graphics (uses bitmaps) and is used in JPEG, PNG, APNG, GIF, and MPEG4 file format.
  2. Vector graphics (uses points, lines, curves and other shapes). Vector graphics are used in the SVG, EPS, PDF or AI graphic file formats.

So if you need to use an image stored in SVG File in your Xcode I would suggest:

  1. Convert SVG file to PDF. I used https://document.online-convert.com/convert/svg-to-pdf

  2. Use Xcode to manage you PDF file.

LD_LIBRARY_PATH vs LIBRARY_PATH

Since I link with gcc why ld is being called, as the error message suggests?

gcc calls ld internally when it is in linking mode.

Complex nesting of partials and templates

You may use ng-include to avoid using nested ng-views.

http://docs.angularjs.org/api/ng/directive/ngInclude
http://plnkr.co/edit/ngdoc:example-example39@snapshot?p=preview

My index page I use ng-view. Then on my sub pages which I need to have nested frames. I use ng-include. The demo shows a dropdown. I replaced mine with a link ng-click. In the function I would put $scope.template = $scope.templates[0]; or $scope.template = $scope.templates[1];

$scope.clickToSomePage= function(){
  $scope.template = $scope.templates[0];
};

PHP refresh window? equivalent to F5 page reload?

With PHP you just can handle server-side stuff. What you can do is print this in your iframe:

parent.window.location.reload();

Manifest Merger failed with multiple errors in Android Studio

The minium sdk version should be same as of the modules/lib you are using For example: Your module min sdk version is 26 and your app min sdk version is 21 It should be same.

@Directive vs @Component in Angular

A @Component requires a view whereas a @Directive does not.

Directives

I liken a @Directive to an Angular 1.0 directive with the option restrict: 'A' (Directives aren't limited to attribute usage.) Directives add behaviour to an existing DOM element or an existing component instance. One example use case for a directive would be to log a click on an element.

import {Directive} from '@angular/core';

@Directive({
    selector: "[logOnClick]",
    hostListeners: {
        'click': 'onClick()',
    },
})
class LogOnClick {
    constructor() {}
    onClick() { console.log('Element clicked!'); }
}

Which would be used like so:

<button logOnClick>I log when clicked!</button>

Components

A component, rather than adding/modifying behaviour, actually creates its own view (hierarchy of DOM elements) with attached behaviour. An example use case for this might be a contact card component:

import {Component, View} from '@angular/core';

@Component({
  selector: 'contact-card',
  template: `
    <div>
      <h1>{{name}}</h1>
      <p>{{city}}</p>
    </div>
  `
})
class ContactCard {
  @Input() name: string
  @Input() city: string
  constructor() {}
}

Which would be used like so:

<contact-card [name]="'foo'" [city]="'bar'"></contact-card>

ContactCard is a reusable UI component that we could use anywhere in our application, even within other components. These basically make up the UI building blocks of our applications.

In summary

Write a component when you want to create a reusable set of DOM elements of UI with custom behaviour. Write a directive when you want to write reusable behaviour to supplement existing DOM elements.

Sources:

Use string contains function in oracle SQL query

By lines I assume you mean rows in the table person. What you're looking for is:

select p.name
from   person p
where  p.name LIKE '%A%'; --contains the character 'A'

The above is case sensitive. For a case insensitive search, you can do:

select p.name
from   person p
where  UPPER(p.name) LIKE '%A%'; --contains the character 'A' or 'a'

For the special character, you can do:

select p.name
from   person p
where  p.name LIKE '%'||chr(8211)||'%'; --contains the character chr(8211)

The LIKE operator matches a pattern. The syntax of this command is described in detail in the Oracle documentation. You will mostly use the % sign as it means match zero or more characters.

How to represent the double quotes character (") in regex?

you need to use backslash before ". like \"

From the doc here you can see that

A character preceded by a backslash ( \ ) is an escape sequence and has special meaning to the compiler.

and " (double quote) is a escacpe sequence

When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence

She said "Hello!" to me.

you would write

System.out.println("She said \"Hello!\" to me.");

Cannot load 64-bit SWT libraries on 32-bit JVM ( replacing SWT file )

I just replaced the swt.jar in my package with the 64bit version and it worked straight away. No need to recompile the whole package, just replace the swt.jar file and make sure your application manifest includes it.

Make one div visible and another invisible

If u want to use display=block it will make the content reader jump, so instead of using display you can set the left attribute to a negative value which does not exist in your html page to be displayed but actually it do.

I hope you must be understanding my point, if I am unable to make u understand u can message me back.

When a 'blur' event occurs, how can I find out which element focus went *to*?

  • document.activeElement could be a parent node (for example body node because it is in a temporary phase switching from a target to another), so it is not usable for your scope
  • ev.explicitOriginalTarget is not always valued

So the best way is to use onclick on body event for understanding indirectly your node(event.target) is on blur

How to check Oracle database for long running queries

You can use the v$sql_monitor view to find queries that are running longer than 5 seconds. This may only be available in Enterprise versions of Oracle. For example this query will identify slow running queries from my TEST_APP service:

select to_char(sql_exec_start, 'dd-Mon hh24:mi'), (elapsed_time / 1000000) run_time,
       cpu_time, sql_id, sql_text 
from   v$sql_monitor
where  service_name = 'TEST_APP'
order  by 1 desc;

Note elapsed_time is in microseconds so / 1000000 to get something more readable

select a value where it doesn't exist in another table

SELECT ID
  FROM A
 WHERE ID NOT IN (
      SELECT ID
        FROM B);

SELECT ID    
  FROM A a
 WHERE NOT EXISTS (
      SELECT 1 
        FROM B b
       WHERE b.ID = a.ID)

         SELECT a.ID 
           FROM A a    
LEFT OUTER JOIN B b 
             ON a.ID = b.ID    
          WHERE b.ID IS NULL

DELETE 
  FROM A 
 WHERE ID NOT IN (
      SELECT ID 
        FROM B) 

How to compile python script to binary executable

# -*- mode: python -*-

block_cipher = None

a = Analysis(['SCRIPT.py'],
             pathex=[
                 'folder path',
                 'C:\\Windows\\WinSxS\\x86_microsoft-windows-m..namespace-downlevel_31bf3856ad364e35_10.0.17134.1_none_50c6cb8431e7428f',
                 'C:\\Windows\\WinSxS\\x86_microsoft-windows-m..namespace-downlevel_31bf3856ad364e35_10.0.17134.1_none_c4f50889467f081d'
             ],
             binaries=[(''C:\\Users\\chromedriver.exe'')],
             datas=[],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          name='NAME OF YOUR EXE',
          debug=False,
          strip=False,
          upx=True,
          runtime_tmpdir=None,
          console=True )

How to make Toolbar transparent?

try below code

<android.support.design.widget.AppBarLayout
                    android:id="@+id/app_bar"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:theme="@style/AppTheme.Transparent"
                    >
                        <android.support.v7.widget.Toolbar
                            android:id="@+id/toolbar"
                            android:layout_width="match_parent"
                            android:layout_height="?attr/actionBarSize"
                            app:popupTheme="@style/AppTheme.PopupOverlay" />
                </android.support.design.widget.AppBarLayout>

style.xml

<style name="AppTheme.Transparent" parent="ThemeOverlay.AppCompat.Light">
        <item name="colorPrimary">@android:color/transparent</item>
        <item name="colorControlActivated">@color/colorWhite</item>
        <item name="colorControlNormal">@color/colorWhite</item>
    </style>

Background service with location listener in android

Background location service. It will be restarted even after killing the app.

MainActivity.java

public class MainActivity extends AppCompatActivity {
    AlarmManager alarmManager;
    Button stop;
    PendingIntent pendingIntent;

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

        if (alarmManager == null) {
            alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(this, AlarmReceive.class);
            pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 30000,
                    pendingIntent);
        }
    }
}

BookingTrackingService.java

public class BookingTrackingService extends Service implements LocationListener {

    private static final String TAG = "BookingTrackingService";
    private Context context;
    boolean isGPSEnable = false;
    boolean isNetworkEnable = false;
    double latitude, longitude;
    LocationManager locationManager;
    Location location;
    private Handler mHandler = new Handler();
    private Timer mTimer = null;
    long notify_interval = 30000;

    public double track_lat = 0.0;
    public double track_lng = 0.0;
    public static String str_receiver = "servicetutorial.service.receiver";
    Intent intent;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

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

        mTimer = new Timer();
        mTimer.schedule(new TimerTaskToGetLocation(), 5, notify_interval);
        intent = new Intent(str_receiver);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        this.context = this;


        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy <<");
        if (mTimer != null) {
            mTimer.cancel();
        }
    }

    private void trackLocation() {
        Log.e(TAG, "trackLocation");
        String TAG_TRACK_LOCATION = "trackLocation";
        Map<String, String> params = new HashMap<>();
        params.put("latitude", "" + track_lat);
        params.put("longitude", "" + track_lng);

        Log.e(TAG, "param_track_location >> " + params.toString());

        stopSelf();
        mTimer.cancel();

    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    /******************************/

    private void fn_getlocation() {
        locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
        isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnable && !isNetworkEnable) {
            Log.e(TAG, "CAN'T GET LOCATION");
            stopSelf();
        } else {
            if (isNetworkEnable) {
                location = null;
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {

                        Log.e(TAG, "isNetworkEnable latitude" + location.getLatitude() + "\nlongitude" + location.getLongitude() + "");
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                        track_lat = latitude;
                        track_lng = longitude;
//                        fn_update(location);
                    }
                }
            }

            if (isGPSEnable) {
                location = null;
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (location != null) {
                        Log.e(TAG, "isGPSEnable latitude" + location.getLatitude() + "\nlongitude" + location.getLongitude() + "");
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                        track_lat = latitude;
                        track_lng = longitude;
//                        fn_update(location);
                    }
                }
            }

            Log.e(TAG, "START SERVICE");
            trackLocation();

        }
    }

    private class TimerTaskToGetLocation extends TimerTask {
        @Override
        public void run() {

            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    fn_getlocation();
                }
            });

        }
    }

//    private void fn_update(Location location) {
//
//        intent.putExtra("latutide", location.getLatitude() + "");
//        intent.putExtra("longitude", location.getLongitude() + "");
//        sendBroadcast(intent);
//    }
}

AlarmReceive.java (BroadcastReceiver)

public class AlarmReceive extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e("Service_call_"  , "You are in AlarmReceive class.");
        Intent background = new Intent(context, BookingTrackingService.class);
//        Intent background = new Intent(context, GoogleService.class);
        Log.e("AlarmReceive ","testing called broadcast called");
        context.startService(background);
    }
}

AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

 <service
            android:name=".ServiceAndBroadcast.BookingTrackingService"
            android:enabled="true" />

        <receiver
            android:name=".ServiceAndBroadcast.AlarmReceive"
            android:exported="false">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

How to run .APK file on emulator

Step-by-Step way to do this:

  1. Install Android SDK
  2. Start the emulator by going to $SDK_root/emulator.exe
  3. Go to command prompt and go to the directory $SDK_root/platform-tools (or else add the path to windows environment)
  4. Type in the command adb install
  5. Bingo. Your app should be up and running on the emulator

C# "must declare a body because it is not marked abstract, extern, or partial"

You DO NOT have to provide a body for getters and setters IF you'd like the automated compiler to provide a basic implementation.

This DOES however require you to make sure you're using the v3.5 compiler by updating your web.config to something like

 <compilers>
   <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider,System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4">
    <providerOption name="CompilerVersion" value="v3.5"/>
    <providerOption name="WarnAsError" value="false"/>
  </compiler>
</compilers>

How to disable scientific notation?

format(99999999,scientific = F)

gives

99999999

Where to install Android SDK on Mac OS X?

From http://developer.android.com/sdk/index.html, it seems that you can install the SDK anywhere, so long as you

  1. "execute the android tool in the <sdk>/tools/ folder"
  2. Add the <sdk>/tools directory to your system path

More info can be found here: http://developer.android.com/sdk/installing.html

Django Cookies, how can I set them?

UPDATE : check Peter's answer below for a builtin solution :

This is a helper to set a persistent cookie:

import datetime

def set_cookie(response, key, value, days_expire=7):
    if days_expire is None:
        max_age = 365 * 24 * 60 * 60  # one year
    else:
        max_age = days_expire * 24 * 60 * 60
    expires = datetime.datetime.strftime(
        datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age),
        "%a, %d-%b-%Y %H:%M:%S GMT",
    )
    response.set_cookie(
        key,
        value,
        max_age=max_age,
        expires=expires,
        domain=settings.SESSION_COOKIE_DOMAIN,
        secure=settings.SESSION_COOKIE_SECURE or None,
    )

Use the following code before sending a response.

def view(request):
    response = HttpResponse("hello")
    set_cookie(response, 'name', 'jujule')
    return response

UPDATE : check Peter's answer below for a builtin solution :

CSS Box Shadow - Top and Bottom Only

I've played around with it and I think I have a solution. The following example shows how to set Box-Shadow so that it will only show a shadow for the inset top and bottom of an element.

Legend: insetOption leftPosition topPosition blurStrength spreadStrength color

Description
The key to accomplishing this is to set the blur value to <= the negative of the spread value (ex. inset 0px 5px -?px 5px #000; the blur value should be -5 and lower) and to also keep the blur value > 0 when subtracted from the primary positioning value (ex. using the example from above, the blur value should be -9 and up, thus giving us an optimal value for the the blur to be between -5 and -9).

Solution

.styleName {   
/* for IE 8 and lower */
background-color:#888; filter: progid:DXImageTransform.Microsoft.dropShadow(color=#FFFFCC, offX=0, offY=0, positive=true);  

/* for IE 9 */ 
box-shadow: inset 0px 2px -2px 2px rgba(255,255,204,0.7), inset 0px -2px -2px 2px rgba(255,255,204,0.7); 

/* for webkit browsers */ 
-webkit-box-shadow: inset 0px 2px -2px 2px rgba(255,255,204,0.7), inset 0px -2px -2px 2px rgba(255,255,204,0.7); 

/* for firefox 3.6+ */
-moz-box-shadow: inset 0px 2px -2px 2px rgba(255,255,204,0.7), inset 0px -2px -2px 2px rgba(255,255,204,0.7);   
}

How to convert a list of numbers to jsonarray in Python

Use the json module to produce JSON output:

import json

with open(outputfilename, 'wb') as outfile:
    json.dump(row, outfile)

This writes the JSON result directly to the file (replacing any previous content if the file already existed).

If you need the JSON result string in Python itself, use json.dumps() (added s, for 'string'):

json_string = json.dumps(row)

The L is just Python syntax for a long integer value; the json library knows how to handle those values, no L will be written.

Demo string output:

>>> import json
>>> row = [1L,[0.1,0.2],[[1234L,1],[134L,2]]]
>>> json.dumps(row)
'[1, [0.1, 0.2], [[1234, 1], [134, 2]]]'

JFrame Exit on close Java

The following code works for me:

System.exit(home.EXIT_ON_CLOSE);

Nesting await in Parallel.ForEach

Wrap the Parallel.Foreach into a Task.Run() and instead of the await keyword use [yourasyncmethod].Result

(you need to do the Task.Run thing to not block the UI thread)

Something like this:

var yourForeachTask = Task.Run(() =>
        {
            Parallel.ForEach(ids, i =>
            {
                ICustomerRepo repo = new CustomerRepo();
                var cust = repo.GetCustomer(i).Result;
                customers.Add(cust);
            });
        });
await yourForeachTask;

mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource

$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '%$username%'") or die(mysql_error());

while($row = mysql_fetch_array($result))
{
    echo $row['FirstName'];
}

Sometimes suppressing the query as @mysql_query(your query);

YAML: Do I need quotes for strings in YAML?

I had this concern when working on a Rails application with Docker.

My most preferred approach is to generally not use quotes. This includes not using quotes for:

  • variables like ${RAILS_ENV}
  • values separated by a colon (:) like postgres-log:/var/log/postgresql
  • other strings values

I, however, use double-quotes for integer values that need to be converted to strings like:

  • docker-compose version like version: "3.8"
  • port numbers like "8080:8080"

However, for special cases like booleans, floats, integers, and other cases, where using double-quotes for the entry values could be interpreted as strings, please do not use double-quotes.

Here's a sample docker-compose.yml file to explain this concept:

version: "3"

services:
  traefik:
    image: traefik:v2.2.1
    command:
      - --api.insecure=true # Don't do that in production
      - --providers.docker=true
      - --providers.docker.exposedbydefault=false
      - --entrypoints.web.address=:80
    ports:
      - "80:80"
      - "8080:8080"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro

That's all.

I hope this helps

Delete all nodes and relationships in neo4j 1.8

for a big database you should either remove the database from the disk (after you stop the engine first I guess) or use in Cypher something like:

MATCH (n)
OPTIONAL MATCH (n)-[r]-()
WITH n,r LIMIT 50000
DELETE n,r
RETURN count(n) as deletedNodesCount

see https://zoomicon.wordpress.com/2015/04/18/howto-delete-all-nodes-and-relationships-from-neo4j-graph-database/ for some more info I've gathered on this from various answers

Run jar file in command prompt

java [any other JVM options you need to give it] -jar foo.jar

Bootstrap Modal sitting behind backdrop

Just move the entire modal outside of the rest of your code, to the very bottom. It doesn't need to be nested in any other element, other than the body.

<body>
    <!-- All other HTML -->
    <div>
        ...
    </div>

    <!-- Modal -->
    <div class="modal fade" id="myModal">
        ...
    </div>
</body>

Demo

They hint at this solution in the documentation.

Modal Markup Placement
Always try to place a modal's HTML code in a top-level position in your document to avoid other components affecting the modal's appearance and/or functionality.

Error: free(): invalid next size (fast):

It means that you have a memory error. You may be trying to free a pointer that wasn't allocated by malloc (or delete an object that wasn't created by new) or you may be trying to free/delete such an object more than once. You may be overflowing a buffer or otherwise writing to memory to which you shouldn't be writing, causing heap corruption.

Any number of programming errors can cause this problem. You need to use a debugger, get a backtrace, and see what your program is doing when the error occurs. If that fails and you determine you have corrupted the heap at some previous point in time, you may be in for some painful debugging (it may not be too painful if the project is small enough that you can tackle it piece by piece).

Colorized grep -- viewing the entire file with highlighted matches

Alternatively you can use The Silver Searcher and do

ag <search> --passthrough

Save modifications in place with awk

following won't work

echo $(awk '{awk code}' file) > file

this should work

echo "$(awk '{awk code}' file)" > file

How to find if directory exists in Python

There is a convenient Unipath module.

>>> from unipath import Path 
>>>  
>>> Path('/var/log').exists()
True
>>> Path('/var/log').isdir()
True

Other related things you might need:

>>> Path('/var/log/system.log').parent
Path('/var/log')
>>> Path('/var/log/system.log').ancestor(2)
Path('/var')
>>> Path('/var/log/system.log').listdir()
[Path('/var/foo'), Path('/var/bar')]
>>> (Path('/var/log') + '/system.log').isfile()
True

You can install it using pip:

$ pip3 install unipath

It's similar to the built-in pathlib. The difference is that it treats every path as a string (Path is a subclass of the str), so if some function expects a string, you can easily pass it a Path object without a need to convert it to a string.

For example, this works great with Django and settings.py:

# settings.py
BASE_DIR = Path(__file__).ancestor(2)
STATIC_ROOT = BASE_DIR + '/tmp/static'

Specify an SSH key for git push for a given domain

One possibility to use ~/.ssh/config is to use the Match restriction instead of the Host restriction. In particular Match Exec calls a shell command to decide whether to apply the declarations or not. In bash you could use the following command:

[ [email protected]:gitolite-admin = $(git config --get remote.origin.url)'' ]

This uses the bash [ command to verify if two strings are equal. In this case it is testing if the string [email protected]:gitolite-admin matches the output that is obtained from the $(git config --get remote.origin.url)'' command.

You can use any other command that identifies the repository that the shell is on. For this to work it is important to have the $SHELL variable defined to your shell, in my case /bin/bash. The full example would then be the following ~/.ssh/config:

Match Exec "[ [email protected]:gitolite-admin = $(git config --get remote.origin.url)'' ]"
  IdentityFile ~/.ssh/gitolite-admin
  IdentitiesOnly yes
  ForwardAgent no
  ForwardX11 no
  ForwardX11Trusted no

Match Exec "[ [email protected]:some_repo = $(git config --get remote.origin.url)'' ]"
  IdentityFile ~/.ssh/yourOwnPrivateKey
  IdentitiesOnly yes
  ForwardAgent no
  ForwardX11 no
  ForwardX11Trusted no

In this example I assumed that ~/.ssh/yourOwnPrivateKey contains your own private key and that ~/.ssh/gitolite-admin contains the private key of the user gitolite-admin. I included the IdentitiesOnly yes declaration to make sure that only one key is offered to the git server, mentioned by Mark Longair. The other declarations are just standard ssh options for git.

You can add this configuration if you have several some_repo that you want to use with different keys. If you have several repositories at [email protected] and most of them use the ~/.ssh/yourOwnPrivateKey it makes more sense to include this key as default for the host. In this case the ~/.ssh/config would be:

Match Exec "[ [email protected]:gitolite-admin = $(git config --get remote.origin.url)'' ]"
  IdentityFile ~/.ssh/gitolite-admin
  IdentitiesOnly yes

Host git.company.com
  IdentityFile ~/.ssh/yourOwnPrivateKey
  IdentitiesOnly yes
  ForwardAgent no
  ForwardX11 no
  ForwardX11Trusted no

Note that the order matters and the Host git.company.com restriction should appear after the Match Exec one or ones.

executing a function in sql plus

As another answer already said, call select myfunc(:y) from dual; , but you might find declaring and setting a variable in sqlplus a little tricky:

sql> var y number

sql> begin
  2  select 7 into :y from dual;
  3  end;
  4  /

PL/SQL procedure successfully completed.

sql> print :y

         Y
----------
         7

sql> select myfunc(:y) from dual;

How to convert List<Integer> to int[] in Java?

I'll throw one more in here. I've noticed several uses of for loops, but you don't even need anything inside the loop. I mention this only because the original question was trying to find less verbose code.

int[] toArray(List<Integer> list) {
    int[] ret = new int[ list.size() ];
    int i = 0;
    for( Iterator<Integer> it = list.iterator(); 
         it.hasNext(); 
         ret[i++] = it.next() );
    return ret;
}

If Java allowed multiple declarations in a for loop the way C++ does, we could go a step further and do for(int i = 0, Iterator it...

In the end though (this part is just my opinion), if you are going to have a helping function or method to do something for you, just set it up and forget about it. It can be a one-liner or ten; if you'll never look at it again you won't know the difference.

How to label scatterplot points by name?

None of these worked for me. I'm on a mac using Microsoft 360. I found this which DID work: This workaround is for Excel 2010 and 2007, it is best for a small number of chart data points.

Click twice on a label to select it. Click in formula bar. Type = Use your mouse to click on a cell that contains the value you want to use. The formula bar changes to perhaps =Sheet1!$D$3

Repeat step 1 to 5 with remaining data labels.

Simple

Different ways of loading a file as an InputStream

It Works , try out this :

InputStream in_s1 =   TopBrandData.class.getResourceAsStream("/assets/TopBrands.xml");

How can I give eclipse more memory than 512M?

While working on an enterprise project in STS (heavily Eclipse based) I was crashing constantly and STS plateaued at around 1GB of RAM usage. I couldn't add new .war files to my local tomcat server and after deleting the tomcat folder to re-add it, found I couldn't re-add it either. Essentially almost anything that required a new popup besides the main menus was causing STS to freeze up.

I edited the STS.ini (your Eclipse.ini can be configured similarly) to:

--launcher.XXMaxPermSize 1024M -vmargs -Xms1536m -Xmx2048m -XX:MaxPermSize=1024m

Rebooted STS immediately and saw it plateau at about 1.5 gigs before finally not crashing

Git Pull vs Git Rebase

git pull and git rebase are not interchangeable, but they are closely connected.

git pull fetches the latest changes of the current branch from a remote and applies those changes to your local copy of the branch. Generally this is done by merging, i.e. the local changes are merged into the remote changes. So git pull is similar to git fetch & git merge.

Rebasing is an alternative to merging. Instead of creating a new commit that combines the two branches, it moves the commits of one of the branches on top of the other.

You can pull using rebase instead of merge (git pull --rebase). The local changes you made will be rebased on top of the remote changes, instead of being merged with the remote changes.

Atlassian has some excellent documentation on merging vs. rebasing.

jQuery attr('onclick')

Do it the jQuery way (and fix the errors):

$('#stop').click(function() {
     $('#next').click(stopMoving);
     // ^-- missing #
});  // <-- missing );

If the element already has a click handler attached via the onclick attribute, you have to remove it:

$('#next').attr('onclick', '');

Update: As @Drackir pointed out, you might also have to call $('#next').unbind('click'); in order to remove other click handlers attached via jQuery.

But this is guessing here. As always: More information => better answers.

Using relative URL in CSS file, what location is it relative to?

Try using:

body {
  background-attachment: fixed;
  background-image: url(./Images/bg4.jpg);
}

Images being folder holding the picture that you want to post.

How to use HTML to print header and footer on every printed page of a document?

Based on some post, i think position: fixed works for me.

_x000D_
_x000D_
body {_x000D_
  background: #eaeaed;_x000D_
  -webkit-print-color-adjust: exact;_x000D_
}_x000D_
_x000D_
.my-footer {_x000D_
  background: #2db34a;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  position: fixed;_x000D_
  right: 0;_x000D_
}_x000D_
_x000D_
.my-header {_x000D_
  background: red;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  position: fixed;_x000D_
  right: 0;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <meta charset=utf-8 />_x000D_
  <title>Header & Footer</title>_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div>_x000D_
    <div class="my-header">Fixed Header</div>_x000D_
    <div class="my-footer">Fixed Footer</div>_x000D_
    <table>_x000D_
      <thead>_x000D_
        <tr>_x000D_
          <th>TH 1</th>_x000D_
          <th>TH 2</th>_x000D_
        </tr>_x000D_
      </thead>_x000D_
      <tbody>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
      </tbody>_x000D_
    </table>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Press Ctrl+P in chrome see the header & footer text on each page. Hope it helps

How can I remove a substring from a given String?

Here is the implementation to delete all the substrings from the given string

public static String deleteAll(String str, String pattern)
{
    for(int index = isSubstring(str, pattern); index != -1; index = isSubstring(str, pattern))
        str = deleteSubstring(str, pattern, index);

    return str;
}

public static String deleteSubstring(String str, String pattern, int index)
{
    int start_index = index;
    int end_index = start_index + pattern.length() - 1;
    int dest_index = 0;
    char[] result = new char[str.length()];


    for(int i = 0; i< str.length() - 1; i++)
        if(i < start_index || i > end_index)
            result[dest_index++] = str.charAt(i);

    return new String(result, 0, dest_index + 1);
}

The implementation of isSubstring() method is here

How do I check if a column is empty or null in MySQL?

Either

SELECT IF(field1 IS NULL or field1 = '', 'empty', field1) as field1 from tablename

or

SELECT case when field1 IS NULL or field1 = ''
        then 'empty'
        else field1
   end as field1 from tablename

Echo a blank (empty) line to the console from a Windows batch file

There is often the tip to use 'echo.'

But that is slow, and it could fail with an error message, as cmd.exe will search first for a file named 'echo' (without extension) and only when the file doesn't exists it outputs an empty line.

You could use echo(. This is approximately 20 times faster, and it works always. The only drawback could be that it looks odd.

More about the different ECHO:/\ variants is at DOS tips: ECHO. FAILS to give text or blank line.

Hibernate: Automatically creating/updating the db tables based on entity classes

In support to @thorinkor's answer I would extend my answer to use not only @Table (name = "table_name") annotation for entity, but also every child variable of entity class should be annotated with @Column(name = "col_name"). This results into seamless updation to the table on the go.

For those who are looking for a Java class based hibernate config, the rule applies in java based configurations also(NewHibernateUtil). Hope it helps someone else.

What causing this "Invalid length for a Base-64 char array"

This isn't an answer, sadly. After running into the intermittent error for some time and finally being annoyed enough to try to fix it, I have yet to find a fix. I have, however, determined a recipe for reproducing my problem, which might help others.

In my case it is SOLELY a localhost problem, on my dev machine that also has the app's DB. It's a .NET 2.0 app I'm editing with VS2005. The Win7 64 bit machine also has VS2008 and .NET 3.5 installed.

Here's what will generate the error, from a variety of forms:

  1. Load a fresh copy of the form.
  2. Enter some data, and/or postback with any of the form's controls. As long as there is no significant delay, repeat all you like, and no errors occur.
  3. Wait a little while (1 or 2 minutes maybe, not more than 5), and try another postback.

A minute or two delay "waiting for localhost" and then "Connection was reset" by the browser, and global.asax's application error trap logs:

Application_Error event: Invalid length for a Base-64 char array.
Stack Trace:
     at System.Convert.FromBase64String(String s)
     at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString)
     at System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState)
     at System.Web.UI.HiddenFieldPageStatePersister.Load()

In this case, it is not the SIZE of the viewstate, but something to do with page and/or viewstate caching that seems to be biting me. Setting <pages> parameters enableEventValidation="false", and viewStateEncryption="Never" in the Web.config did not change the behavior. Neither did setting the maxPageStateFieldLength to something modest.

Printing out all the objects in array list

Whenever you print any instance of your class, the default toString implementation of Object class is called, which returns the representation that you are getting. It contains two parts: - Type and Hashcode

So, in student.Student@82701e that you get as output ->

  • student.Student is the Type, and
  • 82701e is the HashCode

So, you need to override a toString method in your Student class to get required String representation: -

@Override
public String toString() {
    return "Student No: " + this.getStudentNo() + 
           ", Student Name: " + this.getStudentName();
}

So, when from your main class, you print your ArrayList, it will invoke the toString method for each instance, that you overrided rather than the one in Object class: -

List<Student> students = new ArrayList();

// You can directly print your ArrayList
System.out.println(students); 

// Or, iterate through it to print each instance
for(Student student: students) {
    System.out.println(student);  // Will invoke overrided `toString()` method
}

In both the above cases, the toString method overrided in Student class will be invoked and appropriate representation of each instance will be printed.

cannot call member function without object

You need to instantiate an object in order to call its member functions. The member functions need an object to operate on; they can't just be used on their own. The main() function could, for example, look like this:

int main()
{
   Name_pairs np;
   cout << "Enter names and ages. Use 0 to cancel.\n";
   while(np.test())
   {
      np.read_names();
      np.read_ages();
   }
   np.print();
   keep_window_open();
}

The type arguments for method cannot be inferred from the usage

For those who are wondering why this works in Java but not C#, consider what happens if some doof wrote this class:

public class Trololol : ISignatur<bool>, ISignatur<int>{
    Type ISignatur<bool>.Type => typeof(bool);
    Type ISignatur<int>.Type => typeof(int);
}

How is the compiler supposed to resolve var access = service.Get(new Trololol())? Both int and bool are valid.

The reason this implicit resolution works in Java likely has to do with Erasure and how Java will throw a fit if you try to implement an interface with two or more different type arguments. Such a class is simply not allowed in Java, but is just fine in C#.

How can I set the focus (and display the keyboard) on my EditText programmatically

Here is how a kotlin extension for showing and hiding the soft keyboard can be made:

fun View.showKeyboard() {
  this.requestFocus()
  val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
  inputMethodManager.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}

fun View.hideKeyboard() {
  val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
  inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
}

Then you can just do this:

editText.showKeyboard()
// OR
editText.hideKeyboard()

How to $http Synchronous call with AngularJS

var EmployeeController = ["$scope", "EmployeeService",
        function ($scope, EmployeeService) {
            $scope.Employee = {};
            $scope.Save = function (Employee) {                
                if ($scope.EmployeeForm.$valid) {
                    EmployeeService
                        .Save(Employee)
                        .then(function (response) {
                            if (response.HasError) {
                                $scope.HasError = response.HasError;
                                $scope.ErrorMessage = response.ResponseMessage;
                            } else {

                            }
                        })
                        .catch(function (response) {

                        });
                }
            }
        }]


var EmployeeService = ["$http", "$q",
            function ($http, $q) {
                var self = this;

                self.Save = function (employee) {
                    var deferred = $q.defer();                
                    $http
                        .post("/api/EmployeeApi/Create", angular.toJson(employee))
                        .success(function (response, status, headers, config) {
                            deferred.resolve(response, status, headers, config);
                        })
                        .error(function (response, status, headers, config) {
                            deferred.reject(response, status, headers, config);
                        });

                    return deferred.promise;
                };

An attempt was made to access a socket in a way forbidden by its access permissions

Just Restart-Service hns can change the port occupier by Hyper-V. It might release the port you need.

ReactJS SyntheticEvent stopPropagation() only works with React events?

It is still one intersting moment:

ev.preventDefault()
ev.stopPropagation();
ev.nativeEvent.stopImmediatePropagation();

Use this construction, if your function is wrapped by tag

What is the different between RESTful and RESTless

REST stands for REpresentational State Transfer and goes a little something like this:

We have a bunch of uniquely addressable 'entities' that we want made available via a web application. Those entities each have some identifier and can be accessed in various formats. REST defines a bunch of stuff about what GET, POST, etc mean for these purposes.

the basic idea with REST is that you can attach a bunch of 'renderers' to different entities so that they can be available in different formats easily using the same HTTP verbs and url formats.

For more clarification on what RESTful means and how it is used google rails. Rails is a RESTful framework so there's loads of good information available in its docs and associated blog posts. Worth a read even if you arent keen to use the framework. For example: http://www.sitepoint.com/restful-rails-part-i/

RESTless means not restful. If you have a web app that does not adhere to RESTful principles then it is not RESTful

Error in plot.window(...) : need finite 'xlim' values

The problem is that you're (probably) trying to plot a vector that consists exclusively of missing (NA) values. Here's an example:

> x=rep(NA,100)
> y=rnorm(100)
> plot(x,y)
Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf

In your example this means that in your line plot(costs,pseudor2,type="l"), costs is completely NA. You have to figure out why this is, but that's the explanation of your error.


From comments:

Scott C Wilson: Another possible cause of this message (not in this case, but in others) is attempting to use character values as X or Y data. You can use the class function to check your x and Y values to be sure if you think this might be your issue.

stevec: Here is a quick and easy solution to that problem (basically wrap x in as.factor(x))

How can I get device ID for Admob

To get the device id, connect your phone to USB and open logcat in android studio Use the code below (make sure you have USB debugging enabled in your device). Then open any app (download any random app from play store) which has google Ad. In the Logcat type "set" as shown in the image. Your device id is shown highlighted in the image as

setTestDeviceIds(Arrays.asList("CC9DW7W7R4H0NM3LT9OLOF7455F8800D")).

enter image description here

Use the Test Device in your code as shown

val adRequest = AdRequest
        .Builder()
        .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
        .addTestDevice("CC9DW7W7R4H0NM3LT9OLOF7455F8800D")
        .build()

adb command not found in linux environment

In Ubuntu i could run the following command:

  sudo apt install android-tools-adb

How does a Breadth-First Search work when looking for Shortest Path?

Technically, Breadth-first search (BFS) by itself does not let you find the shortest path, simply because BFS is not looking for a shortest path: BFS describes a strategy for searching a graph, but it does not say that you must search for anything in particular.

Dijkstra's algorithm adapts BFS to let you find single-source shortest paths.

In order to retrieve the shortest path from the origin to a node, you need to maintain two items for each node in the graph: its current shortest distance, and the preceding node in the shortest path. Initially all distances are set to infinity, and all predecessors are set to empty. In your example, you set A's distance to zero, and then proceed with the BFS. On each step you check if you can improve the distance of a descendant, i.e. the distance from the origin to the predecessor plus the length of the edge that you are exploring is less than the current best distance for the node in question. If you can improve the distance, set the new shortest path, and remember the predecessor through which that path has been acquired. When the BFS queue is empty, pick a node (in your example, it's E) and traverse its predecessors back to the origin. This would give you the shortest path.

If this sounds a bit confusing, wikipedia has a nice pseudocode section on the topic.

How can I search an array in VB.NET?

check this..

        string[] strArray = { "ABC", "BCD", "CDE", "DEF", "EFG", "FGH", "GHI" };
        Array.IndexOf(strArray, "C"); // not found, returns -1
        Array.IndexOf(strArray, "CDE"); // found, returns index

Tuning nginx worker_process to obtain 100k hits per min

Config file:

worker_processes  4;  # 2 * Number of CPUs

events {
    worker_connections  19000;  # It's the key to high performance - have a lot of connections available
}

worker_rlimit_nofile    20000;  # Each connection needs a filehandle (or 2 if you are proxying)


# Total amount of users you can serve = worker_processes * worker_connections

more info: Optimizing nginx for high traffic loads

Now() function with time trim

I would prefer to make a function that doesn't work with strings:

'---------------------------------------------------------------------------------------
' Procedure : RemoveTimeFromDate
' Author    : berend.nieuwhof
' Date      : 15-8-2013
' Purpose   : removes the time part of a String and returns the date as a date
'---------------------------------------------------------------------------------------
'
Public Function RemoveTimeFromDate(DateTime As Date) As Date


    Dim dblNumber As Double

    RemoveTimeFromDate = CDate(Floor(CDbl(DateTime)))

End Function

Private Function Floor(ByVal x As Double, Optional ByVal Factor As Double = 1) As Double
    Floor = Int(x / Factor) * Factor
End Function

Android AudioRecord example

Here is an end to end solution I implemented for streaming Android microphone audio to a server for playback: Android AudioRecord to Server over UDP Playback Issues

What characters are allowed in an email address?

Gmail will only allow + sign as special character and in some cases (.) but any other special characters are not allowed at Gmail. RFC's says that you can use special characters but you should avoid sending mail to Gmail with special characters.

Visual Studio opens the default browser instead of Internet Explorer

In the Solution Explorer, right-click any ASPX page and select "Browse With" and select IE as the default.

Note... the same steps can be used to add Google Chrome as a browser option and to optionally set it as the default browser.

Is it possible to use the SELECT INTO clause with UNION [ALL]?

Try something like this: Create the final object table, tmpFerdeen with the structure of the union.

Then

INSERT INTO tmpFerdeen (
SELECT top(100)* 
FROM Customers
UNION All
SELECT top(100)* 
FROM CustomerEurope
UNION All
SELECT top(100)* 
FROM CustomerAsia
UNION All
SELECT top(100)* 
FROM CustomerAmericas
)

How to create an email form that can send email using html

Short answer, you can't.

HTML is used for the page's structure and can't send e-mails, you will need a server side language (such as PHP) to send e-mails, you can also use a third party service and let them handle the e-mail sending for you.

Capture keyboardinterrupt in Python without try-except

An alternative to setting your own signal handler is to use a context-manager to catch the exception and ignore it:

>>> class CleanExit(object):
...     def __enter__(self):
...             return self
...     def __exit__(self, exc_type, exc_value, exc_tb):
...             if exc_type is KeyboardInterrupt:
...                     return True
...             return exc_type is None
... 
>>> with CleanExit():
...     input()    #just to test it
... 
>>>

This removes the try-except block while preserving some explicit mention of what is going on.

This also allows you to ignore the interrupt only in some portions of your code without having to set and reset again the signal handlers everytime.

$(document).ready equivalent without jQuery

If you don't have to support very old browsers, here is a way to do it even when your external script is loaded with async attribute:

HTMLDocument.prototype.ready = new Promise(function(resolve) {
   if(document.readyState != "loading")
      resolve();
   else
      document.addEventListener("DOMContentLoaded", function() {
         resolve();
      });
});

document.ready.then(function() {
   console.log("document.ready");
});

keyword not supported data source

I was getting the same error, then updated my connection string as below,

<add name="EmployeeContext" connectionString="data source=*****;initial catalog=EmployeeDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />

Try this it will solve your issue.

Use C# HttpWebRequest to send json to web service

First of all you missed ScriptService attribute to add in webservice.

[ScriptService]

After then try following method to call webservice via JSON.

        var webAddr = "http://Domain/VBRService.asmx/callJson";
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";            

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{\"x\":\"true\"}";

            streamWriter.Write(json);
            streamWriter.Flush();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            return result;
        }

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.

Python mysqldb: Library not loaded: libmysqlclient.18.dylib

I solved the problem by creating a symbolic link to the library. I.e.

The actual library resides in

/usr/local/mysql/lib

And then I created a symbolic link in

/usr/lib

Using the command:

sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

so that I have the following mapping:

ls -l libmysqlclient.18.dylib 
lrwxr-xr-x  1 root  wheel  44 16 Jul 14:01 libmysqlclient.18.dylib -> /usr/local/mysql/lib/libmysqlclient.18.dylib

That was it. After that everything worked fine.

EDIT:

Notice, that since MacOS El Capitan the System Integrity Protection (SIP, also known as "rootless") will prevent you from creating links in /usr/lib/. You could disable SIP by following these instructions, but you can create a link in /usr/local/lib/ instead:

sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/local/lib/libmysqlclient.18.dylib

How do I pass an object to HttpClient.PostAsync and serialize as a JSON body?

You need to pass your data in the request body as a raw string rather than FormUrlEncodedContent. One way to do so is to serialize it into a JSON string:

var json = JsonConvert.SerializeObject(data); // or JsonSerializer.Serialize if using System.Text.Json

Now all you need to do is pass the string to the post method.

var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json"); // use MediaTypeNames.Application.Json in Core 3.0+ and Standard 2.1+

var client = new HttpClient();
var response = await client.PostAsync(uri, stringContent);

MySQL - Rows to Columns

SELECT 
    hostid, 
    sum( if( itemname = 'A', itemvalue, 0 ) ) AS A,  
    sum( if( itemname = 'B', itemvalue, 0 ) ) AS B, 
    sum( if( itemname = 'C', itemvalue, 0 ) ) AS C 
FROM 
    bob 
GROUP BY 
    hostid;

Postgres: How to do Composite keys?

The error you are getting is in line 3. i.e. it is not in

CONSTRAINT no_duplicate_tag UNIQUE (question_id, tag_id)

but earlier:

CREATE TABLE tags
     (
              (question_id, tag_id) NOT NULL,

Correct table definition is like pilcrow showed.

And if you want to add unique on tag1, tag2, tag3 (which sounds very suspicious), then the syntax is:

CREATE TABLE tags (
    question_id INTEGER NOT NULL,
    tag_id SERIAL NOT NULL,
    tag1 VARCHAR(20),
    tag2 VARCHAR(20),
    tag3 VARCHAR(20),
    PRIMARY KEY(question_id, tag_id),
    UNIQUE (tag1, tag2, tag3)
);

or, if you want to have the constraint named according to your wish:

CREATE TABLE tags (
    question_id INTEGER NOT NULL,
    tag_id SERIAL NOT NULL,
    tag1 VARCHAR(20),
    tag2 VARCHAR(20),
    tag3 VARCHAR(20),
    PRIMARY KEY(question_id, tag_id),
    CONSTRAINT some_name UNIQUE (tag1, tag2, tag3)
);

top nav bar blocking top content of the page

a much more handy solution for your reference, it works perfect in all of my projects:

change your first 'div' from

<div class='navbar navbar-fixed-top'>

to

<div class="navbar navbar-default navbar-static-top">

How to resolve : Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

You are probably targeting a server without built-in JSTL support (e.g. some version of Tomcat.) You will need to provision your own JSTL tag library.

How to have click event ONLY fire on parent DIV, not children?

You can use event.currentTarget. It will do click event only elemnt who got event.

_x000D_
_x000D_
target = e => {_x000D_
    console.log(e.currentTarget);_x000D_
  };
_x000D_
<ul onClick={target} className="folder">_x000D_
      <li>_x000D_
        <p>_x000D_
          <i className="fas fa-folder" />_x000D_
        </p>_x000D_
      </li>_x000D_
    </ul>
_x000D_
_x000D_
_x000D_

How can I disable a specific LI element inside a UL?

Using CSS3: http://www.w3schools.com/cssref/sel_nth-child.asp

If that's not an option for any reason, you could try giving the list items classes:

<ul>
<li class="one"></li>
<li class="two"></li>
<li class="three"></li>
...
</ul>

Then in your css:

li.one{display:none}/*hide first li*/
li.three{display:none}/*hide third li*/

Start an activity from a fragment

If you are using getActivity() then you have to make sure that the calling activity is added already. If activity has not been added in such case so you may get null when you call getActivity()

in such cases getContext() is safe

then the code for starting the activity will be slightly changed like,

Intent intent = new Intent(getContext(), mFragmentFavorite.class);
startActivity(intent);

Activity, Service and Application extends ContextWrapper class so you can use this or getContext() or getApplicationContext() in the place of first argument.

C# Call a method in a new thread

Does it really have to be a thread, or can it be a task too?

if so, the easiest way is:

Task.Factory.StartNew(() => SecondFoo())

Finding the type of an object in C++

If you can access boost library, maybe type_id_with_cvr() function is what you need, which can provide data type without removing const, volatile, & and && modifiers. Here is an simple example in C++11:

#include <iostream>
#include <boost/type_index.hpp>

int a;
int& ff() 
{
    return a;
}

int main() {
    ff() = 10;
    using boost::typeindex::type_id_with_cvr;
    std::cout << type_id_with_cvr<int&>().pretty_name() << std::endl;
    std::cout << type_id_with_cvr<decltype(ff())>().pretty_name() << std::endl;
    std::cout << typeid(ff()).name() << std::endl;
}

Hope this is useful.

How can I add a background thread to flask?

First, you should use any WebSocket or polling mechanics to notify the frontend part about changes that happened. I use Flask-SocketIO wrapper, and very happy with async messaging for my tiny apps.

Nest, you can do all logic which you need in a separate thread(s), and notify the frontend via SocketIO object (Flask holds continuous open connection with every frontend client).

As an example, I just implemented page reload on backend file modifications:

<!doctype html>
<script>
    sio = io()

    sio.on('reload',(info)=>{
        console.log(['sio','reload',info])
        document.location.reload()
    })
</script>
class App(Web, Module):

    def __init__(self, V):
        ## flask module instance
        self.flask = flask
        ## wrapped application instance
        self.app = flask.Flask(self.value)
        self.app.config['SECRET_KEY'] = config.SECRET_KEY
        ## `flask-socketio`
        self.sio = SocketIO(self.app)
        self.watchfiles()

    ## inotify reload files after change via `sio(reload)``
    def watchfiles(self):
        from watchdog.observers import Observer
        from watchdog.events import FileSystemEventHandler
        class Handler(FileSystemEventHandler):
            def __init__(self,sio):
                super().__init__()
                self.sio = sio
            def on_modified(self, event):
                print([self.on_modified,self,event])
                self.sio.emit('reload',[event.src_path,event.event_type,event.is_directory])
        self.observer = Observer()
        self.observer.schedule(Handler(self.sio),path='static',recursive=True)
        self.observer.schedule(Handler(self.sio),path='templates',recursive=True)
        self.observer.start()


How to exit a 'git status' list in a terminal?

for windows :

Ctrl + q and c for exit the running situation .

How to find list intersection?

Here's some Python 2 / Python 3 code that generates timing information for both list-based and set-based methods of finding the intersection of two lists.

The pure list comprehension algorithms are O(n^2), since in on a list is a linear search. The set-based algorithms are O(n), since set search is O(1), and set creation is O(n) (and converting a set to a list is also O(n)). So for sufficiently large n the set-based algorithms are faster, but for small n the overheads of creating the set(s) make them slower than the pure list comp algorithms.

#!/usr/bin/env python

''' Time list- vs set-based list intersection
    See http://stackoverflow.com/q/3697432/4014959
    Written by PM 2Ring 2015.10.16
'''

from __future__ import print_function, division
from timeit import Timer

setup = 'from __main__ import a, b'
cmd_lista = '[u for u in a if u in b]'
cmd_listb = '[u for u in b if u in a]'

cmd_lcsa = 'sa=set(a);[u for u in b if u in sa]'

cmd_seta = 'list(set(a).intersection(b))'
cmd_setb = 'list(set(b).intersection(a))'

reps = 3
loops = 50000

def do_timing(heading, cmd, setup):
    t = Timer(cmd, setup)
    r = t.repeat(reps, loops)
    r.sort()
    print(heading, r)
    return r[0]

m = 10
nums = list(range(6 * m))

for n in range(1, m + 1):
    a = nums[:6*n:2]
    b = nums[:6*n:3]
    print('\nn =', n, len(a), len(b))
    #print('\nn = %d\n%s %d\n%s %d' % (n, a, len(a), b, len(b)))
    la = do_timing('lista', cmd_lista, setup) 
    lb = do_timing('listb', cmd_listb, setup) 
    lc = do_timing('lcsa ', cmd_lcsa, setup)
    sa = do_timing('seta ', cmd_seta, setup)
    sb = do_timing('setb ', cmd_setb, setup)
    print(la/sa, lb/sa, lc/sa, la/sb, lb/sb, lc/sb)

output

n = 1 3 2
lista [0.082171916961669922, 0.082588911056518555, 0.0898590087890625]
listb [0.069530963897705078, 0.070394992828369141, 0.075379848480224609]
lcsa  [0.11858987808227539, 0.1188349723815918, 0.12825107574462891]
seta  [0.26900982856750488, 0.26902294158935547, 0.27298116683959961]
setb  [0.27218389511108398, 0.27459001541137695, 0.34307217597961426]
0.305460649521 0.258469975867 0.440838458259 0.301898526833 0.255455833892 0.435697630214

n = 2 6 4
lista [0.15915989875793457, 0.16000485420227051, 0.16551494598388672]
listb [0.13000702857971191, 0.13060092926025391, 0.13543915748596191]
lcsa  [0.18650484085083008, 0.18742108345031738, 0.19513416290283203]
seta  [0.33592700958251953, 0.34001994132995605, 0.34146714210510254]
setb  [0.29436492919921875, 0.2953648567199707, 0.30039691925048828]
0.473793098554 0.387009751735 0.555194537893 0.540689066428 0.441652573672 0.633583767462

n = 3 9 6
lista [0.27657914161682129, 0.28098297119140625, 0.28311991691589355]
listb [0.21585917472839355, 0.21679902076721191, 0.22272896766662598]
lcsa  [0.22559309005737305, 0.2271728515625, 0.2323150634765625]
seta  [0.36382699012756348, 0.36453008651733398, 0.36750602722167969]
setb  [0.34979605674743652, 0.35533690452575684, 0.36164689064025879]
0.760194128313 0.59330170819 0.62005595016 0.790686848184 0.61710008036 0.644927481902

n = 4 12 8
lista [0.39616990089416504, 0.39746403694152832, 0.41129183769226074]
listb [0.33485794067382812, 0.33914685249328613, 0.37850618362426758]
lcsa  [0.27405810356140137, 0.2745978832244873, 0.28249192237854004]
seta  [0.39211201667785645, 0.39234519004821777, 0.39317893981933594]
setb  [0.36988520622253418, 0.37011313438415527, 0.37571001052856445]
1.01034878821 0.85398540833 0.698928091731 1.07106176249 0.905302334456 0.740927452493

n = 5 15 10
lista [0.56792402267456055, 0.57422614097595215, 0.57740211486816406]
listb [0.47309303283691406, 0.47619009017944336, 0.47628307342529297]
lcsa  [0.32805585861206055, 0.32813096046447754, 0.3349759578704834]
seta  [0.40036201477050781, 0.40322518348693848, 0.40548801422119141]
setb  [0.39103078842163086, 0.39722800254821777, 0.43811702728271484]
1.41852623806 1.18166313332 0.819398061028 1.45237674242 1.20986133789 0.838951479847

n = 6 18 12
lista [0.77897095680236816, 0.78187918663024902, 0.78467702865600586]
listb [0.629547119140625, 0.63210701942443848, 0.63321495056152344]
lcsa  [0.36563992500305176, 0.36638498306274414, 0.38175487518310547]
seta  [0.46695613861083984, 0.46992206573486328, 0.47583580017089844]
setb  [0.47616910934448242, 0.47661614418029785, 0.4850609302520752]
1.66818870637 1.34819326075 0.783028414812 1.63591241329 1.32210827369 0.767878297495

n = 7 21 14
lista [0.9703209400177002, 0.9734041690826416, 1.0182771682739258]
listb [0.82394003868103027, 0.82625699043273926, 0.82796716690063477]
lcsa  [0.40975093841552734, 0.41210508346557617, 0.42286920547485352]
seta  [0.5086359977722168, 0.50968098640441895, 0.51014018058776855]
setb  [0.48688101768493652, 0.4879908561706543, 0.49204087257385254]
1.90769222837 1.61990115188 0.805587768483 1.99293236904 1.69228211566 0.841583309951

n = 8 24 16
lista [1.204819917678833, 1.2206029891967773, 1.258256196975708]
listb [1.014998197555542, 1.0206191539764404, 1.0343101024627686]
lcsa  [0.50966787338256836, 0.51018595695495605, 0.51319599151611328]
seta  [0.50310111045837402, 0.50556015968322754, 0.51335406303405762]
setb  [0.51472997665405273, 0.51948785781860352, 0.52113485336303711]
2.39478683834 2.01748351664 1.01305257092 2.34068341135 1.97190418975 0.990165516871

n = 9 27 18
lista [1.511646032333374, 1.5133969783782959, 1.5639569759368896]
listb [1.2461750507354736, 1.254518985748291, 1.2613379955291748]
lcsa  [0.5565330982208252, 0.56119203567504883, 0.56451296806335449]
seta  [0.5966339111328125, 0.60275578498840332, 0.64791703224182129]
setb  [0.54694414138793945, 0.5508568286895752, 0.55375313758850098]
2.53362406013 2.08867620074 0.932788243907 2.76380331728 2.27843203069 1.01753187594

n = 10 30 20
lista [1.7777848243713379, 2.1453688144683838, 2.4085969924926758]
listb [1.5070111751556396, 1.5202279090881348, 1.5779800415039062]
lcsa  [0.5954139232635498, 0.59703707695007324, 0.60746097564697266]
seta  [0.61563014984130859, 0.62125110626220703, 0.62354087829589844]
setb  [0.56723213195800781, 0.57257509231567383, 0.57460403442382812]
2.88774814689 2.44791645689 0.967161734066 3.13413984189 2.6567803378 1.04968299523

Generated using a 2GHz single core machine with 2GB of RAM running Python 2.6.6 on a Debian flavour of Linux (with Firefox running in the background).

These figures are only a rough guide, since the actual speeds of the various algorithms are affected differently by the proportion of elements that are in both source lists.

mysqldump with create database line

The simplest solution is to use option -B or --databases.Then CREATE database command appears in the output file. For example:

mysqldump -uuser -ppassword -d -B --events --routines --triggers database_example > database_example.sql

Here is a dumpfile's header:

-- MySQL dump 10.13  Distrib 5.5.36-34.2, for Linux (x86_64)
--
-- Host: localhost    Database: database_example
-- ------------------------------------------------------
-- Server version       5.5.36-34.2-log

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Current Database: `database_example`
--

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `database_example` /*!40100 DEFAULT CHARACTER SET utf8 */;

iPhone hide Navigation Bar only on first page

By implement this code in your ViewController you can get this effect Actually the trick is , hide the navigationBar when that Controller is launched

- (void)viewWillAppear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [super viewWillAppear:animated];
}

and unhide the navigation bar when user leave that page do this is viewWillDisappear

- (void)viewWillDisappear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [super viewWillDisappear:animated];
}

CSS /JS to prevent dragging of ghost image?

Try it:

img {
  pointer-events: none;
}

and try to avoid

* {
  pointer-events: none;
}

How to install MySQLdb package? (ImportError: No module named setuptools)

If MySQLdb's now distributed in a way that requires setuptools, your choices are either to download the latter (e.g. from here) or refactor MySQLdb's setup.py to bypass setuptools (maybe just importing setup and Extension from plain distutils instead might work, but you may also need to edit some of the setup_*.py files in the same directory).

Depending on how your site's Python installation is configured, installing extensions for your own individual use without requiring sysadm rights may be hard, but it's never truly impossible if you have shell access. You'll need to tweak your Python's sys.path to start with a directory of your own that's your personal equivalent of the system-wide site pacages directory, e.g. by setting PYTHONPATH persistently in your own environment, and then manually place in said personal directory what normal installs would normally place in site-packages (and/or subdirectories thereof).

Default value in an asp.net mvc view model

<div class="form-group">
                    <label asp-for="Password"></label>
                    <input asp-for="Password"  value="Pass@123" readonly class="form-control" />
                    <span asp-validation-for="Password" class="text-danger"></span>
                </div>

use : value="Pass@123" for default value in input in .net core

text-align:center won't work with form <label> tag (?)

This is because label is an inline element, and is therefore only as big as the text it contains.

The possible is to display your label as a block element like this:

#formItem label {
    display: block;
    text-align: center;
    line-height: 150%;
    font-size: .85em;
}

However, if you want to use the label on the same line with other elements, you either need to set display: inline-block; and give it an explicit width (which doesn't work on most browsers), or you need to wrap it inside a div and do the alignment in the div.

How to write an XPath query to match two attributes?

Sample XML:

<X>
<Y ATTRIB1=attrib1_value ATTRIB2=attrib2_value/>
</X>

string xPath="/" + X + "/" + Y +
"[@" + ATTRIB1 + "='" + attrib1_value + "']" +
"[@" + ATTRIB2 + "='" + attrib2_value + "']"

XPath Testbed: http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm

What is a clearfix?

If you don't need to support IE9 or lower, you can use flexbox freely, and don't need to use floated layouts.

It's worth noting that today, the use of floated elements for layout is getting more and more discouraged with the use of better alternatives.

  • display: inline-block - Better
  • Flexbox - Best (but limited browser support)

Flexbox is supported from Firefox 18, Chrome 21, Opera 12.10, and Internet Explorer 10, Safari 6.1 (including Mobile Safari) and Android's default browser 4.4.

For a detailed browser list see: https://caniuse.com/flexbox.

(Perhaps once its position is established completely, it may be the absolutely recommended way of laying out elements.)


A clearfix is a way for an element to automatically clear its child elements, so that you don't need to add additional markup. It's generally used in float layouts where elements are floated to be stacked horizontally.

The clearfix is a way to combat the zero-height container problem for floated elements

A clearfix is performed as follows:

.clearfix:after {
   content: " "; /* Older browser do not support empty content */
   visibility: hidden;
   display: block;
   height: 0;
   clear: both;
}

Or, if you don't require IE<8 support, the following is fine too:

.clearfix:after {
  content: "";
  display: table;
  clear: both;
}

Normally you would need to do something as follows:

<div>
    <div style="float: left;">Sidebar</div>
    <div style="clear: both;"></div> <!-- Clear the float -->
</div>

With clearfix, you only need the following:

<div class="clearfix">
    <div style="float: left;" class="clearfix">Sidebar</div>
    <!-- No Clearing div! -->
</div>

Read about it in this article - by Chris Coyer @ CSS-Tricks

Test if a property is available on a dynamic variable

If you control the type being used as dynamic, couldn't you return a tuple instead of a value for every property access? Something like...

public class DynamicValue<T>
{
    internal DynamicValue(T value, bool exists)
    {
         Value = value;
         Exists = exists;
    }

    T Value { get; private set; }
    bool Exists { get; private set; }
}

Possibly a naive implementation, but if you construct one of these internally each time and return that instead of the actual value, you can check Exists on every property access and then hit Value if it does with value being default(T) (and irrelevant) if it doesn't.

That said, I might be missing some knowledge on how dynamic works and this might not be a workable suggestion.

I want to truncate a text or line with ellipsis using JavaScript

Try this

function shorten(text, maxLength, delimiter, overflow) {
  delimiter = delimiter || "&hellip;";
  overflow = overflow || false;
  var ret = text;
  if (ret.length > maxLength) {
    var breakpoint = overflow ? maxLength + ret.substr(maxLength).indexOf(" ") : ret.substr(0, maxLength).lastIndexOf(" ");
    ret = ret.substr(0, breakpoint) + delimiter;
  }
  return ret;
}

$(document).ready(function() {
  var $editedText = $("#edited_text");
  var text = $editedText.text();
  $editedText.text(shorten(text, 33, "...", false));
});

Checkout a working sample on Codepen http://codepen.io/Izaias/pen/QbBwwE

Passing a method as a parameter in Ruby

You can pass a method as parameter with method(:function) way. Below is a very simple example:

def double(a)
  return a * 2 
end
=> nil

def method_with_function_as_param( callback, number) 
  callback.call(number) 
end 
=> nil

method_with_function_as_param( method(:double) , 10 ) 
=> 20

Darken background image on hover

Add css:

.image{
    opacity:.5;
}

.image:hover{
    // CSS properties
    opacity:1;
}

What are WSDL, SOAP and REST?

SOAP stands for Simple (sic) Object Access Protocol. It was intended to be a way to do Remote Procedure Calls to remote objects by sending XML over HTTP.

WSDL is Web Service Description Language. A request ending in '.wsdl' to an endpoint will result in an XML message describing request and response that a use can expect. It descibes the contract between service & client.

REST uses HTTP to send messages to services.

SOAP is a spec, REST is a style.

Fixing Xcode 9 issue: "iPhone is busy: Preparing debugger support for iPhone"

I had the same problem many times, these things worked for me:

  • restarting my phone + xCode.
  • checking that both your Mac and your iPhone are connected to the same Network.( has a high potential ).
  • repairing my phone.

Adding Python Path on Windows 7

You need to make changes in your system variable
-- Right click on "My computer"
-- Click "Properties"
-- Click "Advanced system settings" in the side panel
-- Click on Environment Variable -- You will two sections of user variable and system variable
-- Under system variable section search for the variable 'Path' click on edit and add
"C:\Python27;" (without quotes) save it
-- Now open command line type 'path' hit enter you will see path variable has been modified
-- Now type python --version you will see the python version

And it is done

How to split a string at the first `/` (slash) and surround part of it in a `<span>`?

var str = "How are you doing today?";

var res = str.split(" ");

Here the variable "res" is kind of array.

You can also take this explicity by declaring it as

var res[]= str.split(" ");

Now you can access the individual words of the array. Suppose you want to access the third element of the array you can use it by indexing array elements.

var FirstElement= res[0];

Now the variable FirstElement contains the value 'How'

Invalid length for a Base-64 char array

The encrypted string had two special characters, + and =.

'+' sign was giving the error, so below solution worked well:

//replace + sign

encryted_string = encryted_string.Replace("+", "%2b");

//`%2b` is HTTP encoded string for **+** sign

OR

//encode special charactes 

encryted_string = HttpUtility.UrlEncode(encryted_string);

//then pass it to the decryption process
...

How to convert String into Hashmap in java

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

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

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

For example you can switch

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

to

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

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

Change the background color in a twitter bootstrap modal?

It gets a little bit more complicated if you want to add the background to a specific modal. One way of solving that is to add and call something like this function instead of showing the modal directly:

function showModal(selector) {
    $(selector).modal('show');
    $('.modal-backdrop').addClass('background-backdrop');
}

Any css can then be applied to the background-backdrop class.

How can an html element fill out 100% of the remaining screen height, using css only?

forget all the answers, this line of CSS worked for me in 2 seconds :

height:100vh;

1vh = 1% of browser screen height

source

For responsive layout scaling, you might want to use :

min-height: 100vh

[update november 2018] As mentionned in the comments, using the min-height might avoid having issues on reponsive designs

[update april 2018] As mentioned in the comments, back in 2011 when the question was asked, not all browsers supported the viewport units. The other answers were the solutions back then -- vmax is still not supported in IE, so this might not be the best solution for all yet.

How to compare two List<String> to each other?

I discovered that SequenceEqual is not the most efficient way to compare two lists of strings (initially from http://www.dotnetperls.com/sequenceequal).

I wanted to test this myself so I created two methods:

    /// <summary>
    /// Compares two string lists using LINQ's SequenceEqual.
    /// </summary>
    public bool CompareLists1(List<string> list1, List<string> list2)
    {
        return list1.SequenceEqual(list2);
    }

    /// <summary>
    /// Compares two string lists using a loop.
    /// </summary>
    public bool CompareLists2(List<string> list1, List<string> list2)
    {
        if (list1.Count != list2.Count)
            return false;

        for (int i = 0; i < list1.Count; i++)
        {
            if (list1[i] != list2[i])
                return false;
        }

        return true;
    }

The second method is a bit of code I encountered and wondered if it could be refactored to be "easier to read." (And also wondered if LINQ optimization would be faster.)

As it turns out, with two lists containing 32k strings, over 100 executions:

  • Method 1 took an average of 6761.8 ticks
  • Method 2 took an average of 3268.4 ticks

I usually prefer LINQ for brevity, performance, and code readability; but in this case I think a loop-based method is preferred.

Edit:

I recompiled using optimized code, and ran the test for 1000 iterations. The results still favor the loop (even more so):

  • Method 1 took an average of 4227.2 ticks
  • Method 2 took an average of 1831.9 ticks

Tested using Visual Studio 2010, C# .NET 4 Client Profile on a Core i7-920

Try-catch block in Jenkins pipeline script

Look up the AbortException class for Jenkins. You should be able to use the methods to get back simple messages or stack traces. In a simple case, when making a call in a script block (as others have indicated), you can call getMessage() to get the string to echo to the user. Example:

script {
        try {
            sh "sudo docker rmi frontend-test"
        } catch (err) {
            echo err.getMessage()
            echo "Error detected, but we will continue."
        }
        ...continue with other code...
}

Which language uses .pde extension?

Software application written with Arduino, an IDE used for prototyping electronics; contains source code written in the Arduino programming language; enables developers to control the electronics on an Arduino circuit board.

To avoid file association conflicts with the Processing software, Arduino changed the Sketch file extension to .INO with the version 1.0 release. Therefore, while Arduino can still open ".pde" files, the ".ino" file extension should be used instead.

Each PDE file is stored in its own folder when saved from the Processing IDE. It is saved with any other program assets, such as images. The project folder and PDE filename prefix have the same name. When the PDE file is run, it is opened in a Java display window, which renders and runs the resulting program.

Processing is commonly used in educational settings for teaching basic programming skills in a visual environment.

How to detect a route change in Angular?

The answers here are correct for router-deprecated. For the latest version of router:

this.router.changes.forEach(() => {
    // Do whatever in here
});

or

this.router.changes.subscribe(() => {
     // Do whatever in here
});

To see the difference between the two, please check out this SO question.

Edit

For the latest you must do:

this.router.events.subscribe(event: Event => {
    // Handle route change
});

Heap space out of memory

Are you keeping references to variables that you no longer need (e.g. data from the previous simulations)? If so, you have a memory leak. You just need to find where that is happening and make sure that you remove the references to the variables when they are no longer needed (this would automatically happen if they go out of scope).

If you actually need all that data from previous simulations in memory, you need to increase the heap size or change your algorithm.

Git: How to check if a local repo is up to date?

Another alternative is to view the status of the remote branch using git show-branch remote/branch to use it as a comparison you could see git show-branch *branch to see the branch in all remotes as well as your repository! check out this answer for more https://stackoverflow.com/a/3278427/2711378

Free FTP Library

I've just posted an article that presents both an FTP client class and an FTP user control.

They are simple and aren't very fast, but are very easy to use and all source code is included. Just drop the user control onto a form to allow users to navigate FTP directories from your application.

How to place a div below another div?

what about changing the position: relative on your #content #text div to position: absolute

#content #text {
   position:absolute;
   width:950px;
   height:215px;
   color:red;
}

http://jsfiddle.net/CaZY7/12/

then you can use the css properties left and top to position within the #content div

Create an Array of Arraylists

ArrayList<Integer>[] graph = new ArrayList[numCourses] It works.

How to manually include external aar package using new Gradle Android Build System

In my case just work when i add "project" to compile:

repositories {
    mavenCentral()
    flatDir {
        dirs 'libs'
    }
}


dependencies {
   compile project('com.x.x:x:1.0.0')
}

How to create a multiline UITextfield?

This code block is enough. Please don't forget to set delegate in viewDidLoad or by storyboard just before to use the following extension:

extension YOUR_VIEW_CONTROLLER: UITextViewDelegate {

func textViewDidBeginEditing (_ textView: UITextView) {
    if YOUR_TEXT_VIEW.text.isEmpty || YOUR_TEXT_VIEW.text == "YOUR DEFAULT PLACEHOLDER TEXT HERE" {
        YOUR_TEXT_VIEW.text = nil
        YOUR_TEXT_VIEW.textColor = .red // YOUR PREFERED COLOR HERE
    }
}
func textViewDidEndEditing (_ textView: UITextView) {
    if YOUR_TEXT_VIEW.text.isEmpty {
        YOUR_TEXT_VIEW.textColor = UIColor.gray // YOUR PREFERED PLACEHOLDER COLOR HERE
        YOUR_TEXT_VIEW.text =  "YOUR DEFAULT PLACEHOLDER TEXT HERE"
    }
}

}

Reading a JSP variable from JavaScript

The cleanest way, as far as I know:

  1. add your JSP variable to an HTML element's data-* attribute
  2. then read this value via Javascript when required

My opinion regarding the current solutions on this SO page: reading "directly" JSP values using java scriplet inside actual javascript code is probably the most disgusting thing you could do. Makes me wanna puke. haha. Seriously, try to not do it.

The HTML part without JSP:

<body data-customvalueone="1st Interpreted Jsp Value" data-customvaluetwo="another Interpreted Jsp Value">
    Here is your regular page main content
</body>

The HTML part when using JSP:

<body data-customvalueone="${beanName.attrName}" data-customvaluetwo="${beanName.scndAttrName}">
    Here is your regular page main content
</body>

The javascript part (using jQuery for simplicity):

<script type="text/JavaScript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script type="text/javascript">
    jQuery(function(){
        var valuePassedFromJSP = $("body").attr("data-customvalueone");
        var anotherValuePassedFromJSP = $("body").attr("data-customvaluetwo");

        alert(valuePassedFromJSP + " and " + anotherValuePassedFromJSP + " are the values passed from your JSP page");
});
</script>

And here is the jsFiddle to see this in action http://jsfiddle.net/6wEYw/2/

Resources:

JComboBox Selection Change Listener?

It should respond to ActionListeners, like this:

combo.addActionListener (new ActionListener () {
    public void actionPerformed(ActionEvent e) {
        doSomething();
    }
});

@John Calsbeek rightly points out that addItemListener() will work, too. You may get 2 ItemEvents, though, one for the deselection of the previously selected item, and another for the selection of the new item. Just don't use both event types!

Dropdown using javascript onchange

It does not work because your script in JSFiddle is running inside it's own scope (see the "OnLoad" drop down on the left?).

One way around this is to bind your event handler in javascript (where it should be):

document.getElementById('optionID').onchange = function () {
    document.getElementById("message").innerHTML = "Having a Baby!!";
};

Another way is to modify your code for the fiddle environment and explicitly declare your function as global so it can be found by your inline event handler:

window.changeMessage() {
    document.getElementById("message").innerHTML = "Having a Baby!!";
};

?

What is a mutex?

Mutexes are useful in situations where you need to enforce exclusive access to a resource accross multiple processes, where a regular lock won't help since it only works accross threads.

ASP.NET Web Api: The requested resource does not support http method 'GET'

Have the same Setup as OP. One controller with many actions... less "messy" :-)

In my case i forgot the "[HttpGet]" when adding a new action.

[HttpGet]
public IEnumerable<string> TestApiCall()
{
    return new string[] { "aa", "bb" };
}

What does [object Object] mean? (JavaScript)

It means you are alerting an instance of an object. When alerting the object, toString() is called on the object, and the default implementation returns [object Object].

var objA = {};
var objB = new Object;
var objC = {};

objC.toString = function () { return "objC" };

alert(objA); // [object Object]
alert(objB); // [object Object]
alert(objC); // objC

If you want to inspect the object, you should either console.log it, JSON.stringify() it, or enumerate over it's properties and inspect them individually using for in.

ORA-00060: deadlock detected while waiting for resource

I was recently struggling with a similar problem. It turned out that the database was missing indexes on foreign keys. That caused Oracle to lock many more records than required which quickly led to a deadlock during high concurrency.

Here is an excellent article with lots of good detail, suggestions, and details about how to fix a deadlock: http://www.oratechinfo.co.uk/deadlocks.html#unindex_fk

How to open a new form from another form

In my opinion the main form should be responsible for opening both child form. Here is some pseudo that explains what I would do:

// MainForm
private ChildForm childForm;
private MoreForm moreForm;

ButtonThatOpenTheFirstChildForm_Click()
{
    childForm = CreateTheChildForm();
    childForm.MoreClick += More_Click;
    childForm.Show();
}

More_Click()
{
    childForm.Close();
    moreForm = new MoreForm();
    moreForm.Show();
}

You will just need to create a simple event MoreClick in the first child. The main benefit of this approach is that you can replicate it as needed and you can very easily model some sort of basic workflow.

How to update all MySQL table rows at the same time?

Omit the where clause:

update mytable set
column1 = value1,
column2 = value2,
-- other column values etc
;

This will give all rows the same values.

This might not be what you want - consider truncate then a mass insert:

truncate mytable; -- delete all rows efficiently
insert into mytable (column1, column2, ...) values
(row1value1, row1value2, ...), -- row 1
(row2value1, row2value2, ...), -- row 2
-- etc
;