Programs & Examples On #Lifted operators

JComboBox Selection Change Listener?

You may try these

 int selectedIndex = myComboBox.getSelectedIndex();

-or-

Object selectedObject = myComboBox.getSelectedItem();

-or-

String selectedValue = myComboBox.getSelectedValue().toString();

Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents?

While integrating material dialog is possible, I found that the complexity for such a trivial feature is pretty high. The code gets more complex if you are trying to achieve a non-trivial features.

For that reason, I ended up using PrimeNG Dialog, which I found pretty straightforward to use:

m-dialog.component.html:

<p-dialog header="Title">
  Content
</p-dialog>

m-dialog.component.ts:

@Component({
  selector: 'm-dialog',
  templateUrl: 'm-dialog.component.html',
  styleUrls: ['./m-dialog.component.css']
})
export class MDialogComponent {
  // dialog logic here
}

m-dialog.module.ts:

import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";
import { DialogModule } from "primeng/primeng";
import { FormsModule } from "@angular/forms";

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    DialogModule
  ], 
  exports: [
    MDialogComponent,
  ], 
  declarations: [
    MDialogComponent
  ]
})
export class MDialogModule {}

Simply add your dialog into your component's html:

<m-dialog [isVisible]="true"> </m-dialog>

PrimeNG PrimeFaces documentation is easy to follow and very precise.

How do I make bootstrap table rows clickable?

That code transforms any bootstrap table row that has data-href attribute set into a clickable element

Note: data-href attribute is a valid tr attribute (HTML5), href attributes on tr element are not.

$(function(){
    $('.table tr[data-href]').each(function(){
        $(this).css('cursor','pointer').hover(
            function(){ 
                $(this).addClass('active'); 
            },  
            function(){ 
                $(this).removeClass('active'); 
            }).click( function(){ 
                document.location = $(this).attr('data-href'); 
            }
        );
    });
});

LAST_INSERT_ID() MySQL

Instead of this LAST_INSERT_ID() try to use this one

mysqli_insert_id(connection)

Step out of current function with GDB

You can use the finish command.

finish: Continue running until just after function in the selected stack frame returns. Print the returned value (if any). This command can be abbreviated as fin.

(See 5.2 Continuing and Stepping.)

PHP isset() with multiple parameters

The parameters of isset() should be separated by a comma sign (,) and not a dot sign (.). Your current code concatenates the variables into a single parameter, instead of passing them as separate parameters.

So the original code evaluates the variables as a unified string value:

isset($_POST['search_term'] . $_POST['postcode']) // Incorrect

While the correct form evaluates them separately as variables:

isset($_POST['search_term'], $_POST['postcode']) // Correct

What is meant by the term "hook" in programming?

Hook denotes a place in the code where you dispatch an event of certain type, and if this event was registered before with a proper function to call back, then it would be handled by this registered function, otherwise nothing happens.

Hide vertical scrollbar in <select> element

For future reference if somebody else runs into this problem. I found a solution that should work in all modern browsers:

select{
    scrollbar-width: none; /*For Firefox*/;
    -ms-overflow-style: none;  /*For Internet Explorer 10+*/;
}

select:-webkit-scrollbar { /*For WebKit Browsers*/
    width: 0;
    height: 0;
}

Basically this way the scrollbar is set to a width of 0 and is hence not displayed.

Excel- compare two cell from different sheet, if true copy value from other cell

In your destination field you want to use VLOOKUP like so:

=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)

VLOOKUP Arguments:

  1. The set fields you want to lookup.
  2. The table range you want to lookup up your value against. The first column of your defined table should be the column you want compared against your lookup field. The table range should also contain the value you want to display (Column F).
  3. This defines what field you want to display upon a match.
  4. FALSE tells VLOOKUP to do an exact match.

How to create a Restful web service with input parameters?

You can try this... put parameters as :
http://localhost:8080/WebApplication11/webresources/generic/getText?arg1=hello in your browser...

package newpackage;

import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;


import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.QueryParam;

@Path("generic")
public class GenericResource {

    @Context
    private UriInfo context;

    /**
     * Creates a new instance of GenericResource
     */
    public GenericResource() {
    }

    /**
     * Retrieves representation of an instance of newpackage.GenericResource

     * @return an instance of java.lang.String
     */
    @GET
    @Produces("text/plain")
    @Consumes("text/plain")
    @Path("getText/")
    public String getText(@QueryParam("arg1")
            @DefaultValue("") String arg1) {

       return  arg1 ;  }

    @PUT
    @Consumes("text/plain")
    public void putText(String content) {





    }
}

PHP Excel Header

The problem is you typed the wrong file extension for excel file. you used .xsl instead of xls.

I know i came in late but it can help future readers of this post.

Batch file to split .csv file

If splitting very large files, the solution I found is an adaptation from this, with PowerShell "embedded" in a batch file. This works fast, as opposed to many other things I tried (I wouldn't know about other options posted here).

The way to use mysplit.bat below is

mysplit.bat <mysize> 'myfile'

Note: The script was intended to use the first argument as the split size. It is currently hardcoded at 100Mb. It should not be difficult to fix this.

Note 2: The filname should be enclosed in single quotes. Other alternatives for quoting apparently do not work.

Note 3: It splits the file at given number of bytes, not at given number of lines. For me this was good enough. Some lines of code could be probably added to complete each chunk read, up to the next CR/LF. This will split in full lines (not with a constant number of them), with no sacrifice in processing time.

Script mysplit.bat:

@REM Using https://stackoverflow.com/questions/19335004/how-to-run-a-powershell-script-from-a-batch-file
@REM and https://stackoverflow.com/questions/1001776/how-can-i-split-a-text-file-using-powershell
@PowerShell  ^
    $upperBound = 100MB;  ^
    $rootName = %2;  ^
    $from = $rootName;  ^
    $fromFile = [io.file]::OpenRead($from);  ^
    $buff = new-object byte[] $upperBound;  ^
    $count = $idx = 0;  ^
    try {  ^
        do {  ^
            'Reading ' + $upperBound;  ^
            $count = $fromFile.Read($buff, 0, $buff.Length);  ^
            if ($count -gt 0) {  ^
                $to = '{0}.{1}' -f ($rootName, $idx);  ^
                $toFile = [io.file]::OpenWrite($to);  ^
                try {  ^
                    'Writing ' + $count + ' to ' + $to;  ^
                    $tofile.Write($buff, 0, $count);  ^
                } finally {  ^
                    $tofile.Close();  ^
                }  ^
            }  ^
            $idx ++;  ^
        } while ($count -gt 0);  ^
    }  ^
    finally {  ^
        $fromFile.Close();  ^
    }  ^
%End PowerShell%

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

If you are using Django admin, here is the simplest solution.

class ReadonlyFieldsMixin(object):
    def get_readonly_fields(self, request, obj=None):
        if obj:
            return super(ReadonlyFieldsMixin, self).get_readonly_fields(request, obj)
        else:
            return tuple()

class MyAdmin(ReadonlyFieldsMixin, ModelAdmin):
    readonly_fields = ('sku',)

Alternative to deprecated getCellType

You can do this:

private String cellToString(HSSFCell cell) {
    CellType type;
    Object result;
    type = cell.getCellType();

    switch (type) {
        case NUMERIC :  //numeric value in excel
            result = cell.getNumericCellValue();
            break;
        case STRING : //String Value in Excel
            result = cell.getStringCellValue();
            break;
        default :
            throw new RuntimeException("There is no support for this type of value in Apche POI");
    }
    return result.toString();
}

Docker-Compose can't connect to Docker Daemon

I found this and it seemed to fix my issue.

GitHub Fix Docker Daemon Crash

I changed the content of my docker-compose-deps.yml file as seen in the link. Then I ran docker-compose -f docker-compose-deps.yml up -d. Then I changed it back and it worked for some reason. I didn't have to continue the steps in the link I provided, but the first two steps fixed the issue for me.

Wait for page load in Selenium

You can explicitly wait for an element to show up on the webpage before you can take any action (like element.click())

driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
  .until(new ExpectedCondition<WebElement>(){
        @Override
        public WebElement apply(WebDriver d) {
        return d.findElement(By.id("myDynamicElement"));
}});

This is what I used for a similar scenario and it works fine.

SELECT data from another schema in oracle

Does the user that you are using to connect to the database (user A in this example) have SELECT access on the objects in the PCT schema? Assuming that A does not have this access, you would get the "table or view does not exist" error.

Most likely, you need your DBA to grant user A access to whatever tables in the PCT schema that you need. Something like

GRANT SELECT ON pct.pi_int
   TO a;

Once that is done, you should be able to refer to the objects in the PCT schema using the syntax pct.pi_int as you demonstrated initially in your question. The bracket syntax approach will not work.

Good font for code presentations?

I'm personally very fond of Inconsolata

Why isn't Python very good for functional programming?

I would never call Python “functional” but whenever I program in Python the code invariably ends up being almost purely functional.

Admittedly, that's mainly due to the extremely nice list comprehension. So I wouldn't necessarily suggest Python as a functional programming language but I would suggest functional programming for anyone using Python.

How to connect to Oracle 11g database remotely

You will need to run the lsnrctl utility on server A to start the listener. You would then connect from computer B using the following syntax:

sqlplus username/password@hostA:1521 /XE

The port information is optional if the default of 1521 is used.

Listener configuration documentation here. Remote connection documentation here.

Set focus and cursor to end of text input field / string w. Jquery

You can do this using Input.setSelectionRange, part of the Range API for interacting with text selections and the text cursor:

var searchInput = $('#Search');

// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;

searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);

Demo: Fiddle

Twitter Bootstrap Datepicker within modal window

For BootsTrap Calender use this

/The Calender Index CSS/

.bootstrap-datetimepicker-widget {
   z-index:99999 !important;
}

java.net.SocketTimeoutException: Read timed out under Tomcat

Server is trying to read data from the request, but its taking longer than the timeout value for the data to arrive from the client. Timeout here would typically be tomcat connector -> connectionTimeout attribute.

Correct.

Client has a read timeout set, and server is taking longer than that to respond.

No. That would cause a timeout at the client.

One of the threads i went through, said this can happen with high concurrency and if the keepalive is enabled.

That is obviously guesswork, and completely incorrect. It happens if and only if no data arrives within the timeout. Period. Load and keepalive and concurrency have nothing to do with it whatsoever.

It just means the client isn't sending. You don't need to worry about it. Browser clients come and go in all sorts of strange ways.

Display milliseconds in Excel

I've discovered in Excel 2007, if the results are a Table from an embedded query, the ss.000 does not work. I can paste the query results (from SQL Server Management Studio), and format the time just fine. But when I embed the query as a Data Connection in Excel, the format always gives .000 as the milliseconds.

Standard Android menu icons, for example refresh

You can get the icons from the android sdk they are in this folder

$android-sdk\platforms\android-xx\data\res

reactjs giving error Uncaught TypeError: Super expression must either be null or a function, not undefined

Webpack 4 Chunks and Hashes with Uglification by TerserPlugin

This can occur when Webpack uses chunks and hashes with minification and unglification via TerserPlugin (currently on version 1.2.3). In my case the error was narrowed down to the uglification by the Terser Plugin of my vendors.[contenthash].js bundle which holds my node_modules. Everything worked when not using hashes.

Solution was to exclude the bundle in the uglification options:

optimization: {
  minimizer: [
    new TerserPlugin({
      chunkFilter: (chunk) => {
        // Exclude uglification for the `vendors` chunk
        if (chunk.name === 'vendors') {
          return false;
        }
        return true;
      },
    }),
  ],
}

More info

Git status ignore line endings / identical files / windows & linux environment / dropbox / mled

I use both windows and linux, but the solution core.autocrlf true didn't help me. I even got nothing changed after git checkout <filename>.

So I use workaround to substitute git status - gitstatus.sh

#!/bin/bash

git status | grep modified | cut -d' ' -f 4 | while read x; do
 x1="$(git show HEAD:$x | md5sum | cut -d' ' -f 1 )"
 x2="$(cat $x | md5sum | cut -d' ' -f 1 )"

 if [ "$x1" != "$x2" ]; then
    echo "$x NOT IDENTICAL"
 fi
done

I just compare md5sum of a file and its brother at repository.

Example output:

$ ./gitstatus.sh
application/script.php NOT IDENTICAL
application/storage/logs/laravel.log NOT IDENTICAL

How to generate a random string in Ruby

Others have mentioned something similar, but this uses the URL safe function.

require 'securerandom'
p SecureRandom.urlsafe_base64(5) #=> "UtM7aa8"
p SecureRandom.urlsafe_base64 #=> "UZLdOkzop70Ddx-IJR0ABg"
p SecureRandom.urlsafe_base64(nil, true) #=> "i0XQ-7gglIsHGV2_BNPrdQ=="

The result may contain A-Z, a-z, 0-9, “-” and “_”. “=” is also used if padding is true.

Determine if char is a num or letter

C99 standard on c >= '0' && c <= '9'

c >= '0' && c <= '9' (mentioned in another answer) works because C99 N1256 standard draft 5.2.1 "Character sets" says:

In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.

ASCII is not guaranteed however.

How to upgrade docker container after its image changed

Consider for this answers:

  • The database name is app_schema
  • The container name is app_db
  • The root password is root123

How to update MySQL when storing application data inside the container

This is considered a bad practice, because if you lose the container, you will lose the data. Although it is a bad practice, here is a possible way to do it:

1) Do a database dump as SQL:

docker exec app_db sh -c 'exec mysqldump app_schema -uroot -proot123' > database_dump.sql

2) Update the image:

docker pull mysql:5.6

3) Update the container:

docker rm -f app_db
docker run --name app_db --restart unless-stopped \
-e MYSQL_ROOT_PASSWORD=root123 \
-d mysql:5.6

4) Restore the database dump:

docker exec app_db sh -c 'exec mysql -uroot -proot123' < database_dump.sql

How to update MySQL container using an external volume

Using an external volume is a better way of managing data, and it makes easier to update MySQL. Loosing the container will not lose any data. You can use docker-compose to facilitate managing multi-container Docker applications in a single host:

1) Create the docker-compose.yml file in order to manage your applications:

version: '2'
services:
  app_db:
    image: mysql:5.6
    restart: unless-stopped
    volumes_from: app_db_data
  app_db_data:
    volumes: /my/data/dir:/var/lib/mysql

2) Update MySQL (from the same folder as the docker-compose.yml file):

docker-compose pull
docker-compose up -d

Note: the last command above will update the MySQL image, recreate and start the container with the new image.

Creating a new ArrayList in Java

You can use in Java 8

List<Class> myArray= new ArrayList<>();

How to pass variable number of arguments to printf/sprintf

Simple example below. Note you should pass in a larger buffer, and test to see if the buffer was large enough or not

void Log(LPCWSTR pFormat, ...) 
{
    va_list pArg;
    va_start(pArg, pFormat);
    char buf[1000];
    int len = _vsntprintf(buf, 1000, pFormat, pArg);
    va_end(pArg);
    //do something with buf
}

In php, is 0 treated as empty?

I was wondering why nobody suggested the extremely handy Type comparison table. It answers every question about the common functions and compare operators.

A snippet:

Expression      | empty($x)
----------------+--------
$x = "";        | true    
$x = null       | true    
var $x;         | true    
$x is undefined | true    
$x = array();   | true    
$x = false;     | true    
$x = true;      | false   
$x = 1;         | false   
$x = 42;        | false   
$x = 0;         | true    
$x = -1;        | false   
$x = "1";       | false   
$x = "0";       | true    
$x = "-1";      | false   
$x = "php";     | false   
$x = "true";    | false   
$x = "false";   | false   

Along other cheatsheets, I always keep a hardcopy of this table on my desk in case I'm not sure

How to use export with Python on Linux

You actually want to do

import os
os.environ["MY_DATA"] = "my_export"

How to attach a file using mail command on Linux?

mail on every version of modern Linux that I've tried can do it. No need for other software:

matiu@matiu-laptop:~$ mail -a doc.jpg [email protected]
Subject: testing

This is a test
EOT

ctrl+d when you're done typing.

Finding current executable's path without /proc/self/exe

In addition to mark4o's answer, FreeBSD also has

const char* getprogname(void)

It should also be available in macOS. It's available in GNU/Linux through libbsd.

How do I comment out a block of tags in XML?

You can use that style of comment across multiple lines (which exists also in HTML)

<detail>
    <band height="20">
    <!--
      Hello,
         I am a multi-line XML comment
         <staticText>
            <reportElement x="180" y="0" width="200" height="20"/>
            <text><![CDATA[Hello World!]]></text>
          </staticText>
      -->
     </band>
</detail>

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given... what I do wrong?

you are mixing mysql and mysqli

use this mysql_real_escape_string like

$username = mysql_real_escape_string($_POST['username']);

NOTE : mysql_* is deprecated use mysqli_* or PDO

What is the intended use-case for git stash?

I know StackOverflow is not the place for opinion based answers, but I actually have a good opinion on when to shelve changes with a stash.

You don't want to commit you experimental changes

When you make changes in your workspace/working tree, if you need to perform any branch based operations like a merge, push, fetch or pull, you must be at a clean commit point. So if you have workspace changes you need to commit them. But what if you don't want to commit them? What if they are experimental? Something you don't want part of your commit history? Something you don't want others to see when you push to GitHub?

You don't want to lose local changes with a hard reset

In that case, you can do a hard reset. But if you do a hard reset you will lose all of your local working tree changes because everything gets overwritten to where it was at the time of the last commit and you'll lose all of your changes.

So, as for the answer of 'when should you stash', the answer is when you need to get back to a clean commit point with a synchronized working tree/index/commit, but you don't want to lose your local changes in the process. Just shelve your changes in a stash and you're good.

And once you've done your stash and then merged or pulled or pushed, you can just stash pop or apply and you're back to where you started from.

Git stash and GitHub

GitHub is constantly adding new features, but as of right now, there is now way to save a stash there. Again, the idea of a stash is that it's local and private. Nobody else can peek into your stash without physical access to your workstation. Kinda the same way git reflog is private with the git log is public. It probably wouldn't be private if it was pushed up to GitHub.

One trick might be to do a diff of your workspace, check the diff into your git repository, commit and then push. Then you can do a pull from home, get the diff and then unwind it. But that's a pretty messy way to achieve those results.

git diff > git-dif-file.diff

pop the stash

Using python map and other functional tools

Functional programming is about creating side-effect-free code.

map is a functional list transformation abstraction. You use it to take a sequence of something and turn it into a sequence of something else.

You are trying to use it as an iterator. Don't do that. :)

Here is an example of how you might use map to build the list you want. There are shorter solutions (I'd just use comprehensions), but this will help you understand what map does a bit better:

def my_transform_function(input):
    return [input, [1, 2, 3]]

new_list = map(my_transform, input_list)

Notice at this point, you've only done a data manipulation. Now you can print it:

for n,l in new_list:
    print n, ll

-- I'm not sure what you mean by 'without loops.' fp isn't about avoiding loops (you can't examine every item in a list without visiting each one). It's about avoiding side-effects, thus writing fewer bugs.

Jasmine.js comparing arrays

I had a similar issue where one of the arrays was modified. I was using it for $httpBackend, and the returned object from that was actually a $promise object containing the array (not an Array object).

You can create a jasmine matcher to match the array by creating a toBeArray function:

beforeEach(function() {
  'use strict';
  this.addMatchers({
    toBeArray: function(array) {
      this.message = function() {
        return "Expected " + angular.mock.dump(this.actual) + " to be array " + angular.mock.dump(array) + ".";
      };
      var arraysAreSame = function(x, y) {
         var arraysAreSame = true;
         for(var i; i < x.length; i++)
            if(x[i] !== y[i])
               arraysAreSame = false;
         return arraysAreSame;
      };
      return arraysAreSame(this.actual, array);
    }
  });
});

And then just use it in your tests like the other jasmine matchers:

it('should compare arrays properly', function() {
  var array1, array2;
  /* . . . */
  expect(array1[0]).toBe(array2[0]);
  expect(array1).toBeArray(array2);
});

SQL - Create view from multiple tables

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

DROP VIEW IF EXISTS yourview;

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

What does '?' do in C++?

This is commonly referred to as the conditional operator, and when used like this:

condition ? result_if_true : result_if_false

... if the condition evaluates to true, the expression evaluates to result_if_true, otherwise it evaluates to result_if_false.

It is syntactic sugar, and in this case, it can be replaced with

int qempty()
{ 
  if(f == r)
  {
      return 1;
  } 
  else 
  {
      return 0;
  }
}

Note: Some people refer to ?: it as "the ternary operator", because it is the only ternary operator (i.e. operator that takes three arguments) in the language they are using.

Django: TemplateSyntaxError: Could not parse the remainder

You have indented part of your code in settings.py:

# Uncomment the next line to enable the admin:
     'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    #'django.contrib.admindocs',
     'tinymce',
     'sorl.thumbnail',
     'south',
     'django_facebook',
     'djcelery',
     'devserver',
     'main',

Therefore, it is giving you an error.

PHP PDO: charset, set names?

Prior to PHP 5.3.6, the charset option was ignored. If you're running an older version of PHP, you must do it like this:

<?php

    $dbh = new PDO("mysql:$connstr",  $user, $password);

    $dbh -> exec("set names utf8");

?>

SecurityException during executing jnlp file (Missing required Permissions manifest attribute in main jar)

If you'd like to set this globally for all users of a machine, you can create the following directory and file structures:

mkdir %windir%\Sun\Java\Deployment

Create a file deployment.config with the content:

deployment.system.config=file:///c:/windows/Sun/Java/Deployment/deployment.properties
deployment.system.config.mandatory=TRUE

Create a file deployment.properties

deployment.user.security.exception.sites=C\:/WINDOWS/Sun/Java/Deployment/exception.sites

Create a file exception.sites

http://example1.com
http://example2.com/path/to/specific/directory/

Reference https://blogs.oracle.com/java-platform-group/entry/upcoming_exception_site_list_in

How to upgrade docker-compose to latest version

If the above methods aren't working for you, then refer to this answer: https://stackoverflow.com/a/40554985

curl -L "https://github.com/docker/compose/releases/download/1.22.0/docker-compose-$(uname -s)-$(uname -m)" > ./docker-compose
sudo mv ./docker-compose /usr/bin/docker-compose
sudo chmod +x /usr/bin/docker-compose

When to use the !important property in CSS

Overwriting the Style Attribute

Say in the example that you are unable to change the HTML source code but only provide a stylesheet. Some thoughtless person has slapped on a style directly on the element (boo!)

_x000D_
_x000D_
       div { background-color: green !important }
_x000D_
    <div style="background-color:red">_x000D_
    <p>Take that!</p>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

Here, !important can override inline CSS.

Replace HTML page with contents retrieved via AJAX

Can't you just try to replace the body content with the document.body handler?

if your page is this:

<html>
<body>
blablabla
<script type="text/javascript">
document.body.innerHTML="hi!";
</script>
</body>
</html>

Just use the document.body to replace the body.

This works for me. All the content of the BODY tag is replaced by the innerHTML you specify. If you need to even change the html tag and all childs you should check out which tags of the 'document.' are capable of doing so.

An example with javascript scripting inside it:

<html>
<body>
blablabla
<script type="text/javascript">
var changeme = "<button onClick=\"document.bgColor = \'#000000\'\">click</button>";
document.body.innerHTML=changeme;
</script>
</body>

This way you can do javascript scripting inside the new content. Don't forget to escape all double and single quotes though, or it won't work. escaping in javascript can be done by traversing your code and putting a backslash in front of all singe and double quotes.

Bare in mind that server side scripting like php doesn't work this way. Since PHP is server-side scripting it has to be processed before a page is loaded. Javascript is a language which works on client-side and thus can not activate the re-processing of php code.

Remove border from IFrame

Its simple just add attribute in iframe tag frameborder = 0 <iframe src="" width="200" height="200" frameborder="0"></iframe>

Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT

This is a total hack, but here's what I did...

So while playing with setting up a DocumentsProvider, I noticed that the sample code (in getDocIdForFile, around line 450) generates a unique id for a selected document based on the file's (unique) path relative to the specified root you give it (that is, what you set mBaseDir to on line 96).

So the URI ends up looking something like:

content://com.example.provider/document/root:path/to/the/file

As the docs say, it's assuming only a single root (in my case that's Environment.getExternalStorageDirectory() but you may use somewhere else... then it takes the file path, starting at the root, and makes it the unique ID, prepending "root:". So I can determine the path by eliminating the "/document/root:" part from uri.getPath(), creating an actual file path by doing something like this:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
// check resultcodes and such, then...
uri = data.getData();
if (uri.getAuthority().equals("com.example.provider"))  {
    String path = Environment.getExternalStorageDirectory(0.toString()
                 .concat("/")
                 .concat(uri.getPath().substring("/document/root:".length())));
    doSomethingWithThePath(path); }
else {
    // another provider (maybe a cloud-based service such as GDrive)
    // created this uri.  So handle it, or don't.  You can allow specific
    // local filesystem providers, filter non-filesystem path results, etc.
}

I know. It's shameful, but it worked. Again, this relies on you using your own documents provider in your app to generate the document ID.

(Also, there's a better way to build the path that don't assume "/" is the path separator, etc. But you get the idea.)

Link to download apache http server for 64bit windows.

Check out the link given it has Apache HTTP Server 2.4.2 x86 and x64 Windows Installers http://www.anindya.com/apache-http-server-2-4-2-x86-and-x64-windows-installers/

dereferencing pointer to incomplete type

What do you mean, the error only shows up when you assign? For example on GCC, with no assignment in sight:

int main() {
    struct blah *b = 0;
    *b; // this is line 6
}

incompletetype.c:6: error: dereferencing pointer to incomplete type.

The error is at line 6, that's where I used an incomplete type as if it were a complete type. I was fine up until then.

The mistake is that you should have included whatever header defines the type. But the compiler can't possibly guess what line that should have been included at: any line outside of a function would be fine, pretty much. Neither is it going to go trawling through every text file on your system, looking for a header that defines it, and suggest you should include that.

Alternatively (good point, potatoswatter), the error is at the line where b was defined, when you meant to specify some type which actually exists, but actually specified blah. Finding the definition of the variable b shouldn't be too difficult in most cases. IDEs can usually do it for you, compiler warnings maybe can't be bothered. It's some pretty heinous code, though, if you can't find the definitions of the things you're using.

Android: set view style programmatically

I used views defined in XML in my composite ViewGroup, inflated them added to Viewgroup. This way I cannot dynamically change style but I can make some style customizations. My composite:

public class CalendarView extends LinearLayout {

private GridView mCalendarGrid;
private LinearLayout mActiveCalendars;

private CalendarAdapter calendarAdapter;

public CalendarView(Context context) {
    super(context);

}

public CalendarView(Context context, AttributeSet attrs) {
    super(context, attrs);

}

@Override
protected void onFinishInflate() {
    super.onFinishInflate();
    init();
}

private void init() {
    mCalendarGrid = (GridView) findViewById(R.id.calendarContents);
    mCalendarGrid.setNumColumns(CalendarAdapter.NUM_COLS);

    calendarAdapter = new CalendarAdapter(getContext());
    mCalendarGrid.setAdapter(calendarAdapter);
    mActiveCalendars = (LinearLayout) findViewById(R.id.calendarFooter);
}

}

and my view in xml where i can assign styles:

<com.mfitbs.android.calendar.CalendarView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/calendar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:orientation="vertical"
>

<GridView
    android:id="@+id/calendarContents"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

<LinearLayout
    android:id="@+id/calendarFooter"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    />

vuetify center items into v-flex

wrap button inside <div class="text-xs-center">

<div class="text-xs-center">
  <v-btn primary>
    Signup
  </v-btn>
</div>

Dev uses it in his examples.


For centering buttons in v-card-actions we can add class="justify-center" (note in v2 class is text-center (so without xs):

<v-card-actions class="justify-center">
  <v-btn>
    Signup
  </v-btn>
</v-card-actions>

Codepen


For more examples with regards to centering see here

cURL error 60: SSL certificate: unable to get local issuer certificate

I spent too much time to figure out this problem for me.

I had PHP version 5.5 and I needed to upgrade to 5.6.

In versions < 5.6 Guzzle will use it's own cacert.pem file, but in higher versions of PHP it will use system's cacert.pem file.

I also downloaded file from here https://curl.haxx.se/docs/caextract.html and set it in php.ini.

Answer found in Guzzles StreamHandler.php file https://github.com/guzzle/guzzle/blob/0773d442aa96baf19d7195f14ba6e9c2da11f8ed/src/Handler/StreamHandler.php#L437

        // PHP 5.6 or greater will find the system cert by default. When
        // < 5.6, use the Guzzle bundled cacert.

How to set the Android progressbar's height?

From this tutorial:

<style name="CustomProgressBarHorizontal" parent="android:Widget.ProgressBar.Horizontal">
      <item name="android:progressDrawable">@drawable/custom_progress_bar_horizontal</item>
      <item name="android:minHeight">10dip</item>
      <item name="android:maxHeight">20dip</item>
</style>

Then simply apply the style to your progress bars or better, override the default style in your theme to style all of your app's progress bars automatically.

The difference you are seeing in the screenshots is because the phones/emulators are using a difference Android version (latest is the theme from ICS (Holo), top is the original theme).

React eslint error missing in props validation

You need to define propTypes as a static getter if you want it inside the class declaration:

static get propTypes() { 
    return { 
        children: PropTypes.any, 
        onClickOut: PropTypes.func 
    }; 
}

If you want to define it as an object, you need to define it outside the class, like this:

IxClickOut.propTypes = {
    children: PropTypes.any,
    onClickOut: PropTypes.func,
};

Also it's better if you import prop types from prop-types, not react, otherwise you'll see warnings in console (as preparation for React 16):

import PropTypes from 'prop-types';

How to list the size of each file and directory and sort by descending size in Bash?

I tend to use du in a simple way.

du -sh */ | sort -n

This provides me with an idea of what directories are consuming the most space. I can then run more precise searches later.

How do I clone a generic List in Java?

I am not a java professional, but I have the same problem and I tried to solve by this method. (It suppose that T has a copy constructor).

 public static <T extends Object> List<T> clone(List<T> list) {
      try {
           List<T> c = list.getClass().newInstance();
           for(T t: list) {
             T copy = (T) t.getClass().getDeclaredConstructor(t.getclass()).newInstance(t);
             c.add(copy);
           }
           return c;
      } catch(Exception e) {
           throw new RuntimeException("List cloning unsupported",e);
      }
}

Real time face detection OpenCV, Python

Your line:

img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.

Try

cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

getElementsByClassName not working

There are several issues:

  1. Class names (and IDs) are not allowed to start with a digit.
  2. You have to pass a class to getElementsByClassName().
  3. You have to iterate of the result set.

Example (untested):

<script type="text/javascript">
function hideTd(className){
    var elements = document.getElementsByClassName(className);
    for(var i = 0, length = elements.length; i < length; i++) {
       if( elements[i].textContent == ''){
          elements[i].style.display = 'none';
       } 
    }

  }
</script>
</head>
<body onload="hideTd('td');">
<table border="1">
  <tr>
    <td class="td">not empty</td>
  </tr>
  <tr>
    <td class="td"></td>
  </tr>
  <tr>
    <td class="td"></td>
  </tr>
</table>
</body>

Note that getElementsByClassName() is not available up to and including IE8.

Update:

Alternatively you can give the table an ID and use:

var elements = document.getElementById('tableID').getElementsByTagName('td');

to get all td elements.

To hide the parent row, use the parentNode property of the element:

elements[i].parentNode.style.display = "none";

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

Below I have put together everything I learned about Starting/Stopping a Windows Service from a non-Admin user account, if anyone needs to know.

Primarily, there are two ways in which to Start / Stop a Windows Service. 1. Directly accessing the service through logon Windows user account. 2. Accessing the service through IIS using Network Service account.

Command line command to start / stop services:

C:/> net start <SERVICE_NAME>
C:/> net stop <SERVICE_NAME>

C# Code to start / stop services:

ServiceController service = new ServiceController(SERVICE_NAME);

//Start the service
if (service.Status == ServiceControllerStatus.Stopped)
{
      service.Start();
      service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(10.0));
}

//Stop the service
if (service.Status == ServiceControllerStatus.Running)
{
      service.Stop();
      service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10.0));
}

Note 1: When accessing the service through IIS, create a Visual Studio C# ASP.NET Web Application and put the code in there. Deploy the WebService to IIS Root Folder (C:\inetpub\wwwroot\) and you're good to go. Access it by the url http:///.

1. Direct Access Method

If the Windows User Account from which either you give the command or run the code is a non-Admin account, then you need to set the privileges to that particular user account so it has the ability to start and stop Windows Services. This is how you do it. Login to an Administrator account on the computer which has the non-Admin account from which you want to Start/Stop the service. Open up the command prompt and give the following command:

C:/>sc sdshow <SERVICE_NAME>

Output of this will be something like this:

D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)

It lists all the permissions each User / Group on this computer has with regards to .

A description of one part of above command is as follows:

    D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)

It has the default owner, default group, and it has the Security descriptor control flags (A;;CCLCSWRPWPDTLOCRRC;;;SY):

ace_type - "A": ACCESS_ALLOWED_ACE_TYPE,
ace_flags - n/a,
rights - CCLCSWRPWPDTLOCRRC,  please refer to the Access Rights and Access Masks and Directory Services Access Rights
CC: ADS_RIGHT_DS_CREATE_CHILD - Create a child DS object.
LC: ADS_RIGHT_ACTRL_DS_LIST - Enumerate a DS object.
SW: ADS_RIGHT_DS_SELF - Access allowed only after validated rights checks supported by the object are performed. This flag can be used alone to perform all validated rights checks of the object or it can be combined with an identifier of a specific validated right to perform only that check.
RP: ADS_RIGHT_DS_READ_PROP - Read the properties of a DS object.
WP: ADS_RIGHT_DS_WRITE_PROP - Write properties for a DS object.
DT: ADS_RIGHT_DS_DELETE_TREE - Delete a tree of DS objects.
LO: ADS_RIGHT_DS_LIST_OBJECT - List a tree of DS objects.
CR: ADS_RIGHT_DS_CONTROL_ACCESS - Access allowed only after extended rights checks supported by the object are performed. This flag can be used alone to perform all extended rights checks on the object or it can be combined with an identifier of a specific extended right to perform only that check.
RC: READ_CONTROL - The right to read the information in the object's security descriptor, not including the information in the system access control list (SACL). (This is a Standard Access Right, please read more http://msdn.microsoft.com/en-us/library/aa379607(VS.85).aspx)
object_guid - n/a,
inherit_object_guid - n/a,
account_sid - "SY": Local system. The corresponding RID is SECURITY_LOCAL_SYSTEM_RID.

Now what we need to do is to set the appropriate permissions to Start/Stop Windows Services to the groups or users we want. In this case we need the current non-Admin user be able to Start/Stop the service so we are going to set the permissions to that user. To do that, we need the SID of that particular Windows User Account. To obtain it, open up the Registry (Start > regedit) and locate the following registry key.

LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList

Under that there is a seperate Key for each an every user account in this computer, and the key name is the SID of each account. SID are usually of the format S-1-5-21-2103278432-2794320136-1883075150-1000. Click on each Key, and you will see on the pane to the right a list of values for each Key. Locate "ProfileImagePath", and by it's value you can find the User Name that SID belongs to. For instance, if the user name of the account is SACH, then the value of "ProfileImagePath" will be something like "C:\Users\Sach". So note down the SID of the user account you want to set the permissions to.

Note2: Here a simple C# code sample which can be used to obtain a list of said Keys and it's values.

//LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList RegistryKey
RegistryKey profileList = Registry.LocalMachine.OpenSubKey(keyName);

//Get a list of SID corresponding to each account on the computer
string[] sidList = profileList.GetSubKeyNames();

foreach (string sid in sidList)
{
    //Based on above names, get 'Registry Keys' corresponding to each SID
    RegistryKey profile = Registry.LocalMachine.OpenSubKey(Path.Combine(keyName, sid));

    //SID
    string strSID = sid;
    //UserName which is represented by above SID    
    string strUserName = (string)profile.GetValue("ProfileImagePath");
}

Now that we have the SID of the user account we want to set the permissions to, let's get down to it. Let's assume the SID of the user account is S-1-5-21-2103278432-2794320136-1883075150-1000. Copy the output of the [sc sdshow ] command to a text editor. It will look like this:

D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)

Now, copy the (A;;CCLCSWRPWPDTLOCRRC;;;SY) part of the above text, and paste it just before the S:(AU;... part of the text. Then change that part to look like this: (A;;RPWPCR;;;S-1-5-21-2103278432-2794320136-1883075150-1000)

Then add sc sdset at the front, and enclose the above part with quotes. Your final command should look something like the following:

sc sdset <SERVICE_NAME> "D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)(A;;RPWPCR;;;S-1-5-21-2103278432-2794320136-1883075150-1000)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)"

Now execute this in your command prompt, and it should give the output as follows if successful:

[SC] SetServiceObjectSecurity SUCCESS

Now we're good to go! Your non-Admin user account has been granted permissions to Start/Stop your service! Try loggin in to the user account and Start/Stop the service and it should let you do that.

2. Access through IIS Method

In this case, we need to grant the permission to the IIS user "Network Services" instead of the logon Windows user account. The procedure is the same, only the parameters of the command will be changed. Since we set the permission to "Network Services", replace SID with the string "NS" in the final sdset command we used previously. The final command should look something like this:

sc sdset <SERVICE_NAME> "D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)(A;;RPWPCR;;;NS)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)"

Execute it in the command prompt from an Admin user account, and voila! You have the permission to Start / Stop the service from any user account (irrespective of whether it ia an Admin account or not) using a WebMethod. Refer to Note1 to find out how to do so.

http://localhost:8080/ Access Error: 404 -- Not Found Cannot locate document: /

For CentOS users (at least), one will also get a 404 error trying to access the server on port 8080 on a fresh install if the tomcat-webapps package is not installed.

Newline in markdown table?

Just for those that are trying to do this on Jira. Just add \\ at the end of each line and a new line will be created:

|Something|Something else \\ that's rather long|Something else|

Will render this:

enter image description here

Source: Text breaks on Jira

How to check if a String contains another String in a case insensitive manner in Java?

There is a simple concise way, using regex flag (case insensitive {i}):

 String s1 = "hello abc efg";
 String s2 = "ABC";
 s1.matches(".*(?i)"+s2+".*");

/*
 * .*  denotes every character except line break
 * (?i) denotes case insensitivity flag enabled for s2 (String)
 * */

What does "both" mean in <div style="clear:both">

Clear:both gives you that space between them.

For example your code:

  <div style="float:left">Hello</div>
  <div style="float:right">Howdy dere pardner</div>

Will currently display as :

Hello  ...................   Howdy dere pardner

If you add the following to above snippet,

  <div style="clear:both"></div>

In between them it will display as:

Hello ................ 
                       Howdy dere pardner

giving you that space between hello and Howdy dere pardner.

Js fiiddle http://jsfiddle.net/Qk5vR/1/

Remove HTML tags from string including &nbsp in C#

Sanitizing an Html document involves a lot of tricky things. This package maybe of help: https://github.com/mganss/HtmlSanitizer

Oracle DB: How can I write query ignoring case?

Use ALTER SESSION statements to set comparison to case-insensitive:

alter session set NLS_COMP=LINGUISTIC;
alter session set NLS_SORT=BINARY_CI;

If you're still using version 10gR2, use the below statements. See this FAQ for details.

alter session set NLS_COMP=ANSI;
alter session set NLS_SORT=BINARY_CI;

How do I check whether an array contains a string in TypeScript?

do like this:

departments: string[]=[];
if(this.departments.indexOf(this.departmentName.trim()) >-1 ){
            return;
    }

Changing image sizes proportionally using CSS?

You can use object-fit css3 property, something like

_x000D_
_x000D_
<!doctype html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <meta charset='utf-8'>_x000D_
  <style>_x000D_
    .holder {_x000D_
      display: inline;_x000D_
    }_x000D_
    .holder img {_x000D_
      max-height: 200px;_x000D_
      max-width: 200px;_x000D_
      object-fit: cover;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div class='holder'>_x000D_
    <img src='meld.png'>_x000D_
  </div>_x000D_
  <div class='holder'>_x000D_
    <img src='twiddla.png'>_x000D_
  </div>_x000D_
  <div class='holder'>_x000D_
    <img src='meld.png'>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

It is not exactly your answer, though, because of it doesn't stretch the container, but it behaves like the gallery and you can keep styling the img itself.

Another drawback of this solution is still a poor support of the css3 property. More details are available here: http://www.steveworkman.com/html5-2/javascript/2012/css3-object-fit-polyfill/. jQuery solution can be found there as well.

How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error

My problem was related to @BeforeEach of JUnit. And even if I saved the related entities (in my case @ManyToOne), I got the same error.

The problem is somehow related to the sequence that I have in my parent. If I assign the value to that attribute, the problem is solved.

Ex. If I have the entity Question that can have some categories (one or more) and entity Question has a sequence:

@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "feedbackSeq")
@Id
private Long id;

I have to assign the value question.setId(1L);

Console errors. Failed to load resource: net::ERR_INSECURE_RESPONSE

When I had the problem recently it was a cross site issue where our dev server hosts our analytics software as well as the application. In the other environments the chrome console would show this error and the javascript file (tracker) on the dev server as the source. This was causing issues for QA personnel who were trying to view the analytics data for their environment (nothing was being captured because of this issue).

The solution to fix this in-house was to add the SSL certificate the DEV site was using to the Trusted People store on the QA people's machine.

If this was a problem in production I would most likely move the javascript into the actual web apps.

How to convert a private key to an RSA private key?

Newer versions of OpenSSL say BEGIN PRIVATE KEY because they contain the private key + an OID that identifies the key type (this is known as PKCS8 format). To get the old style key (known as either PKCS1 or traditional OpenSSL format) you can do this:

openssl rsa -in server.key -out server_new.key

Alternately, if you have a PKCS1 key and want PKCS8:

openssl pkcs8 -topk8 -nocrypt -in privkey.pem

Gradle: Could not determine java version from '11.0.2'

I've had the same issue. Upgrading to gradle 5.0 did the trick for me.

This link provides detailed steps on how install gradle 5.0: https://linuxize.com/post/how-to-install-gradle-on-ubuntu-18-04/

How to embed fonts in CSS?

Go through http://www.w3.org/TR/css3-fonts/

Try this:

  @font-face {
        font-family: 'EntezareZohoor2';
        src: url('EntezareZohoor2.eot');
        src: local('EntezareZohoor2'), local('EntezareZohoor2'), url('EntezareZohoor2.ttf') format('svg');
       font-weight: normal;
       font-style: normal;
    }

Error when trying to access XAMPP from a network

In your xampppath\apache\conf\extra open file httpd-xampp.conf and find the below tag:

# Close XAMPP sites here
<LocationMatch "^/(?i:(?:xampp|licenses|phpmyadmin|webalizer|server-status|server-info))">
    Order deny,allow
    Deny from all
    Allow from ::1 127.0.0.0/8 
    ErrorDocument 403 /error/HTTP_XAMPP_FORBIDDEN.html.var
</LocationMatch>

and add

"Allow from all"

after Allow from ::1 127.0.0.0/8 {line}

Restart xampp, and you are done.

In later versions of Xampp

...you can simply remove this part

#
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
        Require local
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>

from the same file and it should work over the local network.

Python: How do I make a subclass from a superclass?

You use:

class DerivedClassName(BaseClassName):

For details, see the Python docs, section 9.5.

Is it necessary to write HEAD, BODY and HTML tags?

The Google Style Guide for HTML recommends omitting all optional tags.
That includes <html>, <head>, <body>, <p> and <li>.

https://google.github.io/styleguide/htmlcssguide.html#Optional_Tags

For file size optimization and scannability purposes, consider omitting optional tags. The HTML5 specification defines what tags can be omitted.

(This approach may require a grace period to be established as a wider guideline as it’s significantly different from what web developers are typically taught. For consistency and simplicity reasons it’s best served omitting all optional tags, not just a selection.)

<!-- Not recommended -->
<!DOCTYPE html>
<html>
  <head>
    <title>Spending money, spending bytes</title>
  </head>
  <body>
    <p>Sic.</p>
  </body>
</html>

<!-- Recommended -->
<!DOCTYPE html>
<title>Saving money, saving bytes</title>
<p>Qed.

Copy / Put text on the clipboard with FireFox, Safari and Chrome

I've used Github's Clippy for my needs, simple Flash-based button. Works just fine, if one doesn't need styling and is pleased with inserting what to paste on the server-side beforehand.

Relative imports in Python 3

Put this inside your package's __init__.py file:

# For relative imports to work in Python 3.6
import os, sys; sys.path.append(os.path.dirname(os.path.realpath(__file__)))

Assuming your package is like this:

+-- project
¦   +-- package
¦   ¦   +-- __init__.py
¦   ¦   +-- module1.py
¦   ¦   +-- module2.py
¦   +-- setup.py

Now use regular imports in you package, like:

# in module2.py
from module1 import class1

This works in both python 2 and 3.

Check input value length

You can add a form onsubmit handler, something like:

<form onsubmit="return validate();">

</form>


<script>function validate() {
 // check if input is bigger than 3
 var value = document.getElementById('titleeee').value;
 if (value.length < 3) {
   return false; // keep form from submitting
 }

 // else form is good let it submit, of course you will 
 // probably want to alert the user WHAT went wrong.

 return true;
}</script>

Python "\n" tag extra line

Add , after the print "\n" line

so that it reads print "\n",

How to obtain a Thread id in Python?

I saw examples of thread IDs like this:

class myThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        self.threadID = threadID
        ...

The threading module docs lists name attribute as well:

...

A thread has a name. 
The name can be passed to the constructor, 
and read or changed through the name attribute.

...

Thread.name

A string used for identification purposes only. 
It has no semantics. Multiple threads may
be given the same name. The initial name is set by the constructor.

C#: Dynamic runtime cast

Alternatively:

public static T Cast<T>(this dynamic obj) where T:class
{
   return obj as T;
}

How to draw a standard normal distribution in R

Something like this perhaps?

x<-rnorm(100000,mean=10, sd=2)
hist(x,breaks=150,xlim=c(0,20),freq=FALSE)
abline(v=10, lwd=5)
abline(v=c(4,6,8,12,14,16), lwd=3,lty=3)

What is the best open-source java charting library? (other than jfreechart)

I've used EasyCharts in the past and it lived up to it's name. It's not as powerful as JFreeChart, but the JAR for EasyCharts is much smaller than for JFreeChart.

Xcode 10: A valid provisioning profile for this executable was not found

Finally, I figured out what's going on... almost take me 2 hours

My case is, my phone's date is not correct. I forgot I changed my phone's date. I guess that makes all of my provisioning profiles expired...

So if you've tried all of those answers but nothing works. Go to the SETTINGS, check your phone's date.

SQL-Server: Is there a SQL script that I can use to determine the progress of a SQL Server backup or restore process?

SELECT session_id as SPID, command, a.text AS Query, start_time, percent_complete, dateadd(second,estimated_completion_time/1000, getdate()) as estimated_completion_time 
FROM sys.dm_exec_requests r CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) a 
WHERE r.command in ('BACKUP DATABASE','RESTORE DATABASE')

Selenium Webdriver move mouse to Point

IMHO you should pay your attention to Robot.class

Still if you want to move the mouse pointer physically, you need to take different approach using Robot class

  Point coordinates = driver.findElement(By.id("ctl00_portalmaster_txtUserName")).getLocation();
  Robot robot = new Robot();
  robot.mouseMove(coordinates.getX(),coordinates.getY()+120);

Webdriver provide document coordinates, where as Robot class is based on Screen coordinates, so I have added +120 to compensate the browser header.
Screen Coordinates: These are coordinates measured from the top left corner of the user's computer screen. You'd rarely get coordinates (0,0) because that is usually outside the browser window. About the only time you'd want these coordinates is if you want to position a newly created browser window at the point where the user clicked. In all browsers these are in event.screenX and event.screenY.
Window Coordinates: These are coordinates measured from the top left corner of the browser's content area. If the window is scrolled, vertically or horizontally, this will be different from the top left corner of the document. This is rarely what you want. In all browsers these are in event.clientX and event.clientY.
Document Coordinates: These are coordinates measured from the top left corner of the HTML Document. These are the coordinates that you most frequently want, since that is the coordinate system in which the document is defined.

More details you can get here

Hope this be helpful to you.

Clear the value of bootstrap-datepicker

I know its too late to answer, but in my scenario below code was not working.

 $('#datepicker').val("");
 $('#datepicker').val('').datepicker('update');
 $('#datepicker').datepicker('update','');

here is my solution.

 $('#datepicker').val('').datepicker('remove').datepicker();

I did clear datepicker value first then removed datepicker and again reinitialize datepicker. its resolved my problem.

Google Colab: how to read data from my google drive?

There are many ways to read the files in your colab notebook(**.ipnb), a few are:

  1. Mounting your Google Drive in the runtime's virtual machine.here &, here
  2. Using google.colab.files.upload(). the easiest solution
  3. Using the native REST API;
  4. Using a wrapper around the API such as PyDrive

Method 1 and 2 worked for me, rest I wasn't able to figure out. If anyone could, as others tried in above post please write an elegant answer. thanks in advance.!

First method:

I wasn't able to mount my google drive, so I installed these libraries

# Install a Drive FUSE wrapper.
# https://github.com/astrada/google-drive-ocamlfuse

!apt-get install -y -qq software-properties-common python-software-properties module-init-tools
!add-apt-repository -y ppa:alessandro-strada/ppa 2>&1 > /dev/null
!apt-get update -qq 2>&1 > /dev/null
!apt-get -y install -qq google-drive-ocamlfuse fuse

from google.colab import auth
auth.authenticate_user()
from oauth2client.client import GoogleCredentials
creds = GoogleCredentials.get_application_default()
import getpass

!google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret} < /dev/null 2>&1 | grep URL
vcode = getpass.getpass()
!echo {vcode} | google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret}

Once the installation & authorization process is finished, you first mount your drive.

!mkdir -p drive
!google-drive-ocamlfuse drive

After installation I was able to mount the google drive, everything in your google drive starts from /content/drive

!ls /content/drive/ML/../../../../path_to_your_folder/

Now you can simply read the file from path_to_your_folder folder into pandas using the above path.

import pandas as pd
df = pd.read_json('drive/ML/../../../../path_to_your_folder/file.json')
df.head(5)

you are suppose you use absolute path you received & not using /../..

Second method:

Which is convenient, if your file which you want to read it is present in the current working directory.

If you need to upload any files from your local file system, you could use below code, else just avoid it.!

from google.colab import files
uploaded = files.upload()
for fn in uploaded.keys():
  print('User uploaded file "{name}" with length {length} bytes'.format(
      name=fn, length=len(uploaded[fn])))

suppose you have below the folder hierarchy in your google drive:

/content/drive/ML/../../../../path_to_your_folder/

Then, you simply need below code to load into pandas.

import pandas as pd
import io
df = pd.read_json(io.StringIO(uploaded['file.json'].decode('utf-8')))
df

What are the differences between virtual memory and physical memory?

See here: Physical Vs Virtual Memory

Virtual memory is stored on the hard drive and is used when the RAM is filled. Physical memory is limited to the size of the RAM chips installed in the computer. Virtual memory is limited by the size of the hard drive, so virtual memory has the capability for more storage.

Vertical align text in block element

with thanks to Vlad's answer for inspiration; tested & working on IE11, FF49, Opera40, Chrome53

li > a {
  height: 100px;
  width: 300px;
  display: table-cell;
  text-align: center; /* H align */
  vertical-align: middle;
}

centers in all directions nicely even with text wrapping, line breaks, images, etc.

I got fancy and made a snippet

_x000D_
_x000D_
li > a {_x000D_
  height: 100px;_x000D_
  width: 300px;_x000D_
  display: table-cell;_x000D_
  /*H align*/_x000D_
  text-align: center;_x000D_
  /*V align*/_x000D_
  vertical-align: middle;_x000D_
}_x000D_
a.thin {_x000D_
  width: 40px;_x000D_
}_x000D_
a.break {_x000D_
  /*force text wrap, otherwise `width` is treated as `min-width` when encountering a long word*/_x000D_
  word-break: break-all;_x000D_
}_x000D_
/*more css so you can see this easier*/_x000D_
_x000D_
li {_x000D_
  display: inline-block;_x000D_
}_x000D_
li > a {_x000D_
  padding: 10px;_x000D_
  margin: 30px;_x000D_
  background: aliceblue;_x000D_
}_x000D_
li > a:hover {_x000D_
  padding: 10px;_x000D_
  margin: 30px;_x000D_
  background: aqua;_x000D_
}
_x000D_
<li><a href="">My menu item</a>_x000D_
</li>_x000D_
<li><a href="">My menu <br> break item</a>_x000D_
</li>_x000D_
<li><a href="">My menu item that is really long and unweildly</a>_x000D_
</li>_x000D_
<li><a href="" class="thin">Good<br>Menu<br>Item</a>_x000D_
</li>_x000D_
<li><a href="" class="thin">Fantastically Menu Item</a>_x000D_
</li>_x000D_
<li><a href="" class="thin break">Fantastically Menu Item</a>_x000D_
</li>_x000D_
<br>_x000D_
note: if using "break-all" need to also use "&lt;br>" or suffer the consequences
_x000D_
_x000D_
_x000D_

VBA Object doesn't support this property or method

Object doesn't support this property or method.

Think of it like if anything after the dot is called on an object. It's like a chain.

An object is a class instance. A class instance supports some properties defined in that class type definition. It exposes whatever intelli-sense in VBE tells you (there are some hidden members but it's not related to this). So after each dot . you get intelli-sense (that white dropdown) trying to help you pick the correct action.

(you can start either way - front to back or back to front, once you understand how this works you'll be able to identify where the problem occurs)

Type this much anywhere in your code area

Dim a As Worksheets
a.

you get help from VBE, it's a little dropdown called Intelli-sense

enter image description here

It lists all available actions that particular object exposes to any user. You can't see the .Selection member of the Worksheets() class. That's what the error tells you exactly.

Object doesn't support this property or method.

If you look at the example on MSDN

Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count

It activates the sheet first then calls the Selection... it's not connected together because Selection is not a member of Worksheets() class. Simply, you can't prefix the Selection

What about

Sub DisplayColumnCount()
    Dim iAreaCount As Integer
    Dim i As Integer

    Worksheets("GRA").Activate
    iAreaCount = Selection.Areas.Count

    If iAreaCount <= 1 Then
        MsgBox "The selection contains " & Selection.Columns.Count & " columns."
    Else
        For i = 1 To iAreaCount
        MsgBox "Area " & i & " of the selection contains " & _
        Selection.Areas(i).Columns.Count & " columns."
        Next i
    End If
End Sub

from HERE

How to do SVN Update on my project using the command line

From the command line it would be just:

svn update

(in the directory you've got a copy of a SVN project).

linux shell script: split string, put them in an array then loop through them

Here's a variation on ashirazi's answer which doesn't rely on $IFS. It does have its own issues which I ouline below.

sentence="one;two;three"
sentence=${sentence//;/$'\n'}  # change the semicolons to white space
for word in $sentence
do
    echo "$word"
done

Here I've used a newline, but you could use a tab "\t" or a space. However, if any of those characters are in the text it will be split there, too. That's the advantage of $IFS - it can not only enable a separator, but disable the default ones. Just make sure you save its value before you change it - as others have suggested.

How to use [DllImport("")] in C#?

You can't declare an extern local method inside of a method, or any other method with an attribute. Move your DLL import into the class:

using System.Runtime.InteropServices;


public class WindowHandling
{
    [DllImport("User32.dll")]
    public static extern int SetForegroundWindow(IntPtr point);

    public void ActivateTargetApplication(string processName, List<string> barcodesList)
    {
        Process p = Process.Start("notepad++.exe");
        p.WaitForInputIdle();
        IntPtr h = p.MainWindowHandle;
        SetForegroundWindow(h);
        SendKeys.SendWait("k");
        IntPtr processFoundWindow = p.MainWindowHandle;
    }
}

Targeting .NET Framework 4.5 via Visual Studio 2010

There are pretty limited scenarios that I can think of where this would be useful, but let's assume you can't get funds to purchase VS2012 or something to that effect. If that's the case and you have Windows 7+ and VS 2010 you may be able to use the following hack I put together which seems to work (but I haven't fully deployed an application using this method yet).

  1. Backup your project file!!!

  2. Download and install the Windows 8 SDK which includes the .NET 4.5 SDK.

  3. Open your project in VS2010.

  4. Create a text file in your project named Compile_4_5_CSharp.targets with the following contents. (Or just download it here - Make sure to remove the ".txt" extension from the file name):

    <Project DefaultTargets="Build"
     xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    
        <!-- Change the target framework to 4.5 if using the ".NET 4.5" configuration -->
        <PropertyGroup Condition=" '$(Platform)' == '.NET 4.5' ">
            <DefineConstants Condition="'$(DefineConstants)'==''">
                TARGETTING_FX_4_5
            </DefineConstants>
            <DefineConstants Condition="'$(DefineConstants)'!='' and '$(DefineConstants)'!='TARGETTING_FX_4_5'">
                $(DefineConstants);TARGETTING_FX_4_5
            </DefineConstants>
            <PlatformTarget Condition="'$(PlatformTarget)'!=''"/>
            <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
        </PropertyGroup>
    
        <!-- Import the standard C# targets -->
        <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
    
        <!-- Add .NET 4.5 as an available platform -->
        <PropertyGroup>
           <AvailablePlatforms>$(AvailablePlatforms),.NET 4.5</AvailablePlatforms>
        </PropertyGroup>
    </Project>
    
  5. Unload your project (right click -> unload).

  6. Edit the project file (right click -> Edit *.csproj).

  7. Make the following changes in the project file:

    a. Replace the default Microsoft.CSharp.targets with the target file created in step 4

    <!-- Old Import Entry -->
    <!-- <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> -->
    
    <!-- New Import Entry -->
    <Import Project="Compile_4_5_CSharp.targets" />
    

    b. Change the default platform to .NET 4.5

    <!-- Old default platform entry -->
    <!-- <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> -->
    
    <!-- New default platform entry -->
    <Platform Condition=" '$(Platform)' == '' ">.NET 4.5</Platform>
    

    c. Add AnyCPU platform to allow targeting other frameworks as specified in the project properties. This should be added just before the first <ItemGroup> tag in the file

    <PropertyGroup Condition="'$(Platform)' == 'AnyCPU'">
        <PlatformTarget>AnyCPU</PlatformTarget>
    </PropertyGroup>
    
    .
    .
    .
    <ItemGroup>
    .
    .
    .
    
  8. Save your changes and close the *.csproj file.

  9. Reload your project (right click -> Reload Project).

  10. In the configuration manager (Build -> Configuration Manager) make sure the ".NET 4.5" platform is selected for your project.

  11. Still in the configuration manager, create a new solution platform for ".NET 4.5" (you can base it off "Any CPU") and make sure ".NET 4.5" is selected for the solution.

  12. Build your project and check for errors.

  13. Assuming the build completed you can verify that you are indeed targeting 4.5 by adding a reference to a 4.5 specific class to your source code:

    using System;
    using System.Text;
    
    namespace testing
    {
        using net45check = System.Reflection.ReflectionContext;
    }
    
  14. When you compile using the ".NET 4.5" platform the build should succeed. When you compile under the "Any CPU" platform you should get a compiler error:

    Error 6: The type or namespace name 'ReflectionContext' does not exist in
    the namespace 'System.Reflection' (are you missing an assembly reference?)
    

Slide up/down effect with ng-show and ng-animate

What's wrong with actually using ng-animate for ng-show as you mentioned?

<script src="lib/angulr.js"></script>
<script src="lib/angulr_animate.js"></script>
<script>
    var app=angular.module('ang_app', ['ngAnimate']);
    app.controller('ang_control01_main', function($scope) {

    });
</script>
<style>
    #myDiv {
        transition: .5s;
        background-color: lightblue;
        height: 100px;
    }
    #myDiv.ng-hide {
        height: 0;
    }
</style>
<body ng-app="ang_app" ng-controller="ang_control01_main">
    <input type="checkbox" ng-model="myCheck">
    <div id="myDiv" ng-show="myCheck"></div>
</body>

database attached is read only

There are 3 (at least) parts to this.

Part 1: As everyone else suggested...Ensure the folder and containing files are not read only. You will read about a phantom bug in windows where you remove read only from folders and containing items, only to open the properties again and see it still clicked. This is not a bug. Honestly, its a feature. You see back in the early days. The System and Read Only attributes had specific meanings. Now that windows has evolved and uses a different file system these attributes no longer make sense on folders. So they have been "repurposed" as a marker for the OS to identify folders that have special meaning or customisations (and as such contain the desktop.ini file). Folders such as those containing fonts or special icons and customisations etc. So even though this attribute is still turned on, it doesn't affect the files within them. So it can be ignored once you have turned it off the first time.

Part 2: Again, as others have suggested, right click the database, and properties, find options, ensure that the read only property is set to false. You generally wont be able to change this manually anyway unless you are lucky. But before you go searching for magic commands (sql or powershell), take a look at part 3.

Part 3: Check the permissions on the folder. Ensure your SQL Server user has full access to it. In most cases this user for a default installation is either MSSQLSERVER or MSSQLEXPRESS with "NT Service" prefixed. You'll find them in the security\logins section of the database. Open the properties of the folder, go to the security tab, and add that user to the list.

In all 3 cases you may (or may not) have to detach and reattach to see the read only status removed.

If I find a situation where these 3 solutions don't work for me, and I find another alternative, I will add it here in time. Hope this helps.

SSRS the definition of the report is invalid

I just had this same problem during a SSRS development of a Custom Report for MS CRM Dynamics 2011.

The reason because it occurred is because I am using some Hidden Parameters and for some of them I forget to give a default value.

So, because of I have few time to finish the report I forget to put the default value for some Parameters and I risked to lost more time to fix it.

Luckily I found it very fast because the error shows the textbox and the paragraph with the first wrong parameter but it didn't shows the name of the parameter:

"I cannot post the image of the error because this website don't allows me"

In general during SSRS developments it's very important to remember: - To put the report parameters in the correct sequence (the referred ones for first es. parameters inherited from master report or parameters essentials for sub-datasets) - To assign a default value to the Hide and Internal Parameters.

HTML 'td' width and height

Following width worked well in HTML5: -

<table >
  <tr>
    <th style="min-width:120px">Month</th>
    <th style="min-width:60px">Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
  </tr>
</table>

Please note that

  • TD tag is without CSS style.

Android set bitmap to Imageview

Please try this:

byte[] decodedString = Base64.decode(person_object.getPhoto(),Base64.NO_WRAP);
InputStream inputStream  = new ByteArrayInputStream(decodedString);
Bitmap bitmap  = BitmapFactory.decodeStream(inputStream);
user_image.setImageBitmap(bitmap);

Global variables in c#.net

Just declare the variable at the starting of a class.

e.g. for string variable:

public partial class Login : System.Web.UI.Page
{
    public string sError;

    protected void Page_Load(object sender, EventArgs e)
    {
         //Page Load Code
    }

Java regex to extract text between tags

    final Pattern pattern = Pattern.compile("tag\\](.+?)\\[/tag");
    final Matcher matcher = pattern.matcher("[tag]String I want to extract[/tag]");
    matcher.find();
    System.out.println(matcher.group(1));

Excel VBA Run-time error '13' Type mismatch

You would get a type mismatch if Sheets(name).Cells(4 + i, 57) contains a non-numeric value. You should validate the fields before you assume they are numbers and try to subtract from them.

Also, you should enable Option Strict so you are forced to explicitly convert your variables before trying to perform type-dependent operations on them such as subtraction. That will help you identify and eliminate issues in the future, too.    Unfortunately Option Strict is for VB.NET only. Still, you should look up best practices for explicit data type conversions in VBA.


Update:

If you are trying to go for the quick fix of your code, however, wrap the ** line and the one following it in the following condition:

If IsNumeric(Sheets(name).Cells(4 + i, 57))
    Sheets(name).Cells(4 + i, 58) = Sheets(name).Cells(4 + i, 57) - a
    x = Sheets(name).Cells(4 + i, 57) - a
End If

Note that your x value may not contain its expected value in the next iteration, however.

Gson: How to exclude specific fields from Serialization without annotations

Another approach (especially useful if you need to make a decision to exclude a field at runtime) is to register a TypeAdapter with your gson instance. Example below:

Gson gson = new GsonBuilder()
.registerTypeAdapter(BloodPressurePost.class, new BloodPressurePostSerializer())

In the case below, the server would expect one of two values but since they were both ints then gson would serialize them both. My goal was to omit any value that is zero (or less) from the json that is posted to the server.

public class BloodPressurePostSerializer implements JsonSerializer<BloodPressurePost> {

    @Override
    public JsonElement serialize(BloodPressurePost src, Type typeOfSrc, JsonSerializationContext context) {
        final JsonObject jsonObject = new JsonObject();

        if (src.systolic > 0) {
            jsonObject.addProperty("systolic", src.systolic);
        }

        if (src.diastolic > 0) {
            jsonObject.addProperty("diastolic", src.diastolic);
        }

        jsonObject.addProperty("units", src.units);

        return jsonObject;
    }
}

contenteditable change events

Here is a more efficient version which uses on for all contenteditables. It's based off the top answers here.

$('body').on('focus', '[contenteditable]', function() {
    const $this = $(this);
    $this.data('before', $this.html());
}).on('blur keyup paste input', '[contenteditable]', function() {
    const $this = $(this);
    if ($this.data('before') !== $this.html()) {
        $this.data('before', $this.html());
        $this.trigger('change');
    }
});

The project is here: https://github.com/balupton/html5edit

CSS submit button weird rendering on iPad/iPhone

The above answer for webkit appearance worked, but the button still looked kind pale/dull compared to the browser on other devices/desktop. I also had to set opacity to full (ranges from 0 to 1)

-webkit-appearance:none;
opacity: 1

After setting the opacity, the button looked the same on all the different devices/emulator/desktop.

PowerShell To Set Folder Permissions

Specifying inheritance in the FileSystemAccessRule() constructor fixes this, as demonstrated by the modified code below (notice the two new constuctor parameters inserted between "FullControl" and "Allow").

$Acl = Get-Acl "\\R9N2WRN\Share"

$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("user", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")

$Acl.SetAccessRule($Ar)
Set-Acl "\\R9N2WRN\Share" $Acl

According to this topic

"when you create a FileSystemAccessRule the way you have, the InheritanceFlags property is set to None. In the GUI, this corresponds to an ACE with the Apply To box set to "This Folder Only", and that type of entry has to be viewed through the Advanced settings."

I have tested the modification and it works, but of course credit is due to the MVP posting the answer in that topic.

How to put labels over geom_bar in R with ggplot2

To plot text on a ggplot you use the geom_text. But I find it helpful to summarise the data first using ddply

dfl <- ddply(df, .(x), summarize, y=length(x))
str(dfl)

Since the data is pre-summarized, you need to remember to change add the stat="identity" parameter to geom_bar:

ggplot(dfl, aes(x, y=y, fill=x)) + geom_bar(stat="identity") +
    geom_text(aes(label=y), vjust=0) +
    opts(axis.text.x=theme_blank(),
        axis.ticks=theme_blank(),
        axis.title.x=theme_blank(),
        legend.title=theme_blank(),
        axis.title.y=theme_blank()
)

enter image description here

in a "using" block is a SqlConnection closed on return or exception?

Dispose simply gets called when you leave the scope of using. The intention of "using" is to give developers a guaranteed way to make sure that resources get disposed.

From MSDN:

A using statement can be exited either when the end of the using statement is reached or if an exception is thrown and control leaves the statement block before the end of the statement.

SQLite - UPSERT *not* INSERT or REPLACE

Expanding on Aristotle’s answer you can SELECT from a dummy 'singleton' table (a table of your own creation with a single row). This avoids some duplication.

I've also kept the example portable across MySQL and SQLite and used a 'date_added' column as an example of how you could set a column only the first time.

 REPLACE INTO page (
   id,
   name,
   title,
   content,
   author,
   date_added)
 SELECT
   old.id,
   "about",
   "About this site",
   old.content,
   42,
   IFNULL(old.date_added,"21/05/2013")
 FROM singleton
 LEFT JOIN page AS old ON old.name = "about";

Python error: TypeError: 'module' object is not callable for HeadFirst Python code

You module and class AthleteList have the same name. Change:

import AthleteList

to:

from AthleteList import AthleteList

This now means that you are importing the module object and will not be able to access any module methods you have in AthleteList

Create a simple Login page using eclipse and mysql

use this code it is working

// index.jsp or login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="login" method="post">
Username : <input type="text" name="username"><br>
Password : <input type="password" name="pass"><br>
<input type="submit"><br>
</form>

</body>
</html>

// authentication servlet class

    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    public class auth extends HttpServlet {
        private static final long serialVersionUID = 1L;

        public auth() {
            super();
        }
        protected void doGet(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {

        }

        protected void doPost(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {

            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

            String username = request.getParameter("username");
            String pass = request.getParameter("pass");

            String sql = "select * from reg where username='" + username + "'";
            Connection conn = null;

            try {
                conn = DriverManager.getConnection("jdbc:mysql://localhost/Exam",
                        "root", "");
                Statement s = conn.createStatement();

                java.sql.ResultSet rs = s.executeQuery(sql);
                String un = null;
                String pw = null;
                String name = null;

            /* Need to put some condition in case the above query does not return any row, else code will throw Null Pointer exception */   

            PrintWriter prwr1 = response.getWriter();               
            if(!rs.isBeforeFirst()){
                prwr1.write("<h1> No Such User in Database<h1>");
            } else {

/* Conditions to be executed after at least one row is returned by query execution */ 
                while (rs.next()) {
                    un = rs.getString("username");
                    pw = rs.getString("password");
                    name = rs.getString("name");
                }

                PrintWriter pww = response.getWriter();

                if (un.equalsIgnoreCase(username) && pw.equals(pass)) {
                                // use this or create request dispatcher 
                    response.setContentType("text/html");
                    pww.write("<h1>Welcome, " + name + "</h1>");
                } else {
                    pww.write("wrong username or password\n");
                }
              }

            } catch (SQLException e) {
                e.printStackTrace();
            }

        }

    }

mysql stored-procedure: out parameter

try changing OUT to INOUT for your out_number parameter definition.

CREATE PROCEDURE my_sqrt(input_number INT, INOUT out_number FLOAT)

INOUT means that the input variable for out_number (@out_value in your case.) will also serve as the output variable from which you can select the value from.

Transform DateTime into simple Date in Ruby on Rails

In Ruby 1.9.2 and above they added a .to_date function to DateTime:

http://ruby-doc.org/stdlib-1.9.2/libdoc/date/rdoc/DateTime.html#method-i-to_date

This instance method doesn't appear to be present in earlier versions like 1.8.7.

Making a <button> that's a link in HTML

_x000D_
_x000D_
<a id="reset-authenticator" asp-page="./ResetAuthenticator"><input type="button" class="btn btn-primary" value="Reset app" /></a>
_x000D_
_x000D_
_x000D_

Convert Word doc, docx and Excel xls, xlsx to PDF with PHP

Anyone who is looking to do this in Ubuntu/linux using php -

Ubuntu comes with libre office installed default. Anyone can use the shell command to use the headless libre office for this.

shell_exec('/usr/bin/libreoffice --headless --convert-to pdf:writer_pdf_Export --outdir /var/www/html/demo/public_html/src/var/output /var/www/html/demo/public_html/src/var/source/sample.doc');

Hope it helps others like me.

How to find out if a Python object is a string?

isinstance(your_object, basestring)

will be True if your object is indeed a string-type. 'str' is reserved word.

my apologies, the correct answer is using 'basestring' instead of 'str' in order of it to include unicode strings as well - as been noted above by one of the other responders.

How do detect Android Tablets in general. Useragent?

Based on Agents strings on this site:

http://www.webapps-online.com/online-tools/user-agent-strings

This results came up:
First:

All Tablet Devices have:
1. Tablet
2. iPad

Second:

All Phone Devices have:
1. Mobile
2. Phone

Third:

Tablet and Phone Devices have:
1. Android

If you can detect level by level, I thing the result is 90 percent true. Like SharePoint Device Channels.

How to compile .c file with OpenSSL includes?

Use the -I flag to gcc properly.

gcc -I/path/to/openssl/ -o Opentest -lcrypto Opentest.c

The -I should point to the directory containing the openssl folder.

Android Google Maps v2 - set zoom level for myLocation

Location locaton;
double latitude = location.getlatitude;
double longitude = location.getlongitude;

If you want to save the zoom or get it all the time,you just need to call the following

int zoom = mMap.getCameraPosition().zoom;

//To set that just use

mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(getlatitude(), getlongitude),zoom);

How to run Spring Boot web application in Eclipse itself?

You can also use the "Spring Boot App" run configuration. For that you'll need to install the Spring Tool Suite plug-in for Eclipse (STS).

PDO get the last ID inserted

That's because that's an SQL function, not PHP. You can use PDO::lastInsertId().

Like:

$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();

If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:

$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();

After installing SQL Server 2014 Express can't find local db

Also, if you just installed localDB, you won't see the instance in the configuration manager. You would need to initiate it first, and then connect to it using server name (localdb)\mssqllocaldb. Source

Regex how to match an optional character

You can make the single letter optional by adding a ? after it as:

([A-Z]{1}?)

The quantifier {1} is redundant so you can drop it.

LINQ's Distinct() on a particular property

EDIT: This is now part of MoreLINQ.

What you need is a "distinct-by" effectively. I don't believe it's part of LINQ as it stands, although it's fairly easy to write:

public static IEnumerable<TSource> DistinctBy<TSource, TKey>
    (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
    HashSet<TKey> seenKeys = new HashSet<TKey>();
    foreach (TSource element in source)
    {
        if (seenKeys.Add(keySelector(element)))
        {
            yield return element;
        }
    }
}

So to find the distinct values using just the Id property, you could use:

var query = people.DistinctBy(p => p.Id);

And to use multiple properties, you can use anonymous types, which implement equality appropriately:

var query = people.DistinctBy(p => new { p.Id, p.Name });

Untested, but it should work (and it now at least compiles).

It assumes the default comparer for the keys though - if you want to pass in an equality comparer, just pass it on to the HashSet constructor.

.append(), prepend(), .after() and .before()

append() & prepend() are for inserting content inside an element (making the content its child) while after() & before() insert content outside an element (making the content its sibling).

Get the position of a spinner in Android

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt = findViewById(R.id.button);
        spinner = findViewById(R.id.sp_item);
        setInfo();
        spinnerAdapter = new SpinnerAdapter(this, arrayList);
        spinner.setAdapter(spinnerAdapter);



        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //first,  we have to retrieve the item position as a string
                // then, we can change string value into integer
                String item_position = String.valueOf(position);

                int positonInt = Integer.valueOf(item_position);

                Toast.makeText(MainActivity.this, "value is "+ positonInt, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });







note: the position of items is counted from 0.

Public class is inaccessible due to its protection level

You could go into the designer of the web form and change the "webcontrols" to be "public" instead of "protected" but I'm not sure how safe that is. I prefer to make hidden inputs and have some jQuery set the values into those hidden inputs, then create public properties in the web form's class (code behind), and access the values that way.

Spring: How to get parameters from POST body?

You can try using @RequestBodyParam

@RequestMapping(value = "/saveData", headers="Content-Type=application/json", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Boolean> saveData(@RequestBodyParam String source,@RequestBodyParam JsonDto json) throws MyException {
    ...
}

https://github.com/LambdaExpression/RequestBodyParam

Grant all on a specific schema in the db to a group role in PostgreSQL

My answer is similar to this one on ServerFault.com.

To Be Conservative

If you want to be more conservative than granting "all privileges", you might want to try something more like these.

GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO some_user_;
GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO some_user_;

The use of public there refers to the name of the default schema created for every new database/catalog. Replace with your own name if you created a schema.

Access to the Schema

To access a schema at all, for any action, the user must be granted "usage" rights. Before a user can select, insert, update, or delete, a user must first be granted "usage" to a schema.

You will not notice this requirement when first using Postgres. By default every database has a first schema named public. And every user by default has been automatically been granted "usage" rights to that particular schema. When adding additional schema, then you must explicitly grant usage rights.

GRANT USAGE ON SCHEMA some_schema_ TO some_user_ ;

Excerpt from the Postgres doc:

For schemas, allows access to objects contained in the specified schema (assuming that the objects' own privilege requirements are also met). Essentially this allows the grantee to "look up" objects within the schema. Without this permission, it is still possible to see the object names, e.g. by querying the system tables. Also, after revoking this permission, existing backends might have statements that have previously performed this lookup, so this is not a completely secure way to prevent object access.

For more discussion see the Question, What GRANT USAGE ON SCHEMA exactly do?. Pay special attention to the Answer by Postgres expert Craig Ringer.

Existing Objects Versus Future

These commands only affect existing objects. Tables and such you create in the future get default privileges until you re-execute those lines above. See the other answer by Erwin Brandstetter to change the defaults thereby affecting future objects.

"Stack overflow in line 0" on Internet Explorer

You can turn off the "Disable Script Debugging" option inside of Internet Explorer and start debugging with Visual Studio if you happen to have that around.

I've found that it is one of few ways to diagnose some of those IE specific issues.

Understanding ibeacon distancing

The distance estimate provided by iOS is based on the ratio of the beacon signal strength (rssi) over the calibrated transmitter power (txPower). The txPower is the known measured signal strength in rssi at 1 meter away. Each beacon must be calibrated with this txPower value to allow accurate distance estimates.

While the distance estimates are useful, they are not perfect, and require that you control for other variables. Be sure you read up on the complexities and limitations before misusing this.

When we were building the Android iBeacon library, we had to come up with our own independent algorithm because the iOS CoreLocation source code is not available. We measured a bunch of rssi measurements at known distances, then did a best fit curve to match our data points. The algorithm we came up with is shown below as Java code.

Note that the term "accuracy" here is iOS speak for distance in meters. This formula isn't perfect, but it roughly approximates what iOS does.

protected static double calculateAccuracy(int txPower, double rssi) {
  if (rssi == 0) {
    return -1.0; // if we cannot determine accuracy, return -1.
  }

  double ratio = rssi*1.0/txPower;
  if (ratio < 1.0) {
    return Math.pow(ratio,10);
  }
  else {
    double accuracy =  (0.89976)*Math.pow(ratio,7.7095) + 0.111;    
    return accuracy;
  }
}   

Note: The values 0.89976, 7.7095 and 0.111 are the three constants calculated when solving for a best fit curve to our measured data points. YMMV

C# Inserting Data from a form into an access Database

My Code to insert data is not working. It showing no error but data is not showing in my database.

public partial class Form1 : Form { OleDbConnection connection = new OleDbConnection(check.Properties.Settings.Default.KitchenConnectionString); public Form1() { InitializeComponent(); }

    private void Form1_Load(object sender, EventArgs e)
    {
        
    }

    private void btn_add_Click(object sender, EventArgs e)
    {
        OleDbDataAdapter items = new OleDbDataAdapter();
        connection.Open();
        OleDbCommand command = new OleDbCommand("insert into Sets(SetId, SetName,  SetPassword) values('"+txt_id.Text+ "','" + txt_setname.Text + "','" + txt_password.Text + "');", connection);
        command.CommandType = CommandType.Text;
        command.ExecuteReader();
        connection.Close();
        MessageBox.Show("Insertd!");
    }
}

How to dynamically change header based on AngularJS partial view?

jkoreska's solution is perfect if you know the titles before hand, but you may need to set the title based on data you get from a resource etc.

My solution requires a single service. Since the rootScope is the base of all DOM elements, we don't need to put a controller on the html element like someone mentioned

Page.js

app.service('Page', function($rootScope){
    return {
        setTitle: function(title){
            $rootScope.title = title;
        }
    }
});

index.jade

doctype html
html(ng-app='app')
head
    title(ng-bind='title')
// ...

All controllers that need to change title

app.controller('SomeController', function(Page){
    Page.setTitle("Some Title");
});

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

I used to have this problem sometimes, the solution was to change the USB cable to a new one

Getting and removing the first character of a string

See ?substring.

x <- 'hello stackoverflow'
substring(x, 1, 1)
## [1] "h"
substring(x, 2)
## [1] "ello stackoverflow"

The idea of having a pop method that both returns a value and has a side effect of updating the data stored in x is very much a concept from object-oriented programming. So rather than defining a pop function to operate on character vectors, we can make a reference class with a pop method.

PopStringFactory <- setRefClass(
  "PopString",
  fields = list(
    x = "character"  
  ),
  methods = list(
    initialize = function(x)
    {
      x <<- x
    },
    pop = function(n = 1)
    {
      if(nchar(x) == 0)
      {
        warning("Nothing to pop.")
        return("")
      }
      first <- substring(x, 1, n)
      x <<- substring(x, n + 1)
      first
    }
  )
)

x <- PopStringFactory$new("hello stackoverflow")
x
## Reference class object of class "PopString"
## Field "x":
## [1] "hello stackoverflow"
replicate(nchar(x$x), x$pop())
## [1] "h" "e" "l" "l" "o" " " "s" "t" "a" "c" "k" "o" "v" "e" "r" "f" "l" "o" "w"

Disabled form fields not submitting data

Use the CSS pointer-events:none on fields you want to "disable" (possibly together with a greyed background) which allows the POST action, like:

<input type="text" class="disable">

.disable{
pointer-events:none;
background:grey;
}

Ref: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events

How to create a notification with NotificationCompat.Builder?

Working example:

    Intent intent = new Intent(ctx, HomeActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder b = new NotificationCompat.Builder(ctx);

    b.setAutoCancel(true)
     .setDefaults(Notification.DEFAULT_ALL)
     .setWhen(System.currentTimeMillis())         
     .setSmallIcon(R.drawable.ic_launcher)
     .setTicker("Hearty365")            
     .setContentTitle("Default notification")
     .setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
     .setDefaults(Notification.DEFAULT_LIGHTS| Notification.DEFAULT_SOUND)
     .setContentIntent(contentIntent)
     .setContentInfo("Info");


    NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(1, b.build());

Using client certificate in Curl command

TLS client certificates are not sent in HTTP headers. They are transmitted by the client as part of the TLS handshake, and the server will typically check the validity of the certificate during the handshake as well.

If the certificate is accepted, most web servers can be configured to add headers for transmitting the certificate or information contained on the certificate to the application. Environment variables are populated with certificate information in Apache and Nginx which can be used in other directives for setting headers.

As an example of this approach, the following Nginx config snippet will validate a client certificate, and then set the SSL_CLIENT_CERT header to pass the entire certificate to the application. This will only be set when then certificate was successfully validated, so the application can then parse the certificate and rely on the information it bears.

server {
    listen 443 ssl;
    server_name example.com;
    ssl_certificate /path/to/chainedcert.pem;  # server certificate
    ssl_certificate_key /path/to/key;          # server key

    ssl_client_certificate /path/to/ca.pem;    # client CA
    ssl_verify_client on;
    proxy_set_header SSL_CLIENT_CERT $ssl_client_cert;

    location / {
        proxy_pass http://localhost:3000;
    }
}

How to configure port for a Spring Boot application

By default, spring-web module provides an embedded tomcat server that is running under the port number 8080. If you need to change the port number of the application then go to application.properties file and configure the port number by using server.port property.

  server.port= 9876

then your application is running under the port 9876.

Concat all strings inside a List<string> using LINQ

using System.Linq;

public class Person
{
  string FirstName { get; set; }
  string LastName { get; set; }
}

List<Person> persons = new List<Person>();

string listOfPersons = string.Join(",", persons.Select(p => p.FirstName));

How to remove gem from Ruby on Rails application?

You are using some sort of revision control, right? Then it should be quite simple to restore to the commit before you added the gem, or revert the one where you added it if you have several revisions after that you wish to keep.

ASP.NET MVC Html.ValidationSummary(true) does not display model errors

You can try,

<div asp-validation-summary="All" class="text-danger"></div>

Asp.Net MVC with Drop Down List, and SelectListItem Assistance

Step-1: Your Model class

public class RechargeMobileViewModel
    {
        public string CustomerFullName { get; set; }
        public string TelecomSubscriber { get; set; }
        public int TotalAmount { get; set; }
        public string MobileNumber { get; set; }
        public int Month { get; set; }
        public List<SelectListItem> getAllDaysList { get; set; }

        // Define the list which you have to show in Drop down List
        public List<SelectListItem> getAllWeekDaysList()
        {
            List<SelectListItem> myList = new List<SelectListItem>();
            var data = new[]{
                 new SelectListItem{ Value="1",Text="Monday"},
                 new SelectListItem{ Value="2",Text="Tuesday"},
                 new SelectListItem{ Value="3",Text="Wednesday"},
                 new SelectListItem{ Value="4",Text="Thrusday"},
                 new SelectListItem{ Value="5",Text="Friday"},
                 new SelectListItem{ Value="6",Text="Saturday"},
                 new SelectListItem{ Value="7",Text="Sunday"},
             };
            myList = data.ToList();
            return myList;
        }
}

Step-2: Call this method to fill Drop down in your controller Action

namespace MvcVariousApplication.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
              RechargeMobileViewModel objModel = new RechargeMobileViewModel();
                objModel.getAllDaysList = objModel.getAllWeekDaysList();  
                return View(objModel);
            }
    }
    }

Step-3: Fill your Drop-Down List of View as follows

 @model MvcVariousApplication.Models.RechargeMobileViewModel
    @{
        ViewBag.Title = "Contact";
    }
    @Html.LabelFor(model=> model.CustomerFullName)
    @Html.TextBoxFor(model => model.CustomerFullName)

    @Html.LabelFor(model => model.MobileNumber)
    @Html.TextBoxFor(model => model.MobileNumber)

    @Html.LabelFor(model => model.TelecomSubscriber)
    @Html.TextBoxFor(model => model.TelecomSubscriber)

    @Html.LabelFor(model => model.TotalAmount)
    @Html.TextBoxFor(model => model.TotalAmount)

    @Html.LabelFor(model => model.Month)
    @Html.DropDownListFor(model => model.Month, new SelectList(Model.getAllDaysList, "Value", "Text"), "-Select Day-")

Split Java String by New Line

As an alternative to the previous answers, guava's Splitter API can be used if other operations are to be applied to the resulting lines, like trimming lines or filtering empty lines :

import com.google.common.base.Splitter;

Iterable<String> split = Splitter.onPattern("\r?\n").trimResults().omitEmptyStrings().split(docStr);

Note that the result is an Iterable and not an array.

How can I pass arguments to a batch file?

There is no need to complicate it. It is simply command %1 %2 parameters, for example,

@echo off

xcopy %1 %2 /D /E /C /Q /H /R /K /Y /Z

echo copied %1 to %2

pause

The "pause" displays what the batch file has done and waits for you to hit the ANY key. Save that as xx.bat in the Windows folder.

To use it, type, for example:

xx c:\f\30\*.* f:\sites\30

This batch file takes care of all the necessary parameters, like copying only files, that are newer, etc. I have used it since before Windows. If you like seeing the names of the files, as they are being copied, leave out the Q parameter.

Is it possible to simulate key press events programmatically?

The critical part of getting this to work is to realize that charCode, keyCode and which are all deprecated methods. Therefore if the code processing the key press event uses any of these three, then it'll receive a bogus answer (e.g. a default of 0).

As long as you access the key press event with a non-deprecated method, such as key, you should be OK.

For completion, I've added the basic Javascript code for triggering the event:

_x000D_
_x000D_
const rightArrowKey = 39
const event = new KeyboardEvent('keydown',{'key':rightArrowKey})
document.dispatchEvent(event)
_x000D_
_x000D_
_x000D_

UITapGestureRecognizer - single tap and double tap

Swift 3 solution:

let singleTap = UITapGestureRecognizer(target: self, action:#selector(self.singleTapAction(_:)))
singleTap.numberOfTapsRequired = 1
view.addGestureRecognizer(singleTap)

let doubleTap = UITapGestureRecognizer(target: self, action:#selector(self.doubleTapAction(_:)))
doubleTap.numberOfTapsRequired = 2
view.addGestureRecognizer(doubleTap)

singleTap.require(toFail: doubleTap)

In the code line singleTap.require(toFail: doubleTap) we are forcing the single tap to wait and ensure that the tap event is not a double tap.

What's the best way to store co-ordinates (longitude/latitude, from Google Maps) in SQL Server?

The way I do it: I store the latitude and longitude and then I have a third column which is a automatic derived geography type of the 1st two columns. The table looks like this:

CREATE TABLE [dbo].[Geopoint]
(
    [GeopointId] BIGINT NOT NULL PRIMARY KEY IDENTITY, 
    [Latitude] float NOT NULL, 
    [Longitude] float NOT NULL, 
    [ts] ROWVERSION NOT NULL, 
    [GeographyPoint]  AS ([geography]::STGeomFromText(((('POINT('+CONVERT([varchar](20),[Longitude]))+' ')+CONVERT([varchar](20),[Latitude]))+')',(4326))) 
)

This gives you the flexibility of spatial queries on the geoPoint column and you can also retrieve the latitude and longitude values as you need them for display or extracting for csv purposes.

Read Post Data submitted to ASP.Net Form

NameValueCollection nvclc = Request.Form;
string   uName= nvclc ["txtUserName"];
string   pswod= nvclc ["txtPassword"];
//try login
CheckLogin(uName, pswod);

How best to determine if an argument is not sent to the JavaScript function

There are significant differences. Let's set up some test cases:

var unused; // value will be undefined
Test("test1", "some value");
Test("test2");
Test("test3", unused);
Test("test4", null);
Test("test5", 0);
Test("test6", "");

With the first method you describe, only the second test will use the default value. The second method will default all but the first (as JS will convert undefined, null, 0, and "" into the boolean false. And if you were to use Tom's method, only the fourth test will use the default!

Which method you choose really depends on your intended behavior. If values other than undefined are allowable for argument2, then you'll probably want some variation on the first; if a non-zero, non-null, non-empty value is desired, then the second method is ideal - indeed, it is often used to quickly eliminate such a wide range of values from consideration.

What is the Java equivalent for LINQ?

Not really a "Linq to SQL" equivalent for Java. but something close to it . Query DSL

How to test if list element exists?

Here is a performance comparison of the proposed methods in other answers.

> foo <- sapply(letters, function(x){runif(5)}, simplify = FALSE)
> microbenchmark::microbenchmark('k' %in% names(foo), 
                                 is.null(foo[['k']]), 
                                 exists('k', where = foo))
Unit: nanoseconds
                     expr  min   lq    mean median   uq   max neval cld
      "k" %in% names(foo)  467  933 1064.31    934  934 10730   100  a 
      is.null(foo[["k"]])    0    0  168.50      1  467  3266   100  a 
 exists("k", where = foo) 6532 6998 7940.78   7232 7465 56917   100   b

If you are planing to use the list as a fast dictionary accessed many times, then the is.null approach might be the only viable option. I assume it is O(1), while the %in% approach is O(n)?

Checking for empty result (php, pdo, mysql)

$sql = $dbh->prepare("SELECT * from member WHERE member_email = '$username' AND member_password = '$password'");

$sql->execute();

$fetch = $sql->fetch(PDO::FETCH_ASSOC);

// if not empty result
if (is_array($fetch))  {
    $_SESSION["userMember"] = $fetch["username"];
    $_SESSION["password"] = $fetch["password"];
    echo 'yes this member is registered'; 
}else {
    echo 'empty result!';
}

How to play .wav files with java

You can use an event listener to close the clip after it is played

import java.io.File;
import javax.sound.sampled.*;

public void play(File file) 
{
    try
    {
        final Clip clip = (Clip)AudioSystem.getLine(new Line.Info(Clip.class));

        clip.addLineListener(new LineListener()
        {
            @Override
            public void update(LineEvent event)
            {
                if (event.getType() == LineEvent.Type.STOP)
                    clip.close();
            }
        });

        clip.open(AudioSystem.getAudioInputStream(file));
        clip.start();
    }
    catch (Exception exc)
    {
        exc.printStackTrace(System.out);
    }
}

LDAP root query syntax to search more than one specific OU

You can!!! In short use this as the connection string:

ldap://<host>:3268/DC=<my>,DC=<domain>?cn

together with your search filter, e.g.

(&(sAMAccountName={0})(&((objectCategory=person)(objectclass=user)(mail=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(memberOf:1.2.840.113556.1.4.1941:=CN=<some-special-nested-group>,OU=<ou3>,OU=<ou2>,OU=<ou1>,DC=<dc3>,DC=<dc2>,DC=<dc1>))))

That will search in the so called Global Catalog, that had been available out-of-the-box in our environment.

Instead of the known/common other versions (or combinations thereof) that did NOT work in our environment with multiple OUs:

ldap://<host>/DC=<my>,DC=<domain>
ldap://<host>:389/DC=<my>,DC=<domain>  (standard port)
ldap://<host>/OU=<someOU>,DC=<my>,DC=<domain>
ldap://<host>/CN=<someCN>,DC=<my>,DC=<domain>
ldap://<host>/(|(OU=<someOU1>)(OU=<someOU2>)),DC=<my>,DC=<domain> (search filters here shouldn't work at all by definition)

(I am a developer, not an AD/LDAP guru:) Damn I had been searching for this solution everywhere for almost 2 days and almost gave up, getting used to the thought I might have to implement this obviously very common scenario by hand (with Jasperserver/Spring security(/Tomcat)). (So this shall be a reminder if somebody else or me should have this problem again in the future :O) )

Here some other related threads I found during my research that had been mostly of little help:

And here I will provide our anonymized Tomcat LDAP config in case it may be helpful (/var/lib/tomcat7/webapps/jasperserver/WEB-INF/applicationContext-externalAUTH-LDAP.xml):

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

<!-- ############ LDAP authentication ############ - Sample configuration 
    of external authentication via an external LDAP server. -->


<bean id="proxyAuthenticationProcessingFilter"
    class="com.jaspersoft.jasperserver.api.security.externalAuth.BaseAuthenticationProcessingFilter">
    <property name="authenticationManager">
        <ref local="ldapAuthenticationManager" />
    </property>
    <property name="externalDataSynchronizer">
        <ref local="externalDataSynchronizer" />
    </property>

    <property name="sessionRegistry">
        <ref bean="sessionRegistry" />
    </property>

    <property name="internalAuthenticationFailureUrl" value="/login.html?error=1" />
    <property name="defaultTargetUrl" value="/loginsuccess.html" />
    <property name="invalidateSessionOnSuccessfulAuthentication"
        value="true" />
    <property name="migrateInvalidatedSessionAttributes" value="true" />
</bean>

<bean id="proxyAuthenticationSoapProcessingFilter"
    class="com.jaspersoft.jasperserver.api.security.externalAuth.DefaultAuthenticationSoapProcessingFilter">
    <property name="authenticationManager" ref="ldapAuthenticationManager" />
    <property name="externalDataSynchronizer" ref="externalDataSynchronizer" />

    <property name="invalidateSessionOnSuccessfulAuthentication"
        value="true" />
    <property name="migrateInvalidatedSessionAttributes" value="true" />
    <property name="filterProcessesUrl" value="/services" />
</bean>

<bean id="proxyRequestParameterAuthenticationFilter"
    class="com.jaspersoft.jasperserver.war.util.ExternalRequestParameterAuthenticationFilter">
    <property name="authenticationManager">
        <ref local="ldapAuthenticationManager" />
    </property>
    <property name="externalDataSynchronizer" ref="externalDataSynchronizer" />

    <property name="authenticationFailureUrl">
        <value>/login.html?error=1</value>
    </property>
    <property name="excludeUrls">
        <list>
            <value>/j_spring_switch_user</value>
        </list>
    </property>
</bean>

<bean id="proxyBasicProcessingFilter"
    class="com.jaspersoft.jasperserver.api.security.externalAuth.ExternalAuthBasicProcessingFilter">
    <property name="authenticationManager" ref="ldapAuthenticationManager" />
    <property name="externalDataSynchronizer" ref="externalDataSynchronizer" />

    <property name="authenticationEntryPoint">
        <ref local="basicProcessingFilterEntryPoint" />
    </property>
</bean>

<bean id="proxyAuthenticationRestProcessingFilter"
    class="com.jaspersoft.jasperserver.api.security.externalAuth.DefaultAuthenticationRestProcessingFilter">
    <property name="authenticationManager">
        <ref local="ldapAuthenticationManager" />
    </property>
    <property name="externalDataSynchronizer">
        <ref local="externalDataSynchronizer" />
    </property>

    <property name="filterProcessesUrl" value="/rest/login" />
    <property name="invalidateSessionOnSuccessfulAuthentication"
        value="true" />
    <property name="migrateInvalidatedSessionAttributes" value="true" />
</bean>



<bean id="ldapAuthenticationManager" class="org.springframework.security.providers.ProviderManager">
    <property name="providers">
        <list>
            <ref local="ldapAuthenticationProvider" />
            <ref bean="${bean.daoAuthenticationProvider}" />
            <!--anonymousAuthenticationProvider only needed if filterInvocationInterceptor.alwaysReauthenticate 
                is set to true <ref bean="anonymousAuthenticationProvider"/> -->
        </list>
    </property>
</bean>

<bean id="ldapAuthenticationProvider"
    class="org.springframework.security.providers.ldap.LdapAuthenticationProvider">
    <constructor-arg>
        <bean
            class="org.springframework.security.providers.ldap.authenticator.BindAuthenticator">
            <constructor-arg>
                <ref local="ldapContextSource" />
            </constructor-arg>
            <property name="userSearch" ref="userSearch" />
        </bean>
    </constructor-arg>
    <constructor-arg>
        <bean
            class="org.springframework.security.ldap.populator.DefaultLdapAuthoritiesPopulator">
            <constructor-arg index="0">
                <ref local="ldapContextSource" />
            </constructor-arg>
            <constructor-arg index="1">
                <value></value>
            </constructor-arg>

            <property name="groupRoleAttribute" value="cn" />
            <property name="convertToUpperCase" value="true" />
            <property name="rolePrefix" value="ROLE_" />
            <property name="groupSearchFilter"
                value="(&amp;(member={0})(&amp;(objectCategory=Group)(objectclass=group)(cn=my-nested-group-name)))" />
            <property name="searchSubtree" value="true" />
            <!-- Can setup additional external default roles here <property name="defaultRole" 
                value="LDAP"/> -->
        </bean>
    </constructor-arg>
</bean>

<bean id="userSearch"
    class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch">
    <constructor-arg index="0">
        <value></value>
    </constructor-arg>
    <constructor-arg index="1">
        <value>(&amp;(sAMAccountName={0})(&amp;((objectCategory=person)(objectclass=user)(mail=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(memberOf:1.2.840.113556.1.4.1941:=CN=my-nested-group-name,OU=ou3,OU=ou2,OU=ou1,DC=dc3,DC=dc2,DC=dc1))))
        </value>
    </constructor-arg>
    <constructor-arg index="2">
        <ref local="ldapContextSource" />
    </constructor-arg>
    <property name="searchSubtree">
        <value>true</value>
    </property>
</bean>

<bean id="ldapContextSource"
    class="com.jaspersoft.jasperserver.api.security.externalAuth.ldap.JSLdapContextSource">
    <constructor-arg value="ldap://myhost:3268/DC=dc3,DC=dc2,DC=dc1?cn" />
    <!-- manager user name and password (may not be needed) -->
    <property name="userDn" value="CN=someuser,OU=ou4,OU=1,DC=dc3,DC=dc2,DC=dc1" />
    <property name="password" value="somepass" />
    <!--End Changes -->
</bean>
<!-- ############ LDAP authentication ############ -->

<!-- ############ JRS Synchronizer ############ -->
<bean id="externalDataSynchronizer"
    class="com.jaspersoft.jasperserver.api.security.externalAuth.ExternalDataSynchronizerImpl">
    <property name="externalUserProcessors">
        <list>
            <ref local="externalUserSetupProcessor" />
            <!-- Example processor for creating user folder -->
            <!--<ref local="externalUserFolderProcessor"/> -->
        </list>
    </property>
</bean>

<bean id="abstractExternalProcessor"
    class="com.jaspersoft.jasperserver.api.security.externalAuth.processors.AbstractExternalUserProcessor"
    abstract="true">
    <property name="repositoryService" ref="${bean.repositoryService}" />
    <property name="userAuthorityService" ref="${bean.userAuthorityService}" />
    <property name="tenantService" ref="${bean.tenantService}" />
    <property name="profileAttributeService" ref="profileAttributeService" />
    <property name="objectPermissionService" ref="objectPermissionService" />
</bean>

<bean id="externalUserSetupProcessor"
    class="com.jaspersoft.jasperserver.api.security.externalAuth.processors.ExternalUserSetupProcessor"
    parent="abstractExternalProcessor">
    <property name="userAuthorityService">
        <ref bean="${bean.internalUserAuthorityService}" />
    </property>
    <property name="defaultInternalRoles">
        <list>
            <value>ROLE_USER</value>
        </list>
    </property>

    <property name="organizationRoleMap">
        <map>
            <!-- Example of mapping customer roles to JRS roles -->
            <entry>
                <key>
                    <value>ROLE_MY-NESTED-GROUP-NAME</value>
                </key>
                <!-- JRS role that the <key> external role is mapped to -->
                <value>ROLE_USER</value>
            </entry>
        </map>
    </property>
</bean>

<!--bean id="externalUserFolderProcessor" class="com.jaspersoft.jasperserver.api.security.externalAuth.processors.ExternalUserFolderProcessor" 
    parent="abstractExternalProcessor"> <property name="repositoryService" ref="${bean.unsecureRepositoryService}"/> 
    </bean -->

<!-- ############ JRS Synchronizer ############ -->

Why does make think the target is up to date?

my mistake was making the target name "filename.c:" instead of just "filename:"

HTML email in outlook table width issue - content is wider than the specified table width

I guess problem is in width attributes in table and td remove 'px' for example

<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">

Should be

<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">

Vue.js getting an element within a component

Composition API

Template refs section tells how this has been unified:

  • within template, use ref="myEl"; :ref= with a v-for
  • within script, have a const myEl = ref(null) and expose it from setup

The reference carries the DOM element from mounting onwards.

How can I check that JButton is pressed? If the isEnable() is not work?

Use this Command

if(JButton.getModel().isArmed()){
    //your code here.
    //your code will be only executed if JButton is clicked.
}

Answer is short. But it worked for me. Use the variable name of your button instead of "JButton".

php random x digit number

The following code generates a 4 digits random number:

echo sprintf( "%04d", rand(0,9999));

Error: Specified cast is not valid. (SqlManagerUI)

Sometimes it happens because of the version change like store 2012 db on 2008, so how to check it?

RESTORE VERIFYONLY FROM DISK = N'd:\yourbackup.bak'

if it gives error like:

Msg 3241, Level 16, State 13, Line 2 The media family on device 'd:\alibaba.bak' is incorrectly formed. SQL Server cannot process this media family. Msg 3013, Level 16, State 1, Line 2 VERIFY DATABASE is terminating abnormally.

Check it further:

RESTORE HEADERONLY FROM DISK = N'd:\yourbackup.bak'

BackupName is "* INCOMPLETE *", Position is "1", other fields are "NULL".

Means either your backup is corrupt or taken from newer version.

Differences between TCP sockets and web sockets, one more time

WebSocket is basically an application protocol (with reference to the ISO/OSI network stack), message-oriented, which makes use of TCP as transport layer.

The idea behind the WebSocket protocol consists of reusing the established TCP connection between a Client and Server. After the HTTP handshake the Client and Server start speaking WebSocket protocol by exchanging WebSocket envelopes. HTTP handshaking is used to overcome any barrier (e.g. firewalls) between a Client and a Server offering some services (usually port 80 is accessible from anywhere, by anyone). Client and Server can switch over speaking HTTP in any moment, making use of the same TCP connection (which is never released).

Behind the scenes WebSocket rebuilds the TCP frames in consistent envelopes/messages. The full-duplex channel is used by the Server to push updates towards the Client in an asynchronous way: the channel is open and the Client can call any futures/callbacks/promises to manage any asynchronous WebSocket received message.

To put it simply, WebSocket is a high level protocol (like HTTP itself) built on TCP (reliable transport layer, on per frame basis) that makes possible to build effective real-time application with JS Clients (previously Comet and long-polling techniques were used to pull updates from the Server before WebSockets were implemented. See Stackoverflow post: Differences between websockets and long polling for turn based game server ).

ViewDidAppear is not called when opening app from background

try adding this in AppDelegate applicationWillEnterForeground.

func applicationWillEnterForeground(_ application: UIApplication) {        
    // makes viewWillAppear run
    self.window?.rootViewController?.beginAppearanceTransition(true, animated: false)
    self.window?.rootViewController?.endAppearanceTransition()
}

How can I get all element values from Request.Form without specifying exactly which one with .GetValues("ElementIdName")

Here is a way to do it without adding an ID to the form elements.

<form method="post">
    ...
    <select name="List">
        <option value="1">Test1</option>
        <option value="2">Test2</option>
    </select>
    <select name="List">
        <option value="3">Test3</option>
        <option value="4">Test4</option>
    </select>
    ...
</form>

public ActionResult OrderProcessor()
{
    string[] ids = Request.Form.GetValues("List");
}

Then ids will contain all the selected option values from the select lists. Also, you could go down the Model Binder route like so:

public class OrderModel
{
    public string[] List { get; set; }
}

public ActionResult OrderProcessor(OrderModel model)
{
    string[] ids = model.List;
}

Hope this helps.

How to get File Created Date and Modified Date

You could use below code:

DateTime creation = File.GetCreationTime(@"C:\test.txt");
DateTime modification = File.GetLastWriteTime(@"C:\test.txt");

How to control border height?

A border will always be at the full length of the containing box (the height of the element plus its padding), it can't be controlled except for adjusting the height of the element to which it applies. If all you need is a vertical divider, you could use:

<div id="left">
  content
</div>
<span class="divider"></span>
<div id="right">
  content
</div>

With css:

span {
 display: inline-block;
 width: 0;
 height: 1em;
 border-left: 1px solid #ccc;
 border-right: 1px solid #ccc;
}

Demo at JS Fiddle, adjust the height of the span.container to adjust the border 'height'.

Or, to use pseudo-elements (::before or ::after), given the following HTML:

<div id="left">content</div>
<div id="right">content</div>

The following CSS adds a pseudo-element before any div element that's the adjacent sibling of another div element:

div {
    display: inline-block;
    position: relative;
}

div + div {
    padding-left: 0.3em;
}

div + div::before {
    content: '';
    border-left: 2px solid #000;
    position: absolute;
    height: 50%;
    left: 0;
    top: 25%;
}

JS Fiddle demo.

Show a message box from a class in c#?

Try this:

System.Windows.Forms.MessageBox.Show("Here's a message!");

Pass user defined environment variable to tomcat

In case of Windows, if you can't find setenv.bat, in the 2nd line of catalina.bat (after @echo off) add this:
SET APP_MASTER_PASSWORD=foo

May not be the best approach, but works

Get hostname of current request in node.js Express

You can use the os Module:

var os = require("os");
os.hostname();

See http://nodejs.org/docs/latest/api/os.html#os_os_hostname

Caveats:

  1. if you can work with the IP address -- Machines may have several Network Cards and unless you specify it node will listen on all of them, so you don't know on which NIC the request came in, before it comes in.

  2. Hostname is a DNS matter -- Don't forget that several DNS aliases can point to the same machine.

How to display count of notifications in app launcher icon

This is sample and best way for showing badge on notification launcher icon.

Add This Class in your application

public class BadgeUtils {

    public static void setBadge(Context context, int count) {
        setBadgeSamsung(context, count);
        setBadgeSony(context, count);
    }

    public static void clearBadge(Context context) {
        setBadgeSamsung(context, 0);
        clearBadgeSony(context);
    }


    private static void setBadgeSamsung(Context context, int count) {
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null) {
            return;
        }
        Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
        intent.putExtra("badge_count", count);
        intent.putExtra("badge_count_package_name", context.getPackageName());
        intent.putExtra("badge_count_class_name", launcherClassName);
        context.sendBroadcast(intent);
    }

    private static void setBadgeSony(Context context, int count) {
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null) {
            return;
        }

        Intent intent = new Intent();
        intent.setAction("com.sonyericsson.home.action.UPDATE_BADGE");
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", launcherClassName);
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", true);
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", String.valueOf(count));
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", context.getPackageName());

        context.sendBroadcast(intent);
    }


    private static void clearBadgeSony(Context context) {
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null) {
            return;
        }

        Intent intent = new Intent();
        intent.setAction("com.sonyericsson.home.action.UPDATE_BADGE");
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", launcherClassName);
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", false);
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", String.valueOf(0));
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", context.getPackageName());

        context.sendBroadcast(intent);
    }

    private static String getLauncherClassName(Context context) {

        PackageManager pm = context.getPackageManager();

        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);

        List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
        for (ResolveInfo resolveInfo : resolveInfos) {
            String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
            if (pkgName.equalsIgnoreCase(context.getPackageName())) {
                String className = resolveInfo.activityInfo.name;
                return className;
            }
        }
        return null;
    }


}

==> MyGcmListenerService.java Use BadgeUtils class when notification comes.

public class MyGcmListenerService extends GcmListenerService { 

    private static final String TAG = "MyGcmListenerService"; 
    @Override
    public void onMessageReceived(String from, Bundle data) {

            String message = data.getString("Msg");
            String Type = data.getString("Type"); 
            Intent intent = new Intent(this, SplashActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                    PendingIntent.FLAG_ONE_SHOT);

            Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            NotificationCompat.BigTextStyle bigTextStyle= new NotificationCompat.BigTextStyle();

            bigTextStyle .setBigContentTitle(getString(R.string.app_name))
                    .bigText(message);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(getNotificationIcon())
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText(message)
                    .setStyle(bigTextStyle) 
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);

            int color = getResources().getColor(R.color.appColor);
            notificationBuilder.setColor(color);
            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);


            int unOpenCount=AppUtill.getPreferenceInt("NOTICOUNT",this);
            unOpenCount=unOpenCount+1;

            AppUtill.savePreferenceLong("NOTICOUNT",unOpenCount,this);  
            notificationManager.notify(unOpenCount /* ID of notification */, notificationBuilder.build()); 

// This is for bladge on home icon          
        BadgeUtils.setBadge(MyGcmListenerService.this,(int)unOpenCount);

    }


    private int getNotificationIcon() {
        boolean useWhiteIcon = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP);
        return useWhiteIcon ? R.drawable.notification_small_icon : R.drawable.icon_launcher;
    }
}

And clear notification from preference and also with badge count

 public class SplashActivity extends AppCompatActivity { 
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_splash);

                    AppUtill.savePreferenceLong("NOTICOUNT",0,this);
                    BadgeUtils.clearBadge(this);
            }
    }
<uses-permission android:name="com.sonyericsson.home.permission.BROADCAST_BADGE" />

Prevent scroll-bar from adding-up to the Width of page on Chrome

body {
    width: calc( 100% );
    max-width: calc( 100vw - 1em );
}

works with default scroll bars as well. could add:

overflow-x: hidden;

to ensure horizontal scroll bars remain hidden for the parent frame. unless this is desired from your clients.

How to import popper.js?

You can download and import all of Bootstrap, and Popper, with a single command using Fetch Injection:

fetchInject([
  'https://npmcdn.com/[email protected]/dist/js/bootstrap.min.js',
  'https://cdn.jsdelivr.net/popper.js/1.0.0-beta.3/popper.min.js'
], fetchInject([
  'https://cdn.jsdelivr.net/jquery/3.1.1/jquery.slim.min.js',
  'https://npmcdn.com/[email protected]/dist/js/tether.min.js'
]));

Add CSS files if you need those too. Adjust versions and external sources to meet your needs and consider using sub-resource integrity checking if you're not hosting the files on your own domain or don't trust the source.

Angular 4: no component factory found,did you add it to @NgModule.entryComponents?

My error was calling NgbModal open method with incorrect parameters from .html

js 'types' can only be used in a .ts file - Visual Studio Code using @ts-check

Use "javascript.validate.enable": false in your VS Code settings, It doesn't disable ESLINT. I use both ESLINT & Flow. Simply follow the instructions Flow For Vs Code Setup

Adding this line in settings.json. Helps "javascript.validate.enable": false

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

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

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

Function pointer as parameter

You need to declare disconnectFunc as a function pointer, not a void pointer. You also need to call it as a function (with parentheses), and no "*" is needed.

Select multiple columns from a table, but group by one

==EDIT==

I checked your question again and have concluded this can't be done.

ProductName is not unique, It must either be part of the Group By or excluded from your results.

For example how would SQL present these results to you if you Group By only ProductID?

ProductID | ProductName | OrderQuantity 
---------------------------------------
1234      | abc         | 1
1234      | def         | 1
1234      | ghi         | 1
1234      | jkl         | 1

How to JUnit test that two List<E> contain the same elements in the same order?

I prefer using Hamcrest because it gives much better output in case of a failure

Assert.assertThat(listUnderTest, 
       IsIterableContainingInOrder.contains(expectedList.toArray()));

Instead of reporting

expected true, got false

it will report

expected List containing "1, 2, 3, ..." got list containing "4, 6, 2, ..."

IsIterableContainingInOrder.contain

Hamcrest

According to the Javadoc:

Creates a matcher for Iterables that matches when a single pass over the examined Iterable yields a series of items, each logically equal to the corresponding item in the specified items. For a positive match, the examined iterable must be of the same length as the number of specified items

So the listUnderTest must have the same number of elements and each element must match the expected values in order.

Adding class to element using Angular JS

querySelector is not from Angular but it's in document and it's in all DOM elements (expensive). You can use ng-class or inside directive add addClass on the element:

myApp.directive('yourDirective', [function(){
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
            // Remove class
            elem.addClass("my-class"); 
        }
    }
}

Global variables in Java

You are better off using dependency injection:

public class Globals {
    public int a;
    public int b;
}

public class UsesGlobals {
    private final Globals globals;
    public UsesGlobals(Globals globals) {
        this.globals = globals;
    }
}

Why do 64-bit DLLs go to System32 and 32-bit DLLs to SysWoW64 on 64-bit Windows?

System32 is where Windows historically placed all 32bit DLLs, and System was for the 16bit DLLs. When microsoft created the 64 bit OS, everyone I know of expected the files to reside under System64, but Microsoft decided it made more sense to put 64bit files under System32. The only reasoning I have been able to find, is that they wanted everything that was 32bit to work in a 64bit Windows w/o having to change anything in the programs -- just recompile, and it's done. The way they solved this, so that 32bit applications could still run, was to create a 32bit windows subsystem called Windows32 On Windows64. As such, the acronym SysWOW64 was created for the System directory of the 32bit subsystem. The Sys is short for System, and WOW64 is short for Windows32OnWindows64.
Since windows 16 is already segregated from Windows 32, there was no need for a Windows 16 On Windows 64 equivalence. Within the 32bit subsystem, when a program goes to use files from the system32 directory, they actually get the files from the SysWOW64 directory. But the process is flawed.

It's a horrible design. And in my experience, I had to do a lot more changes for writing 64bit applications, that simply changing the System32 directory to read System64 would have been a very small change, and one that pre-compiler directives are intended to handle.

nginx missing sites-available directory

I tried sudo apt install nginx-full. You will get all the required packages.

Any way to clear python's IDLE window?

File -> New Window

In the new window**

Run -> Python Shell

The problem with this method is that it will clear all the things you defined, such as variables.

Alternatively, you should just use command prompt.

open up command prompt

type "cd c:\python27"

type "python example.py" , you have to edit this using IDLE when it's not in interactive mode. If you're in python shell, file -> new window.

Note that the example.py needs to be in the same directory as C:\python27, or whatever directory you have python installed.

Then from here, you just press the UP arrow key on your keyboard. You just edit example.py, use CTRL + S, then go back to command prompt, press the UP arrow key, hit enter.

If the command prompt gets too crowded, just type "clr"

The "clr" command only works with command prompt, it will not work with IDLE.

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

Using JQuery : http://api.jquery.com/hide/

$('li.two').hide()

In :

<ul class="lul">
    <li class="one">a</li>
    <li class="two">b</li>
    <li class="three">c</li>
</ul>

On document ready.

http://jsfiddle.net/2dDSG/

MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource

You need to enable CORS in your Web Api. The easier and preferred way to enable CORS globally is to add the following into web.config

<system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="Content-Type" />
      <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    </customHeaders>
  </httpProtocol>
</system.webServer>

Please note that the Methods are all individually specified, instead of using *. This is because there is a bug occurring when using *.

You can also enable CORS by code.

Update
The following NuGet package is required: Microsoft.AspNet.WebApi.Cors.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.EnableCors();

        // ...
    }
}

Then you can use the [EnableCors] attribute on Actions or Controllers like this

[EnableCors(origins: "http://www.example.com", headers: "*", methods: "*")]

Or you can register it globally

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute("http://www.example.com", "*", "*");
        config.EnableCors(cors);

        // ...
    }
}

You also need to handle the preflight Options requests with HTTP OPTIONS requests.

Web API needs to respond to the Options request in order to confirm that it is indeed configured to support CORS.

To handle this, all you need to do is send an empty response back. You can do this inside your actions, or you can do it globally like this:

# Global.asax.cs
protected void Application_BeginRequest()
{
    if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
    {
        Response.Flush();
    }
}

This extra check was added to ensure that old APIs that were designed to accept only GET and POST requests will not be exploited. Imagine sending a DELETE request to an API designed when this verb didn't exist. The outcome is unpredictable and the results might be dangerous.

How can I format DateTime to web UTC format?

string foo = yourDateTime.ToUniversalTime()
                         .ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");

Row count where data exists

If you need VBA, you could do something quick like this:

Sub Test()
    With ActiveSheet
    lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    MsgBox lastRow
    End With
End Sub

This will print the number of the last row with data in it. Obviously don't need MsgBox in there if you're using it for some other purpose, but lastRow will become that value nonetheless.

Best practices for SQL varchar column length

I haven't checked this lately, but I know in the past with Oracle that the JDBC driver would reserve a chunk of memory during query execution to hold the result set coming back. The size of the memory chunk is dependent on the column definitions and the fetch size. So the length of the varchar2 columns affects how much memory is reserved. This caused serious performance issues for me years ago as we always used varchar2(4000) (the max at the time) and garbage collection was much less efficient than it is today.

Explain the concept of a stack frame in a nutshell

If you understand stack very well then you will understand how memory works in program and if you understand how memory works in program you will understand how function store in program and if you understand how function store in program you will understand how recursive function works and if you understand how recursive function works you will understand how compiler works and if you understand how compiler works your mind will works as compiler and you will debug any program very easily

Let me explain how stack works:

First you have to know how functions are represented in stack :

Heap stores dynamically allocated values.
Stack stores automatic allocation and deletion values.

enter image description here

Let's understand with example :

def hello(x):
    if x==1:
        return "op"
    else:
        u=1
        e=12
        s=hello(x-1)
        e+=1
        print(s)
        print(x)
        u+=1
    return e

hello(4)

Now understand parts of this program :

enter image description here

Now let's see what is stack and what are stack parts:

enter image description here

Allocation of the stack :

Remember one thing: if any function's return condition gets satisfied, no matter it has loaded the local variables or not, it will immediately return from stack with it's stack frame. It means that whenever any recursive function get base condition satisfied and we put a return after base condition, the base condition will not wait to load local variables which are located in the “else” part of program. It will immediately return the current frame from the stack following which the next frame is now in the activation record.

See this in practice:

enter image description here

Deallocation of the block:

So now whenever a function encounters return statement, it delete the current frame from the stack.

While returning from the stack, values will returned in reverse of the original order in which they were allocated in stack.

enter image description here

Writing outputs to log file and console

I wanted to display logs on stdout and log file along with the timestamp. None of the above answers worked for me. I made use of process substitution and exec command and came up with the following code. Sample logs:

2017-06-21 11:16:41+05:30 Fetching information about files in the directory...

Add following lines at the top of your script:

LOG_FILE=script.log
exec > >(while read -r line; do printf '%s %s\n' "$(date --rfc-3339=seconds)" "$line" | tee -a $LOG_FILE; done)
exec 2> >(while read -r line; do printf '%s %s\n' "$(date --rfc-3339=seconds)" "$line" | tee -a $LOG_FILE; done >&2)

Hope this helps somebody!

What is the { get; set; } syntax in C#?

That is an Auto-Implemented Property. It's basically a shorthand way of creating properties for a class in C#, without having to define private variables for them. They are normally used when no extra logic is required when getting or setting the value of a variable.

You can read more on MSDN's Auto-Implemented Properties Programming Guide.

How may I sort a list alphabetically using jQuery?

HTML

<ul id="list">
    <li>alpha</li>
    <li>gamma</li>
    <li>beta</li>
</ul>

JavaScript

function sort(ul) {
    var ul = document.getElementById(ul)
    var liArr = ul.children
    var arr = new Array()
    for (var i = 0; i < liArr.length; i++) {
        arr.push(liArr[i].textContent)
    }
    arr.sort()
    arr.forEach(function(content, index) {
        liArr[index].textContent = content
    })
}

sort("list")

JSFiddle Demo https://jsfiddle.net/97oo61nw/

Here we are push all values of li elements inside ul with specific id (which we provided as function argument) to array arr and sort it using sort() method which is sorted alphabetical by default. After array arr is sorted we are loop this array using forEach() method and just replace text content of all li elements with sorted content

How to change the default docker registry from docker.io to my private registry?

if you are using the fedora distro, you can change the file

/etc/containers/registries.conf

Adding domain docker.io