Programs & Examples On #Errordocument

Use .htaccess to redirect HTTP to HTTPs

This is tested and safe to use

Why?: When Wordpress editing your re-write rules, so make sure your HTTPS rule should not be removed! so this is no conflict with native Wordpress rules.

<IfModule mod_rewrite.c>
   RewriteCond %{HTTPS} !=on
   RewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L]
</IfModule>

# BEGIN WordPress
<IfModule mod_rewrite.c>
  #Your our Wordpress rewrite rules...
</IfModule>
# END WordPress

Note: You have to change WordPress Address & Site Address urls to https:// in General Settings also (wp-admin/options-general.php)

httpd-xampp.conf: How to allow access to an external IP besides localhost?

<Directory "E:/xampp/phpMyAdmin/">
AllowOverride AuthConfig Limit
Order allow,deny
Allow from all
Require all granted

New xampp security concept: Access Forbidden Error 403 - Windows 7 - phpMyAdmin

You will have to edit 2 files - 1. httpd-vhosts.conf & 2. httpd-xampp.conf

NOTE : Make sure u backup files ( httpd-xampp.conf ) and ( httpd-vhosts.conf ) , Both Files are located in Drive:\xampp\apache\conf\extra

Open httpd-vhosts.conf file and in the bottom of the file change it

<VirtualHost *:80>
DocumentRoot “E:/xampp/htdocs/”
ServerName localhost
<Directory E:/xampp/htdocs/>.
Require all granted 
</Directory>
</VirtualHost>

Here E:/xampp is my project workspace, you can change it as per your settings

and Second Change is on httpd-xampp.conf file and in the bottom of the file change it

#
# New XAMPP security concept
#
<LocationMatch “^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))”>
Order deny,allow
Allow from all
Allow from ::1 127.0.0.0/8
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>

Proxy Error 502 : The proxy server received an invalid response from an upstream server

The java application takes too long to respond(maybe due start-up/jvm being cold) thus you get the proxy error.

Proxy Error

The proxy server received an invalid response from an upstream server.
 The proxy server could not handle the request GET /lin/Campaignn.jsp.

As Albert Maclang said amending the http timeout configuration may fix the issue. I suspect the java application throws a 500+ error thus the apache gateway error too. You should look in the logs.

Laravel - Forbidden You don't have permission to access / on this server

Chances are that, if all the answers above didn't work for you, and you are using a request validation, you forgot to put the authorization to true.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class EquipmentRequest extends FormRequest {
  /**
   * Determine if the user is authorized to make this request.
   *
   * @return bool
   */
  public function authorize() {
    /*******************************************************/
    return true; /************ THIS VALUE NEEDS TO BE TRUE */
    /*******************************************************/
  }

  /* ... */
}

500 Internal Server Error for php file not for html

I know this question is old, however I ran into this problem on Windows 8.1 while trying to use .htaccess files for rewriting. My solution was simple, I forgot to modify the following line in httpd.conf

#LoadModule rewrite_module modules/mod_rewrite.so

to

LoadModule rewrite_module modules/mod_rewrite.so

Restarted the apache monitor, now all works well. Just posting this as an answer because someone in the future may run across the same issue with a simple fix.

Good luck!

No input file specified

In my case, I fixed it by butting the rules inside a LocationMatch Directive

<LocationMatch "^/.">
    #your rewrite rules here
</LocationMatch>

/. matches any location

I have the rewrite rules inside one of the .conf files of Apache NOT .htaccess file.

I don't know why this worked with me, this is my current setup

  • Apache version 2.4
  • PHP 7.1
  • OS Centos 7
  • PHP-FPM

What is .htaccess file?

.htaccess file create in directory /var/www/html/.htaccess

<IfModule mod_rewrite.c>

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
</IfModule>

Getting 404 Not Found error while trying to use ErrorDocument

When we apply local url, ErrorDocument directive expect the full path from DocumentRoot. There fore,

 ErrorDocument 404 /yourfoldernames/errors/404.html

.htaccess not working apache

use RewriteBase /{your folder}/ on your .htaccess

Error message "Forbidden You don't have permission to access / on this server"

Remember that the correct file to be configured in this situation is not the httpd.conf in the phpMyAdmin alias, but in bin/apache/your_version/conf/httpd.conf.

Look for the following line:

DocumentRoot "c:/wamp/www/"

#
# Each directory to which Apache has access can be configured with respect
# to which services and features are allowed and/or disabled in that
# directory (and its subdirectories).
#
# First, we configure the "default" to be a very restrictive set of
# features.
#
<Directory />
    Options FollowSymLinks
    AllowOverride None
    Order deny,allow
    Allow from all
</Directory>

Make sure it is set to Allow from all...

If not, phpMyAdmin might even work, but not your root and other folders under it. Also, remember to restart WAMP and then put online...

This solved my headache.

CodeIgniter 500 Internal Server Error

Try this to your .htaccess file:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule >

header('HTTP/1.0 404 Not Found'); not doing anything

i think this will help you

content of .htaccess

ErrorDocument 404 /error.php
ErrorDocument 400 /error.php
ErrorDocument 401 /error.php
ErrorDocument 403 /error.php
ErrorDocument 405 /error.php
ErrorDocument 406 /error.php
ErrorDocument 409 /error.php
ErrorDocument 413 /error.php
ErrorDocument 414 /error.php
ErrorDocument 500 /error.php
ErrorDocument 501 /error.php

error.php and .htaccess should be put in the same directory [in this case]

Deny all, allow only one IP through htaccess

This can be improved by using the directive designed for that task.

ErrorDocument 403 /specific_page.html
Order Allow,Deny
Allow from 111.222.333.444

Where 111.222.333.444 is your static IP address.

When using the "Order Allow,Deny" directive the requests must match either Allow or Deny, if neither is met, the request is denied.

http://httpd.apache.org/docs/2.2/mod/mod_authz_host.html#order

Wordpress 403/404 Errors: You don't have permission to access /wp-admin/themes.php on this server

The first error you're getting - permissions - is the most indicative. Bump wp-content and wp-admin to 777 and try it, and if it works, then change them both back to 755 and see if it still works. What are you using to change folder permissions? An FTP client?

.htaccess mod_rewrite - how to exclude directory from rewrite rule

RewriteEngine On

RewriteRule ^(wordpress)($|/) - [L]

How can I create an error 404 in PHP?

Try this:

<?php
header("HTTP/1.0 404 Not Found");
?>

Trimming text strings in SQL Server 2008

SQL Server does not have a TRIM function, but rather it has two. One each for specifically trimming spaces from the "front" of a string (LTRIM) and one for trimming spaces from the "end" of a string (RTRIM).

Something like the following will update every record in your table, trimming all extraneous space (either at the front or the end) of a varchar/nvarchar field:

UPDATE 
   [YourTableName]
SET
   [YourFieldName] = LTRIM(RTRIM([YourFieldName]))

(Strangely, SSIS (Sql Server Integration Services) does have a single TRIM function!)

How to get HttpClient to pass credentials along with the request?

I was also having this same problem. I developed a synchronous solution thanks to the research done by @tpeczek in the following SO article: Unable to authenticate to ASP.NET Web Api service with HttpClient

My solution uses a WebClient, which as you correctly noted passes the credentials without issue. The reason HttpClient doesn't work is because of Windows security disabling the ability to create new threads under an impersonated account (see SO article above.) HttpClient creates new threads via the Task Factory thus causing the error. WebClient on the other hand, runs synchronously on the same thread thereby bypassing the rule and forwarding its credentials.

Although the code works, the downside is that it will not work async.

var wi = (System.Security.Principal.WindowsIdentity)HttpContext.Current.User.Identity;

var wic = wi.Impersonate();
try
{
    var data = JsonConvert.SerializeObject(new
    {
        Property1 = 1,
        Property2 = "blah"
    });

    using (var client = new WebClient { UseDefaultCredentials = true })
    {
        client.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");
        client.UploadData("http://url/api/controller", "POST", Encoding.UTF8.GetBytes(data));
    }
}
catch (Exception exc)
{
    // handle exception
}
finally
{
    wic.Undo();
}

Note: Requires NuGet package: Newtonsoft.Json, which is the same JSON serializer WebAPI uses.

how to change text in Android TextView

@Zordid @Iambda answer is great, but I found that if I put

mHandler.postDelayed(mUpdateUITimerTask, 10 * 1000);

in the run() method and

mHandler.postDelayed(mUpdateUITimerTask, 0);

in the onCreate method make the thing keep updating.

C# '@' before a String

It also means you can use reserved words as variable names

say you want a class named class, since class is a reserved word, you can instead call your class class:

IList<Student> @class = new List<Student>();

Tests not running in Test Explorer

Since I got here with this kind of error I post my problem/solution:

Symptoms:

  • Not all tests running, but they didn't depend per project, just some of them were executed.
  • All executed ones were green.
  • Tech stack: dotnet core / XUnit / FluentAssertions
  • All tests detected and updated if it changed.
  • By selection or running "Not runned tests" several times they could be executed.

Problem:

There was an error in the code that throw an exception inside another thread. All test assertions passed but it cancelled the test execution. I could see the error in the "Tests output" (NullException).

Selenium using Python - Geckodriver executable needs to be in PATH

Some additional input/clarification for future readers of this thread:

The following suffices as a resolution for Windows 7, Python 3.6, and Selenium 3.11:

dsalaj's note for another answer for Unix is applicable to Windows as well; tinkering with the PATH environment variable at the Windows level and restart of the Windows system can be avoided.

(1) Download geckodriver (as described in this thread earlier) and place the (unzipped) geckdriver.exe at X:\Folder\of\your\choice

(2) Python code sample:

import os;
os.environ["PATH"] += os.pathsep + r'X:\Folder\of\your\choice';

from selenium import webdriver;
browser = webdriver.Firefox();
browser.get('http://localhost:8000')
assert 'Django' in browser.title

Notes: (1) It may take about 10 seconds for the above code to open up the Firefox browser for the specified URL. (2) The Python console would show the following error if there's no server already running at the specified URL or serving a page with the title containing the string 'Django': selenium.common.exceptions.WebDriverException: Message: Reached error page: about:neterror?e=connectionFailure&u=http%3A//localhost%3A8000/&c=UTF-8&f=regular&d=Firefox%20can%E2%80%9

Text blinking jQuery

One more made from the core jQuery functionality(it could be better):

function blink( el ) {
    if (!el) {
        el = this
    }

    $(el).animate( { opacity: 0.5 },1200, function() {
        $(this).animate( {opacity: 1 }, 1200, blink );
    } );
}

You can tweak the animation opacity change(0.5- 1) and delay(1200) to get a better "blink". This one is less annoying than the blink of the 90es :-)

Unable to verify leaf signature

Just putting this here in case it helps someone, my case was different and a bit of an odd mix. I was getting this on a request that was accessed via superagent - the problem had nothing to do with certificates (which were setup properly) and all to do with the fact that I was then passing the superagent result through the async module's waterfall callback. To fix: Instead of passing the entire result, just pass result.body through the waterfall's callback.

PHP call Class method / function

Create object for the class and call, if you want to call it from other pages.

$obj = new Functions();

$var = $obj->filter($_GET['params']);

Or inside the same class instances [ methods ], try this.

$var = $this->filter($_GET['params']);

How to embed small icon in UILabel

Swift 3 UILabel extention

Tip: If you need some space between the image and the text just use a space or two before the labelText.

extension UILabel {
    func addIconToLabel(imageName: String, labelText: String, bounds_x: Double, bounds_y: Double, boundsWidth: Double, boundsHeight: Double) {
        let attachment = NSTextAttachment()
        attachment.image = UIImage(named: imageName)
        attachment.bounds = CGRect(x: bounds_x, y: bounds_y, width: boundsWidth, height: boundsHeight)
        let attachmentStr = NSAttributedString(attachment: attachment)
        let string = NSMutableAttributedString(string: "")
        string.append(attachmentStr)
        let string2 = NSMutableAttributedString(string: labelText)
        string.append(string2)
        self.attributedText = string
    }
}

How to delete a cookie?

Here a good link on Quirksmode.

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function eraseCookie(name) {   
    document.cookie = name+'=; Max-Age=-99999999;';  
}

How to get the name of the current method from code

You can also use MethodBase.GetCurrentMethod() which will inhibit the JIT compiler from inlining the method where it's used.


Update:

This method contains a special enumeration StackCrawlMark that from my understanding will specify to the JIT compiler that the current method should not be inlined.

This is my interpretation of the comment associated to that enumeration present in SSCLI. The comment follows:

// declaring a local var of this enum type and passing it by ref into a function 
// that needs to do a stack crawl will both prevent inlining of the calle and 
// pass an ESP point to stack crawl to
// 
// Declaring these in EH clauses is illegal; 
// they must declared in the main method body

Add ArrayList to another ArrayList in java

Your Problem

Mainly, you've got 2 major problems:

You are using adding a List of Strings. You want a List containing Lists of Strings.

Note as well that when you invoke this:

NodeList.addAll(nodes);

... all you say is to add all elements of nodes (which is a list of Strings) to the (badly named) NodeList, which is using Objects and thus adds only the strings inside. Which leads me to the next point.

You seem to be confused between your nodes and NodeList. Your NodeList keeps growing over time, and that's what you add to your list.

So, even if doing things right, if we were to look at the end of each iteration at your nodes, nodeList and list, we'd see:

  • i = 0

    nodes: [PropertyStart,a,b,c,PropertyEnd]
    nodeList: [PropertyStart,a,b,c,PropertyEnd]
    list: [[PropertyStart,a,b,c,PropertyEnd]]
    
  • i = 1

    nodes: [PropertyStart,d,e,f,PropertyEnd]
    nodeList: [PropertyStart,a,b,c,PropertyEnd, PropertyStart,d,e,f,PropertyEnd]
    list: [[PropertyStart,a,b,c,PropertyEnd],[PropertyStart,a,b,c,PropertyEnd, PropertyStart,d,e,f,PropertyEnd]]
    
  • i = 2

    nodes: [PropertyStart,g,h,i,PropertyEnd]
    nodeList: [PropertyStart,a,b,c,PropertyEnd,PropertyStart,d,e,f,PropertyEnd,PropertyStart,g,h,i,PropertyEnd]
    list: [[PropertyStart,a,b,c,PropertyEnd],[PropertyStart,a,b,c,PropertyEnd, PropertyStart,d,e,f,PropertyEnd],[PropertyStart,a,b,c,PropertyEnd,PropertyStart,d,e,f,PropertyEnd,PropertyStart,g,h,i,PropertyEnd]]
    
  • and so on...

Some Other Corrections

Follow the Java Naming Conventions

Don't use variable names starting with uppercase letters. So here, replace NodeList with nodeList).

Learn a Bit More About Types

You say "I want the "list" array [...]". This is confusing for whoever you will be communicating with: It's not an array. It's an implementation of List backed by an array.

There's a difference between a type, an interface, and an implementation.

Use Generics for Stronger Typing in Collections

Use generic types, because static typing really helps with these errors. Also, use interfaces where possible, except if you have a good reason to use the concrete type.

So your code becomes:

List<String> nodes = new ArrayList<String>();
List<String> nodeList = new ArrayList<String>();
List<List<String>> list = new ArrayList<List<String>>();

Remove Unnecessary Code

You could do away with the nodeList entirely, and write the following once you've fixed your types:

list.add(nodes);

Use the Right Scope

Except if you have a very strong reason to do so, prefer to use the inner-most scope to declare variables and limit both their lifespan for their references and facilitate the separation of concerns in your code.

Here you could then move List<String> nodes to be declared within the loop (and then forget the nodes.clear() invocation).

A reason not to do this could be performance, as you might want to avoid recreating an ArrayList on each iteration of the loop, but it's very unlikely that's a concern to you (and clean, readable and maintainable code has priority over pre-optimized code).

SSCCE

Last but not least, if you want help give us the exact reproducible case with a short, self-Contained, correct example.

Here you give us your program's outputs, but don't mention how you got them, so we're left to assume you did a System.out.println(list). And you confused a lot of people, as I think the output you give us is not what you actually got.

Download old version of package with NuGet

Another option is to change the version number in the packages.config file. This will cause NuGet to download the dlls for that version the next time you build.

Converting Java file:// URL to File(...) path, platform independent, including UNC paths

Based on the hint and link provided in Simone Giannis answer, this is my hack to fix this.

I am testing on uri.getAuthority(), because UNC path will report an Authority. This is a bug - so I rely on the existence of a bug, which is evil, but it apears as if this will stay forever (since Java 7 solves the problem in java.nio.Paths).

Note: In my context I will receive absolute paths. I have tested this on Windows and OS X.

(Still looking for a better way to do it)

package com.christianfries.test;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

public class UNCPathTest {

    public static void main(String[] args) throws MalformedURLException, URISyntaxException {
        UNCPathTest upt = new UNCPathTest();

        upt.testURL("file://server/dir/file.txt");  // Windows UNC Path

        upt.testURL("file:///Z:/dir/file.txt");     // Windows drive letter path

        upt.testURL("file:///dir/file.txt");        // Unix (absolute) path
    }

    private void testURL(String urlString) throws MalformedURLException, URISyntaxException {
        URL url = new URL(urlString);
        System.out.println("URL is: " + url.toString());

        URI uri = url.toURI();
        System.out.println("URI is: " + uri.toString());

        if(uri.getAuthority() != null && uri.getAuthority().length() > 0) {
            // Hack for UNC Path
            uri = (new URL("file://" + urlString.substring("file:".length()))).toURI();
        }

        File file = new File(uri);
        System.out.println("File is: " + file.toString());

        String parent = file.getParent();
        System.out.println("Parent is: " + parent);

        System.out.println("____________________________________________________________");
    }

}

Turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server

If you want to do this by code, you can add the behavior like this:

serviceHost.Description.Behaviors.Remove(
    typeof(ServiceDebugBehavior));
serviceHost.Description.Behaviors.Add(
    new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true });

USB Debugging option greyed out

How to Enable USB Debugging for LG Optimus (LGD415). Android version 4.4.2 (KitKat)
Go to this website and download the drivers to your phone:
http://www.lg.com/us/support/mobile-support
For example, mine would be:
http://www.lg.com/us/support-mobile/lg-LGD415RD. Then click on “Software Update & Drivers”

On your phone, you need to enable USB debugging. To do so,
Go to “Settings”.
Go to “About Phone”
Go to “Software Information”
Tap “Build number” five times.
A pop-up will appear saying “You are now a developer”. Your’re not done yet.

Go back to your phone’s home page by pushing the home button.
Go to “Settings”.
Go to “Developer options”
Click the “USB debugging- Turn on debug mode when USB is connected”. A blue checkmark will appear.

(EDIT: If USB Debugging is greyed out, unplug your phone. USB Debugging should no longer be greyed out. If it is not greyed out, check the box and plug your phone into your PC.)

Unplug your phone from your PC. Then plug it back in. On the pop-up, make sure you set it to “Media Sync (MTP)”.

Now your phone will show up on an option when you want to run your app in Eclipse.

(Look for dialog box on phone and agree to allow debugging connection with your computer.)

(Also, go to Control Panel | Device Manager and make sure there are TWO entries for your phone, similar to those expanded below.)

enter image description here

Clearing an HTML file upload field via JavaScript

I know it is quite old, but testing in the browser:

$0.value=null; // when $0 is the file upload element we talking about

erased the value and allow me to rechoose THE SAME FILE as before (means it worked!)

Tested in Chrome 81, FF 76, Safari (on iPad mini), 360 browser, Baidu browser, QQ browser, android browser.

Explanation:

As per my point of view that files selected can be more than 1, you'd better not set the value to a string - the final value sits in $0.files which may be more than 1. The browser need to parse the selected values from "value", so it is an active property. Set it to null, as per my understanding, will cause the browser to parse it to [] empty list in $0.files (this is what happened...)

How do I add a newline using printf?

To write a newline use \n not /n the latter is just a slash and a n

Find the min/max element of an array in JavaScript

For big arrays (~107 elements), Math.min and Math.max procuces a RangeError (Maximum call stack size exceeded) in node.js.

For big arrays, a quick & dirty solution is:

Array.prototype.min = function() {
    var r = this[0];
    this.forEach(function(v,i,a){if (v<r) r=v;});
    return r;
};

How to create border in UIButton?

You don't need to import QuartzCore.h now. Taking iOS 8 sdk and Xcode 6.1 in referrence.

Directly use:

[[myButton layer] setBorderWidth:2.0f];
[[myButton layer] setBorderColor:[UIColor greenColor].CGColor];

How to run JUnit tests with Gradle?

If you created your project with Spring Initializr, everything should be configured correctly and all you need to do is run...

./gradlew clean test --info
  • Use --info if you want to see test output.
  • Use clean if you want to re-run tests that have already passed since the last change.

Dependencies required in build.gradle for testing in Spring Boot...

dependencies {
    compile('org.springframework.boot:spring-boot-starter')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

For some reason the test runner doesn't tell you this, but it produces an HTML report in build/reports/tests/test/index.html.

Can I mask an input text in a bat file?

I wrote an open source program called editenv that replaces my older editv32/editv64 utilities:

https://github.com/Bill-Stewart/editenv

The --maskinput (-m) option[*] lets you hide (mask) the typed input and has a configurable character (default character is *); e.g.:

editenv -m -p "Password: " PWD

The --prompt (-p) option lets you specify an input prompt. The above will display a Password: prompt and wait for you to enter something. Typed characters will appear as *. Pressing Ctrl+C will end the program with an exit code of 1223.

Download is here:

https://github.com/Bill-Stewart/editenv/releases

[*] Note that the --maskinput (-m) option is not secure -- the entered string is entered as plain-text in the environment. This feature is for convenience only.

How to write macro for Notepad++?

My personal experience is that shortcuts.xml is overwritten with the initially loaded + later recorded macros and settings when Notepad++ exits. So you can't use Notepad++ itself for editing this file.

Close Notepad++, edit shortcuts.xml by another tool, save it and restart Notepad++.

Better way to find index of item in ArrayList?

The best way to find the position of item in the list is by using Collections interface,

Eg,

List<Integer> sampleList = Arrays.asList(10,45,56,35,6,7);
Collections.binarySearch(sampleList, 56);

Output : 2

List files with certain extensions with ls and grep

it is easy try to use this command :

ls | grep \.txt$ && ls | grep \.exe

Android MediaPlayer Stop and Play

You should use only one mediaplayer object

    public class PlayaudioActivity extends Activity {

        private MediaPlayer mp;

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            Button b = (Button) findViewById(R.id.button1);
            Button b2 = (Button) findViewById(R.id.button2);
            final TextView t = (TextView) findViewById(R.id.textView1);

            b.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    stopPlaying();
                    mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.far);
                    mp.start();
                }

            });

            b2.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    stopPlaying();
                    mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.beet);
                    mp.start();
                }
            });
        }

        private void stopPlaying() {
            if (mp != null) {
                mp.stop();
                mp.release();
                mp = null;
           }
        }
    }

Setting PATH environment variable in OSX permanently

You have to add it to /etc/paths.

Reference (which works for me) : Here

How to add Headers on RESTful call using Jersey Client API

String sBodys="Body";
HashMap<String,String> headers= new HashMap<>();
Client c = Client.create();
WebResource resource = c.resource("http://consulta/rs");
WebResource.Builder builder = resource.accept(MediaType.APPLICATION_JSON);
builder.type(MediaType.APPLICATION_JSON);
if(headers!=null){
      LOGGER.debug("se setean los headers");
      for (Map.Entry<String, String> entry : headers.entrySet()) {
          String key = entry.getKey();
          String value = entry.getValue();
          LOGGER.debug("key: "+entry.getKey());
          LOGGER.debug("value: "+entry.getValue());
          builder.header(key, value);
      }
  }
ClientResponse response = builder.post(ClientResponse.class,sBodys);

Aligning two divs side-by-side

The HTML code is for three div align side by side and can be used for two also by some changes

<div id="wrapper">
  <div id="first">first</div>
  <div id="second">second</div>
  <div id="third">third</div>
</div>

The CSS will be

#wrapper {
  display:table;
  width:100%;
}
#row {
  display:table-row;
}
#first {
  display:table-cell;
  background-color:red;
  width:33%;
}
#second {
  display:table-cell;
  background-color:blue;
  width:33%;
}
#third {
  display:table-cell;
  background-color:#bada55;
  width:34%;
}

This code will workup towards responsive layout as it will resize the

<div> 

according to device width. Even one can silent anyone

<div>

as

<!--<div id="third">third</div> --> 

and can use rest two for two

<div> 

side by side.

Add days to JavaScript Date

I've used this approach to get the right date in one line to get the time plus one day following what people were saying above.

((new Date()).setDate((new Date()).getDate()+1))

I just figured I would build off a normal (new Date()):

(new Date()).getDate()
> 21

Using the code above I can now set all of that within Date() in (new Date()) and it behaves normally.

(new Date(((new Date()).setDate((new Date()).getDate()+1)))).getDate()
> 22

or to get the Date object:

(new Date(((new Date()).setDate((new Date()).getDate()+1))))

Navigate to another page with a button in angular 2

Having the router link on the button seems to work fine for me:

<button class="nav-link" routerLink="/" (click)="hideMenu()">
     <i class="fa fa-home"></i> 
     <span>Home</span>
</button>

C# Debug - cannot start debugging because the debug target is missing

Please try with the steps below:

  1. Right click on the Visual Studio Project - Properties - Debug - (Start Action section) - select "Start project" radio button.
  2. Right click on the Visual Studio Project - Properties - Debug - (Enable Debuggers section) - mark "Enable the Visual Studio hosting process"
  3. Save changes Ctrl + Shift + S) and run the project again.

P.S. I experienced the same problem when I was playing with the options to redirect the console input / output to text file and have selected the option Properties - Debug - (Start Action section) - Start external program. When I moved the Solution to another location on my computer the problem occurred because it was searching for an absolute path to the executable file. Restoring the Visual Studio Project default settings (see above) fixed the problem. For your reference I am using Visual Studio 2013 Professional.

OS detecting makefile

I was recently experimenting in order to answer this question I was asking myself. Here are my conclusions:

Since in Windows, you can't be sure that the uname command is available, you can use gcc -dumpmachine. This will display the compiler target.

There may be also a problem when using uname if you want to do some cross-compilation.

Here's a example list of possible output of gcc -dumpmachine:

  • mingw32
  • i686-pc-cygwin
  • x86_64-redhat-linux

You can check the result in the makefile like this:

SYS := $(shell gcc -dumpmachine)
ifneq (, $(findstring linux, $(SYS)))
 # Do Linux things
else ifneq(, $(findstring mingw, $(SYS)))
 # Do MinGW things
else ifneq(, $(findstring cygwin, $(SYS)))
 # Do Cygwin things
else
 # Do things for others
endif

It worked well for me, but I'm not sure it's a reliable way of getting the system type. At least it's reliable about MinGW and that's all I need since it does not require to have the uname command or MSYS package in Windows.

To sum up, uname gives you the system on which you're compiling, and gcc -dumpmachine gives you the system for which you are compiling.

Uploading files to file server using webclient class

Just use

File.Copy(filepath, "\\\\192.168.1.28\\Files");

A windows fileshare exposed via a UNC path is treated as part of the file system, and has nothing to do with the web.

The credentials used will be that of the ASP.NET worker process, or any impersonation you've enabled. If you can tweak those to get it right, this can be done.

You may run into problems because you are using the IP address instead of the server name (windows trust settings prevent leaving the domain - by using IP you are hiding any domain details). If at all possible, use the server name!

If this is not on the same windows domain, and you are trying to use a different domain account, you will need to specify the username as "[domain_or_machine]\[username]"

If you need to specify explicit credentials, you'll need to look into coding an impersonation solution.

Is there a destructor for Java?

Nope, no destructors here. The reason is that all Java objects are heap allocated and garbage collected. Without explicit deallocation (i.e. C++'s delete operator) there is no sensible way to implement real destructors.

Java does support finalizers, but they are meant to be used only as a safeguard for objects holding a handle to native resources like sockets, file handles, window handles, etc. When the garbage collector collects an object without a finalizer it simply marks the memory region as free and that's it. When the object has a finalizer, it's first copied into a temporary location (remember, we're garbage collecting here), then it's enqueued into a waiting-to-be-finalized queue and then a Finalizer thread polls the queue with very low priority and runs the finalizer.

When the application exits, the JVM stops without waiting for the pending objects to be finalized, so there practically no guarantees that your finalizers will ever run.

Line Break in XML?

<song>
  <title>Song Tigle</title>
  <lyrics>
    <line>The is the very first line</line>
    <line>Number two and I'm still feeling fine</line>
    <line>Number three and a pattern begins</line>
    <line>Add lines like this and everyone wins!</line>
  </lyrics>
</song>

(Sung to the tune of Home on the Range)

If it was mine I'd wrap the choruses and verses in XML elements as well.

Detect if HTML5 Video element is playing

It seems to me like you could just check for !stream.paused.

Error: Module not specified (IntelliJ IDEA)

Faced the same issue. To solve it,

Add a month to a Date

"mondate" is somewhat similar to "Date" except that adding n adds n months rather than n days:

> library(mondate)
> d <- as.Date("2004-01-31")
> as.mondate(d) + 1
mondate: timeunits="months"
[1] 2004-02-29

casting int to char using C++ style casting

You should use static_cast<char>(i) to cast the integer i to char.

reinterpret_cast should almost never be used, unless you want to cast one type into a fundamentally different type.

Also reinterpret_cast is machine dependent so safely using it requires complete understanding of the types as well as how the compiler implements the cast.

For more information about C++ casting see:

Python wildcard search in string

You could try the fnmatch module, it's got a shell-like wildcard syntax

or can use regular expressions

import re

What is the best Java email address validation method?

If you're looking to verify whether an email address is valid, then VRFY will get you some of the way. I've found it's useful for validating intranet addresses (that is, email addresses for internal sites). However it's less useful for internet mail servers (see the caveats at the top of this page)

com.google.android.gms:play-services-measurement-base is being requested by various other libraries

A similar issue arose with me when I tried to add Firebase Database to my project.

implementation 'com.google.firebase:firebase-core:16.0.1'
implementation 'com.google.firebase:firebase-database:16.0.3'

The issue can be resolved by downgrading or upgrading both the versions to a similar level. So I downgraded firebase database to

implementation 'com.google.firebase:firebase-core:16.0.1'
implementation 'com.google.firebase:firebase-database:16.0.1'

and it worked! All available versions can be searched on this site: https://mvnrepository.com/

How to make android listview scrollable?

I found a tricky solution... which works only in a RelativeLayout. We only need to put a View above a ListView and set clickable 'true' on View and false for the ListView

 <ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/listview
    android:clickable="false" />

<View
    android:layout_width="match_parent"
    android:background="@drawable/gradient_white"
    android:layout_height="match_parent"
    android:clickable="true"
    android:layout_centerHorizontal="true"
    android:layout_alignTop="@+id/listview" />

Multiple linear regression in Python

I think this may the most easy way to finish this work:

from random import random
from pandas import DataFrame
from statsmodels.api import OLS
lr = lambda : [random() for i in range(100)]
x = DataFrame({'x1': lr(), 'x2':lr(), 'x3':lr()})
x['b'] = 1
y = x.x1 + x.x2 * 2 + x.x3 * 3 + 4

print x.head()

         x1        x2        x3  b
0  0.433681  0.946723  0.103422  1
1  0.400423  0.527179  0.131674  1
2  0.992441  0.900678  0.360140  1
3  0.413757  0.099319  0.825181  1
4  0.796491  0.862593  0.193554  1

print y.head()

0    6.637392
1    5.849802
2    7.874218
3    7.087938
4    7.102337
dtype: float64

model = OLS(y, x)
result = model.fit()
print result.summary()

                            OLS Regression Results                            
==============================================================================
Dep. Variable:                      y   R-squared:                       1.000
Model:                            OLS   Adj. R-squared:                  1.000
Method:                 Least Squares   F-statistic:                 5.859e+30
Date:                Wed, 09 Dec 2015   Prob (F-statistic):               0.00
Time:                        15:17:32   Log-Likelihood:                 3224.9
No. Observations:                 100   AIC:                            -6442.
Df Residuals:                      96   BIC:                            -6431.
Df Model:                           3                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [95.0% Conf. Int.]
------------------------------------------------------------------------------
x1             1.0000   8.98e-16   1.11e+15      0.000         1.000     1.000
x2             2.0000   8.28e-16   2.41e+15      0.000         2.000     2.000
x3             3.0000   8.34e-16    3.6e+15      0.000         3.000     3.000
b              4.0000   8.51e-16    4.7e+15      0.000         4.000     4.000
==============================================================================
Omnibus:                        7.675   Durbin-Watson:                   1.614
Prob(Omnibus):                  0.022   Jarque-Bera (JB):                3.118
Skew:                           0.045   Prob(JB):                        0.210
Kurtosis:                       2.140   Cond. No.                         6.89
==============================================================================

Setting an environment variable before a command in Bash is not working for the second command in a pipe

Use env.

For example, env FOO=BAR command. Note that the environment variables will be restored/unchanged again when command finishes executing.

Just be careful about about shell substitution happening, i.e. if you want to reference $FOO explicitly on the same command line, you may need to escape it so that your shell interpreter doesn't perform the substitution before it runs env.

$ export FOO=BAR
$ env FOO=FUBAR bash -c 'echo $FOO'
FUBAR
$ echo $FOO
BAR

How to change date format (MM/DD/YY) to (YYYY-MM-DD) in date picker

this also worked for me. Go to the bootstrap-datepicker.js.

replace this code :

_x000D_
_x000D_
var defaults = $.fn.datepicker.defaults = {_x000D_
  autoclose: false,_x000D_
  beforeShowDay: $.noop,_x000D_
  calendarWeeks: false,_x000D_
  clearBtn: false,_x000D_
  daysOfWeekDisabled: [],_x000D_
  endDate: Infinity,_x000D_
  forceParse: true,_x000D_
  format: 'mm/dd/yyyy',_x000D_
  keyboardNavigation: true,_x000D_
  language: 'en',_x000D_
  minViewMode: 0,_x000D_
  multidate: false,_x000D_
  multidateSeparator: ',',_x000D_
  orientation: "auto",_x000D_
  rtl: false,_x000D_
  startDate: -Infinity,_x000D_
  startView: 0,_x000D_
  todayBtn: false,_x000D_
  todayHighlight: false,_x000D_
  weekStart: 0_x000D_
 };
_x000D_
_x000D_
_x000D_

with :

_x000D_
_x000D_
var defaults = $.fn.datepicker.defaults = {_x000D_
  autoclose: false,_x000D_
  beforeShowDay: $.noop,_x000D_
  calendarWeeks: false,_x000D_
  clearBtn: false,_x000D_
  daysOfWeekDisabled: [],_x000D_
  endDate: Infinity,_x000D_
  forceParse: true,_x000D_
  format: 'yyyy-mm-dd',_x000D_
  keyboardNavigation: true,_x000D_
  language: 'en',_x000D_
  minViewMode: 0,_x000D_
  multidate: false,_x000D_
  multidateSeparator: ',',_x000D_
  orientation: "auto",_x000D_
  rtl: false,_x000D_
  startDate: -Infinity,_x000D_
  startView: 0,_x000D_
  todayBtn: false,_x000D_
  todayHighlight: false,_x000D_
  weekStart: 0_x000D_
 };
_x000D_
_x000D_
_x000D_

Check if table exists in SQL Server

Just wanted to mention one situation where it would probably be a little easier to use the OBJECT_ID method. The INFORMATION_SCHEMA views are objects under each database-

The information schema views are defined in a special schema named INFORMATION_SCHEMA. This schema is contained in each database.

https://msdn.microsoft.com/en-us/library/ms186778.aspx

Therefore all tables you access using

IF EXISTS (SELECT 1 
           FROM [database].INFORMATION_SCHEMA.TABLES 
           WHERE TABLE_TYPE='BASE TABLE' 
           AND TABLE_NAME='mytablename') 
   SELECT 1 AS res ELSE SELECT 0 AS res;

will only reflect what is in [database]. If you wanted to check if tables in another database exist, without dynamically changing the [database] each time, OBJECT_ID will let you do this out of the box. Ex-

IF OBJECT_ID (N'db1.schema.table1', N'U') IS NOT NULL 
   SELECT 1 AS res ELSE SELECT 0 AS res;

works just as well as

IF OBJECT_ID (N'db2.schema.table1', N'U') IS NOT NULL 
   SELECT 1 AS res ELSE SELECT 0 AS res;

SQL SERVER 2016 Edit:

Starting with 2016, Microsoft simplified the ability to check for non-existent objects prior to dropping, by adding the if exists keywords to drop statements. For example,

drop table if exists mytablename

will do the same thing as OBJECT_ID / INFORMATION_SCHEMA wrappers, in 1 line of code.

https://blogs.msdn.microsoft.com/sqlserverstorageengine/2015/11/03/drop-if-exists-new-thing-in-sql-server-2016/

How do I rotate the Android emulator display?

For Linux the F12 combination does not work. Instead, use:

Left Ctrl + F11

npm WARN package.json: No repository field

Have you run npm init? That command runs you through everything...

Error during installing HAXM, VT-X not working

I really hated this awful problem after upgrading Windows 10 Anniversary Update (version 1607). It's just about Driver Signing Changes in Windows 10. If you force install HAXM, you have to disable Driver Signature Enforcement too.

  1. Restart W10 in Safe Mode.
  2. Enter Troubleshoot.
  3. Advanced options>Startup Settings.
  4. Choose "Disable driver signature enforcement"
  5. When Windows 10 loaded, install HAXM latest version.

Select all columns except one in MySQL?

You can do:

SELECT column1, column2, column4 FROM table WHERE whatever

without getting column3, though perhaps you were looking for a more general solution?

Angular2 get clicked element id

do like this simply: (as said in comment here is with example with two methods)

import {Component} from 'angular2/core';

@Component({
    selector: 'my-app', 
    template: `
      <button (click)="checkEvent($event,'a')" id="abc" class="def">Display Toastr</button>
      <button (click)="checkEvent($event,'b')" id="abc1" class="def1">Display Toastr1</button>
    `
})
export class AppComponent {
  checkEvent(event, id){
    console.log(event, id, event.srcElement.attributes.id);
  }
}

demo: http://plnkr.co/edit/5kJaj9D13srJxmod213r?p=preview

git push rejected

If push request is shows Rejected, then try first pull from your github account and then try push.

Ex:

In my case it was giving an error-

 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'https://github.com/ashif8984/git-github.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

****So what I did was-****

$ git pull
$ git push

And the code was pushed successfully into my Github Account.

Copy struct to struct in C

memcpy expects the first two arguments to be void*.

Try: memcpy( (void*)&RTCclk, (void*)&RTCclkBuffert, sizeof(RTCclk) );

P.S. although not necessary, convention dictates the brackets for the sizeof operator. You can get away with a lot in C that leaves code impossible to maintain, so following convention is the mark of a good (employable) C programmer.

How to restart Jenkins manually?

If you want to just reload the configuration file, one can do

    <jenkins_url>/reload

This is quicker if you have made some small change in the configuration file, like config.xml directly in the file system or made copies of the job through the filesystem (not through the browser).

How do I list all files of a directory?

I prefer using the glob module, as it does pattern matching and expansion.

import glob
print(glob.glob("/home/adam/*.txt"))

It will return a list with the queried files:

['/home/adam/file1.txt', '/home/adam/file2.txt', .... ]

INSERT and UPDATE a record using cursors in oracle

This is a highly inefficient way of doing it. You can use the merge statement and then there's no need for cursors, looping or (if you can do without) PL/SQL.

MERGE INTO studLoad l
USING ( SELECT studId, studName FROM student ) s
ON (l.studId = s.studId)
WHEN MATCHED THEN
  UPDATE SET l.studName = s.studName
   WHERE l.studName != s.studName
WHEN NOT MATCHED THEN 
INSERT (l.studID, l.studName)
VALUES (s.studId, s.studName)

Make sure you commit, once completed, in order to be able to see this in the database.


To actually answer your question I would do it something like as follows. This has the benefit of doing most of the work in SQL and only updating based on the rowid, a unique address in the table.

It declares a type, which you place the data within in bulk, 10,000 rows at a time. Then processes these rows individually.

However, as I say this will not be as efficient as merge.

declare

   cursor c_data is
    select b.rowid as rid, a.studId, a.studName
      from student a
      left outer join studLoad b
        on a.studId = b.studId
       and a.studName <> b.studName
           ;

   type t__data is table of c_data%rowtype index by binary_integer;
   t_data t__data;

begin

   open c_data;
   loop
      fetch c_data bulk collect into t_data limit 10000;

      exit when t_data.count = 0;

      for idx in t_data.first .. t_data.last loop
         if t_data(idx).rid is null then
            insert into studLoad (studId, studName)
            values (t_data(idx).studId, t_data(idx).studName);
         else
            update studLoad
               set studName = t_data(idx).studName
             where rowid = t_data(idx).rid
                   ;
         end if;
      end loop;

   end loop;
   close c_data;

end;
/

How can I lock the first row and first column of a table when scrolling, possibly using JavaScript and CSS?

Here is one that I made that is pure javascript/css only.

https://jsfiddle.net/KirbyLWallace/x5sbe0dk/5/

It's meant to be used in full width screen, but I've modified to fit a specific width for the fiddle.

<body onResize="scaleElements()">

<div id="table-container-div">

<table id="data-table">
  <thead id="th-header">
    <tr id="th-header-row">
      <td>Column1</td>
      <td>Column2</td>
      <td>Column3</td>
      <td>Column4</td>
    </tr>
  </thead>

  <tbody id="tbl-body">
    <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
    <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
    <tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>
    <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
    <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
    <tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>
    <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
    <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
    <tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>
    <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
    <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
    <tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>
    <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
    <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
    <tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>
    <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
    <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
    <tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>
    <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
    <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
    <tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>
    <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
    <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
    <tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>
    <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
    <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
    <tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>
    <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
    <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
    <tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>
    <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
    <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
    <tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>
    <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
    <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
    <tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>
    <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
    <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
    <tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>
    <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>
    <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
    <tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>
  </tbody>

</table>

javascript:

(() => {
        scaleElements();  
    })();


  function scaleElements() {

        // element() is just shorthand for document.getElementById().

        // scaleElements() scales a number of other things, not included here, 
        // that get rescaled any time the browser, or a container is resized.
        // the table header row here is just one of them...
        //
        // this thing includes checks to see if a table with the table & thead 
        // is on the page.  If it is, it checks to see if the span container is
        // here (it's not on the first run, but it is on subsequent calls.  So, 
        // it adds it if it needs it, or reuses it if it's there.

        if (element("data-table")) {

            if (element("th-span-container")) {
                element("th-span-container").parentElement.removeChild(element("th-span-container"));
            }

            var x = document.createElement("div");
                x.id = "th-span-container";
                x.style.cssFloat = "left";
                x.style.position = "fixed";
                x.style.top = "10px";

                // you will want to fiddle with your own particular positioning. 
                // this one is positioned to work on a table that is below a page 
                // logo banner.

            var tds = element("th-header-row").getElementsByTagName("td");

            for (i = 0; i < tds.length; i++) {

                let z = tds[i];
                let y = document.createElement("span");

                y.style.padding = "0px";
                y.style.margin = "0px";
                y.style.fontFamily = "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif";
                y.style.fontSize = "13px";
                y.style.border = "0px";
                y.style.position = "absolute";
                y.style.color = "white";
                y.style.backgroundColor = "#3D6588";
                y.style.left = z.offsetLeft + "px";
                y.style.height = z.offsetHeight + "px";
                y.style.lineHeight = z.offsetHeight + "px";
                y.style.width = z.offsetWidth + "px";
                y.innerHTML = z.innerHTML;
                x.appendChild(y);

            }

            element("table-container-div").appendChild(x);
            element("th-header-row").style.visibility = "hidden";

        }

    }

function element(e) {
    return document.getElementById(e);
}

css:

body {
  background: black;
}

#table-container-div {
            width: 310px;
            position: absolute;
            top: 10px;
            bottom: 10px;
            overflow-x: hidden;
            overflow-y: auto;
            min-width: 320px;
        }

        table {
            font-size: 13px;
            height: 120px;
            width: 300px;
            border: 0px solid red;
            background-color: #11171F;
        }

        tr {
            height: 22px;
            color: #cff3ff;
        }

            tr:hover {
                background-color: dimgrey;
            }

        td {
          color:white;
            border-right: 1px dotted #4F4F4F;
        }

        #th-header-row {
            background-color: #3D6588;
            color: white;
        }

Make a link in the Android browser start up my app?

I think you'll want to look at the <intent-filter> element of your Mainfest file. Specifically, take a look at the documentation for the <data> sub-element.

Basically, what you'll need to do is define your own scheme. Something along the lines of:

<intent-filter>
    <data android:scheme="anton" />
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" /> <--Not positive if this one is needed
    ...
</intent-filter>

Then you should be able to launch your app with links that begin with the anton: URI scheme.

"make clean" results in "No rule to make target `clean'"

You have fallen victim to the most common of errors in Makefiles. You always need to put a Tab at the beginning of each command. You've put spaces before the $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS) and @rm -f $(PROGRAMS) *.o core lines. If you replace them with a Tab, you'll be fine.

However, this error doesn't lead to a "No rule to make target ..." error. That probably means your issue lies beyond your Makefile. Have you checked this is the correct Makefile, as in the one you want to be specifying your commands? Try explicitly passing it as a parameter to make, make -f Makefile and let us know what happens.

How do I remove diacritics (accents) from a string in .NET?

I've not used this method, but Michael Kaplan describes a method for doing so in his blog post (with a confusing title) that talks about stripping diacritics: Stripping is an interesting job (aka On the meaning of meaningless, aka All Mn characters are non-spacing, but some are more non-spacing than others)

static string RemoveDiacritics(string text) 
{
    var normalizedString = text.Normalize(NormalizationForm.FormD);
    var stringBuilder = new StringBuilder();

    foreach (var c in normalizedString)
    {
        var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c);
        if (unicodeCategory != UnicodeCategory.NonSpacingMark)
        {
            stringBuilder.Append(c);
        }
    }

    return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
}

Note that this is a followup to his earlier post: Stripping diacritics....

The approach uses String.Normalize to split the input string into constituent glyphs (basically separating the "base" characters from the diacritics) and then scans the result and retains only the base characters. It's just a little complicated, but really you're looking at a complicated problem.

Of course, if you're limiting yourself to French, you could probably get away with the simple table-based approach in How to remove accents and tilde in a C++ std::string, as recommended by @David Dibben.

Remove all HTMLtags in a string (with the jquery text() function)

Another option:

 $("<p>").html(myContent).text();

nodeJs callbacks simple example

var myCallback = function(data) {
  console.log('got data: '+data);
};

var usingItNow = function(callback) {
  callback('get it?');
};

Now open node or browser console and paste the above definitions.

Finally use it with this next line:

usingItNow(myCallback);

With Respect to the Node-Style Error Conventions

Costa asked what this would look like if we were to honor the node error callback conventions.

In this convention, the callback should expect to receive at least one argument, the first argument, as an error. Optionally we will have one or more additional arguments, depending on the context. In this case, the context is our above example.

Here I rewrite our example in this convention.

var myCallback = function(err, data) {
  if (err) throw err; // Check for the error and throw if it exists.
  console.log('got data: '+data); // Otherwise proceed as usual.
};

var usingItNow = function(callback) {
  callback(null, 'get it?'); // I dont want to throw an error, so I pass null for the error argument
};

If we want to simulate an error case, we can define usingItNow like this

var usingItNow = function(callback) {
  var myError = new Error('My custom error!');
  callback(myError, 'get it?'); // I send my error as the first argument.
};

The final usage is exactly the same as in above:

usingItNow(myCallback);

The only difference in behavior would be contingent on which version of usingItNow you've defined: the one that feeds a "truthy value" (an Error object) to the callback for the first argument, or the one that feeds it null for the error argument.

Build Android Studio app via command line

Adding value to all these answers,

many have asked the command for running App in AVD after build sucessful.

adb install -r {path-to-your-bild-folder}/{yourAppName}.apk

How do you create a Swift Date object?

I often have a need to combine date values from one place with time values for another. I wrote a helper function to accomplish this.

let startDateTimeComponents = NSDateComponents()
startDateTimeComponents.year = NSCalendar.currentCalendar().components(NSCalendarUnit.Year, fromDate: date).year
startDateTimeComponents.month = NSCalendar.currentCalendar().components(NSCalendarUnit.Month, fromDate: date).month
startDateTimeComponents.day = NSCalendar.currentCalendar().components(NSCalendarUnit.Day, fromDate: date).day
startDateTimeComponents.hour = NSCalendar.currentCalendar().components(NSCalendarUnit.Hour, fromDate: time).hour
startDateTimeComponents.minute = NSCalendar.currentCalendar().components(NSCalendarUnit.Minute, fromDate: time).minute
let startDateCalendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
combinedDateTime = startDateCalendar!.dateFromComponents(startDateTimeComponents)!

Removing "bullets" from unordered list <ul>

Have you tried setting

li {list-style-type: none;}

According to Need an unordered list without any bullets, you need to add this style to the li elements.

Where does Chrome store extensions?

This link "Finding All Installed Browsers in Windows XP and Vista – beware 64bit!" may be useful for Windows as suggested by "How to find all the browsers installed on a machine".

The installed web browsers are saved in this registry,

HKEY_LOCAL_MACHINE\SOFTWARE\Clients\StartMenuInternet

HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Clients\StartMenuInternet.

How can I combine multiple nested Substitute functions in Excel?

Thanks for the idea of breaking down a formula Werner!

Using Alt+Enter allows one to put each bit of a complex substitute formula on separate lines: they become easier to follow and automatically line themselves up when Enter is pressed.

Just make sure you have enough end statements to match the number of substitute( lines either side of the cell reference.

As in this example:

=
substitute(
substitute(
substitute(
substitute(
B11
,"(","")
,")","")
,"[","")
,"]","")

becomes:

=
SUBSTITUTE(
SUBSTITUTE(
SUBSTITUTE(
SUBSTITUTE(B12,"(",""),")",""),"[",""),"]","")

which works fine as is, but one can always delete the extra paragraphs manually:

=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(B12,"(",""),")",""),"[",""),"]","")

Name > substitute()

[American Samoa] > American Samoa

Is there a Pattern Matching Utility like GREP in Windows?

Update: This wasn't true when the question was originally asked, but now Microsoft lets one Install the Windows Subsystem for Linux, and Windows will then run grep. In PowerShell, run:

Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux

Get exit code for command in bash/ksh

The normal idea would be to run the command and then use $? to get the exit code. However, some times you have multiple cases in which you need to get the exit code. For example, you might need to hide it's output but still return the exit code, or print both the exit code and the output.

ec() { [[ "$1" == "-h" ]] && { shift && eval $* > /dev/null 2>&1; ec=$?; echo $ec; } || eval $*; ec=$?; }

This will give you the option to suppress the output of the command you want the exit code for. When the output is suppressed for the command, the exit code will directly be returned by the function.

I personally like to put this function in my .bashrc file

Below I demonstrate a few ways in which you can use this:


# In this example, the output for the command will be
# normally displayed, and the exit code will be stored
# in the variable $ec.

$ ec echo test
test
$ echo $ec
0

# In this example, the exit code is output
# and the output of the command passed
# to the `ec` function is suppressed.

$ echo "Exit Code: $(ec -h echo test)"
Exit Code: 0

# In this example, the output of the command
# passed to the `ec` function is suppressed
# and the exit code is stored in `$ec`

$ ec -h echo test
$ echo $ec
0

Solution to your code using this function

#!/bin/bash
if [[ "$(ec -h 'ls -l | grep p')" != "0" ]]; then
    echo "Error when executing command: 'grep p' [$ec]"
    exit $ec;
fi

You should also note that the exit code you will be seeing will be for the grep command that's being run, as it is the last command being executed. Not the ls.

How to make a edittext box in a dialog

Setting margin in layout params will not work in Alertdialog. you have to set padding in parent layout and then add edittext in that layout.

This is my working kotlin code...

val alert =  AlertDialog.Builder(context!!)

val edittext = EditText(context!!)
edittext.hint = "Enter Name"
edittext.maxLines = 1

val layout = FrameLayout(context!!)

//set padding in parent layout
layout.setPaddingRelative(45,15,45,0)

alert.setTitle(title)

layout.addView(edittext)

alert.setView(layout)

alert.setPositiveButton(getString(R.string.label_save), DialogInterface.OnClickListener {

    dialog, which ->
    run {

        val qName = edittext.text.toString()

        Utility.hideKeyboard(context!!, dialogView!!)

    }

})
alert.setNegativeButton(getString(R.string.label_cancel), DialogInterface.OnClickListener {

            dialog, which ->
            run {
                dismiss()
            }

})

alert.show()

What's the difference between a POST and a PUT HTTP REQUEST?

As far as i know, PUT is mostly used for update the records.

  1. POST - To create document or any other resource

  2. PUT - To update the created document or any other resource.

But to be clear on that PUT usually 'Replaces' the existing record if it is there and creates if it not there..

QED symbol in latex

enter image description here

\documentclass{scrartcl}
\usepackage{amssymb}
\begin{document}
$\backslash$blacksquare: $\blacksquare$

$\backslash$square: $\square$
\end{document}

You can easily find such symbols with http://write-math.com

When you want to align it to the right, add \hfill.

I use:

\renewcommand{\qed}{\hfill\blacksquare}
\newcommand{\qedwhite}{\hfill \ensuremath{\Box}}

Ruby class instance variable vs. class variable

Source

Availability to instance methods

  • Class instance variables are available only to class methods and not to instance methods.
  • Class variables are available to both instance methods and class methods.

Inheritability

  • Class instance variables are lost in the inheritance chain.
  • Class variables are not.
class Vars

  @class_ins_var = "class instance variable value"  #class instance variable
  @@class_var = "class variable value" #class  variable

  def self.class_method
    puts @class_ins_var
    puts @@class_var
  end

  def instance_method
    puts @class_ins_var
    puts @@class_var
  end
end

Vars.class_method

puts "see the difference"

obj = Vars.new

obj.instance_method

class VarsChild < Vars


end

VarsChild.class_method

MySQL trigger if condition exists

I think you mean to update it back to the OLD password, when the NEW one is not supplied.

DROP TRIGGER IF EXISTS upd_user;

DELIMITER $$

    CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
    FOR EACH ROW BEGIN
      IF (NEW.password IS NULL OR NEW.password = '') THEN
            SET NEW.password = OLD.password;
      ELSE
            SET NEW.password = Password(NEW.Password);
      END IF;
    END$$

DELIMITER ;

However, this means a user can never blank out a password.


If the password field (already encrypted) is being sent back in the update to mySQL, then it will not be null or blank, and MySQL will attempt to redo the Password() function on it. To detect this, use this code instead

DELIMITER $$

    CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
    FOR EACH ROW BEGIN
      IF (NEW.password IS NULL OR NEW.password = '' OR NEW.password = OLD.password) THEN
            SET NEW.password = OLD.password;
      ELSE
            SET NEW.password = Password(NEW.Password);
      END IF;
    END$$

DELIMITER ;

Change Screen Orientation programmatically using a Button

Yes, you can set the screen orientation programatically anytime you want using:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

for landscape and portrait mode respectively. The setRequestedOrientation() method is available for the Activity class, so it can be used inside your Activity.

And this is how you can get the current screen orientation and set it adequatly depending on its current state:

Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
final int orientation = display.getOrientation(); 
 // OR: orientation = getRequestedOrientation(); // inside an Activity

// set the screen orientation on button click
Button btn = (Button) findViewById(R.id.yourbutton);
btn.setOnClickListener(new View.OnClickListener() {
          public void onClick(View v) {

              switch(orientation) {
                   case Configuration.ORIENTATION_PORTRAIT:
                       setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                       break;
                   case Configuration.ORIENTATION_LANDSCAPE:
                       setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                       break;                   
               }
          }
   });

Taken from here: http://techblogon.com/android-screen-orientation-change-rotation-example/

EDIT

Also, you can get the screen orientation using the Configuration:

Activity.getResources().getConfiguration().orientation

Differences between Emacs and Vim

Vim is not a shell. And it does not communicate well with subprocesses. This is nearly by design, whereas in Emacs, these elements are included by design. This means that some stuff, like embedding a debugger or an interpreter (yielding a sort of IDE), is difficult in Vim.

Also, Emacs shortcuts are mainly accessed through modifiers, and obviously the Vim interface is famously modal, giving access to an absurd amount of direct keys for manipulation.

Emacs used to be the only editor of the two that was programmable, and while Vim has a lot of weird levels to its programmability, with the addition of Python and Ruby bindings (and more, I forget), Vim is also programmable in most ways you'd care for.

I use Vim, and I'm fairly happy with it.

Python - Check If Word Is In A String

Advanced way to check the exact word, that we need to find in a long string:

import re
text = "This text was of edited by Rock"
#try this string also
#text = "This text was officially edited by Rock" 
for m in re.finditer(r"\bof\b", text):
    if m.group(0):
        print "Present"
    else:
        print "Absent"

$_POST not working. "Notice: Undefined index: username..."

first of all,

be sure that there is a post

if(isset($_POST['username'])) { 
    // check if the username has been set
}

second, and most importantly, sanitize the data, meaning that

$query = "SELECT password FROM users WHERE username='".$_POST['username']."'";

is deadly dangerous, instead use

$query = "SELECT password FROM users WHERE username='".mysql_real_escape_string($_POST['username'])."'";

and please research the subject sql injection

Bootstrap 4: responsive sidebar menu to top navbar

If this isn't a good solution for any reason, please let me know. It worked fine for me.

What I did is to hide the Sidebar and then make appear the navbar with breakpoints

@media screen and (max-width: 771px) {
    #fixed-sidebar {
        display: none;
    }
    #navbar-superior {
        display: block !important;
    }
}

Python how to write to a binary file?

As of Python 3.2+, you can also accomplish this using the to_bytes native int method:

newFileBytes = [123, 3, 255, 0, 100]
# make file
newFile = open("filename.txt", "wb")
# write to file
for byte in newFileBytes:
    newFile.write(byte.to_bytes(1, byteorder='big'))

I.e., each single call to to_bytes in this case creates a string of length 1, with its characters arranged in big-endian order (which is trivial for length-1 strings), which represents the integer value byte. You can also shorten the last two lines into a single one:

newFile.write(''.join([byte.to_bytes(1, byteorder='big') for byte in newFileBytes]))

How to make a <button> in Bootstrap look like a normal link in nav-tabs?

Just get rid of the background color, borders and add hover effects. Here's a fiddle: http://jsfiddle.net/yPU29/

<form action="..." method="post">
<div class="row-fluid">
<!-- Navigation for the form -->
<div class="span3">
  <ul class="nav nav-tabs nav-stacked">
    <li><button type="submit" name="op" value="Link 1" class="button-link">Link 1</button></li>
    <li><button type="submit" name="op" value="Link 2" class="button-link">Link 2</button></li>
    <!-- ... -->
  </ul>
</div>
<!-- The actual form -->
<div class="span9">
  <!-- ... -->
</div>
</div>
</form>

CSS:

.button-link {
background-color: transparent;
border: none;
}

.button-link:hover {
color: blue;
text-decoration: underline;
}

From a Sybase Database, how I can get table description ( field names and types)?

Check sysobjects and syscolumns tables.

Here is a diagram of Sybase system tables.

List of all user tables:

SELECT * FROM sysobjects WHERE type = 'U'

You can change 'U' to other objects:

  • C – computed column
  • D – default
  • F – SQLJ function
  • L – log
  • N – partition condition
  • P – Transact-SQL or SQLJ procedure
  • PR – prepare objects (created by Dynamic SQL)
  • R – rule
  • RI – referential constraint
  • S – system table
  • TR – trigger
  • U – user table
  • V – view
  • XP – extended stored procedure

List of columns in a table:

SELECT sc.* 
FROM syscolumns sc
INNER JOIN sysobjects so ON sc.id = so.id
WHERE so.name = 'my_table_name'

Dynamically generating a QR code with PHP

The phpqrcode library is really fast to configure and the API documentation is easy to understand.

In addition to abaumg's answer I have attached 2 examples in PHP from http://phpqrcode.sourceforge.net/examples/index.php

1. QR code encoder

first include the library from your local path

include('../qrlib.php');

then to output the image directly as PNG stream do for example:

QRcode::png('your texte here...');

to save the result locally as a PNG image:

$tempDir = EXAMPLE_TMP_SERVERPATH;

$codeContents = 'your message here...';

$fileName = 'qrcode_name.png';

$pngAbsoluteFilePath = $tempDir.$fileName;
$urlRelativeFilePath = EXAMPLE_TMP_URLRELPATH.$fileName;

QRcode::png($codeContents, $pngAbsoluteFilePath); 

2. QR code decoder

See also the zxing decoder:

http://zxing.org/w/decode.jspx

Pretty useful to check the output.

3. List of Data format

A list of data format you can use in your QR code according to the data type :

  • Website URL: http://stackoverflow.com (including the protocole http://)
  • email address: mailto:[email protected]
  • Telephone Number: +16365553344 (including country code)
  • SMS Message: smsto:number:message
  • MMS Message: mms:number:subject
  • YouTube Video: youtube://ID (may work on iPhone, not standardized)

What does "wrong number of arguments (1 for 0)" mean in Ruby?

When you define a function, you also define what info (arguments) that function needs to work. If it is designed to work without any additional info, and you pass it some, you are going to get that error.

Example: Takes no arguments:

def dog
end

Takes arguments:

def cat(name)
end

When you call these, you need to call them with the arguments you defined.

dog                  #works fine
cat("Fluffy")        #works fine


dog("Fido")          #Returns ArgumentError (1 for 0)
cat                  #Returns ArgumentError (0 for 1)

Check out the Ruby Koans to learn all this.

Is it possible to auto-format your code in Dreamweaver?

Please click on "edit" -> then keyboard shortcuts. It`s straight forward from there. Just select the command from the list, and press the + button.

You will need to create a duplicate set, then select it again from the list. And finally set a keyboard shortcut!

Now, before saving, press the shortcut you just created!

Install MySQL on Ubuntu without a password prompt

sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password password your_password'
sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password_again password your_password'
sudo apt-get -y install mysql-server

For specific versions, such as mysql-server-5.6, you'll need to specify the version in like this:

sudo debconf-set-selections <<< 'mysql-server-5.6 mysql-server/root_password password your_password'
sudo debconf-set-selections <<< 'mysql-server-5.6 mysql-server/root_password_again password your_password'
sudo apt-get -y install mysql-server-5.6

For mysql-community-server, the keys are slightly different:

sudo debconf-set-selections <<< 'mysql-community-server mysql-community-server/root-pass password your_password'
sudo debconf-set-selections <<< 'mysql-community-server mysql-community-server/re-root-pass password your_password'
sudo apt-get -y install mysql-community-server

Replace your_password with the desired root password. (it seems your_password can also be left blank for a blank root password.)

If your shell doesn't support here-strings (zsh, ksh93 and bash support them), use:

echo ... | sudo debconf-set-selections 

How to remove array element in mongodb?

You can simply use $pull to remove a sub-document. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.

Collection.update({
    _id: parentDocumentId
  }, {
    $pull: {
      subDocument: {
        _id: SubDocumentId
      }
    }
  });

This will find your parent document against given ID and then will remove the element from subDocument which matched the given criteria.

Read more about pull here.

Fastest way to count exact number of rows in a very large table?

The fastest way by far on MySQL is:

SHOW TABLE STATUS;

You will instantly get all your tables with the row count (which is the total) along with plenty of extra information if you want.

How do I determine whether an array contains a particular value in Java?

You can check it by two methods

A)By converting the array into string and then check the required string by .contains method

 String a=Arrays.toString(VALUES);
    System.out.println(a.contains("AB"));
    System.out.println(a.contains("BC"));
    System.out.println(a.contains("CD"));
    System.out.println(a.contains("AE"));

B)this is a more efficent method

 Scanner s=new Scanner(System.in);


   String u=s.next();
   boolean d=true;
    for(int i=0;i<VAL.length;i++)
    {
        if(VAL[i].equals(u)==d)
            System.out.println(VAL[i] +" "+u+VAL[i].equals(u));  

    }

Quick Sort Vs Merge Sort

For Merge sort worst case is O(n*log(n)), for Quick sort: O(n2). For other cases (avg, best) both have O(n*log(n)). However Quick sort is space constant where Merge sort depends on the structure you're sorting.

See this comparison.

You can also see it visually.

Set selected item of spinner programmatically

This is what I use in Kotlin:

spinner.setSelection(resources.getStringArray(R.array.choices).indexOf("Choice 1"))

UIDevice uniqueIdentifier deprecated - What to do now?

UIDevice identifierForVendor introduced in iOS 6 would work for your purposes.

identifierForVendor is an alphanumeric string that uniquely identifies a device to the app’s vendor. (read-only)

@property(nonatomic, readonly, retain) NSUUID *identifierForVendor

The value of this property is the same for apps that come from the same vendor running on the same device. A different value is returned for apps onthe same device that come from different vendors, and for apps on different devices regardles of vendor.

Available in iOS 6.0 and later and declared in UIDevice.h

For iOS 5 refer this link UIDevice-with-UniqueIdentifier-for-iOS-5

How to open, read, and write from serial port in C?

I wrote this a long time ago (from years 1985-1992, with just a few tweaks since then), and just copy and paste the bits needed into each project.

You must call cfmakeraw on a tty obtained from tcgetattr. You cannot zero-out a struct termios, configure it, and then set the tty with tcsetattr. If you use the zero-out method, then you will experience unexplained intermittent failures, especially on the BSDs and OS X. "Unexplained intermittent failures" include hanging in read(3).

#include <errno.h>
#include <fcntl.h> 
#include <string.h>
#include <termios.h>
#include <unistd.h>

int
set_interface_attribs (int fd, int speed, int parity)
{
        struct termios tty;
        if (tcgetattr (fd, &tty) != 0)
        {
                error_message ("error %d from tcgetattr", errno);
                return -1;
        }

        cfsetospeed (&tty, speed);
        cfsetispeed (&tty, speed);

        tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8;     // 8-bit chars
        // disable IGNBRK for mismatched speed tests; otherwise receive break
        // as \000 chars
        tty.c_iflag &= ~IGNBRK;         // disable break processing
        tty.c_lflag = 0;                // no signaling chars, no echo,
                                        // no canonical processing
        tty.c_oflag = 0;                // no remapping, no delays
        tty.c_cc[VMIN]  = 0;            // read doesn't block
        tty.c_cc[VTIME] = 5;            // 0.5 seconds read timeout

        tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl

        tty.c_cflag |= (CLOCAL | CREAD);// ignore modem controls,
                                        // enable reading
        tty.c_cflag &= ~(PARENB | PARODD);      // shut off parity
        tty.c_cflag |= parity;
        tty.c_cflag &= ~CSTOPB;
        tty.c_cflag &= ~CRTSCTS;

        if (tcsetattr (fd, TCSANOW, &tty) != 0)
        {
                error_message ("error %d from tcsetattr", errno);
                return -1;
        }
        return 0;
}

void
set_blocking (int fd, int should_block)
{
        struct termios tty;
        memset (&tty, 0, sizeof tty);
        if (tcgetattr (fd, &tty) != 0)
        {
                error_message ("error %d from tggetattr", errno);
                return;
        }

        tty.c_cc[VMIN]  = should_block ? 1 : 0;
        tty.c_cc[VTIME] = 5;            // 0.5 seconds read timeout

        if (tcsetattr (fd, TCSANOW, &tty) != 0)
                error_message ("error %d setting term attributes", errno);
}


...
char *portname = "/dev/ttyUSB1"
 ...
int fd = open (portname, O_RDWR | O_NOCTTY | O_SYNC);
if (fd < 0)
{
        error_message ("error %d opening %s: %s", errno, portname, strerror (errno));
        return;
}

set_interface_attribs (fd, B115200, 0);  // set speed to 115,200 bps, 8n1 (no parity)
set_blocking (fd, 0);                // set no blocking

write (fd, "hello!\n", 7);           // send 7 character greeting

usleep ((7 + 25) * 100);             // sleep enough to transmit the 7 plus
                                     // receive 25:  approx 100 uS per char transmit
char buf [100];
int n = read (fd, buf, sizeof buf);  // read up to 100 characters if ready to read

The values for speed are B115200, B230400, B9600, B19200, B38400, B57600, B1200, B2400, B4800, etc. The values for parity are 0 (meaning no parity), PARENB|PARODD (enable parity and use odd), PARENB (enable parity and use even), PARENB|PARODD|CMSPAR (mark parity), and PARENB|CMSPAR (space parity).

"Blocking" sets whether a read() on the port waits for the specified number of characters to arrive. Setting no blocking means that a read() returns however many characters are available without waiting for more, up to the buffer limit.


Addendum:

CMSPAR is needed only for choosing mark and space parity, which is uncommon. For most applications, it can be omitted. My header file /usr/include/bits/termios.h enables definition of CMSPAR only if the preprocessor symbol __USE_MISC is defined. That definition occurs (in features.h) with

#if defined _BSD_SOURCE || defined _SVID_SOURCE
 #define __USE_MISC     1
#endif

The introductory comments of <features.h> says:

/* These are defined by the user (or the compiler)
   to specify the desired environment:

...
   _BSD_SOURCE          ISO C, POSIX, and 4.3BSD things.
   _SVID_SOURCE         ISO C, POSIX, and SVID things.
...
 */

comparing two strings in ruby

var1 is a regular string, whereas var2 is an array, this is how you should compare (in this case):

puts var1 == var2[0]

MongoDB inserts float when trying to insert integer

Well, it's JavaScript, so what you have in 'value' is a Number, which can be an integer or a float. But there's not really a difference in JavaScript. From Learning JavaScript:

The Number Data Type

Number data types in JavaScript are floating-point numbers, but they may or may not have a fractional component. If they don’t have a decimal point or fractional component, they’re treated as integers—base-10 whole numbers in a range of –253 to 253.

Downloading an entire S3 bucket?

You can use s3cmd to download your bucket:

s3cmd --configure
s3cmd sync s3://bucketnamehere/folder /destination/folder

There is another tool you can use called rclone. This is a code sample in the Rclone documentation:

rclone sync /home/local/directory remote:bucket

Better way to cast object to int

Maybe Convert.ToInt32.

Watch out for exception, in both cases.

How to parse XML using vba

Often it is easier to parse without VBA, when you don't want to enable macros. This can be done with the replace function. Enter your start and end nodes into cells B1 and C1.

Cell A1: {your XML here}
Cell B1: <X>
Cell C1: </X>
Cell D1: =REPLACE(A1,1,FIND(A2,A1)+LEN(A2)-1,"")
Cell E1: =REPLACE(A4,FIND(A3,A4),LEN(A4)-FIND(A3,A4)+1,"")

And the result line E1 will have your parsed value:

Cell A1: {your XML here}
Cell B1: <X>
Cell C1: </X>
Cell D1: 24.365<X><Y>78.68</Y></PointN>
Cell E1: 24.365

Why can't variables be declared in a switch statement?

You can't do this, because case labels are actually just entry points into the containing block.

This is most clearly illustrated by Duff's device. Here's some code from Wikipedia:

strcpy(char *to, char *from, size_t count) {
    int n = (count + 7) / 8;
    switch (count % 8) {
    case 0: do { *to = *from++;
    case 7:      *to = *from++;
    case 6:      *to = *from++;
    case 5:      *to = *from++;
    case 4:      *to = *from++;
    case 3:      *to = *from++;
    case 2:      *to = *from++;
    case 1:      *to = *from++;
               } while (--n > 0);
    }
}

Notice how the case labels totally ignore the block boundaries. Yes, this is evil. But this is why your code example doesn't work. Jumping to a case label is the same as using goto, so you aren't allowed to jump over a local variable with a constructor.

As several other posters have indicated, you need to put in a block of your own:

switch (...) {
    case FOO: {
        MyObject x(...);
        ...
        break; 
    }
    ...
 }

How to set connection timeout with OkHttp

It's changed now. Replace .Builder() with .newBuilder()

As of okhttp:3.9.0 the code goes as follows:

OkHttpClient okHttpClient = new OkHttpClient()
    .newBuilder()
    .connectTimeout(10,TimeUnit.SECONDS)
    .writeTimeout(10,TimeUnit.SECONDS)
    .readTimeout(30,TimeUnit.SECONDS)
    .build();

Sun JSTL taglib declaration fails with "Can not find the tag library descriptor"

Just check our own JSTL wiki page for the proper download links and crystal clear installation instructions.

Put your mouse above the [jstl] tag which you put on the question yourself until a black box shows up and click therein the info link.

enter image description here

Then scroll a bit down to JSTL versions information until you find download link to JSTL 1.2 (or 1.2.1).

enter image description here

Finally just drop exactly that file in webapp's /WEB-INF/lib.

enter image description here

This way the taglib declaration must not give any errors anymore and the JSTL tags and functions should just work.

Compile error: package javax.servlet does not exist

This happens because java does not provide with Servlet-api.jar to import directly, so you need to import it externally like from Tomcat , for this we need to provide the classpath of lib folder from which we will be importing the Servlet and it's related Classes.

For Windows you can apply this method:

  1. open command prompt
  2. type
 javac -classpath "C:\Program Files\Apache Software Foundation\Tomcat 9.0\lib\*;" YourFileName.java 
     
  1. It will take all jar files which needed for importing Servlet, HttpServlet ,etc and compile your java file.

  2. You can add multiple classpaths Eg.

javac -classpath "C:\Users\Project1\WEB-INF\lib\*; C:\Program Files\Apache Software Foundation\Tomcat 9.0\lib\*;" YourFileName.java

Add zero-padding to a string

You can use PadLeft

var newString = Your_String.PadLeft(4, '0');

Check if Variable is Empty - Angular 2

Ar you looking for that:

isEmptyObject(obj) {
  return (obj && (Object.keys(obj).length === 0));
}

(found here)

or that :

function isEmpty(obj) {
    for(var key in obj) {
        if(obj.hasOwnProperty(key))
            return false;
    }
    return true;
}

found here

CSS: how to get scrollbars for div inside container of fixed height

FWIW, here is my approach = a simple one that works for me:

<div id="outerDivWrapper">
   <div id="outerDiv">
      <div id="scrollableContent">
blah blah blah
      </div>
   </div>
</div>

html, body {
   height: 100%;
   margin: 0em;
}

#outerDivWrapper, #outerDiv {
   height: 100%;
   margin: 0em;
}

#scrollableContent {
   height: 100%;
   margin: 0em;
   overflow-y: auto;
}

How to link C++ program with Boost using CMake

In CMake you could use find_package to find libraries you need. There usually is a FindBoost.cmake along with your CMake installation.

As far as I remember, it will be installed to /usr/share/cmake/Modules/ along with other find-scripts for common libraries. You could just check the documentation in that file for more information about how it works.

An example out of my head:

FIND_PACKAGE( Boost 1.40 COMPONENTS program_options REQUIRED )
INCLUDE_DIRECTORIES( ${Boost_INCLUDE_DIR} )

ADD_EXECUTABLE( anyExecutable myMain.cpp )

TARGET_LINK_LIBRARIES( anyExecutable LINK_PUBLIC ${Boost_LIBRARIES} )

I hope this code helps.

Cannot enqueue Handshake after invoking quit

SOLUTION: to prevent this error(for AWS LAMBDA):

In order to exit of "Nodejs event Loop" you must end the connection, and then reconnect. Add the next code to invoke the callback:

connection.end( function(err) {
        if (err) {console.log("Error ending the connection:",err);}

       //  reconnect in order to prevent the"Cannot enqueue Handshake after invoking quit"

         connection = mysql.createConnection({
                host     : 'rds.host',
                port     :  3306,
                user     : 'user',
               password : 'password',
               database : 'target database'

               });
        callback(null, {
            statusCode: 200,
            body: response,

        });
    });

Target Unreachable, identifier resolved to null in JSF 2.2

I solved this problem.

My Java version was the 1.6 and I found that was using 1.7 with CDI however after that I changed the Java version to 1.7 and import the package javax.faces.bean.ManagedBean and everything worked.

Thanks @PM77-1


Can I export a variable to the environment from a bash script without sourcing it?

The answer is no, but for me I did the following

the script: myExport

#! \bin\bash
export $1

an alias in my .bashrc

alias myExport='source myExport' 

Still you source it, but maybe in this way it is more useable and it is interesting for someone else.

How to select all records from one table that do not exist in another table?

Watch out for pitfalls. If the field Name in Table1 contain Nulls you are in for surprises. Better is:

SELECT name
FROM table2
WHERE name NOT IN
    (SELECT ISNULL(name ,'')
     FROM table1)

How to do a deep comparison between 2 objects with lodash?

just using vanilla js

_x000D_
_x000D_
let a = {};_x000D_
let b = {};_x000D_
_x000D_
a.prop1 = 2;_x000D_
a.prop2 = { prop3: 2 };_x000D_
_x000D_
b.prop1 = 2;_x000D_
b.prop2 = { prop3: 3 };_x000D_
_x000D_
JSON.stringify(a) === JSON.stringify(b);_x000D_
// false_x000D_
b.prop2 = { prop3: 2};_x000D_
_x000D_
JSON.stringify(a) === JSON.stringify(b);_x000D_
// true
_x000D_
_x000D_
_x000D_

enter image description here

cannot download, $GOPATH not set

This one worked

Setting up Go development environment on Ubuntu, and how to fix $GOPATH / $GOROOT

Steps

mkdir ~/go

Set $GOPATH in .bashrc,

export GOPATH=~/go
export PATH=$PATH:$GOPATH/bin

Python 2.7: %d, %s, and float()

See String Formatting Operations:

%d is the format code for an integer. %f is the format code for a float.

%s prints the str() of an object (What you see when you print(object)).

%r prints the repr() of an object (What you see when you print(repr(object)).

For a float %s, %r and %f all display the same value, but that isn't the case for all objects. The other fields of a format specifier work differently as well:

>>> print('%10.2s' % 1.123) # print as string, truncate to 2 characters in a 10-place field.
        1.
>>> print('%10.2f' % 1.123) # print as float, round to 2 decimal places in a 10-place field.
      1.12

Is there a command line utility for rendering GitHub flavored Markdown?

Use marked. It supports GitHub Flavored Markdown, can be used as a Node.js module and from the command line.

An example would be:

$ marked -o hello.html
hello world
^D
$ cat hello.html
<p>hello world</p>

Select 50 items from list at random to write to file

One easy way to select random items is to shuffle then slice.

import random
a = [1,2,3,4,5,6,7,8,9]
random.shuffle(a)
print a[:4] # prints 4 random variables

How to implement OnFragmentInteractionListener

In addition to @user26409021 's answer, If you have added a ItemFragment, The message in the ItemFragment is;

Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener} interface.

And You should add in your activity;

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener, ItemFragment.OnListFragmentInteractionListener {

//the code is omitted

 public void onListFragmentInteraction(DummyContent.DummyItem uri){
    //you can leave it empty
}

Here the dummy item is what you have on the bottom of your ItemFragment

JQuery Parsing JSON array

Use the parseJSON method:

var json = '["City1","City2","City3"]';
var arr = $.parseJSON(json);

Then you have an array with the city names.

How to download Visual Studio 2017 Community Edition for offline installation?

  • Saved the "vs_professional.exe" in my user Download directory, didn't work in any other disk or path.
  • Installed the certificate, without the reboot.
  • Executed the customized (2 languages and some workloads) command from administrative Command Prompt window targetting an offline root folder on a secondary disk "E:\vs2017offline".

Never thought MS could distribute this way, I understand that people downloading Visual Studio should have advanced knowledge of computers and OS but this is like a jump in time to 30 years back.

Mailto links do nothing in Chrome but work in Firefox?

I found this answer on a Google forum that has worked me. In the footnotes it mentions 'googleapps.exe' - I don't have this and it has still worked. Simply follow the instructions below but close down all applications before making changes to the Registry. Also I saved the existing value just in case it didn't work.


Simply type "run" in your search bar, then type "regedit" then travel to:

HKEY_LOCAL_MACHINE\SOFTWARE\Classes\mailto\shell\open\command\ 

edit (double click) "(Default)" to:

"C:\Program Files (x86)\Google\Google Apps\googleapps.exe" --domain= --mailto.google.com="%1" 

That's it! Save and close it and it should work beautifully!

Using this method prevents you from having to download the GMail Notifier, which for those of us with GTalk don't need since it does it for us. I'm not sure why Google can't solve this issue easily.. i've heard Google Apps haven't been tested fully on Windows 7 but it's obvious the same tag works with it.

Note: The only thing with this solution is you need to have the googleapps.exe file on your machine. I believe I got it with my free GooglePack from their site which has now been discontinued. I tried searching the net for a way to download it but weirdly enough it seems it's reserved only for Businesses now and there is no download link available from the web because everyone who has it streamed it using the google updater.. Odd. Anyway good luck!

Better way to check variable for null or empty string?

This one checks arrays and strings:

function is_set($val) {
  if(is_array($val)) return !empty($val);

  return strlen(trim($val)) ? true : false;
}

How to create a numeric vector of zero length in R

Suppose you want to create a vector x whose length is zero. Now let v be any vector.

> v<-c(4,7,8)
> v
[1] 4 7 8
> x<-v[0]
> length(x)
[1] 0

How to implement a tree data-structure in Java?

You can use any XML API of Java as Document and Node..as XML is a tree structure with Strings

What is the App_Data folder used for in Visual Studio?

From the documentation about ASP.NET Web Project Folder Structure in MSDN:

You can keep your Web project's files in any folder structure that is convenient for your application. To make it easier to work with your application, ASP.NET reserves certain file and folder names that you can use for specific types of content.

App_Data contains application data files including .mdf database files, XML files, and other data store files. The App_Data folder is used by ASP.NET to store an application's local database, such as the database for maintaining membership and role information. For more information, see Introduction to Membership and Understanding Role Management.

Extract first item of each sublist

You said that you have an existing list. So I'll go with that.

>>> lst1 = [['a','b','c'], [1,2,3], ['x','y','z']]
>>> lst2 = [1, 2, 3]

Right now you are appending the generator object to your second list.

>>> lst2.append(item[0] for item in lst)
>>> lst2
[1, 2, 3, <generator object <genexpr> at 0xb74b3554>]

But you probably want it to be a list of first items

>>> lst2.append([item[0] for item in lst])
>>> lst2
[1, 2, 3, ['a', 1, 'x']]

Now we appended the list of first items to the existing list. If you'd like to add the items themeselves, not a list of them, to the existing ones, you'd use list.extend. In that case we don't have to worry about adding a generator, because extend will use that generator to add each item it gets from there, to extend the current list.

>>> lst2.extend(item[0] for item in lst)
>>> lst2
[1, 2, 3, 'a', 1, 'x']

or

>>> lst2 + [x[0] for x in lst]
[1, 2, 3, 'a', 1, 'x']
>>> lst2
[1, 2, 3]

https://docs.python.org/3.4/tutorial/datastructures.html#more-on-lists https://docs.python.org/3.4/tutorial/datastructures.html#list-comprehensions

Wavy shape with css

I think this is the right way to make a shape like you want. By using the SVG possibilities, and an container to keep the shape responsive.

_x000D_
_x000D_
svg {_x000D_
  display: inline-block;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
}_x000D_
.container {_x000D_
  display: inline-block;_x000D_
  position: relative;_x000D_
  width: 100%;_x000D_
  padding-bottom: 100%;_x000D_
  vertical-align: middle;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
  <svg viewBox="0 0 500 500" preserveAspectRatio="xMinYMin meet">_x000D_
    <path d="M0,100 C150,200 350,0 500,100 L500,00 L0,0 Z" style="stroke: none; fill:red;"></path>_x000D_
  </svg>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Jmeter - Run .jmx file through command line and get the summary report in a excel

You can use this command,

jmeter -n -t /path to the script.jmx -l /path to save results with file name file.jtl

But if you really want to run a load test in a remote machine, you should be able to make it run eventhough you close the window. So we can use nohup to ignore the HUP (hangup) signal. So you can use this command as below.

nohup sh jmeter.sh -n -t /path to the script.jmx -l /path to save results with file name file.jtl &

Where should I put <script> tags in HTML markup?

The best place to put <script> tag is before closing </body> tag, so the downloading and executing it doesn't block the browser to parse the html in document,

Also loading the js files externally has it's own advantages like it will be cached by browsers and can speed up page load times, it separates the HTML and JavaScript code and help to manage the code base better.

but modern browsers also support some other optimal ways like async and defer to load external javascript files.

Async and Defer

Normally HTML page execution starts line by line. When an external JavaScript element is encountered, HTML parsing is stopped until a JavaScript is download and ready for execution. This normal page execution can be changed using defer and async attribute.

Defer

When a defer attribute is used, JavaScript is downloaded parallelly with HTML parsing but will be execute only after full HTML parsing is done.

<script src="/local-js-path/myScript.js" defer></script>

Async

When async attribute is used, JavaScript is downloaded as soon as the script is encountered and after the download, it will be executed asynchronously (parallelly) along with HTML parsing.

<script src="/local-js-path/myScript.js" async></script>

When to use which attributes

  • If your script is independent of other scripts and is modular, use async.
  • If you are loading script1 and script2 with async, both will run
    parallelly along with HTML parsing, as soon as they are downloaded
    and available.
  • If your script depends on another script then use defer for both:
  • When script1 and script2 are loaded in that order with defer, then script1 is guaranteed to execute first,
  • Then script2 will execute after script1 is fully executed.
  • Must do this if script2 depends on script1.
  • If your script is small enough and is depended by another script of type async then use your script with no attributes and place it above all the async scripts.

reference:knowledgehills.com

Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies

I ended up in this situation several times with my .NET 4.6.1 web site. I created the problem each time when I added a reference to a separate .NET Core project. Upon building, Visual Studio correctly alerted me that such cross-framework references are invalid, and I quickly deleted the project reference. The project built fine after that, but the System.Runtime error appeared when accessing the web site and refused to go away.

The fix each time was lame but effective: I deleted the project directory and redownloaded it from source control. Even though there was no difference between before and after, I was able to build the project and access the page with no complaints.

How I add Headers to http.get or http.post in Typescript and angular 2?

Be sure to declare HttpHeaders without null values.

    this.http.get('url', {headers: new HttpHeaders({'a': a || '', 'b': b || ''}))

Otherwise, if you try to add a null value to HttpHeaders it will give you an error.

How can I use getSystemService in a non-activity class (LocationManager)?

For some non-activity classes, like Worker, you're already given a Context object in the public constructor.

Worker(Context context, WorkerParameters workerParams)

You can just use that, e.g., save it to a private Context variable in the class (say, mContext), and then, for example

mContext.getSystenService(Context.ACTIVITY_SERVICE)

Error Message: Type or namespace definition, or end-of-file expected

This line:

public  object Hours { get; set; }}

Your have a redundand } at the end

what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean?

Your secondNumber seems to be an ivar, so you have to use a local var to unwrap the optional. And careful. You don't test secondNumber for 0, which can lead into a division by zero. Technically you need another case to handle an impossible operation. For instance checkin if the number is 0 and do nothing in that case would at least not crash.

@IBAction func equals(sender: AnyObject) {

    guard let number = Screen.text?.toInt(), number > 0 else {
        return
    }

    secondNumber = number

    if operation == "+"{
        result = firstNumber + secondNumber
    }
    else if operation == "-" {
        result = firstNumber - secondNumber
    }
    else if operation == "x" {
        result = firstNumber * secondNumber
    }
    else {
        result = firstNumber / secondNumber
    }
    Screen.text = "\(result)"
}

How do I remove blank pages coming between two chapters in Appendix?

I tried Noah's suggestion which leads to the best solution up to now.

Just insert \let\cleardoublepage\clearpage before all the parts with the blank pages Especially when you use \documentclass[12pt,a4paper]{book}

frederic snyers's advice \documentclass[oneside]{book} is also very good and solves the problem, but if we just want to use the book.cls or article.cls, the one would make a big difference presenting your particles.

Hence, Big support to \let\cleardoublepage\clearpage for the people who will ask the same question in the future.

How do I fix a compilation error for unhandled exception on call to Thread.sleep()?

You can get rid of the first line. You don't need import java.lang.*;

Just change your 5th line to:

public static void main(String [] args) throws Exception

Can't choose class as main class in IntelliJ

Select the folder containing the package tree of these classes, right-click and choose "Mark Directory as -> Source Root"

Passing multiple parameters with $.ajax url

why not just pass an data an object with your key/value pairs then you don't have to worry about encoding

$.ajax({
    type: "Post",
    url: "getdata.php",
    data:{
       timestamp: timestamp,
       uid: id,
       uname: name
    },
    async: true,
    cache: false,
    success: function(data) {


    };
}?);?

javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer

If using Nginx and getting a similar problem, then this might help:

Scan your domain on this sslTesturl, and see if the connection is allowed for your device version.

If lower version devices(like < Android 4.4.2 etc) are not able to connect due to TLS support, then try adding this to your Nginx config file,

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

Is there a way to reduce the size of the git folder?

I'm not sure what you want. First of all, of course each time you commit/push the directory is going to get a little larger, since it has to store each of those additional commits.

However, probably you want git gc which will "cleanup unnecessary files and optimize the local repository" (manual page).

Another possibly relevant command is git clean which will delete untracked files from your tree (manual page).

What is the purpose of Looper and how to use it?

Android Looper is a wrapper to attach MessageQueue to Thread and it manages Queue processing. It looks very cryptic in Android documentation and many times we may face Looper related UI access issues. If we don't understand the basics it becomes very tough to handle.

Here is an article which explains Looper life cycle, how to use it and usage of Looper in Handler

enter image description here

Looper = Thread + MessageQueue

How do I check if string contains substring?

You can also check if the exact word is contained in a string. E.g.:

function containsWord(haystack, needle) {
    return (" " + haystack + " ").indexOf(" " + needle + " ") !== -1;
}

Usage:

containsWord("red green blue", "red"); // true
containsWord("red green blue", "green"); // true
containsWord("red green blue", "blue"); // true
containsWord("red green blue", "yellow"); // false

This is how jQuery does its hasClass method.

Simple JavaScript Checkbox Validation

var confirm=document.getElementById("confirm").value;
         if((confirm.checked==false)
         {
         alert("plz check the checkbox field");
         document.getElementbyId("confirm").focus();
         return false;
         }

Convert an integer to a float number

There is no float type. Looks like you want float64. You could also use float32 if you only need a single-precision floating point value.

package main

import "fmt"

func main() {
    i := 5
    f := float64(i)
    fmt.Printf("f is %f\n", f)
}

Python Threading String Arguments

I hope to provide more background knowledge here.

First, constructor signature of the of method threading::Thread:

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)

args is the argument tuple for the target invocation. Defaults to ().

Second, A quirk in Python about tuple:

Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses).

On the other hand, a string is a sequence of characters, like 'abc'[1] == 'b'. So if send a string to args, even in parentheses (still a sting), each character will be treated as a single parameter.

However, Python is so integrated and is not like JavaScript where extra arguments can be tolerated. Instead, it throws an TypeError to complain.

Toggle show/hide on click with jQuery

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js</script>        <script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").toggle();
  });
});
</script>
</head>
<body>
<p>Welcome !!!</p>
<button>Toggle between hide() and show()</button>
</body>
</html>

Watching variables contents in Eclipse IDE

This video does an excellent job of showing you how to set breakpoints and watch variables in the Eclipse Debugger. http://youtu.be/9gAjIQc4bPU

SQL: How To Select Earliest Row

SELECT company
   , workflow
   , MIN(date)
FROM workflowTable
GROUP BY company
       , workflow

Run a php app using tomcat?

Caucho Quercus can run PHP code on the jvm.

git is not installed or not in the PATH

Installing git and running npm install from git-bash worked for me. Make sure you are in the correct directory.

Using wire or reg with input or output in Verilog

The Verilog code compiler you use will dictate what you have to do. If you use illegal syntax, you will get a compile error.

An output must also be declared as a reg only if it is assigned using a "procedural assignment". For example:

output reg a;
always @* a = b;

There is no need to declare an output as a wire.

There is no need to declare an input as a wire or reg.

Collections.emptyList() returns a List<Object>?

the emptyList method has this signature:

public static final <T> List<T> emptyList()

That <T> before the word List means that it infers the value of the generic parameter T from the type of variable the result is assigned to. So in this case:

List<String> stringList = Collections.emptyList();

The return value is then referenced explicitly by a variable of type List<String>, so the compiler can figure it out. In this case:

setList(Collections.emptyList());

There's no explicit return variable for the compiler to use to figure out the generic type, so it defaults to Object.

How can I keep Bootstrap popovers alive while being hovered?

Here is a solution I devised that seems to work well while also allowing you to use the normal Bootstrap implementation for turning on all popovers.

Original fiddle: https://jsfiddle.net/eXpressive/hfear592/

Ported to this question:

<a href="#" id="example" class="btn btn-danger" rel="popover" >hover for popover</a>

$('#example').popover({
    html : true,
    trigger : 'hover',
    content : function() {
        return '<div class="box"></div>';
    }
}).on('hide.bs.popover', function () {
    if ($(".popover:hover").length) {
      return false;
    }                
}); 

$('body').on('mouseleave', '.popover', function(){
    $('.popover').popover('hide');
});

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression

I got the same error in this case:

var result = Db.SystemLog
.Where(log =>
    eventTypeValues.Contains(log.EventType)
    && (
        search.Contains(log.Id.ToString())
        || log.Message.Contains(search)
        || log.PayLoad.Contains(search)
        || log.Timestamp.ToString(CultureInfo.CurrentUICulture).Contains(search)
    )
)
.OrderByDescending(log => log.Id)
.Select(r => r);

After spending way too much time debugging, I figured out that error appeared in the logic expression.

The first line search.Contains(log.Id.ToString()) does work fine, but the last line that deals with a DateTime object made it fail miserably:

|| log.Timestamp.ToString(CultureInfo.CurrentUICulture).Contains(search)

Remove the problematic line and problem solved.

I do not fully understand why, but it seems as ToString() is a LINQ expression for strings, but not for Entities. LINQ for Entities deals with database queries like SQL, and SQL has no notion of ToString(). As such, we can not throw ToString() into a .Where() clause.

But how then does the first line work? Instead of ToString(), SQL have CAST and CONVERT, so my best guess so far is that linq for entities uses that in some simple cases. DateTime objects are not always found to be so simple...

JQuery datepicker language

You need the following line:

<script src="../jquery/development-bundle/ui/i18n/jquery.ui.datepicker-sv.js"></script>

Adjust the path depending on where you put the jquery-files.

Package signatures do not match the previously installed version

you need uninstall completely for LG devices by using cmd adb uninstall packageName

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries

From Django 2.0 on_delete is required:

user = models.OneToOneField(User, on_delete=models.CASCADE)

It will delete the child table data if the User is deleted. For more details check the Django documentation.

HTML5 - mp4 video does not play in IE9

Ended up using http://videojs.com/ to support all browsers.

But to get the video working in IE9 and Chrome I just added html5 doc type and used mp4:

<!DOCTYPE html>
<html>
<body>
  <video src="video.mp4" width="400" height="300" preload controls>
  </video>
</body>
</html>

javascript - match string against the array of regular expressions

So we make a function that takes in a literal string, and the array we want to look through. it returns a new array with the matches found. We create a new regexp object inside this function and then execute a String.search on each element element in the array. If found, it pushes the string into a new array and returns.

// literal_string: a regex search, like /thisword/ig
// target_arr: the array you want to search /thisword/ig for.

function arr_grep(literal_string, target_arr) {
  var match_bin = [];
  // o_regex: a new regex object.
  var o_regex = new RegExp(literal_string);
  for (var i = 0; i < target_arr.length; i++) {
    //loop through array. regex search each element.
    var test = String(target_arr[i]).search(o_regex);
    if (test > -1) {
    // if found push the element@index into our matchbin.
    match_bin.push(target_arr[i]);
    }
  }
  return match_bin;
}

// arr_grep(/.*this_word.*/ig, someArray)

Difference between id and name attributes in HTML

Below is an interesting use of the id attribute. It is used within the tag and used to identify the form for elements outside of the boundaries so that they will be included with the other fields within the form.

 <form action="action_page.php" id="form1">
 First name: <input type="text" name="fname"><br>
 <input type="submit" value="Submit">
 </form>

 <p>The "Last name" field below is outside the form element, but still part of the form.</p>
 Last name: <input type="text" name="lname" form="form1">

How to iterate (keys, values) in JavaScript?

The Object.entries() method has been specified in ES2017 (and is supported in all modern browsers):

for (const [ key, value ] of Object.entries(dictionary)) {
    // do something with `key` and `value`
}

Explanation:

  • Object.entries() takes an object like { a: 1, b: 2, c: 3 } and turns it into an array of key-value pairs: [ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ].

  • With for ... of we can loop over the entries of the so created array.

  • Since we are guaranteed that each of the so iterated array items is itself a two-entry array, we can use destructuring to directly assign variables key and value to its first and second item.

Resetting a form in Angular 2 after submit

I used in similar case the answer from Günter Zöchbauer, and it was perfect to me, moving the form creation to a function and calling it from ngOnInit().

For illustration, that's how I made it, including the fields initialization:

ngOnInit() {
    // initializing the form model here
    this.createForm();
}

createForm() {
    let EMAIL_REGEXP = /^[^@]+@([^@\.]+\.)+[^@\.]+$/i; // here just to add something more, useful too

    this.userForm = new FormGroup({
        name: new FormControl('', [Validators.required, Validators.minLength(3)]),
        city: new FormControl(''),
        email: new FormControl(null, Validators.pattern(EMAIL_REGEXP))
    });

    this.initializeFormValues();
}

initializeFormValues() {
    const people = {
        name: '',
        city: 'Rio de Janeiro',  // Only for demonstration
        email: ''
    };
    (<FormGroup>this.userForm).setValue(people, { onlySelf: true });
}

resetForm() {
    this.createForm();
    this.submitted = false;
}

I added a button to the form for a smart reset (with the fields initialization):

In the HTML file (or inline template):

<button type="button" [disabled]="userForm.pristine" (click)="resetForm()">Reset</button>

After loading the form at first time or after clicking the reset button we have the following status:

FORM pristine: true 
FORM valid: false (because I have required a field) 
FORM submitted: false
Name pristine: true
City pristine: true
Email pristine: true

And all the field initializations that a simple form.reset() doesn't make for us! :-)

How to increase application heap size in Eclipse?

  1. Go to Eclipse Folder
  2. Find Eclipse Icon in Eclipse Folder
  3. Right Click on it you will get option "Show Package Content"
  4. Contents folder will open on screen
  5. If you are on Mac then you'll find "MacOS"
  6. Open MacOS folder you'll find eclipse.ini file
  7. Open it in word or any file editor for edit

    ...

    -XX:MaxPermSize=256m
    
    -Xms40m
    
    -Xmx512m
    

    ...

  8. Replace -Xmx512m to -Xmx1024m

  9. Save the file and restart your Eclipse
  10. Have a Nice time :)

Java Web Service client basic authentication

for Axis2 client this may be helpful

...
serviceStub = new TestBeanServiceStub("<WEB SERVICE URL>"); // Set your value
HttpTransportProperties.Authenticator basicAuthenticator = new HttpTransportProperties.Authenticator();
List<String> authSchemes = new ArrayList<String>();
authSchemes.add(Authenticator.BASIC);
basicAuthenticator.setAuthSchemes(authSchemes); 
basicAuthenticator.setUsername("<UserName>"); // Set your value
basicAuthenticator.setPassword("<Password>"); // Set your value
basicAuthenticator.setPreemptiveAuthentication(true);
serviceStub._getServiceClient().getOptions().setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, basicAuthenticator);
serviceStub._getServiceClient().getOptions().setProperty(org.apache.axis2.transport.http.HTTPConstants.CHUNKED, "false");
...

load jquery after the page is fully loaded

I have asked this question more than 6 years ago, and any answers I got had some flaws. Later I myself worked out a solution that I have been using for years since then. Now that I came across my own question again and I saw that it has many views, I'd like to share it because I think it may help others.

This problem mainly occurs on Master-Detail type of pages (can be old .master and .aspx pages) or (layout and views in asp.net) or any similar situation maybe on other web development languages, however always there is a master-detail pattern involved.

For the solution, I just add an array at the beginning of my page:

<script>var after = [];</script>

any function that requires jQuery or any other script that would run after this section, instead of running it, I just push it to this array:

after.push(function(){
     // code that requires scripts that will load later,
     //might be for example a jQuery selector or ...
}); 

and then at the very end of the page, right before closing the body tag (of course scripts are loaded by now) I run all the functions inside the (here named) after array:

<script>for(var i=0;i<after.length;i++)after[i]();</script>
</body>

I find this way very easy, simple and flawless.

Remove an element from a Bash array

Here's a one-line solution with mapfile:

$ mapfile -d $'\0' -t arr < <(printf '%s\0' "${arr[@]}" | grep -Pzv "<regexp>")

Example:

$ arr=("Adam" "Bob" "Claire"$'\n'"Smith" "David" "Eve" "Fred")

$ echo "Size: ${#arr[*]} Contents: ${arr[*]}"

Size: 6 Contents: Adam Bob Claire
Smith David Eve Fred

$ mapfile -d $'\0' -t arr < <(printf '%s\0' "${arr[@]}" | grep -Pzv "^Claire\nSmith$")

$ echo "Size: ${#arr[*]} Contents: ${arr[*]}"

Size: 5 Contents: Adam Bob David Eve Fred

This method allows for great flexibility by modifying/exchanging the grep command and doesn't leave any empty strings in the array.

Twitter Bootstrap 3 Sticky Footer

I wanted a flexible sticky footer, which is why I came here. Top answers got me in the right direction.

The current (2 Oct 16) Bootstrap 3 css Sticky footer (Fixed size) looks like this:

html {
  position: relative;
  min-height: 100%;
}
body {
  /* Margin bottom by footer height */
  margin-bottom: 60px;
}
.footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  /* Set the fixed height of the footer here */
  height: 60px;
  background-color: #f5f5f5;
}

As long as the footer has a fixed size, the body margin-bottom creates a push to allow a pocket for the footer to sit in. In this case, both are set to 60px. But if the footer is not fixed and exceeds 60px height, it will cover your page content.

Make Flexible: Delete the css body margin and footer height. Then add JavaScript to get the footer height and set the body marginBottom. That is done with the setfooter() function. Next add event listeners for when the page first loads and on resizing that run the setfooter. Note: If you footer has an accordion or anything else that triggers a size change, without a resize of window, you must call the setfooter() function again.

Run the snippet and then fullscreen to demo it.

_x000D_
_x000D_
function setfooter(){_x000D_
 var ht = document.getElementById("footer").scrollHeight;_x000D_
 document.body.style.marginBottom = ht + "px";_x000D_
}_x000D_
_x000D_
window.addEventListener('resize', function(){_x000D_
  setfooter();_x000D_
 }, true);_x000D_
window.addEventListener('load', function(){_x000D_
 setfooter();_x000D_
}, true);
_x000D_
html {_x000D_
  position: relative;_x000D_
  min-height: 100%;_x000D_
}_x000D_
.footer {_x000D_
  position: absolute;_x000D_
  bottom: 0;_x000D_
  width: 100%;_x000D_
  _x000D_
  /* additional style for effect only */_x000D_
   text-align: center;_x000D_
    background-color: #333;_x000D_
    color: #fff;_x000D_
}_x000D_
  _x000D_
_x000D_
_x000D_
body{_x000D_
/* additional style for effect only not needed in bootstrap*/_x000D_
  padding:0;_x000D_
  margin: 0;_x000D_
  }
_x000D_
<div>_x000D_
  Page content_x000D_
  <br>  <br>_x000D_
  line 3_x000D_
  <br>  <br>_x000D_
  line 5_x000D_
  <br>  <br>_x000D_
  line 7_x000D_
  _x000D_
 </div>_x000D_
_x000D_
_x000D_
<footer id="footer" class="footer">_x000D_
      <div class="container">_x000D_
        <p class="text-muted">Footer with a long text, so that resizing, to a smaller screen size, will cause the footer to grow taller. But the footer will not overflow onto the main page.</p>_x000D_
      </div>_x000D_
    </footer>
_x000D_
_x000D_
_x000D_

Why would anybody use C over C++?

In addition to several other points mentioned already:

Less surprise

that is, it is much easier to see what a piece of code will do do exactly . In C++ you need to approach guru level to be able to know exactly what code the compiler generates (try a combination of templates, multiple inheritance, auto generated constructors, virtual functions and mix in a bit of namespace magic and argument dependent lookup).

In many cases this magic is nice, but for example in real-time systems it can really screw up your day.

Superscript in CSS only?

This is another clean solution:

sub, sup {vertical-align: baseline; position: relative; font-size: 70%;} /* 70% size of its parent element font-size which is good. */
sub {bottom: -0.6em;} /* use em becasue they adapt to parent font-size */
sup {top: -0.6em;} /* use em becasue they adapt to parent font-size */

In this way you can still use sup/sub tags but you fixed their idious behavior to always screw up paragraph line height.

So now you can do:

  <p>This is a line of text.</p>
  <p>This is a line of text, <sub>with sub text.</sub></p>
  <p>This is a line of text, <sup>with sup text.</sup></p>
  <p>This is a line of text.</p>

And your paragraph line height should not get screwed up.

Tested on IE7, IE8, FF3.6, SAFARI4, CHROME5, OPERA9

I tested using a p {line-height: 1.3;} (that is a good line height unless you want your lines to stick too close) and it still works, cause "-0.6em" is such a small amount that also with that line height the sub/sub text will fit and don't go over each other.

Forgot a detail that might be relevant I always use DOCTYPE in the 1st line of my page (specifically I use the HTML 4.01 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">). So I don't know if this solution works well when browser is in quirkmode (or not standard mode) due to lack of DOCTYPE or to a DOCTYPE that does not triggers Standard/Almost Standard mode.

Forbidden: You don't have permission to access / on this server, WAMP Error

1.

first of all Port 80(or what ever you are using) and 443 must be allow for both TCP and UDP packets. To do this, create 2 inbound rules for TPC and UDP on Windows Firewall for port 80 and 443. (or you can disable your whole firewall for testing but permanent solution if allow inbound rule)

2.

If you are using WAMPServer 3 See bottom of answer

For WAMPServer versions <= 2.5

You need to change the security setting on Apache to allow access from anywhere else, so edit your httpd.conf file.

Change this section from :

#   onlineoffline tag - don't remove
     Order Deny,Allow
     Deny from all
     Allow from 127.0.0.1
     Allow from ::1
     Allow from localhost

To :

#   onlineoffline tag - don't remove
    Order Allow,Deny
      Allow from all

if "Allow from all" line not work for your then use "Require all granted" then it will work for you.

WAMPServer 3 has a different method

In version 3 and > of WAMPServer there is a Virtual Hosts pre defined for localhost so dont amend the httpd.conf file at all, leave it as you found it.

Using the menus, edit the httpd-vhosts.conf file.

enter image description here

It should look like this :

<VirtualHost *:80>
    ServerName localhost
    DocumentRoot D:/wamp/www
    <Directory  "D:/wamp/www/">
        Options +Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require local
    </Directory>
</VirtualHost>

Amend it to

<VirtualHost *:80>
    ServerName localhost
    DocumentRoot D:/wamp/www
    <Directory  "D:/wamp/www/">
        Options +Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

Note:if you are running wamp for other than port 80 then VirtualHost will be like VirtualHost *:86.(86 or port whatever you are using) instead of VirtualHost *:80

3. Dont forget to restart All Services of Wamp or Apache after making this change

memcpy() vs memmove()

compiler could optimize memcpy, for example:

int x;
memcpy(&x, some_pointer, sizeof(int));

This memcpy may be optimized as: x = *(int*)some_pointer;

MySQL: How to reset or change the MySQL root password?

If you know the 'root' users password, log in to mysql with that credentials. Then execute the following query to update the password.

ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_passowrd';

jQuery not working with IE 11

The problem was caused because the page was an intranet site, & IE had compatibility mode set to default for this. IE11 does support addEventListener()

Why does find -exec mv {} ./target/ + not work?

no, the difference between + and \; should be reversed. + appends the files to the end of the exec command then runs the exec command and \; runs the command for each file.

The problem is find . -type f -iname '*.cpp' -exec mv {} ./test/ \+ should be find . -type f -iname '*.cpp' -exec mv {} ./test/ + no need to escape it or terminate the +

xargs I haven't used in a long time but I think works like +.

Get file size before uploading

I had the same problem and seems like we haven't had an accurate solution. Hope this can help other people.

After take time exploring around, I finally found the answer. This is my code to get file attach with jQuery:

var attach_id = "id_of_attachment_file";
var size = $('#'+attach_id)[0].files[0].size;
alert(size);

This is just the example code for getting the file size. If you want do other stuffs, feel free to change the code to satisfy your needs.

When do I need to do "git pull", before or after "git add, git commit"?

pull = fetch + merge.

You need to commit what you have done before merging.

So pull after commit.

Directory-tree listing in Python

import os

for filename in os.listdir("C:\\temp"):
    print  filename

Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`

I've had exactly the same problem as you for a while now, and after looking at some of the suggestions above, I finally solved the problem.

It turns out (at least for me anyway), I needed to supply a key (a prop called 'key') to the component I am returning from my renderSeparator method. Adding a key to my renderRow or renderSectionHeader didn't do anything, but adding it to renderSeparator made the warning go away.

Hope that helps.

open read and close a file in 1 line of code

I frequently do something like this when I need to get a few lines surrounding something I've grepped in a log file:

$ grep -n "xlrd" requirements.txt | awk -F ":" '{print $1}'
54

$ python -c "with open('requirements.txt') as file: print ''.join(file.readlines()[52:55])"
wsgiref==0.1.2
xlrd==0.9.2
xlwt==0.7.5

IFRAMEs and the Safari on the iPad, how can the user scroll the content?

The Problem

I help maintain a big, complicated, messy old site in which everything (literally) is nested in multiple levels of iframes-- many of which are dynamically created and/or have a dynamic src. That creates the following challenges:

  1. Any changes to the HTML structure risk breaking scripts and stylesheets that haven't been touched in years.
  2. Finding and fixing all of the iframes and src documents manually would take way too much time and effort.

Of the solutions posted so far, this is the only one I've seen that overcomes challenge 1. Unfortunately, it doesn't seem to work on some iframes, and when it does, the scrolling is very glitchy (which seems to cause other bugs on the page, such as unresponsive links and form controls).

The Solution

If the above sounds anything like your situation, you may want to give the following script a try. It forgoes native scrolling and instead makes all iframes draggable within the bounds of their viewport. You only need to add it to the document that contains the top level iframes; it will apply the fix as needed to them and their descendants.

Here's a working fiddle*, and here's the code:

(function() {
  var mouse = false //Set mouse=true to enable mouse support
    , iOS = /iPad|iPhone|iPod/.test(navigator.platform);
  if(mouse || iOS) {
    (function() {
      var currentFrame
        , startEvent, moveEvent, endEvent
        , screenY, translateY, minY, maxY
        , matrixPrefix, matrixSuffix
        , matrixRegex = /(.*([\.\d-]+, ?){5,13})([\.\d-]+)(.*)/
        , min = Math.min, max = Math.max
        , topWin = window;
      if(!iOS) {
        startEvent = 'mousedown';
        moveEvent = 'mousemove';
        endEvent = 'mouseup';
      }
      else {
        startEvent = 'touchstart';
        moveEvent = 'touchmove';
        endEvent = 'touchend';
      }
      setInterval(scrollFix, 500);
      function scrollFix() {fixSubframes(topWin.frames);}
      function fixSubframes(wins) {for(var i = wins.length; i; addListeners(wins[--i]));}
      function addListeners(win) {
        try {
          var doc = win.document;
          if(!doc.draggableframe) {
            win.addEventListener('unload', resetFrame);
            doc.draggableframe = true;
            doc.addEventListener(startEvent, touchStart);
            doc.addEventListener(moveEvent, touchMove);
            doc.addEventListener(endEvent, touchEnd);
          }
          fixSubframes(win.frames);
        }
        catch(e) {}
      }
      function resetFrame(e) {
        var doc = e.target
          , win = doc.defaultView
          , iframe = win.frameElement
          , style = getComputedStyle(iframe).transform;
        if(iframe===currentFrame) currentFrame = null;
        win.removeEventListener('unload', resetFrame);
        doc.removeEventListener(startEvent, touchStart);
        doc.removeEventListener(moveEvent, touchMove);
        doc.removeEventListener(endEvent, touchEnd);
        if(style !== 'none') {
          style = style.replace(matrixRegex, '$1|$3|$4').split('|');
          iframe.style.transform = style[0] + 0 + style[2];
        }
        else iframe.style.transform = null;
        iframe.style.WebkitClipPath = null;
        iframe.style.clipPath = null;
        delete doc.draggableiframe;
      }
      function touchStart(e) {
        var iframe, style, offset, coords
          , touch = e.touches ? e.touches[0] : e
          , elem = touch.target
          , tag = elem.tagName;
        currentFrame = null;
        if(tag==='TEXTAREA' || tag==='SELECT' || tag==='HTML') return;
        for(;elem.parentElement; elem = elem.parentElement) {
          if(elem.scrollHeight > elem.clientHeight) {
            style = getComputedStyle(elem).overflowY;
            if(style==='auto' || style==='scroll') return;
          }
        }
        elem = elem.ownerDocument.body;
        iframe = elem.ownerDocument.defaultView.frameElement;
        coords = getComputedViewportY(elem.clientHeight < iframe.clientHeight ? elem : iframe);
        if(coords.elemTop >= coords.top && coords.elemBottom <= coords.bottom) return;
        style = getComputedStyle(iframe).transform;
        if(style !== 'none') {
          style = style.replace(matrixRegex, '$1|$3|$4').split('|');
          matrixPrefix = style[0];
          matrixSuffix = style[2];
          offset = parseFloat(style[1]);
        }
        else {
          matrixPrefix = 'matrix(1, 0, 0, 1, 0, ';
          matrixSuffix = ')';
          offset = 0;
        }
        translateY = offset;
        minY = min(0, offset - (coords.elemBottom - coords.bottom));
        maxY = max(0, offset + (coords.top - coords.elemTop));
        screenY = touch.screenY;
        currentFrame = iframe;
      }
      function touchMove(e) {
        var touch, style;
        if(currentFrame) {
          touch = e.touches ? e.touches[0] : e;
          style = min(maxY, max(minY, translateY + (touch.screenY - screenY)));
          if(style===translateY) return;
          e.preventDefault();
          currentFrame.contentWindow.getSelection().removeAllRanges();
          translateY = style;
          currentFrame.style.transform = matrixPrefix + style + matrixSuffix;
          style = 'inset(' + (-style) + 'px 0px ' + style + 'px 0px)';
          currentFrame.style.WebkitClipPath = style;
          currentFrame.style.clipPath = style;
          screenY = touch.screenY;
        }
      }
      function touchEnd() {currentFrame = null;}
      function getComputedViewportY(elem) {
        var style, offset
          , doc = elem.ownerDocument
          , bod = doc.body
          , elemTop = elem.getBoundingClientRect().top + elem.clientTop
          , elemBottom = elem.clientHeight
          , viewportTop = elemTop
          , viewportBottom = elemBottom + elemTop
          , position = getComputedStyle(elem).position;
        try {
          while(true) {
            if(elem === bod || position === 'fixed') {
              if(doc.defaultView.frameElement) {
                elem = doc.defaultView.frameElement;
                position = getComputedStyle(elem).position;
                offset = elem.getBoundingClientRect().top + elem.clientTop;
                viewportTop += offset;
                viewportBottom = min(viewportBottom + offset, elem.clientHeight + offset);
                elemTop += offset;
                doc = elem.ownerDocument;
                bod = doc.body;
                continue;
              }
              else break;
            }
            else {
              if(position === 'absolute') {
                elem = elem.offsetParent;
                style = getComputedStyle(elem);
                position = style.position;
                if(position === 'static') continue;
              }
              else {
                elem = elem.parentElement;
                style = getComputedStyle(elem);
                position = style.position;
              }
              if(style.overflowY !== 'visible') {
                offset = elem.getBoundingClientRect().top + elem.clientTop;
                viewportTop = max(viewportTop, offset);
                viewportBottom = min(viewportBottom, elem.clientHeight + offset);
              }
            }
          }
        }
        catch(e) {}
        return {
          top: max(viewportTop, 0)
          ,bottom: min(viewportBottom, doc.defaultView.innerHeight)
          ,elemTop: elemTop
          ,elemBottom: elemBottom + elemTop
        };
      }
    })();
  }
})();

* The jsfiddle has mouse support enabled for testing purposes. On a production site, you'd want to set mouse=false.

NoClassDefFoundError in Java: com/google/common/base/Function

When I caught the exception java.lang.NoClassDefFoundError: com/google/common/base/Function it was caused by errors in Project Libraries.

Please check it in your project settings. For Intellij IDEA go to File - Project Structure and select Modules tab. All I needed to do to resolve this exception was re-adding the selenium library

How to center div vertically inside of absolutely positioned parent div

Use flex blox in your absoutely positioned div to center its content.

See example https://plnkr.co/edit/wJIX2NpbNhO34X68ZyoY?p=preview

.some-absolute-div {    
  display: -webkit-box;
  display: -webkit-flex;
  display: -moz-box;
  display: -moz-flex;
  display: -ms-flexbox;
  display: flex;

  -webkit-box-pack: center;
  -ms-flex-pack: center;
  -webkit-justify-content: center;
  -moz-justify-content: center;
  justify-content: center;

  -webkit-box-align: center;
  -ms-flex-align: center;
  -webkit-align-items: center;
  -moz-align-items: center;
  align-items: center;
}

Convert a String to a byte array and then back to the original String

Use [String.getBytes()][1] to convert to bytes and use [String(byte[] data)][2] constructor to convert back to string.

Mutex lock threads

What you need to do is to call pthread_mutex_lock to secure a mutex, like this:

pthread_mutex_lock(&mutex);

Once you do this, any other calls to pthread_mutex_lock(mutex) will not return until you call pthread_mutex_unlock in this thread. So if you try to call pthread_create, you will be able to create a new thread, and that thread will be able to (incorrectly) use the shared resource. You should call pthread_mutex_lock from within your fooAPI function, and that will cause the function to wait until the shared resource is available.

So you would have something like this:

#include <pthread.h>
#include <stdio.h>

int sharedResource = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void* fooAPI(void* param)
{
    pthread_mutex_lock(&mutex);
    printf("Changing the shared resource now.\n");
    sharedResource = 42;
    pthread_mutex_unlock(&mutex);
    return 0;
}

int main()
{
    pthread_t thread;

    // Really not locking for any reason other than to make the point.
    pthread_mutex_lock(&mutex);
    pthread_create(&thread, NULL, fooAPI, NULL);
    sleep(1);
    pthread_mutex_unlock(&mutex);

    // Now we need to lock to use the shared resource.
    pthread_mutex_lock(&mutex);
    printf("%d\n", sharedResource);
    pthread_mutex_unlock(&mutex);
}

Edit: Using resources across processes follows this same basic approach, but you need to map the memory into your other process. Here's an example using shmem:

#include <stdio.h>
#include <unistd.h>
#include <sys/file.h>
#include <sys/mman.h>
#include <sys/wait.h>

struct shared {
    pthread_mutex_t mutex;
    int sharedResource;
};

int main()
{
    int fd = shm_open("/foo", O_CREAT | O_TRUNC | O_RDWR, 0600);
    ftruncate(fd, sizeof(struct shared));

    struct shared *p = (struct shared*)mmap(0, sizeof(struct shared),
        PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

    p->sharedResource = 0;

    // Make sure it can be shared across processes
    pthread_mutexattr_t shared;
    pthread_mutexattr_init(&shared);
    pthread_mutexattr_setpshared(&shared, PTHREAD_PROCESS_SHARED);

    pthread_mutex_init(&(p->mutex), &shared);

    int i;
    for (i = 0; i < 100; i++) {
        pthread_mutex_lock(&(p->mutex));
        printf("%d\n", p->sharedResource);
        pthread_mutex_unlock(&(p->mutex));
        sleep(1);
    }

    munmap(p, sizeof(struct shared*));
    shm_unlink("/foo");
}

Writing the program to make changes to p->sharedResource is left as an exercise for the reader. :-)

Forgot to note, by the way, that the mutex has to have the PTHREAD_PROCESS_SHARED attribute set, so that pthreads will work across processes.

Increasing Heap Size on Linux Machines

Changing Tomcat config wont effect all JVM instances to get theses settings. This is not how it works, the setting will be used only to launch JVMs used by Tomcat, not started in the shell.

Look here for permanently changing the heap size.

How to append elements at the end of ArrayList in Java?

Here is the syntax, along with some other methods you might find useful:

    //add to the end of the list
    stringList.add(random);

    //add to the beginning of the list
    stringList.add(0,  random);

    //replace the element at index 4 with random
    stringList.set(4, random);

    //remove the element at index 5
    stringList.remove(5);

    //remove all elements from the list
    stringList.clear();

Slide up/down effect with ng-show and ng-animate

This can actually be done in CSS and very minimal JS just by adding a CSS class (don't set styles directly in JS!) with e.g. a ng-clickevent. The principle is that one can't animate height: 0; to height: auto; but this can be tricked by animating the max-height property. The container will expand to it's "auto-height" value when .foo-open is set - no need for fixed height or positioning.

.foo {
    max-height: 0;
}

.foo--open {
    max-height: 1000px; /* some arbitrary big value */
    transition: ...
}

see this fiddle by the excellent Lea Verou

As a concern raised in the comments, note that while this animation works perfectly with linear easing, any exponential easing will produce a behaviour different from what could be expected - due to the fact that the animated property is max-height and not height itself; specifically, only the height fraction of the easing curve of max-height will be displayed.

JUnit Testing private variables?

Despite the danger of stating the obvious: With a unit test you want to test the correct behaviour of the object - and this is defined in terms of its public interface. You are not interested in how the object accomplishes this task - this is an implementation detail and not visible to the outside. This is one of the things why OO was invented: That implementation details are hidden. So there is no point in testing private members. You said you need 100% coverage. If there is a piece of code that cannot be tested by using the public interface of the object, then this piece of code is actually never called and hence not testable. Remove it.

How to change DataTable columns order

We Can use this method for changing the column index but should be applied to all the columns if there are more than two number of columns otherwise it will show all the Improper values from data table....................

curl: (6) Could not resolve host: google.com; Name or service not known

Try nslookup google.com to determine if there's a DNS issue. 192.168.1.254 is your local network address and it looks like your system is using it as a DNS server. Is this your gateway/modem router as well? What happens when you try ping google.com. Can you browse to it on a Internet web browser?

What does 'var that = this;' mean in JavaScript?

From Crockford

By convention, we make a private that variable. This is used to make the object available to the private methods. This is a workaround for an error in the ECMAScript Language Specification which causes this to be set incorrectly for inner functions.

JS Fiddle

function usesThis(name) {
    this.myName = name;

    function returnMe() {
        return this;        //scope is lost because of the inner function
    }

    return {
        returnMe : returnMe
    }
}

function usesThat(name) {
    var that = this;
    this.myName = name;

    function returnMe() {
        return that;            //scope is baked in with 'that' to the "class"
    }

    return {
        returnMe : returnMe
    }
}

var usesthat = new usesThat('Dave');
var usesthis = new usesThis('John');
alert("UsesThat thinks it's called " + usesthat.returnMe().myName + '\r\n' +
      "UsesThis thinks it's called " + usesthis.returnMe().myName);

This alerts...

UsesThat thinks it's called Dave

UsesThis thinks it's called undefined

Dynamically Dimensioning A VBA Array?

You can use a dynamic array when you don't know the number of values it will contain until run-time:

Dim Zombies() As Integer
ReDim Zombies(NumberOfZombies)

Or you could do everything with one statement if you're creating an array that's local to a procedure:

ReDim Zombies(NumberOfZombies) As Integer

Fixed-size arrays require the number of elements contained to be known at compile-time. This is why you can't use a variable to set the size of the array—by definition, the values of a variable are variable and only known at run-time.

You could use a constant if you knew the value of the variable was not going to change:

Const NumberOfZombies = 2000

but there's no way to cast between constants and variables. They have distinctly different meanings.

Website screenshots

cutycapt saves webpages to most image formats(jpg,png..) download it from your synaptic, it works much better than wkhtmltopdf

How to configure Chrome's Java plugin so it uses an existing JDK in the machine

I looked around for a solution to this for a while. It appears that the JDK doesn't have the Mozilla plugins (which is what Chrome uses) in it's installation. It is only in the JRE installation. There are a couple of DLLs that make up the plugin and they all start with np*