Programs & Examples On #Pljava

identifier "string" undefined?

You want to do #include <string> instead of string.h and then the type string lives in the std namespace, so you will need to use std::string to refer to it.

Java Date cut off time information

You can do this to avoid timezone issue:

public static Date truncDate(Date date) {
    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    cal.setTime(date);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    return cal.getTime();
}

Although Java Date object is timestamp value, but during truncate, it will be converted to local timezone, so you will get surprising value if you expect value from UTC timezone.

How can I call a function using a function pointer?

//Declare the pointer and asign it to the function
bool (*pFunc)() = A;
//Call the function A
pFunc();
//Call function B
pFunc = B;
pFunc();
//Call function C
pFunc = C;
pFunc();

get and set in TypeScript

You can write this

class Human {
    private firstName : string;
    private lastName : string;

    constructor (
        public FirstName?:string, 
        public LastName?:string) {

    }

    get FirstName() : string {
        console.log("Get FirstName : ", this.firstName);
        return this.firstName;
    }
    set FirstName(value : string) {
        console.log("Set FirstName : ", value);
        this.firstName = value;
    } 

    get LastName() : string {
        console.log("Get LastName : ", this.lastName);
        return this.lastName;
    }
    set LastName(value : string) {
        console.log("Set LastName : ", value);
        this.lastName = value;
    } 

}

How to use wget in php?

wget

wget is a linux command, not a PHP command, so to run this you woud need to use exec, which is a PHP command for executing shell commands.

exec("wget --http-user=[user] --http-password=[pass] http://www.example.com/file.xml");

This can be useful if you are downloading a large file - and would like to monitor the progress, however when working with pages in which you are just interested in the content, there are simple functions for doing just that.

The exec function is enabled by default, but may be disabled in some situations. The configuration options for this reside in your php.ini, to enable, remove exec from the disabled_functions config string.

alternative

Using file_get_contents we can retrieve the contents of the specified URL/URI. When you just need to read the file into a variable, this would be the perfect function to use as a replacement for curl - follow the URI syntax when building your URL.

// standard url
$content = file_get_contents("http://www.example.com/file.xml");

// or with basic auth
$content = file_get_contents("http://user:[email protected]/file.xml");

As noted by Sean the Bean - you may also need to change allow_url_fopen to true in your php.ini to allow the use of a URL in this method, however, this should be true by default.

If you want to then store that file locally, there is a function file_put_contents to write that into a file, combined with the previous, this could emulate a file download:

file_put_contents("local_file.xml", $content);

Returning a pointer to a vector element in c++

Say, you have the following:

std::vector<myObject>::const_iterator first = vObj.begin();

Then the first object in the vector is: *first. To get the address, use: &(*first).

However, in keeping with the STL design, I'd suggest return an iterator instead if you plan to pass it around later on to STL algorithms.

Convert json to a C# array?

Yes, Json.Net is what you need. You basically want to deserialize a Json string into an array of objects.

See their examples:

string myJsonString = @"{
  "Name": "Apple",
  "Expiry": "\/Date(1230375600000+1300)\/",
  "Price": 3.99,
  "Sizes": [
    "Small",
    "Medium",
    "Large"
  ]
}";

// Deserializes the string into a Product object
Product myProduct = JsonConvert.DeserializeObject<Product>(myJsonString);

How to output an Excel *.xls file from classic ASP

It's AddHeader, not AppendHeader.

<%@ Language=VBScript %>
<%  Option Explicit

Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader "Content-Disposition", "attachment; filename=excelTest.xls"
%>
<table>
    <tr>
        <td>Test</td>
    </tr>
</table>

Update: I've written a blog post about how to generate Excel files in ASP Classic. It contains a rather useful piece of code to generate both xls and csv files.

z-index issue with twitter bootstrap dropdown menu

Ran into the same bug here. This worked for me.

.navbar {
    position: static;
}

By setting the position to static, it means the navbar will fall into the flow of the document as it normally would.

Mobile website "WhatsApp" button to send message to a specific number

i used this code and it works fine for me, just change +92xxxxxxxxxx to your valid whatsapp number, with country code

<script type="text/javascript">
        (function () {
            var options = {
                whatsapp: "+92xxxxxxxxxx", // WhatsApp number
                call_to_action: "Message us", // Call to action
                position: "right", // Position may be 'right' or 'left'

            };
            var proto = document.location.protocol, host = "whatshelp.io", url = proto + "//static." + host;
            var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = url + '/widget-send-button/js/init.js';
            s.onload = function () { WhWidgetSendButton.init(host, proto, options); };
            var x = document.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x);
        })();
    </script> 

Closing Excel Application Process in C# after Data Access

workbook.Close(0);
excelApp.Quit();

Worked for me.

How do I make a comment in a Dockerfile?

You can use # at the beginning of a line to start a comment (whitespaces before # are allowed):

# do some stuff
RUN apt-get update \
    # install some packages
    apt-get install -y cron

#'s in the middle of a string are passed to the command itself, e.g.:

RUN echo 'we are running some # of cool things'

How to convert a String to Bytearray

The easiest way in 2018 should be TextEncoder but the returned element is not byte array, it is Uint8Array. (And not all browsers support it)

let utf8Encode = new TextEncoder();
utf8Encode.encode("eee")
> Uint8Array [ 101, 101, 101 ]

JQuery: Change value of hidden input field

Seems to work

$(".selector").change(function() {

    var $value = $(this).val();

    var $title = $(this).children('option[value='+$value+']').html();

    $('#bacon').val($title);

});

Just check with your firebug. And don't put css on hidden input.

This certificate has an invalid issuer Apple Push Services

This is not actually a development issue. It happens due to expiration of the Apple Worldwide Developer Relations Intermediate Certificate issued by Apple Worldwide Developer Relations Certificate Authority. WWDRCA issues the certificate to sign your software for Apple devices, allowing our systems to confirm that your software is delivered to users as intended and has not been modified.

To resolve this issue, you have to follow the below steps:

  1. Open Keychain Access
  2. Go to View -> Show Expired Certificates

Enter image description here

  1. Go to System in Keychain Enter image description here

  2. Here you find that "Apple Worldwide Developer Relations Certificate Authority" is marked as expired. So delete it. Also check under Login Tab and delete expired WWDRCA.

  3. Download new WWDR Intermediate Certificate from here(The renewed Apple Worldwide Developer Relations Certification Intermediate Certificate will expire on February 7, 2023).

  4. Install it by double clicking on it.

If you still face any issue with your iOS apps, Mac apps, Safari extensions, Apple Wallet and Safari push notifications, then please follow this link of expiration.

The Apple Worldwide Developer Relations Certification Intermediate Certificate expires soon and we've issued a renewed certificate that must be included when signing all new Apple Wallet Passes, push packages for Safari Push Notifications, and Safari Extensions starting February 14, 2016.

While most developers and users will not be affected by the certificate change, we recommend that all developers download and install the renewed certificate on their development systems and servers as a best practice. All apps will remain available on the App Store for iOS, Mac, and Apple TV.

Alternate table row color using CSS?

There is a fairly easy way to do this in PHP, if I understand your query, I assume that you code in PHP and you are using CSS and javascript to enhance the output.

The dynamic output from the database will carry a for loop to iterate through results which are then loaded into the table. Just add a function call to the like this:

echo "<tr style=".getbgc($i).">";  //this calls the function based on the iteration of the for loop.

then add the function to the page or library file:

function getbgc($trcount)
{

$blue="\"background-color: #EEFAF6;\"";
$green="\"background-color: #D4F7EB;\"";
$odd=$trcount%2;
    if($odd==1){return $blue;}
    else{return $green;}    

}

Now this will alternate dynamically between colors at each newly generated table row.

It's a lot easier than messing about with CSS that doesn't work on all browsers.

Hope this helps.

JavaFX How to set scene background image

In addition to @Elltz answer, we can use both fill and image for background:

someNode.setBackground(
            new Background(
                    Collections.singletonList(new BackgroundFill(
                            Color.WHITE, 
                            new CornerRadii(500), 
                            new Insets(10))),
                    Collections.singletonList(new BackgroundImage(
                            new Image("image/logo.png", 100, 100, false, true),
                            BackgroundRepeat.NO_REPEAT,
                            BackgroundRepeat.NO_REPEAT,
                            BackgroundPosition.CENTER,
                            BackgroundSize.DEFAULT))));

Use

setBackground(
                new Background(
                        Collections.singletonList(new BackgroundFill(
                                Color.WHITE,
                                new CornerRadii(0),
                                new Insets(0))),
                        Collections.singletonList(new BackgroundImage(
                                new Image("file:clouds.jpg", 100, 100, false, true),
                                BackgroundRepeat.NO_REPEAT,
                                BackgroundRepeat.NO_REPEAT,
                                BackgroundPosition.DEFAULT,
                                new BackgroundSize(1.0, 1.0, true, true, false, false)
                        ))));

(different last argument) to make the image full-window size.

How to crop an image in OpenCV using Python

Below is the way to crop an image.

image_path: The path to the image to edit

coords: A tuple of x/y coordinates (x1, y1, x2, y2)[open the image in mspaint and check the "ruler" in view tab to see the coordinates]

saved_location: Path to save the cropped image

from PIL import Image
    def crop(image_path, coords, saved_location:
        image_obj = Image.open("Path of the image to be cropped")
            cropped_image = image_obj.crop(coords)
            cropped_image.save(saved_location)
            cropped_image.show()


if __name__ == '__main__':
    image = "image.jpg"
    crop(image, (100, 210, 710,380 ), 'cropped.jpg')

Failed to load resource 404 (Not Found) - file location error?

Looks like the path you gave doesn't have any bootstrap files in them.

href="~/lib/bootstrap/dist/css/bootstrap.min.css"

Make sure the files exist over there , else point the files to the correct path, which should be in your case

href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"

error LNK2001: unresolved external symbol (C++)

That means that the definition of your function is not present in your program. You forgot to add that one.cpp to your program.

What "to add" means in this case depends on your build environment and its terminology. In MSVC (since you are apparently use MSVC) you'd have to add one.cpp to the project.

In more practical terms, applicable to all typical build methodologies, when you link you program, the object file created form one.cpp is missing.

Rendering raw html with reactjs

dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack.

It is better/safer to sanitise your raw HTML (using e.g., DOMPurify) before injecting it into the DOM via dangerouslySetInnerHTML.

DOMPurify - a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG. DOMPurify works with a secure default, but offers a lot of configurability and hooks.

Example:

import React from 'react'
import createDOMPurify from 'dompurify'
import { JSDOM } from 'jsdom'

const window = (new JSDOM('')).window
const DOMPurify = createDOMPurify(window)

const rawHTML = `
<div class="dropdown">
  <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
    Dropdown
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Action</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Another action</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Something else here</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Separated link</a></li>
  </ul>
</div>
`

const YourComponent = () => (
  <div>
    { <div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(rawHTML) }} /> }
  </div>
)

export default YourComponent

How do I add an "Add to Favorites" button or link on my website?

This code is the corrected version of iambriansreed's answer:

<script type="text/javascript">
    $(function() {
        $("#bookmarkme").click(function() {
            // Mozilla Firefox Bookmark
            if ('sidebar' in window && 'addPanel' in window.sidebar) { 
                window.sidebar.addPanel(location.href,document.title,"");
            } else if( /*@cc_on!@*/false) { // IE Favorite
                window.external.AddFavorite(location.href,document.title); 
            } else { // webkit - safari/chrome
                alert('Press ' + (navigator.userAgent.toLowerCase().indexOf('mac') != - 1 ? 'Command/Cmd' : 'CTRL') + ' + D to bookmark this page.');
            }
        });
    });
</script>

Convert string to date then format the date

In one line:

String date=new SimpleDateFormat("MM-dd-yyyy").format(new SimpleDateFormat("yyyy-MM-dd").parse("2011-01-01"));

Where:

String date=new SimpleDateFormat("FinalFormat").format(new SimpleDateFormat("InitialFormat").parse("StringDate"));

How to get the type of a variable in MATLAB?

Use the class function

>> b = 2
b =
     2
>> a = 'Hi'
a =
Hi
>> class(b)
ans =
double
>> class(a)
ans =
char

ASP.NET document.getElementById('<%=Control.ClientID%>'); returns null

Is Button1 visible? I mean, from the server side. Make sure Button1.Visible is true.

Controls that aren't Visible won't be rendered in HTML, so although they are assigned a ClientID, they don't actually exist on the client side.

IIS: Where can I find the IIS logs?

Enabling Tracing may be a better alternative to the Windows Event Log. This gave me the information I needed to fix my own WebService.

Run an Ansible task only when the variable contains a specific string

This example uses regex_search to perform a substring search.

- name: make conditional variable
  command: "file -s /dev/xvdf"
  register: fsm_out

- name: makefs
  command: touch "/tmp/condition_satisfied"
  when: fsm_out.stdout | regex_search(' data')

ansible version: 2.4.3.0

Show div #id on click with jQuery

This is simple way to Display Div using:-

$("#musicinfo").show();  //or
$("#musicinfo").css({'display':'block'});  //or
$("#musicinfo").toggle("slow");   //or
$("#musicinfo").fadeToggle();    //or

Fully change package name including company domain

1) Open the project folder in Android Studio.
2) Select app folder -> Right click, and select refactor.
3) Click on move. It will ask to which package name type you own full package name and it will ask to create a new package yes create new automatically it ask for gradle to sync.

elasticsearch bool query combine must with OR

  • OR is spelled should
  • AND is spelled must
  • NOR is spelled should_not

Example:

You want to see all the items that are (round AND (red OR blue)):

{
    "query": {
        "bool": {
            "must": [
                {
                    "term": {"shape": "round"}
                },
                {
                    "bool": {
                        "should": [
                            {"term": {"color": "red"}},
                            {"term": {"color": "blue"}}
                        ]
                    }
                }
            ]
        }
    }
}

You can also do more complex versions of OR, for example if you want to match at least 3 out of 5, you can specify 5 options under "should" and set a "minimum_should" of 3.

Thanks to Glen Thompson and Sebastialonso for finding where my nesting wasn't quite right before.

Thanks also to Fatmajk for pointing out that "term" becomes "match" in ElasticSearch 6.

Get ID of element that called a function

You can code the handler setup like this:

<area id="nose" shape="rect" coords="280,240,330,275" onmouseover="zoom.call(this)"/>

Then this in your handler will refer to the element. Now, I'll offer the caveat that I'm not 100% sure what happens when you've got a handler in an <area> tag, largely because I haven't seen an <area> tag in like a decade or so. I think it should give you the image tag, but that could be wrong.

edit — yes, it's wrong - you get the <area> tag, not the <img>. So you'll have to get that element's parent (the map), and then find the image that's using it (that is, the <img> whose "usemap" attribute refers to the map's name).

edit again — except it doesn't matter because you want the area's "id" durr. Sorry for not reading correctly.

Reset local repository branch to be just like remote repository HEAD

Here is a script that automates what the most popular answer suggests ... See https://stackoverflow.com/a/13308579/1497139 for an improved version that supports branches

#!/bin/bash
# reset the current repository
# WF 2012-10-15
# see https://stackoverflow.com/questions/1628088/how-to-reset-my-local-repository-to-be-just-like-the-remote-repository-head
timestamp=`date "+%Y-%m-%d-%H_%M_%S"`
git commit -a -m "auto commit at $timestamp"
if [ $? -eq 0 ]
then
  git branch "auto-save-at-$timestamp" 
fi
git fetch origin
git reset --hard origin/master

How to force cp to overwrite without confirmation

You can do yes | cp -rf xxx yyy, but my gutfeeling says that if you do it as root - your .bashrc or .profile has an alias of cp to cp -i, most modern systems (primarily RH-derivatives) do that to root profiles.

You can check existing aliases by running alias at the command prompt, or which cp to check aliases only for cp.

If you do have an alias defined, running unalias cp will abolish that for the current session, otherwise you can just remove it from your shell profile.

You can temporarily bypass an alias and use the non-aliased version of a command by prefixing it with \, e.g. \cp whatever

How to get a responsive button in bootstrap 3

I know this already has a marked answer, but I feel I have an improvement to it.

The marked answer is a bit misleading. He set a width to the button, which is not necessary, and set widths are not "responsive". To his defense, he mentions in a comment below it, that the width is not necessary and just an example.

One thing not mentioned here, is that the words may break in the middle of a word and look messed up.

My solution, forces the break to happen between words, a nice word wrap.

.btn-responsive {
    white-space: normal !important;
    word-wrap: break-word;
}

<a href="#" class="btn btn-primary btn-responsive">Click Here</a>

How to find out which package version is loaded in R?

Based on the previous answers, here is a simple alternative way of printing the R-version, followed by the name and version of each package loaded in the namespace. It works in the Jupyter notebook, where I had troubles running sessionInfo() and R --version.

print(paste("R", getRversion()))
print("-------------")
for (package_name in sort(loadedNamespaces())) {
    print(paste(package_name, packageVersion(package_name)))
}

Out:

[1] "R 3.2.2"
[1] "-------------"
[1] "AnnotationDbi 1.32.2"
[1] "Biobase 2.30.0"
[1] "BiocGenerics 0.16.1"
[1] "BiocParallel 1.4.3"
[1] "DBI 0.3.1"
[1] "DESeq2 1.10.0"
[1] "Formula 1.2.1"
[1] "GenomeInfoDb 1.6.1"
[1] "GenomicRanges 1.22.3"
[1] "Hmisc 3.17.0"
[1] "IRanges 2.4.6"
[1] "IRdisplay 0.3"
[1] "IRkernel 0.5"

Can we convert a byte array into an InputStream in Java?

Use ByteArrayInputStream:

InputStream is = new ByteArrayInputStream(decodedBytes);

Server is already running in Rails

Just open that C:/Sites/folder/Pids/Server.pids and copy that 4 digit value.that 4 digit value is nothing but a PID, which you need to kill to stop the already running process.

then to stop the process use below command

 kill -9 <pid>

once that already running process get stopped then hit

rails s to start the rails server

Laravel is there a way to add values to a request array

I used this code to add something to my request.

$req->query->add(['key'=>'variable']);
$req->request->add(['key'=>'variable']);

Put content in HttpResponseMessage object?

For a string specifically, the quickest way is to use the StringContent constructor

response.Content = new StringContent("Your response text");

There are a number of additional HttpContent class descendants for other common scenarios.

Echo off but messages are displayed

For me this issue was caused by the file encoding format being wrong. I used another editor and it was saved as UTF-8-BOM so the very first line I had was @echo off but there was a hidden character in the front of it.

So I changed the encoding to plain old ANSI text, and then the issue went away.

How can I check if a directory exists?

The best way is probably trying to open it, using just opendir() for instance.

Note that it's always best to try to use a filesystem resource, and handling any errors occuring because it doesn't exist, rather than just checking and then later trying. There is an obvious race condition in the latter approach.

How to ignore SSL certificate errors in Apache HttpClient 4.0

With fluent 4.5.2 i had to make the following modification to make it work.

try {
    TrustManager[] trustAllCerts = new TrustManager[] {
       new X509TrustManager() {
    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        return null;
    }
    public void checkClientTrusted(X509Certificate[] certs, String authType) {  }

    public void checkServerTrusted(X509Certificate[] certs, String authType) {  }
    }
    };

    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new SecureRandom());
    CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSslcontext(sc).build();

    String output = Executor.newInstance(httpClient).execute(Request.Get("https://127.0.0.1:3000/something")
                                      .connectTimeout(1000)
                                      .socketTimeout(1000)).returnContent().asString();
    } catch (Exception e) {
    }

How to use BigInteger?

Biginteger is an immutable class. You need to explicitly assign value of your output to sum like this:

sum = sum.add(BigInteger.valueof(i));    

Method with a bool return

     public bool roomSelected()
    {
        int a = 0;
        foreach (RadioButton rb in GroupBox1.Controls)
        {
            if (rb.Checked == true)
            {
                a = 1;
            }
        }
        if (a == 1)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

this how I solved my problem

Decode HTML entities in Python string?

Beautiful Soup handles entity conversion. In Beautiful Soup 3, you'll need to specify the convertEntities argument to the BeautifulSoup constructor (see the 'Entity Conversion' section of the archived docs). In Beautiful Soup 4, entities get decoded automatically.

Beautiful Soup 3

>>> from BeautifulSoup import BeautifulSoup
>>> BeautifulSoup("<p>&pound;682m</p>", 
...               convertEntities=BeautifulSoup.HTML_ENTITIES)
<p>£682m</p>

Beautiful Soup 4

>>> from bs4 import BeautifulSoup
>>> BeautifulSoup("<p>&pound;682m</p>")
<html><body><p>£682m</p></body></html>

java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy

It is simple use below codes.

final Date todayDate = new Date();

System.out.println(todayDate);

System.out.println(new SimpleDateFormat("MM-dd-yyyy").format(todayDate));

System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(todayDate));

System.out.println(todayDate);

Keyboard shortcuts with jQuery

You could also try the shortKeys jQuery plugin. Usage example:

$(document).shortkeys({
  'g': function () { alert('g'); }
});

Maven: The packaging for this project did not assign a file to the build artifact

I have same issue. Error message for me is not complete. But in my case, I've added generation jar with sources. By placing this code in pom.xml:

<build> 
    <pluginManagement>
        <plugins>
            <plugin>
                <artifactId>maven-source-plugin</artifactId>
                <version>2.1.2</version>
                <executions>
                    <execution>
                        <phase>deploy</phase>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </pluginManagement>
</build>

So in deploy phase I execute source:jar goal which produces jar with sources. And deploy ends with BUILD SUCCESS

How to rollback everything to previous commit

If you have pushed the commits upstream...

Select the commit you would like to roll back to and reverse the changes by clicking Reverse File, Reverse Hunk or Reverse Selected Lines. Do this for all the commits after the commit you would like to roll back to also.

reverse stuff reverse commit

If you have not pushed the commits upstream...

Right click on the commit and click on Reset current branch to this commit.

reset branch to commit

Using a batch to copy from network drive to C: or D: drive

Most importantly you need to mount the drive

net use z: \\yourserver\sharename

Of course, you need to make sure that the account the batch file runs under has permission to access the share. If you are doing this by using a Scheduled Task, you can choose the account by selecting the task, then:

  • right click Properties
  • click on General tab
  • change account under

"When running the task, use the following user account:" That's on Windows 7, it might be slightly different on different versions of Windows.

Then run your batch script with the following changes

copy "z:\FolderName" "C:\TEST_BACKUP_FOLDER"

Post values from a multiple select

try this : here select is your select element

let select = document.getElementsByClassName('lstSelected')[0],
    options = select.options,
    len = options.length,
    data='',
    i=0;
while (i<len){
    if (options[i].selected)
        data+= "&" + select.name + '=' + options[i].value;
    i++;
}
return data;

Data is in the form of query string i.e.name=value&name=anotherValue

How to select a schema in postgres when using psql?

quick solution could be:

SELECT your_db_column_name from "your_db_schema_name"."your_db_tabel_name";

Hide Command Window of .BAT file that Executes Another .EXE File

Great tip. It works with batch files that are running a java program also.

start javaw -classpath "%CP%" main.Main

ORA-01017 Invalid Username/Password when connecting to 11g database from 9i client

I had a similar problem recently with Oracle 12c. I created a new user with a lower case password and was able to login fine from the database server but all clients failed with an ORA-01017. The fix turned out to be simple in the end (reset the password to upper case) but took a lot of frustrating effort to get there.

How to return history of validation loss in Keras

Thanks to Alloush,

Following parameter must be included in model.fit():

validation_data = (x_test, y_test)

If it is not defined, val_acc and val_loss will not be exist at output.

Android Studio doesn't start, fails saying components not installed

I also had issues with OS X Yosemite on a fresh install of Android Studio.

My situation was that I was using a VPN. In the preferences, I ended up setting the HTTP Proxy setting to detect automatically after trying running it as sudo and setting a static proxy setting, but neither worked. I was able to download successfully after that. Hope this helps someone with a similar situation (VPN).

Android HTTP Proxy Settings

How to reverse a singly linked list using only two pointers?

Solution using 1 variable (Only p):

typedef unsigned long AddressType;

#define A (*( AddressType* )&p )
#define B (*( AddressType* )&first->link->link )
#define C (*( AddressType* )&first->link )

/* Reversing linked list */
p = first;

while( first->link )
{
    A = A + B + C;
    B = A - B - C;
    A = A - B;
    C = A - C;
    A = A - C;
}

first = p;

Why do I have to define LD_LIBRARY_PATH with an export every time I run my application?

You can just put this all on one line:

LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/path/to/library" ./sync_test

Should make things a little easier, even if it doesn't change anything fundamental

How to manage exceptions thrown in filters in Spring?

You do not need to create a custom Filter for this. We solved this by creating custom exceptions that extend ServletException (which is thrown from the doFilter method, shown in the declaration). These are then caught and handled by our global error handler.

edit: grammar

How can I reverse the order of lines in a file?

The simplest method is using the tac command. tac is cat's inverse. Example:

$ cat order.txt
roger shah 
armin van buuren
fpga vhdl arduino c++ java gridgain
$ tac order.txt > inverted_file.txt
$ cat inverted_file.txt
fpga vhdl arduino c++ java gridgain
armin van buuren
roger shah 

Flask Python Buttons

I think this solution is good:

@app.route('/contact', methods=['GET', 'POST'])
def contact():
    form = ContactForm()
    if form.validate_on_submit():
        if form.submit.data:
            pass
        elif form.submit2.data:
            pass
    return render_template('contact.html', form=form)

Form:

class ContactForm(FlaskForm):

    submit = SubmitField('Do this')
    submit2 = SubmitField('Do that')

Could not find a version that satisfies the requirement <package>

Below command worked for me -

python -m pip install flask

How to send json data in the Http request using NSURLRequest

Most of you already know this by now, but I am posting this, just incase, some of you are still struggling with JSON in iOS6+.

In iOS6 and later, we have the NSJSONSerialization Class that is fast and has no dependency on including "outside" libraries.

NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[resultStr dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil]; 

This is the way iOS6 and later can now parse JSON efficiently.The use of SBJson is also pre-ARC implementation and brings with it those issues too if you are working in an ARC environment.

I hope this helps!

Node / Express: EADDRINUSE, Address already in use - Kill server

You may use hot-node to prevent your server from crashing/ run-time-errors. Hot-node automatically restarts the nodejs application for you whenever there is a change in the node program[source] / process[running node program].

Install hot-node using npm using the global option:

npm install -g hotnode

What's the CMake syntax to set and use variables?

Here are a couple basic examples to get started quick and dirty.

One item variable

Set variable:

SET(INSTALL_ETC_DIR "etc")

Use variable:

SET(INSTALL_ETC_CROND_DIR "${INSTALL_ETC_DIR}/cron.d")

Multi-item variable (ie. list)

Set variable:

SET(PROGRAM_SRCS
        program.c
        program_utils.c
        a_lib.c
        b_lib.c
        config.c
        )

Use variable:

add_executable(program "${PROGRAM_SRCS}")

CMake docs on variables

How to hide console window in python?

This will hide your console. Implement these lines in your code first to start hiding your console at first.

import win32gui, win32con

the_program_to_hide = win32gui.GetForegroundWindow()
win32gui.ShowWindow(the_program_to_hide , win32con.SW_HIDE)

Update May 2020 :

If you've got trouble on pip install win32con on Command Prompt, you can simply pip install pywin32.Then on your python script, execute import win32.lib.win32con as win32con instead of import win32con.

To show back your program again win32con.SW_SHOW works fine:

win32gui.ShowWindow(the_program_to_hide , win32con.SW_SHOW)

Cannot find control with name: formControlName in angular reactive form

I tried to generate a form dynamically because the amount of questions depend on an object and for me the error was fixed when I added ngDefaultControl to my mat-form-field.

    <form [formGroup]="questionsForm">
        <ng-container *ngFor="let question of questions">
            <mat-form-field [formControlName]="question.id" ngDefaultControl>
                <mat-label>{{question.questionContent}}</mat-label>
                <textarea matInput rows="3" required></textarea>
            </mat-form-field>
        </ng-container>
        <button mat-raised-button (click)="sendFeedback()">Submit all questions</button>
    </form>

In sendFeedback() I get the value from my dynamic form by selecting the formgroup's value as such

  sendFeedbackAsAgent():void {
    if (this.questionsForm.valid) {
      console.log(this.questionsForm.value)
    }
  }

grep from tar.gz without extracting [faster one]

If this is really slow, I suspect you're dealing with a large archive file. It's going to uncompress it once to extract the file list, and then uncompress it N times--where N is the number of files in the archive--for the grep. In addition to all the uncompressing, it's going to have to scan a fair bit into the archive each time to extract each file. One of tar's biggest drawbacks is that there is no table of contents at the beginning. There's no efficient way to get information about all the files in the archive and only read that portion of the file. It essentially has to read all of the file up to the thing you're extracting every time; it can't just jump to a filename's location right away.

The easiest thing you can do to speed this up would be to uncompress the file first (gunzip file.tar.gz) and then work on the .tar file. That might help enough by itself. It's still going to loop through the entire archive N times, though.

If you really want this to be efficient, your only option is to completely extract everything in the archive before processing it. Since your problem is speed, I suspect this is a giant file that you don't want to extract first, but if you can, this will speed things up a lot:

tar zxf file.tar.gz
for f in hopefullySomeSubdir/*; do
  grep -l "string" $f
done

Note that grep -l prints the name of any matching file, quits after the first match, and is silent if there's no match. That alone will speed up the grepping portion of your command, so even if you don't have the space to extract the entire archive, grep -l will help. If the files are huge, it will help a lot.

Python: How to check if keys exists and retrieve value from Dictionary in descending priority

Use .get(), which if the key is not found, returns None.

for i in keySet:
    temp = myDict.get(i)
    if temp is not None:
        print temp
        break

Android : How to read file in bytes?

A simple InputStream will do

byte[] fileToBytes(File file){
    byte[] bytes = new byte[0];
    try(FileInputStream inputStream = new FileInputStream(file)) {
        bytes = new byte[inputStream.available()];
        //noinspection ResultOfMethodCallIgnored
        inputStream.read(bytes);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bytes;
}

VirtualBox: mount.vboxsf: mounting failed with the error: No such device

I am able to resolved this by running below commmand

modprobe -a vboxguest vboxsf vboxvideo

How can I see CakePHP's SQL dump in the controller?

In CakePHP 1.2 ..

$db =& ConnectionManager::getDataSource('default');
$db->showLog();

Using OpenGl with C#?

What would you like these support libraries to do? Just using OpenGL from C# is simple enough and does not require any additional libraries afaik.

How to loop in excel without VBA or macros?

I was just searching for something similar:

I want to sum every odd row column.

SUMIF has TWO possible ranges, the range to sum from, and a range to consider criteria in.

SUMIF(B1:B1000,1,A1:A1000)

This function will consider if a cell in the B range is "=1", it will sum the corresponding A cell only if it is.

To get "=1" to return in the B range I put this in B:

=MOD(ROWNUM(B1),2)

Then auto fill down to get the modulus to fill, you could put and calculatable criteria here to get the SUMIF or SUMIFS conditions you need to loop through each cell.

Easier than ARRAY stuff and hides the back-end of loops!

jQuery hover and class selector

Since this is a menu, might as well take it to the next level, and clean up the HTML, and make it more semantic by using a list element:

HTML:

  <ul id="menu">
    <li><a href="#">Bla</a></li>
    <li><a href="#">Bla</a></li>
    <li><a href="#">Bla</a></li>
  </ul>

CSS:

#menu {
  margin: 0;
}
#menu li {
  float: left;
  list-style: none;
  margin: 0;
}
#menu li a {
  display: block;
  line-height:30px;
  width:100px;
  background-color:#000;
}
#menu li a:hover {
  background-color:#F00;
}

JWT authentication for ASP.NET Web API

I think you should use some 3d party server to support the JWT token and there is no out of the box JWT support in WEB API 2.

However there is an OWIN project for supporting some format of signed token (not JWT). It works as a reduced OAuth protocol to provide just a simple form of authentication for a web site.

You can read more about it e.g. here.

It's rather long, but most parts are details with controllers and ASP.NET Identity that you might not need at all. Most important are

Step 9: Add support for OAuth Bearer Tokens Generation

Step 12: Testing the Back-end API

There you can read how to set up endpoint (e.g. "/token") that you can access from frontend (and details on the format of the request).

Other steps provide details on how to connect that endpoint to the database, etc. and you can chose the parts that you require.

How can I count occurrences with groupBy?

Here are slightly different options to accomplish the task at hand.

using toMap:

list.stream()
    .collect(Collectors.toMap(Function.identity(), e -> 1, Math::addExact));

using Map::merge:

Map<String, Integer> accumulator = new HashMap<>();
list.forEach(s -> accumulator.merge(s, 1, Math::addExact));

List all liquibase sql types

I've found the liquibase.database.typeconversion.core.AbstractTypeConverter class. It lists all types that can be used:

protected DataType getDataType(String columnTypeString, Boolean autoIncrement, String dataTypeName, String precision, String additionalInformation) {
    // Translate type to database-specific type, if possible
    DataType returnTypeName = null;
    if (dataTypeName.equalsIgnoreCase("BIGINT")) {
        returnTypeName = getBigIntType();
    } else if (dataTypeName.equalsIgnoreCase("NUMBER") || dataTypeName.equalsIgnoreCase("NUMERIC")) {
        returnTypeName = getNumberType();
    } else if (dataTypeName.equalsIgnoreCase("BLOB")) {
        returnTypeName = getBlobType();
    } else if (dataTypeName.equalsIgnoreCase("BOOLEAN")) {
        returnTypeName = getBooleanType();
    } else if (dataTypeName.equalsIgnoreCase("CHAR")) {
        returnTypeName = getCharType();
    } else if (dataTypeName.equalsIgnoreCase("CLOB")) {
        returnTypeName = getClobType();
    } else if (dataTypeName.equalsIgnoreCase("CURRENCY")) {
        returnTypeName = getCurrencyType();
    } else if (dataTypeName.equalsIgnoreCase("DATE") || dataTypeName.equalsIgnoreCase(getDateType().getDataTypeName())) {
        returnTypeName = getDateType();
    } else if (dataTypeName.equalsIgnoreCase("DATETIME") || dataTypeName.equalsIgnoreCase(getDateTimeType().getDataTypeName())) {
        returnTypeName = getDateTimeType();
    } else if (dataTypeName.equalsIgnoreCase("DOUBLE")) {
        returnTypeName = getDoubleType();
    } else if (dataTypeName.equalsIgnoreCase("FLOAT")) {
        returnTypeName = getFloatType();
    } else if (dataTypeName.equalsIgnoreCase("INT")) {
        returnTypeName = getIntType();
    } else if (dataTypeName.equalsIgnoreCase("INTEGER")) {
        returnTypeName = getIntType();
    } else if (dataTypeName.equalsIgnoreCase("LONGBLOB")) {
        returnTypeName = getLongBlobType();
    } else if (dataTypeName.equalsIgnoreCase("LONGVARBINARY")) {
        returnTypeName = getBlobType();
    } else if (dataTypeName.equalsIgnoreCase("LONGVARCHAR")) {
        returnTypeName = getClobType();
    } else if (dataTypeName.equalsIgnoreCase("SMALLINT")) {
        returnTypeName = getSmallIntType();
    } else if (dataTypeName.equalsIgnoreCase("TEXT")) {
        returnTypeName = getClobType();
    } else if (dataTypeName.equalsIgnoreCase("TIME") || dataTypeName.equalsIgnoreCase(getTimeType().getDataTypeName())) {
        returnTypeName = getTimeType();
    } else if (dataTypeName.toUpperCase().contains("TIMESTAMP")) {
        returnTypeName = getDateTimeType();
    } else if (dataTypeName.equalsIgnoreCase("TINYINT")) {
        returnTypeName = getTinyIntType();
    } else if (dataTypeName.equalsIgnoreCase("UUID")) {
        returnTypeName = getUUIDType();
    } else if (dataTypeName.equalsIgnoreCase("VARCHAR")) {
        returnTypeName = getVarcharType();
    } else if (dataTypeName.equalsIgnoreCase("NVARCHAR")) {
        returnTypeName = getNVarcharType();
    } else {
        return new CustomType(columnTypeString,0,2);
    }

Entity Framework Core: A second operation started on this context before a previous operation completed

  • Solve my problem using this line of code in my Startup.cs file.
    Adding a transient service means that each time the service is requested, a new instance is created when you are working with Dependency injection

           services.AddDbContext<Context>(options =>
                            options.UseSqlServer(_configuration.GetConnectionString("ContextConn")),
                 ServiceLifetime.Transient);
    

Copying files using rsync from remote server to local machine

I think it is better to copy files from your local computer, because if files number or file size is very big, copying process could be interrupted if your current ssh session would be lost (broken pipe or whatever).

If you have configured ssh key to connect to your remote server, you could use the following command:

rsync -avP -e "ssh -i /home/local_user/ssh/key_to_access_remote_server.pem" remote_user@remote_host.ip:/home/remote_user/file.gz /home/local_user/Downloads/

Where v option is --verbose, a option is --archive - archive mode, P option same as --partial - keep partially transferred files, e option is --rsh=COMMAND - specifying the remote shell to use.

rsync man page

Check if something is (not) in a list in Python

How do I check if something is (not) in a list in Python?

The cheapest and most readable solution is using the in operator (or in your specific case, not in). As mentioned in the documentation,

The operators in and not in test for membership. x in s evaluates to True if x is a member of s, and False otherwise. x not in s returns the negation of x in s.

Additionally,

The operator not in is defined to have the inverse true value of in.

y not in x is logically the same as not y in x.

Here are a few examples:

'a' in [1, 2, 3]
# False

'c' in ['a', 'b', 'c']
# True

'a' not in [1, 2, 3]
# True

'c' not in ['a', 'b', 'c']
# False

This also works with tuples, since tuples are hashable (as a consequence of the fact that they are also immutable):

(1, 2) in [(3, 4), (1, 2)]
#  True

If the object on the RHS defines a __contains__() method, in will internally call it, as noted in the last paragraph of the Comparisons section of the docs.

... in and not in, are supported by types that are iterable or implement the __contains__() method. For example, you could (but shouldn't) do this:

[3, 2, 1].__contains__(1)
# True

in short-circuits, so if your element is at the start of the list, in evaluates faster:

lst = list(range(10001))
%timeit 1 in lst
%timeit 10000 in lst  # Expected to take longer time.

68.9 ns ± 0.613 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
178 µs ± 5.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

If you want to do more than just check whether an item is in a list, there are options:

  • list.index can be used to retrieve the index of an item. If that element does not exist, a ValueError is raised.
  • list.count can be used if you want to count the occurrences.

The XY Problem: Have you considered sets?

Ask yourself these questions:

  • do you need to check whether an item is in a list more than once?
  • Is this check done inside a loop, or a function called repeatedly?
  • Are the items you're storing on your list hashable? IOW, can you call hash on them?

If you answered "yes" to these questions, you should be using a set instead. An in membership test on lists is O(n) time complexity. This means that python has to do a linear scan of your list, visiting each element and comparing it against the search item. If you're doing this repeatedly, or if the lists are large, this operation will incur an overhead.

set objects, on the other hand, hash their values for constant time membership check. The check is also done using in:

1 in {1, 2, 3} 
# True

'a' not in {'a', 'b', 'c'}
# False

(1, 2) in {('a', 'c'), (1, 2)}
# True

If you're unfortunate enough that the element you're searching/not searching for is at the end of your list, python will have scanned the list upto the end. This is evident from the timings below:

l = list(range(100001))
s = set(l)

%timeit 100000 in l
%timeit 100000 in s

2.58 ms ± 58.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
101 ns ± 9.53 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

As a reminder, this is a suitable option as long as the elements you're storing and looking up are hashable. IOW, they would either have to be immutable types, or objects that implement __hash__.

Run Python script at startup in Ubuntu

Create file ~/.config/autostart/MyScript.desktop with

[Desktop Entry]
Encoding=UTF-8
Name=MyScript
Comment=MyScript
Icon=gnome-info
Exec=python /home/your_path/script.py
Terminal=false
Type=Application
Categories=

X-GNOME-Autostart-enabled=true
X-GNOME-Autostart-Delay=0

It helps me!

Should you use rgba(0, 0, 0, 0) or rgba(255, 255, 255, 0) for transparency in CSS?

There a small difference when u use rgba(255,255,255,a),background color becomes more and more lighter as the value of 'a' increase from 0.0 to 1.0. Where as when use rgba(0,0,0,a), the background color becomes more and more darker as the value of 'a' increases from 0.0 to 1.0. Having said that, its clear that both (255,255,255,0) and (0,0,0,0) make background transparent. (255,255,255,1) would make the background completely white where as (0,0,0,1) would make background completely black.

Convert string to symbol-able in ruby

Rails got ActiveSupport::CoreExtensions::String::Inflections module that provides such methods. They're all worth looking at. For your example:

'Book Author Title'.parameterize.underscore.to_sym # :book_author_title

Get combobox value in Java swing

If the string is empty, comboBox.getSelectedItem().toString() will give a NullPointerException. So better to typecast by (String).

Prevent HTML5 video from being downloaded (right-click saved)?

The

<body oncontextmenu="return false;"> 

no longer works. Chrome and Opera as of June 2018 has a submenu on the timeline to allow straight download, so user doesn't need to right click to download that video. Interestingly Firefox and Edge don't have this ...

Disable Auto Zoom in Input "Text" tag - Safari on iPhone

I did this, also with jQuery:

$('input[type=search]').on('focus', function(){
  // replace CSS font-size with 16px to disable auto zoom on iOS
  $(this).data('fontSize', $(this).css('font-size')).css('font-size', '16px');
}).on('blur', function(){
  // put back the CSS font-size
  $(this).css('font-size', $(this).data('fontSize'));
});

Of course, some other elements in the interface may have to be adapted if this 16px font-size breaks the design.

How to check if a table is locked in sql server

sys.dm_tran_locks contains the locking information of the sessions

If you want to know a specific table is locked or not, you can use the following query

SELECT 
 * 
from 
 sys.dm_tran_locks 
where 
  resource_associated_entity_id = object_id('schemaname.tablename')

if you are interested in finding both login name of the user and the query being run

SELECT
 DB_NAME(resource_database_id)
 , s.original_login_name
 , s.status
 , s.program_name
 , s.host_name
 , (select text from sys.dm_exec_sql_text(exrequests.sql_handle))
 ,*
from
  sys.dm_tran_locks dbl
     JOIN sys.dm_exec_sessions s ON dbl.request_session_id = s.session_id
  INNER JOIN  sys.dm_exec_requests exrequests on dbl.request_session_id = exrequests.session_id
where
 DB_NAME(dbl.resource_database_id) = 'dbname'

For more infomraton locking query

More infor about sys.dm_tran_locks

Android OnClickListener - identify a button

In addition to Cristian C's answer (sorry, I do not have the ability to make comments), if you make one handler for both buttons, you may directly compare v to b1 and b2, or if you want to compare by the ID, you do not need to cast v to Button (View has getId() method, too), and that way there is no worry of cast exception.

Prevent text selection after double click

FWIW, I set user-select: none to the parent element of those child elements that I don't want somehow selected when double clicking anywhere on the parent element. And it works! Cool thing is contenteditable="true", text selection and etc. still works on the child elements!

So like:

<div style="user-select: none">
  <p>haha</p>
  <p>haha</p>
  <p>haha</p>
  <p>haha</p>
</div>

What does "select 1 from" do?

The construction is usually used in "existence" checks

if exists(select 1 from customer_table where customer = 'xxx')

or

if exists(select * from customer_table where customer = 'xxx')

Both constructions are equivalent. In the past people said the select * was better because the query governor would then use the best indexed column. This has been proven not true.

How do android screen coordinates work?

For Android API level 13 and you need to use this:

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int maxX = size.x; 
int maxY = size.y;

Then (0,0) is top left corner and (maxX,maxY) is bottom right corner of the screen.

The 'getWidth()' for screen size is deprecated since API 13

Furthermore getwidth() and getHeight() are methods of android.view.View class in android.So when your java class extends View class there is no windowManager overheads.

          int maxX=getwidht();
          int maxY=getHeight();

as simple as that.

JavaScript and Threads

You could use Narrative JavaScript, a compiler that will transforms your code into a state machine, effectively allowing you to emulate threading. It does so by adding a "yielding" operator (notated as '->') to the language that allows you to write asynchronous code in a single, linear code block.

Why are hexadecimal numbers prefixed with 0x?

It's a prefix to indicate the number is in hexadecimal rather than in some other base. The C programming language uses it to tell compiler.

Example:

0x6400 translates to 6*16^3 + 4*16^2 + 0*16^1 +0*16^0 = 25600. When compiler reads 0x6400, It understands the number is hexadecimal with the help of 0x term. Usually we can understand by (6400)16 or (6400)8 or whatever ..

For binary it would be:

0b00000001

Hope I have helped in some way.

Good day!

Failed to resolve version for org.apache.maven.archetypes

I had the same problem i solved it by only adding remote catalog in eclipse go to Window -> Preferences ->Maven ->Archetypes ->click on add remote Catalog then a window will open in that paste
http://repo.maven.apache.org/maven2/archetype-catalog.xml in that catalog file then hit ok restart eclipse now all working fine

@angular/material/index.d.ts' is not a module

After upgrading to Angular 9 (released today), I ran into this issue as well and found that they made the breaking change mentioned in the answer. I can't find a reason for why they made this change.

I have a material.module.ts file that I import / export all the material components (not the most efficient, but useful for quick development). I went through and updated all my imports to the individual material folders, although an index.ts barrel might be better. Again, not sure why they made this change, but I'm guessing it has to do with tree-shaking efficiencies.

Including my material.module.ts below in case it helps anyone, it's inspired off other material modules I've found:

NOTE: As other blog posts have mentioned and from my personal experience, be careful when using a shared module like below. I have 5~ different feature modules (lazy loaded) in my app that I imported my material module into. Out of curiosity, I stopped using the shared module and instead only imported the individual material components each feature module needed. This reduced my bundle size quite a bit, almost a 200kb reduction. I assumed that the build optimization process would properly drop any component not used by my modules, but it doesn't seem to be the case...

// material.module.ts
import { ModuleWithProviders, NgModule} from "@angular/core";
import { MAT_LABEL_GLOBAL_OPTIONS, MatNativeDateModule, MAT_DATE_LOCALE } from '@angular/material/core';
import { MatIconRegistry } from '@angular/material/icon';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatBadgeModule } from '@angular/material/badge';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatChipsModule } from '@angular/material/chips';
import { MatStepperModule } from '@angular/material/stepper';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatDialogModule } from '@angular/material/dialog';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatListModule } from '@angular/material/list';
import { MatMenuModule } from '@angular/material/menu';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatRadioModule } from '@angular/material/radio';
import { MatRippleModule } from '@angular/material/core';
import { MatSelectModule } from '@angular/material/select';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatSliderModule } from '@angular/material/slider';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { MatSortModule } from '@angular/material/sort';
import { MatTableModule } from '@angular/material/table';
import { MatTabsModule } from '@angular/material/tabs';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatTreeModule } from '@angular/material/tree';

@NgModule({
    imports: [
        MatAutocompleteModule,
        MatBadgeModule,
        MatButtonModule,
        MatButtonToggleModule,
        MatCardModule,
        MatCheckboxModule,
        MatChipsModule,
        MatStepperModule,
        MatDatepickerModule,
        MatDialogModule,
        MatExpansionModule,
        MatFormFieldModule,
        MatGridListModule,
        MatIconModule,
        MatInputModule,
        MatListModule,
        MatMenuModule,
        MatPaginatorModule,
        MatProgressBarModule,
        MatProgressSpinnerModule,
        MatRadioModule,
        MatRippleModule,
        MatSelectModule,
        MatSidenavModule,
        MatSliderModule,
        MatSlideToggleModule,
        MatSnackBarModule,
        MatSortModule,
        MatTableModule,
        MatTabsModule,
        MatToolbarModule,
        MatTooltipModule,
        MatTreeModule,
        MatNativeDateModule
    ],
    exports: [
        MatAutocompleteModule,
        MatBadgeModule,
        MatButtonModule,
        MatButtonToggleModule,
        MatCardModule,
        MatCheckboxModule,
        MatChipsModule,
        MatStepperModule,
        MatDatepickerModule,
        MatDialogModule,
        MatExpansionModule,
        MatFormFieldModule,
        MatGridListModule,
        MatIconModule,
        MatInputModule,
        MatListModule,
        MatMenuModule,
        MatPaginatorModule,
        MatProgressBarModule,
        MatProgressSpinnerModule,
        MatRadioModule,
        MatRippleModule,
        MatSelectModule,
        MatSidenavModule,
        MatSliderModule,
        MatSlideToggleModule,
        MatSnackBarModule,
        MatSortModule,
        MatTableModule,
        MatTabsModule,
        MatToolbarModule,
        MatTooltipModule,
        MatTreeModule,
        MatNativeDateModule
    ],
    providers: [     
    ]
})
export class MaterialModule {
    constructor(public matIconRegistry: MatIconRegistry) {
        // matIconRegistry.registerFontClassAlias('fontawesome', 'fa');
    }

    static forRoot(): ModuleWithProviders<MaterialModule> {
        return {
            ngModule: MaterialModule,
            providers: [MatIconRegistry]
        };
    }
}

How to make a new List in Java

One example:

List somelist = new ArrayList();

You can look at the javadoc for List and find all known implementing classes of the List interface that are included with the java api.

How can I lock a file using java (if possible)

Below is a sample snippet code to lock a file until it's process is done by JVM.

 public static void main(String[] args) throws InterruptedException {
    File file = new File(FILE_FULL_PATH_NAME);
    RandomAccessFile in = null;
    try {
        in = new RandomAccessFile(file, "rw");
        FileLock lock = in.getChannel().lock();
        try {

            while (in.read() != -1) {
                System.out.println(in.readLine());
            }
        } finally {
            lock.release();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Retain precision with double in Java

Do not waste your efford using BigDecimal. In 99.99999% cases you don't need it. java double type is of cource approximate but in almost all cases, it is sufficiently precise. Mind that your have an error at 14th significant digit. This is really negligible!

To get nice output use:

System.out.printf("%.2f\n", total);

Create instance of generic type in Java?

return   (E)((Class)((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0]).newInstance();

Jenkins - passing variables between jobs?

(for fellow googlers)

If you are building a serious pipeline with the Build Flow Plugin, you can pass parameters between jobs with the DSL like this :

Supposing an available string parameter "CVS_TAG", in order to pass it to other jobs :

build("pipeline_begin", CVS_TAG: params['CVS_TAG'])
parallel (
   // will be scheduled in parallel.
   { build("pipeline_static_analysis", CVS_TAG: params['CVS_TAG']) },
   { build("pipeline_nonreg", CVS_TAG: params['CVS_TAG']) }
)
// will be triggered after previous jobs complete
build("pipeline_end", CVS_TAG: params['CVS_TAG'])

Hint for displaying available variables / params :

// output values
out.println '------------------------------------'
out.println 'Triggered Parameters Map:'
out.println params
out.println '------------------------------------'
out.println 'Build Object Properties:'
build.properties.each { out.println "$it.key -> $it.value" }
out.println '------------------------------------'

openssl s_client -cert: Proving a client certificate was sent to the server

I know this is an old question but it does not yet appear to have an answer. I've duplicated this situation, but I'm writing the server app, so I've been able to establish what happens on the server side as well. The client sends the certificate when the server asks for it and if it has a reference to a real certificate in the s_client command line. My server application is set up to ask for a client certificate and to fail if one is not presented. Here is the command line I issue:

Yourhostname here -vvvvvvvvvv s_client -connect <hostname>:443 -cert client.pem -key cckey.pem -CAfile rootcert.pem -cipher ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH -tls1 -state

When I leave out the "-cert client.pem" part of the command the handshake fails on the server side and the s_client command fails with an error reported. I still get the report "No client certificate CA names sent" but I think that has been answered here above.

The short answer then is that the server determines whether a certificate will be sent by the client under normal operating conditions (s_client is not normal) and the failure is due to the server not recognizing the CA in the certificate presented. I'm not familiar with many situations in which two-way authentication is done although it is required for my project.

You are clearly sending a certificate. The server is clearly rejecting it.

The missing information here is the exact manner in which the certs were created and the way in which the provider loaded the cert, but that is probably all wrapped up by now.

Remove Datepicker Function dynamically

You can try the enable/disable methods instead of using the option method:

$("#txtSearch").datepicker("enable");
$("#txtSearch").datepicker("disable");

This disables the entire textbox. So may be you can use datepicker.destroy() instead:

$(document).ready(function() {
    $("#ddlSearchType").change(function() {
        if ($(this).val() == "Required Date" || $(this).val() == "Submitted Date") {
            $("#txtSearch").datepicker();
        }
        else {
            $("#txtSearch").datepicker("destroy");
        }
    }).change();
});

Demo here.

HTTP Error 500.19 and error code : 0x80070021

As the error idnicates - "This happens when the section is locked at a parent level". To unlock the section you can use appcmd.exe and execute the following command:

%windir%\system32\inetsrv\appcmd.exe unlock config -section:system.webServer/handlers -commitpath:apphost

For more information on about section locking and what a parent configuration context is refer to IIS documentation.

How to use mongoose findOne

Mongoose basically wraps mongodb's api to give you a pseudo relational db api so queries are not going to be exactly like mongodb queries. Mongoose findOne query returns a query object, not a document. You can either use a callback as the solution suggests or as of v4+ findOne returns a thenable so you can use .then or await/async to retrieve the document.

// thenables
Auth.findOne({nick: 'noname'}).then(err, result) {console.log(result)};
Auth.findOne({nick: 'noname'}).then(function (doc) {console.log(doc)});

// To use a full fledge promise you will need to use .exec()
var auth = Auth.findOne({nick: 'noname'}).exec();
auth.then(function (doc) {console.log(doc)});

// async/await
async function auth() {
  const doc = await Auth.findOne({nick: 'noname'}).exec();
  return doc;
}
auth();

See the docs if you would like to use a third party promise library.

How many significant digits do floats and doubles have in java?

Floating point numbers are encoded using an exponential form, that is something like m * b ^ e, i.e. not like integers at all. The question you ask would be meaningful in the context of fixed point numbers. There are numerous fixed point arithmetic libraries available.

Regarding floating point arithmetic: The number of decimal digits depends on the presentation and the number system. For example there are periodic numbers (0.33333) which do not have a finite presentation in decimal but do have one in binary and vice versa.

Also it is worth mentioning that floating point numbers up to a certain point do have a difference larger than one, i.e. value + 1 yields value, since value + 1 can not be encoded using m * b ^ e, where m, b and e are fixed in length. The same happens for values smaller than 1, i.e. all the possible code points do not have the same distance.

Because of this there is no precision of exactly n digits like with fixed point numbers, since not every number with n decimal digits does have a IEEE encoding.

There is a nearly obligatory document which you should read then which explains floating point numbers: What every computer scientist should know about floating point arithmetic.

ASP.NET MVC passing an ID in an ActionLink to the controller

On MVC 5 is quite similar

@Html.ActionLink("LinkText", "ActionName", new { id = "id" })

How to install a package inside virtualenv?

Avoiding Headaches and Best Practices:

  • Virtual Environments are not part of your git project (they don't need to be versioned) !

  • They can reside on the project folder (locally), but, ignored on your .gitignore.

  • After activating the virtual environment of your project, never "sudo pip install package".
  • After finishing your work, always "deactivate" your environment.
  • Avoid renaming your project folder.


For a better representation, here's a simulation:

creating a folder for your projects/environments

$ mkdir venv

creating environment

$ cd venv/ 

$ virtualenv google_drive
New python executable in google_drive/bin/python
Installing setuptools, pip...done.

activating environment

$ source google_drive/bin/activate

installing packages

(google_drive) $ pip install PyDrive
Downloading/unpacking PyDrive
Downloading PyDrive-1.3.1-py2-none-any.whl
...
...
...    
Successfully installed PyDrive PyYAML google-api-python-client oauth2client six uritemplate httplib2 pyasn1 rsa pyasn1-modules
Cleaning up...

package available inside the environment

(google_drive) $ python
Python 2.7.6 (default, Oct 26 2016, 20:30:19) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import pydrive.auth
>>>  
>>> gdrive = pydrive.auth.GoogleAuth()
>>>

deactivate environment

(google_drive) $ deactivate 

$ 

package NOT AVAILABLE outside the environment

$ python
Python 2.7.6 (default, Oct 26 2016, 20:32:10) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import pydrive.auth
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named pydrive.auth
>>> 

Notes:

Why not sudo?

Virtualenv creates a whole new environment for you, defining $PATH and some other variables and settings. When you use sudo pip install package, you are running Virtualenv as root, escaping the whole environment which was created, and then, installing the package on global site-packages, and not inside the project folder where you have a Virtual Environment, although you have activated the environment.

If you rename the folder of your project...

...you'll have to adjust some variables from some files inside the bin directory of your project.

For example:

bin/pip, line 1 (She Bang)

bin/activate, line 42 (VIRTUAL_ENV)

Reading tab-delimited file with Pandas - works on Windows, but not on Mac

Another option would be to add engine='python' to the command pandas.read_csv(filename, sep='\t', engine='python')

Convert interface{} to int

To better understand the type conversion, look at the code below:

package main
import "fmt"
func foo(a interface{}) {
    fmt.Println(a.(int))  // conversion of interface into int
}
func main() {
    var a int = 10
    foo(a)
}

This code executes perfectly and converts interface type to int type

For an expression x of interface type and a type T, the primary expression x.(T) asserts that x is not nil and that the value stored in x is of type T. The notation x.(T) is called a type assertion. More precisely, if T is not an interface type, x.(T) asserts that the dynamic type of x is identical to the type T. In this case, T must implement the (interface) type of x; otherwise the type assertion is invalid since it is not possible for x to store a value of type T. If T is an interface type, x.(T) asserts that the dynamic type of x implements the interface T.

Going back to your code, this

iAreaId := val.(int)

should work good. If you want to check error occured while conversion, you can also re-write above line as

iAreaId, ok := val.(int)

urllib and "SSL: CERTIFICATE_VERIFY_FAILED" Error

Already lots of answers here, but we ran into this in a very specific case and blew a lot of time investigating, so adding yet another one. We saw it in the following case:

  • In a debian-stretch-slim docker container
  • Default Python 3.5.3 easy_install3
  • For LetsEncrypt certificates registered using cert-manager in our Kubernetes cluster

pip3 and openssl command line were both able to verify the cert and easy_install3 was able to verify other LetsEncrypt certs successfully.

The workaround was to build the latest Python (3.7.3 at the time) from source. The instructions here are detailed and easy to follow.

How to use pip with python 3.4 on windows?

"On Windows and Mac OS X, the CPython installers now default to installing pip along with CPython itself (users may opt out of installing it during the installation process). Window users will need to opt in to the automatic PATH modifications to have pip available from the command line by default, otherwise it can still be accessed through the Python launcher for Windows as py -m pip."

Have you tried it?

Selenium Webdriver move mouse to Point

Why use java.awt.Robot when org.openqa.selenium.interactions.Actions.class would probably work fine? Just sayin.

Actions builder = new Actions(driver);

builder.keyDown(Keys.CONTROL)
   .click(someElement)
   .moveByOffset( 10, 25 );
   .click(someOtherElement)
   .keyUp(Keys.CONTROL).build().perform();

Telnet is not recognized as internal or external command

If your Windows 7 machine is a member of an AD, or if you have UAC enabled, or if security policies are in effect, telnet more often than not must be run as an admin. The easiest way to do this is as follows

  1. Create a shortcut that calls cmd.exe

  2. Go to the shortcut's properties

  3. Click on the Advanced button

  4. Check the "Run as an administrator" checkbox

    After these steps you're all set and telnet should work now.

Check for special characters (/*-+_@&$#%) in a string?

Simple:

function HasSpecialChars(string yourString)
{
    return yourString.Any( ch => ! Char.IsLetterOrDigit( ch ) )
}

Move top 1000 lines from text file to a new file using Unix shell commands

Perl approach:

perl -ne 'if($i<1000) { print; } else { print STDERR;}; $i++;' in 1> in.new 2> out && mv in.new in

How to vertically center <div> inside the parent element with CSS?

I needed to specify min-height

#login
    display: flex
    align-items: center
    justify-content: center
    min-height: 16em

How can I change Mac OS's default Java VM returned from /usr/libexec/java_home

I think JAVA_HOME is the best you can do. The command-line tools like java and javac will respect that environment variable, you can use /usr/libexec/java_home -v '1.7*' to give you a suitable value to put into JAVA_HOME in order to make command line tools use Java 7.

export JAVA_HOME="`/usr/libexec/java_home -v '1.7*'`"

But standard double-clickable application bundles don't use JDKs installed under /Library/Java at all. Old-style .app bundles using Apple's JavaApplicationStub will use Apple Java 6 from /System/Library/Frameworks, and new-style ones built with AppBundler without a bundled JRE will use the "public" JRE in /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home - that's hard-coded in the stub code and can't be changed, and you can't have two different public JREs installed at the same time.


Edit: I've had a look at VisualVM specifically, assuming you're using the "application bundle" version from the download page, and this particular app is not an AppBundler application, instead its main executable is a shell script that calls a number of other shell scripts and reads various configuration files. It defaults to picking the newest JDK from /Library/Java as long as that is 7u10 or later, or uses Java 6 if your Java 7 installation is update 9 or earlier. But unravelling the logic in the shell scripts it looks to me like you can specify a particular JDK using a configuration file.

Create a text file ~/Library/Application Support/VisualVM/1.3.6/etc/visualvm.conf (replace 1.3.6 with whatever version of VisualVM you're using) containing the line

visualvm_jdkhome="`/usr/libexec/java_home -v '1.7*'`"

and this will force it to choose Java 7 instead of 8.

How to set Internet options for Android emulator?

-http-proxy can be set in eclipse this way:

  1. Menu Window
  2. Submenu Preferences
  3. In Preferences Dialog Click Android in left part Click Launch Near Default Emulator Options: input ur -http-proxy

How to re-render flatlist?

For quick and simple solution Try:

  1. set extra data to a boolean value.

    extraData={this.state.refresh}

  2. Toggle the value of boolean state when you want to re-render/refresh list

    this.setState({ 
        refresh: !this.state.refresh
    })
    

How do you access the value of an SQL count () query in a Java program

I would expect this query to work with your program:

"SELECT COUNT(*) AS count FROM "+lastTempTable+")"

(You need to alias the column, not the table)

How to filter specific apps for ACTION_SEND intent (and set a different text for each app)

I had same problem and this accepted solution didn't helped me, if someone has same problem you can use my code snippet:

// example of filtering and sharing multiple images with texts
// remove facebook from sharing intents
private void shareFilter(){

    String share = getShareTexts();
    ArrayList<Uri> uris = getImageUris();

    List<Intent> targets = new ArrayList<>();
    Intent template = new Intent(Intent.ACTION_SEND_MULTIPLE);
    template.setType("image/*");
    List<ResolveInfo> candidates = getActivity().getPackageManager().
            queryIntentActivities(template, 0);

    // remove facebook which has a broken share intent
    for (ResolveInfo candidate : candidates) {
        String packageName = candidate.activityInfo.packageName;
        if (!packageName.equals("com.facebook.katana")) {
            Intent target = new Intent(Intent.ACTION_SEND_MULTIPLE);
            target.setType("image/*");
            target.putParcelableArrayListExtra(Intent.EXTRA_STREAM,uris);
            target.putExtra(Intent.EXTRA_TEXT, share);
            target.setPackage(packageName);
            targets.add(target);
        }
    }
    Intent chooser = Intent.createChooser(targets.remove(0), "Share Via");
    chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, targets.toArray(new Parcelable[targets.size()]));
    startActivity(chooser);

}

Facebook Javascript SDK Problem: "FB is not defined"

This error will also appear if you omit the semicolon after the fbAsyncInit definition.

window.fbAsyncInit = function() {
    FB.init({
        appId: 'YOUR APP ID',
        status: true,
        cookie: true,
        xfbml: true
    });
    //do stuff
}; //<-- semicolon required!

Without the semicolon, the situation is the same as in this shorter example:

var x = function () {
    console.log('This is never called. Or is it?');
}

('bar');

The function gets called, because without the semicolon the ('bar') part is seen as a call to the function just defined.

How to print all key and values from HashMap in Android?

String text="";

    for (Iterator i = keys.iterator(); i.hasNext() 
       {
           String key = (String) i.next();
           String value = (String) map.get(key);
           text+=key + " = " + value;
       }

        textview.setText(text);

Removing a model in rails (reverse of "rails g model Title...")

Here's a different implementation of Jenny Lang's answer that works for Rails 5.

First create the migration file:

bundle exec be rails g migration DropEpisodes

Then populate the migration file as follows:

class DropEpisodes < ActiveRecord::Migration[5.1]
  def change
    drop_table :episodes
  end
end

Running rails db:migrate will drop the table. If you run rails db:rollback, Rails will throw a ActiveRecord::IrreversibleMigration error.

Using `window.location.hash.includes` throws “Object doesn't support property or method 'includes'” in IE11

I had a similar issue with an Angular project. In my polyfills.ts I had to add both:

    import "core-js/es7/array";
    import "core-js/es7/object";

In addition to enabling all the other IE 11 defaults. (See comments in polyfills.ts if using angular)

After adding these imports the error went away and my Object data populated as intended.

How to extend available properties of User.Identity

Check out this great blog post by John Atten: ASP.NET Identity 2.0: Customizing Users and Roles

It has great step-by-step info on the whole process. Go read it : )

Here are some of the basics.

Extend the default ApplicationUser class by adding new properties (i.e.- Address, City, State, etc.):

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> 
    GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this,  DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    }
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }

    // Use a sensible display name for views:
    [Display(Name = "Postal Code")]
    public string PostalCode { get; set; }

    // Concatenate the address info for display in tables and such:
    public string DisplayAddress
    {
        get
        {
            string dspAddress = string.IsNullOrWhiteSpace(this.Address) ? "" : this.Address;
            string dspCity = string.IsNullOrWhiteSpace(this.City) ? "" : this.City;
            string dspState = string.IsNullOrWhiteSpace(this.State) ? "" : this.State;
            string dspPostalCode = string.IsNullOrWhiteSpace(this.PostalCode) ? "" : this.PostalCode;

            return string.Format("{0} {1} {2} {3}", dspAddress, dspCity, dspState, dspPostalCode);
        }
    }

Then you add your new properties to your RegisterViewModel.

    // Add the new address properties:
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }

Then update the Register View to include the new properties.

    <div class="form-group">
        @Html.LabelFor(m => m.Address, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Address, new { @class = "form-control" })
        </div>
    </div>

Then update the Register() method on AccountController with the new properties.

    // Add the Address properties:
    user.Address = model.Address;
    user.City = model.City;
    user.State = model.State;
    user.PostalCode = model.PostalCode;

How to upload a file and JSON data in Postman?

If somebody wants to send json data in form-data format just need to declare the variables like this

Postman:

As you see, the description parameter will be in basic json format, result of that:

{ description: { spanish: 'hola', english: 'hello' } }

Node.js, can't open files. Error: ENOENT, stat './path/to/file'

Paths specified with a . are relative to the current working directory, not relative to the script file. So the file might be found if you run node app.js but not if you run node folder/app.js. The only exception to this is require('./file') and that is only possible because require exists per-module and thus knows what module it is being called from.

To make a path relative to the script, you must use the __dirname variable.

var path = require('path');

path.join(__dirname, 'path/to/file')

or potentially

path.join(__dirname, 'path', 'to', 'file')

How to set margin of ImageView using code, not xml

For me this worked:

int imgCarMarginRightPx = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, definedValueInDp, res.getDisplayMetrics());

MarginLayoutParams lp = (MarginLayoutParams) imgCar.getLayoutParams();
lp.setMargins(0,0,imgCarMarginRightPx,0);
imgCar.setLayoutParams(lp);

Install opencv for Python 3.3

Someone has published a docker container / file for this:

https://github.com/vipul-sharma20/docker-opencv3-python3

https://hub.docker.com/r/vipul20/docker-opencv3-python3/~/dockerfile/

You can pull the image directly from docker hub or follow the instructions in the Dockerfile to install.

Passing multiple values to a single PowerShell script parameter

I call a scheduled script who must connect to a list of Server this way:

Powershell.exe -File "YourScriptPath" "Par1,Par2,Par3"

Then inside the script:

param($list_of_servers)
...
Connect-Viserver $list_of_servers.split(",")

The split operator returns an array of string

How to check if a list is empty in Python?

Empty lists evaluate to False in boolean contexts (such as if some_list:).

Assign width to half available screen width declaratively

Using constraints layout

  1. Add a Guideline
  2. Set the percentage to 50%
  3. Constrain your view to the Guideline and the parent.

enter image description here

If you are having trouble changing it to a percentage, then see this answer.

XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="81dp">

    <android.support.constraint.Guideline
        android:id="@+id/guideline8"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.5"/>

    <TextView
        android:id="@+id/textView6"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="TextView"
        app:layout_constraintBottom_toTopOf="@+id/guideline8"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
    
</android.support.constraint.ConstraintLayout>

Is there a limit to the length of a GET request?

As Requested By User Erickson, I Post My comment As Answer:

I have done some more testing with IE8, IE9, FF14, Opera11, Chrome20 and Tomcat 6.0.32 (fresh installation), Jersey 1.13 on the server side. I used the jQuery function $.getJson and JSONP. Results: All Browsers allowed up to around 5400 chars. FF and IE9 did up to around 6200 chars. Everything above returned "400 Bad request". I did not further investigate what was responsible for the 400. I was fine with the maximum I found, because I needed around 2000 chars in my case.

How to add a RequiredFieldValidator to DropDownList control?

For the most part you treat it as if you are validating any other kind of control but use the InitialValue property of the required field validator.

<asp:RequiredFieldValidator ID="rfv1" runat="server" ControlToValidate="your-dropdownlist" InitialValue="Please select" ErrorMessage="Please select something" />

Basically what it's saying is that validation will succeed if any other value than the 1 set in InitialValue is selected in the dropdownlist.

If databinding you will need to insert the "Please select" value afterwards as follows

this.ddl1.Items.Insert(0, "Please select");

Bin size in Matplotlib (Histogram)

This answer support the @ macrocosme suggestion.

I am using heat map as hist2d plot. Additionally I use cmin=0.5 for no count value and cmap for color, r represent the reverse of given color.

Describe statistics. enter image description here

# np.arange(data.min(), data.max()+binwidth, binwidth)
bin_x = np.arange(0.6, 7 + 0.3, 0.3)
bin_y = np.arange(12, 58 + 3, 3)
plt.hist2d(data=fuel_econ, x='displ', y='comb', cmin=0.5, cmap='viridis_r', bins=[bin_x, bin_y]);
plt.xlabel('Dispalcement (1)');
plt.ylabel('Combine fuel efficiency (mpg)');

plt.colorbar();

enter image description here

AngularJS multiple filter with custom filter function

Try this:

<tr ng-repeat="player in players | filter:{id: player_id, name:player_name} | filter:ageFilter">

$scope.ageFilter = function (player) {
    return (player.age > $scope.min_age && player.age < $scope.max_age);
}

How to make the script wait/sleep in a simple way in unity

With .Net 4.x you can use Task-based Asynchronous Pattern (TAP) to achieve this:

// .NET 4.x async-await
using UnityEngine;
using System.Threading.Tasks;
public class AsyncAwaitExample : MonoBehaviour
{
     private async void Start()
     {
        Debug.Log("Wait.");
        await WaitOneSecondAsync();
        DoMoreStuff(); // Will not execute until WaitOneSecond has completed
     }
    private async Task WaitOneSecondAsync()
    {
        await Task.Delay(TimeSpan.FromSeconds(1));
        Debug.Log("Finished waiting.");
    }
}

this is a feature to use .Net 4.x with Unity please see this link for description about it

and this link for sample project and compare it with coroutine

But becareful as documentation says that This is not fully replacement with coroutine

Convert JSON string to array of JSON objects in Javascript

As Luca indicated, add extra [] to your string and use the code below:

var myObject = eval('(' + myJSONtext + ')');

to test it you can use the snippet below.

var s =" [{'id':1,'name':'Test1'},{'id':2,'name':'Test2'}]";
var myObject = eval('(' + s + ')');
for (i in myObject)
{
   alert(myObject[i]["name"]);
}

hope it helps..

Nginx Different Domains on Same IP

Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.

They should be

server {
    listen      80;
    server_name www.domain1.com;
    root /var/www/domain1;
}

server {
    listen       80;
    server_name www.domain2.com;
    root /var/www/domain2;
}

Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.

How do I use sudo to redirect output to a location I don't have permission to write to?

I would do it this way:

sudo su -c 'ls -hal /root/ > /root/test.out'

Where can I download english dictionary database in a text format?

Check if these free resources fit your need -

How to pass values across the pages in ASP.net without using Session

There are multiple ways to achieve this. I can explain you in brief about the 4 types which we use in our daily programming life cycle.

Please go through the below points.

1 Query String.

FirstForm.aspx.cs

Response.Redirect("SecondForm.aspx?Parameter=" + TextBox1.Text);

SecondForm.aspx.cs

TextBox1.Text = Request.QueryString["Parameter"].ToString();

This is the most reliable way when you are passing integer kind of value or other short parameters. More advance in this method if you are using any special characters in the value while passing it through query string, you must encode the value before passing it to next page. So our code snippet of will be something like this:

FirstForm.aspx.cs

Response.Redirect("SecondForm.aspx?Parameter=" + Server.UrlEncode(TextBox1.Text));

SecondForm.aspx.cs

TextBox1.Text = Server.UrlDecode(Request.QueryString["Parameter"].ToString());

URL Encoding

  1. Server.URLEncode
  2. HttpServerUtility.UrlDecode

2. Passing value through context object

Passing value through context object is another widely used method.

FirstForm.aspx.cs

TextBox1.Text = this.Context.Items["Parameter"].ToString();

SecondForm.aspx.cs

this.Context.Items["Parameter"] = TextBox1.Text;
Server.Transfer("SecondForm.aspx", true);

Note that we are navigating to another page using Server.Transfer instead of Response.Redirect.Some of us also use Session object to pass values. In that method, value is store in Session object and then later pulled out from Session object in Second page.

3. Posting form to another page instead of PostBack

Third method of passing value by posting page to another form. Here is the example of that:

FirstForm.aspx.cs

private void Page_Load(object sender, System.EventArgs e)
{
   buttonSubmit.Attributes.Add("onclick", "return PostPage();");
}

And we create a javascript function to post the form.

SecondForm.aspx.cs

function PostPage()
{
   document.Form1.action = "SecondForm.aspx";
   document.Form1.method = "POST";
   document.Form1.submit();
}
TextBox1.Text = Request.Form["TextBox1"].ToString();

Here we are posting the form to another page instead of itself. You might get viewstate invalid or error in second page using this method. To handle this error is to put EnableViewStateMac=false

4. Another method is by adding PostBackURL property of control for cross page post back

In ASP.NET 2.0, Microsoft has solved this problem by adding PostBackURL property of control for cross page post back. Implementation is a matter of setting one property of control and you are done.

FirstForm.aspx.cs

<asp:Button id=buttonPassValue style=”Z-INDEX: 102" runat=”server” Text=”Button”         PostBackUrl=”~/SecondForm.aspx”></asp:Button>

SecondForm.aspx.cs

TextBox1.Text = Request.Form["TextBox1"].ToString();

In above example, we are assigning PostBackUrl property of the button we can determine the page to which it will post instead of itself. In next page, we can access all controls of the previous page using Request object.

You can also use PreviousPage class to access controls of previous page instead of using classic Request object.

SecondForm.aspx

TextBox textBoxTemp = (TextBox) PreviousPage.FindControl(“TextBox1");
TextBox1.Text = textBoxTemp.Text;

As you have noticed, this is also a simple and clean implementation of passing value between pages.

Reference: MICROSOFT MSDN WEBSITE

HAPPY CODING!

Remove duplicated rows

The function distinct() in the dplyr package performs arbitrary duplicate removal, either from specific columns/variables (as in this question) or considering all columns/variables. dplyr is part of the tidyverse.

Data and package

library(dplyr)
dat <- data.frame(a = rep(c(1,2),4), b = rep(LETTERS[1:4],2))

Remove rows duplicated in a specific column (e.g., columna)

Note that .keep_all = TRUE retains all columns, otherwise only column a would be retained.

distinct(dat, a, .keep_all = TRUE)

  a b
1 1 A
2 2 B

Remove rows that are complete duplicates of other rows:

distinct(dat)

  a b
1 1 A
2 2 B
3 1 C
4 2 D

How to get the first element of the List or Set?

You can use the get(index) method to access an element from a List.

Sets, by definition, simply contain elements and have no particular order. Therefore, there is no "first" element you can get, but it is possible to iterate through it using iterator (using the for each loop) or convert it to an array using the toArray() method.

get jquery `$(this)` id

Do you mean that for a select element with an id of "next" you need to perform some specific script?

$("#next").change(function(){
    //enter code here
});

ngFor with index as value in attribute

You can use [attr.data-index] directly to save the index to data-index attribute which is available in Angular versions 2 and above.

    <ul*ngFor="let item of items; let i = index" [attr.data-index]="i">
         <li>{{item}}</li>
    </ul>

How to modify a global variable within a function in bash?

I had a similar problem, when I wanted to automatically remove temp files I had created. The solution I came up with was not to use command substitution, but rather to pass the name of the variable, that should take the final result, into the function. E.g.

#! /bin/bash

remove_later=""
new_tmp_file() {
    file=$(mktemp)
    remove_later="$remove_later $file"
    eval $1=$file
}
remove_tmp_files() {
    rm $remove_later
}
trap remove_tmp_files EXIT

new_tmp_file tmpfile1
new_tmp_file tmpfile2

So, in your case that would be:

#!/bin/bash

e=2

function test1() {
  e=4
  eval $1="hello"
}

test1 ret

echo "$ret"
echo "$e"

Works and has no restrictions on the "return value".

Creating a folder if it does not exists - "Item already exists"

With New-Item you can add the Force parameter

New-Item -Force -ItemType directory -Path foo

Or the ErrorAction parameter

New-Item -ErrorAction Ignore -ItemType directory -Path foo

Globally catch exceptions in a WPF application?

In addition what others mentioned here, note that combining the Application.DispatcherUnhandledException (and its similars) with

<configuration>
  <runtime>  
    <legacyUnhandledExceptionPolicy enabled="1" />
  </runtime>
</configuration>

in the app.config will prevent your secondary threads exception from shutting down the application.

Current timestamp as filename in Java

Use SimpleDateFormat as aix suggested to format the current time into a string. You should use a format that does not include / characters etc. I would suggest something like yyyyMMddhhmm

How do I disable a Pylint warning?

I had this problem using Eclipse and solved it as follows:

In the pylint folder (e.g. C:\Python26\Lib\site-packages\pylint), hold Shift, right-click and choose to open the windows command in that folder. Type:

lint.py --generate-rcfile > standard.rc

This creates the standard.rc configuration file. Open it in Notepad and under [MESSAGES CONTROL], uncomment disable= and add the message ID's you want to disable, e.g.:

disable=W0511, C0321

Save the file, and in Eclipse ? Window ? Preferences ? PyDev ? *pylint, in the arguments box, type:

--rcfile=C:\Python26\Lib\site-packages\pylint\standard.rc

Now it should work...


You can also add a comment at the top of your code that will be interpreted by Pylint:

# pylint: disable=C0321

Pylint message codes.


Adding e.g. --disable-ids=C0321 in the arguments box does not work.

All available Pylint messages are stored in the dictionary _messages, an attribute of an instance of the pylint.utils.MessagesHandlerMixIn class. When running Pylint with the argument --disable-ids=... (at least without a configuration file), this dictionary is initially empty, raising a KeyError exception within Pylint (pylint.utils.MessagesHandlerMixIn.check_message_id().

In Eclipse, you can see this error-message in the Pylint Console (windows* ? show view ? Console, select Pylint console from the console options besides the console icon.)

How to sort a collection by date in MongoDB?

Additional Square [ ] Bracket is required for sorting parameter to work.

collection.find({}, {"sort" : [['datefield', 'asc']]} ).toArray(function(err,docs) {});

Convert array to JSON string in swift

How to convert array to json String in swift 2.3

var yourString : String = ""
do
{
    if let postData : NSData = try NSJSONSerialization.dataWithJSONObject(yourArray, options: NSJSONWritingOptions.PrettyPrinted)
    {
        yourString = NSString(data: postData, encoding: NSUTF8StringEncoding)! as String
    }
}
catch
{
    print(error)
}

And now you can use yourSting as JSON string..

CKEditor instance already exists

Indeed, removing the ".ckeditor" class from your code solves the issue. Most of us followed the jQuery integration example from the ckeditor's documentation:

$('.jquery_ckeditor')
.ckeditor( function() { /* callback code */ }, { skin : 'office2003' } );

and thought "... maybe I can just get rid or the '.jquery_' part".

I've been wasting my time tweaking the callback function (because the {skin:'office2003'} actually worked), while the problem was coming from elsewhere.

I think the documentation should mention that the use of "ckeditor" as a class name is not recommended, because it is a reserved keyword.

Cheers.

Detect and exclude outliers in Pandas data frame

Another option is to transform your data so that the effect of outliers is mitigated. You can do this by winsorizing your data.

import pandas as pd
from scipy.stats import mstats
%matplotlib inline

test_data = pd.Series(range(30))
test_data.plot()

Original data

# Truncate values to the 5th and 95th percentiles
transformed_test_data = pd.Series(mstats.winsorize(test_data, limits=[0.05, 0.05])) 
transformed_test_data.plot()

Winsorized data

When to use extern in C++

It is useful when you share a variable between a few modules. You define it in one module, and use extern in the others.

For example:

in file1.cpp:

int global_int = 1;

in file2.cpp:

extern int global_int;
//in some function
cout << "global_int = " << global_int;

Python datetime - setting fixed hour and minute after using strptime to get day,month,year

Use datetime.replace:

from datetime import datetime
dt = datetime.strptime('26 Sep 2012', '%d %b %Y')
newdatetime = dt.replace(hour=11, minute=59)

JavaScript, get date of the next day

Using Date object guarantees that. For eg if you try to create April 31st :

new Date(2014,3,31)        // Thu May 01 2014 00:00:00

Please note that it's zero indexed, so Jan. is 0, Feb. is 1 etc.

Best practice for Django project working directory structure

There're two kind of Django "projects" that I have in my ~/projects/ directory, both have a bit different structure.:

  • Stand-alone websites
  • Pluggable applications

Stand-alone website

Mostly private projects, but doesn't have to be. It usually looks like this:

~/projects/project_name/

docs/               # documentation
scripts/
  manage.py         # installed to PATH via setup.py
project_name/       # project dir (the one which django-admin.py creates)
  apps/             # project-specific applications
    accounts/       # most frequent app, with custom user model
    __init__.py
    ...
  settings/         # settings for different environments, see below
    __init__.py
    production.py
    development.py
    ...
        
  __init__.py       # contains project version
  urls.py
  wsgi.py
static/             # site-specific static files
templates/          # site-specific templates
tests/              # site-specific tests (mostly in-browser ones)
tmp/                # excluded from git
setup.py
requirements.txt
requirements_dev.txt
pytest.ini
...

Settings

The main settings are production ones. Other files (eg. staging.py, development.py) simply import everything from production.py and override only necessary variables.

For each environment, there are separate settings files, eg. production, development. I some projects I have also testing (for test runner), staging (as a check before final deploy) and heroku (for deploying to heroku) settings.

Requirements

I rather specify requirements in setup.py directly. Only those required for development/test environment I have in requirements_dev.txt.

Some services (eg. heroku) requires to have requirements.txt in root directory.

setup.py

Useful when deploying project using setuptools. It adds manage.py to PATH, so I can run manage.py directly (anywhere).

Project-specific apps

I used to put these apps into project_name/apps/ directory and import them using relative imports.

Templates/static/locale/tests files

I put these templates and static files into global templates/static directory, not inside each app. These files are usually edited by people, who doesn't care about project code structure or python at all. If you are full-stack developer working alone or in a small team, you can create per-app templates/static directory. It's really just a matter of taste.

The same applies for locale, although sometimes it's convenient to create separate locale directory.

Tests are usually better to place inside each app, but usually there is many integration/functional tests which tests more apps working together, so global tests directory does make sense.

Tmp directory

There is temporary directory in project root, excluded from VCS. It's used to store media/static files and sqlite database during development. Everything in tmp could be deleted anytime without any problems.

Virtualenv

I prefer virtualenvwrapper and place all venvs into ~/.venvs directory, but you could place it inside tmp/ to keep it together.

Project template

I've created project template for this setup, django-start-template

Deployment

Deployment of this project is following:

source $VENV/bin/activate
export DJANGO_SETTINGS_MODULE=project_name.settings.production
git pull
pip install -r requirements.txt

# Update database, static files, locales
manage.py syncdb  --noinput
manage.py migrate
manage.py collectstatic --noinput
manage.py makemessages -a
manage.py compilemessages

# restart wsgi
touch project_name/wsgi.py

You can use rsync instead of git, but still you need to run batch of commands to update your environment.

Recently, I made django-deploy app, which allows me to run single management command to update environment, but I've used it for one project only and I'm still experimenting with it.

Sketches and drafts

Draft of templates I place inside global templates/ directory. I guess one can create folder sketches/ in project root, but haven't used it yet.

Pluggable application

These apps are usually prepared to publish as open-source. I've taken example below from django-forme

~/projects/django-app/

docs/
app/
tests/
example_project/
LICENCE
MANIFEST.in
README.md
setup.py
pytest.ini
tox.ini
.travis.yml
...

Name of directories is clear (I hope). I put test files outside app directory, but it really doesn't matter. It is important to provide README and setup.py, so package is easily installed through pip.

Setting Windows PowerShell environment variables

If, some time during a PowerShell session, you need to append to the PATH environment variable temporarily, you can do it this way:

$env:Path += ";C:\Program Files\GnuWin32\bin"

How do I define and use an ENUM in Objective-C?

Apple provides a macro to help provide better code compatibility, including Swift. Using the macro looks like this.

typedef NS_ENUM(NSInteger, PlayerStateType) {
  PlayerStateOff,
  PlayerStatePlaying,
  PlayerStatePaused
};

Documented here

Make header and footer files to be included in multiple html pages

Save the HTML you want to include in an .html file:

Content.html

<a href="howto_google_maps.asp">Google Maps</a><br>
<a href="howto_css_animate_buttons.asp">Animated Buttons</a><br>
<a href="howto_css_modals.asp">Modal Boxes</a><br>
<a href="howto_js_animate.asp">Animations</a><br>
<a href="howto_js_progressbar.asp">Progress Bars</a><br>
<a href="howto_css_dropdown.asp">Hover Dropdowns</a><br>
<a href="howto_js_dropdown.asp">Click Dropdowns</a><br>
<a href="howto_css_table_responsive.asp">Responsive Tables</a><br>

Include the HTML

Including HTML is done by using a w3-include-html attribute:

Example

    <div w3-include-html="content.html"></div>

Add the JavaScript

HTML includes are done by JavaScript.

    <script>
    function includeHTML() {
      var z, i, elmnt, file, xhttp;
      /*loop through a collection of all HTML elements:*/
      z = document.getElementsByTagName("*");
      for (i = 0; i < z.length; i++) {
        elmnt = z[i];
        /*search for elements with a certain atrribute:*/
        file = elmnt.getAttribute("w3-include-html");
        if (file) {
          /*make an HTTP request using the attribute value as the file name:*/
          xhttp = new XMLHttpRequest();
          xhttp.onreadystatechange = function() {
            if (this.readyState == 4) {
              if (this.status == 200) {elmnt.innerHTML = this.responseText;}
              if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
              /*remove the attribute, and call this function once more:*/
              elmnt.removeAttribute("w3-include-html");
              includeHTML();
            }
          } 
          xhttp.open("GET", file, true);
          xhttp.send();
          /*exit the function:*/
          return;
        }
      }
    }
    </script>

Call includeHTML() at the bottom of the page:

Example

<!DOCTYPE html>
<html>
<script>
function includeHTML() {
  var z, i, elmnt, file, xhttp;
  /*loop through a collection of all HTML elements:*/
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
    elmnt = z[i];
    /*search for elements with a certain atrribute:*/
    file = elmnt.getAttribute("w3-include-html");
    if (file) {
      /*make an HTTP request using the attribute value as the file name:*/
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4) {
          if (this.status == 200) {elmnt.innerHTML = this.responseText;}
          if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
          /*remove the attribute, and call this function once more:*/
          elmnt.removeAttribute("w3-include-html");
          includeHTML();
        }
      }      
      xhttp.open("GET", file, true);
      xhttp.send();
      /*exit the function:*/
      return;
    }
  }
};
</script>
<body>

<div w3-include-html="h1.html"></div> 
<div w3-include-html="content.html"></div> 

<script>
includeHTML();
</script>

</body>
</html>

Windows batch script to unhide files hidden by virus

Try this.

Does not require any options to change.

Does not require any command line activity.

Just run software and you will done the job.

www.vhghorecha.in/unhide-all-files-folders-virus/

Happy Knowledge Sharing

Xcopy Command excluding files and folders

It is same as above answers, but is simple in steps

c:\SRC\folder1

c:\SRC\folder2

c:\SRC\folder3

c:\SRC\folder4

to copy all above folders to c:\DST\ except folder1 and folder2.

Step1: create a file c:\list.txt with below content, one folder name per one line

folder1\

folder2\

Step2: Go to command pompt and run as below xcopy c:\SRC*.* c:\DST*.* /EXCLUDE:c:\list.txt

Simpler way to create dictionary of separate variables?

This is a hack. It will not work on all Python implementations distributions (in particular, those that do not have traceback.extract_stack.)

import traceback

def make_dict(*expr):
    (filename,line_number,function_name,text)=traceback.extract_stack()[-2]
    begin=text.find('make_dict(')+len('make_dict(')
    end=text.find(')',begin)
    text=[name.strip() for name in text[begin:end].split(',')]
    return dict(zip(text,expr))

bar=True
foo=False
print(make_dict(bar,foo))
# {'foo': False, 'bar': True}

Note that this hack is fragile:

make_dict(bar,
          foo)

(calling make_dict on 2 lines) will not work.

Instead of trying to generate the dict out of the values foo and bar, it would be much more Pythonic to generate the dict out of the string variable names 'foo' and 'bar':

dict([(name,locals()[name]) for name in ('foo','bar')])

Execute Immediate within a stored procedure keeps giving insufficient priviliges error

You should use this example with AUTHID CURRENT_USER :

CREATE OR REPLACE PROCEDURE Create_sequence_for_tab (VAR_TAB_NAME IN VARCHAR2)
   AUTHID CURRENT_USER
IS
   SEQ_NAME       VARCHAR2 (100);
   FINAL_QUERY    VARCHAR2 (100);
   COUNT_NUMBER   NUMBER := 0;
   cur_id         NUMBER;
BEGIN
   SEQ_NAME := 'SEQ_' || VAR_TAB_NAME;

   SELECT COUNT (*)
     INTO COUNT_NUMBER
     FROM USER_SEQUENCES
    WHERE SEQUENCE_NAME = SEQ_NAME;

   DBMS_OUTPUT.PUT_LINE (SEQ_NAME || '>' || COUNT_NUMBER);

   IF COUNT_NUMBER = 0
   THEN
      --DBMS_OUTPUT.PUT_LINE('DROP SEQUENCE ' || SEQ_NAME);
      -- EXECUTE IMMEDIATE 'DROP SEQUENCE ' || SEQ_NAME;
      -- ELSE
      SELECT 'CREATE SEQUENCE COMPTABILITE.' || SEQ_NAME || ' START WITH ' || ROUND (DBMS_RANDOM.VALUE (100000000000, 999999999999), 0) || ' INCREMENT BY 1'
        INTO FINAL_QUERY
        FROM DUAL;

      DBMS_OUTPUT.PUT_LINE (FINAL_QUERY);
      cur_id := DBMS_SQL.OPEN_CURSOR;
      DBMS_SQL.parse (cur_id, FINAL_QUERY, DBMS_SQL.v7);
      DBMS_SQL.CLOSE_CURSOR (cur_id);
   -- EXECUTE IMMEDIATE FINAL_QUERY;

   END IF;

   COMMIT;
END;
/

Remove the last three characters from a string

myString = myString.Remove(myString.Length - 3, 3);

get parent's view from a layout

The getParent method returns a ViewParent, not a View. You need to cast the first call to getParent() also:

RelativeLayout r = (RelativeLayout) ((ViewGroup) this.getParent()).getParent();

As stated in the comments by the OP, this is causing a NPE. To debug, split this up into multiple parts:

ViewParent parent = this.getParent();
RelativeLayout r;
if (parent == null) {
    Log.d("TEST", "this.getParent() is null");
}
else {
    if (parent instanceof ViewGroup) {
        ViewParent grandparent = ((ViewGroup) parent).getParent();
        if (grandparent == null) {
            Log.d("TEST", "((ViewGroup) this.getParent()).getParent() is null");
        }
        else {
            if (parent instanceof RelativeLayout) {
                r = (RelativeLayout) grandparent;
            }
            else {
                Log.d("TEST", "((ViewGroup) this.getParent()).getParent() is not a RelativeLayout");
            }
        }
    }
    else {
        Log.d("TEST", "this.getParent() is not a ViewGroup");
    }
}

//now r is set to the desired RelativeLayout.

Java: How to stop thread?

You can create a boolean field and check it inside run:

public class Task implements Runnable {

   private volatile boolean isRunning = true;

   public void run() {

     while (isRunning) {
         //do work
     }
   }

   public void kill() {
       isRunning = false;
   }

}

To stop it just call

task.kill();

This should work.

AngularJS performs an OPTIONS HTTP request for a cross-origin resource

Perfectly described in pkozlowski's comment. I had working solution with AngularJS 1.2.6 and ASP.NET Web Api but when I had upgraded AngularJS to 1.3.3 then requests failed.

  • Solution for Web Api server was to add handling of the OPTIONS requests at the beginning of configuration method (more info in this blog post):

    app.Use(async (context, next) =>
    {
        IOwinRequest req = context.Request;
        IOwinResponse res = context.Response;
        if (req.Path.StartsWithSegments(new PathString("/Token")))
        {
            var origin = req.Headers.Get("Origin");
            if (!string.IsNullOrEmpty(origin))
            {
                res.Headers.Set("Access-Control-Allow-Origin", origin);
            }
            if (req.Method == "OPTIONS")
            {
                res.StatusCode = 200;
                res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Methods", "GET", "POST");
                res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Headers", "authorization", "content-type");
                return;
            }
        }
        await next();
    });
    

Website screenshots

you can use cutycapt .

kwhtml is deprecated and show page like old browser.

Store a closure as a variable in Swift

I've provide an example not sure if this is what you're after.

var completionHandler: (_ value: Float) -> ()

func printFloat(value: Float) {
    print(value)
}

completionHandler = printFloat

completionHandler(5)

It simply prints 5 using the completionHandler variable declared.

Generate Controller and Model

See this video: http://youtu.be/AjQ5e9TOZVk?t=1m45s You can do php artisan list to view all commands, The command for generating REST-ful controllers is controller:make You can view the usage with: php artisan help make:controller

'DataFrame' object has no attribute 'sort'

Pandas Sorting 101

sort has been replaced in v0.20 by DataFrame.sort_values and DataFrame.sort_index. Aside from this, we also have argsort.

Here are some common use cases in sorting, and how to solve them using the sorting functions in the current API. First, the setup.

# Setup
np.random.seed(0)
df = pd.DataFrame({'A': list('accab'), 'B': np.random.choice(10, 5)})    
df                                                                                                                                        
   A  B
0  a  7
1  c  9
2  c  3
3  a  5
4  b  2

Sort by Single Column

For example, to sort df by column "A", use sort_values with a single column name:

df.sort_values(by='A')

   A  B
0  a  7
3  a  5
4  b  2
1  c  9
2  c  3

If you need a fresh RangeIndex, use DataFrame.reset_index.

Sort by Multiple Columns

For example, to sort by both col "A" and "B" in df, you can pass a list to sort_values:

df.sort_values(by=['A', 'B'])

   A  B
3  a  5
0  a  7
4  b  2
2  c  3
1  c  9

Sort By DataFrame Index

df2 = df.sample(frac=1)
df2

   A  B
1  c  9
0  a  7
2  c  3
3  a  5
4  b  2

You can do this using sort_index:

df2.sort_index()

   A  B
0  a  7
1  c  9
2  c  3
3  a  5
4  b  2

df.equals(df2)                                                                                                                            
# False
df.equals(df2.sort_index())                                                                                                               
# True

Here are some comparable methods with their performance:

%timeit df2.sort_index()                                                                                                                  
%timeit df2.iloc[df2.index.argsort()]                                                                                                     
%timeit df2.reindex(np.sort(df2.index))                                                                                                   

605 µs ± 13.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
610 µs ± 24.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
581 µs ± 7.63 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Sort by List of Indices

For example,

idx = df2.index.argsort()
idx
# array([0, 7, 2, 3, 9, 4, 5, 6, 8, 1])

This "sorting" problem is actually a simple indexing problem. Just passing integer labels to iloc will do.

df.iloc[idx]

   A  B
1  c  9
0  a  7
2  c  3
3  a  5
4  b  2

Android - How to achieve setOnClickListener in Kotlin?

    val button = findViewById<Button>(R.id.button)
    button.setOnClickListener {
        val intent = 
    Intent(this@MainActivity,ThirdActivity::class.java)
        intent.putExtra("key", "Kotlin")
        startActivity(intent)
    }

HTML / CSS Popup div on text click

For the sake of completeness, what you are trying to create is a "modal window".

Numerous JS solutions allow you to create them with ease, take the time to find the one which best suits your needs.

I have used Tinybox 2 for small projects : http://sandbox.scriptiny.com/tinybox2/

How to continue the code on the next line in VBA

If you want to insert this formula =SUMIFS(B2:B10,A2:A10,F2) into cell G2, here is how I did it.

Range("G2")="=sumifs(B2:B10,A2:A10," & _

"F2)"

To split a line of code, add an ampersand, space and underscore.

"id cannot be resolved or is not a field" error?

Just throwing this out there, but try retyping things manually. There's a chance that your quotation marks are the "wrong" ones as there's a similar unicode character which looks similar but is NOT a quotation mark.

If you copy/pasted the code snippits off a website, that might be your problem.

Python: SyntaxError: keyword can't be an expression

I just got that problem when converting from % formatting to .format().

Previous code:

"SET !TIMEOUT_STEP %{USER_TIMEOUT_STEP}d" % {'USER_TIMEOUT_STEP' = 3}

Problematic syntax:

"SET !TIMEOUT_STEP {USER_TIMEOUT_STEP}".format('USER_TIMEOUT_STEP' = 3)

The problem is that format is a function that needs parameters. They cannot be strings. That is one of worst python error messages I've ever seen.

Corrected code:

"SET !TIMEOUT_STEP {USER_TIMEOUT_STEP}".format(USER_TIMEOUT_STEP = 3)

How to use z-index in svg elements?

The clean, fast, and easy solutions posted as of the date of this answer are unsatisfactory. They are constructed over the flawed statement that SVG documents lack z order. Libraries are not necessary either. One line of code can perform most operations to manipulate the z order of objects or groups of objects that might be required in the development of an app that moves 2D objects around in an x-y-z space.

Z Order Definitely Exists in SVG Document Fragments

What is called an SVG document fragment is a tree of elements derived from the base node type SVGElement. The root node of an SVG document fragment is an SVGSVGElement, which corresponds to an HTML5 <svg> tag. The SVGGElement corresponds to the <g> tag and permits aggregating children.

Having a z-index attribute on the SVGElement as in CSS would defeat the SVG rendering model. Sections 3.3 and 3.4 of W3C SVG Recommendation v1.1 2nd Edition state that SVG document fragments (trees of offspring from an SVGSVGElement) are rendered using what is called a depth first search of the tree. That scheme is a z order in every sense of the term.

Z order is actually a computer vision shortcut to avoid the need for true 3D rendering with the complexities and computing demands of ray tracing. The linear equation for the implicit z-index of elements in an SVG document fragment.

z-index = z-index_of_svg_tag + depth_first_tree_index / tree_node_qty

This is important because if you want to move a circle that was below a square to above it, you simply insert the square before the circle. This can be done easily in JavaScript.

Supporting Methods

SVGElement instances have two methods that support simple and easy z order manipulation.

  • parent.removeChild(child)
  • parent.insertBefore(child, childRef)

The Correct Answer That Doesn't Create a Mess

Because the SVGGElement (<g> tag) can be removed and inserted just as easily as a SVGCircleElement or any other shape, image layers typical of Adobe products and other graphics tools can be implemented with ease using the SVGGElement. This JavaScript is essentially a Move Below command.

parent.insertBefore(parent.removeChild(gRobot), gDoorway)

If the layer of a robot drawn as children of SVGGElement gRobot was before the doorway drawn as children of SVGGElement gDoorway, the robot is now behind the doorway because the z order of the doorway is now one plus the z order of the robot.

A Move Above command is almost as easy.

parent.insertBefore(parent.removeChild(gRobot), gDoorway.nextSibling())

Just think a=a and b=b to remember this.

insert after = move above
insert before = move below

Leaving the DOM in a State Consistent With the View

The reason this answer is correct is because it is minimal and complete and, like the internals of Adobe products or other well designed graphics editors, leaves the internal representation in a state that is consistent with the view created by rendering.

Alternative But Limited Approach

Another approach commonly used is to use CSS z-index in conjunction with multiple SVG document fragments (SVG tags) with mostly transparent backgrounds in all but the bottom one. Again, this defeats the elegance of the SVG rendering model, making it difficult to move objects up or down in the z order.


NOTES:

  1. (https://www.w3.org/TR/SVG/render.html v 1.1, 2nd Edition, 16 August 2011)

    3.3 Rendering Order Elements in an SVG document fragment have an implicit drawing order, with the first elements in the SVG document fragment getting "painted" first. Subsequent elements are painted on top of previously painted elements.

    3.4 How groups are rendered Grouping elements such as the ‘g’ element (see container elements) have the effect of producing a temporary separate canvas initialized to transparent black onto which child elements are painted. Upon the completion of the group, any filter effects specified for the group are applied to create a modified temporary canvas. The modified temporary canvas is composited into the background, taking into account any group-level masking and opacity settings on the group.

Checking if a collection is empty in Java: which is the best method?

I would use the first one. It is clear to see right away what it does. I dont think the null check is necessary here.

installing apache: no VCRUNTIME140.dll

Also, please make sure you installed the correct version of apache on your computer. For example, not install a x86 on a 64bit system. Vice versa.

In Java, how to append a string more efficiently?

- Each time you append or do any modification with it, it creates a new String object.

- So use append() method of StringBuilder(If thread safety is not important), else use StringBuffer(If thread safety is important.), that will be efficient way to do it.

In DB2 Display a table's definition

I know this is an old question, but this will do the job.

SELECT colname, typename, length, scale, default, nulls
  FROM syscat.columns
 WHERE tabname = '<table name>'
   AND tabschema = '<schema name>'
 ORDER BY colno

What is Shelving in TFS?

I come across this all the time, so supplemental information regarding branches:

If you're working with multiple branches, shelvesets are tied to the specific branch in which you created them. So, if you let a changeset rust on the shelf for too long and have to unshelve to a different branch, then you have to do that with the July release of the power tools.

tfpt unshelve /migrate

how to make negative numbers into positive

abs() is for integers only. For floating point, use fabs() (or one of the fabs() line with the correct precision for whatever a actually is)

PHPmailer sending HTML CODE

just you need to pass true as an argument to IsHTML() function.

How to Change Font Size in drawString Java

Because you can't count on a particular font being available, a good approach is to derive a new font from the current font. This gives you the same family, weight, etc. just larger...

Font currentFont = g.getFont();
Font newFont = currentFont.deriveFont(currentFont.getSize() * 1.4F);
g.setFont(newFont);

You can also use TextAttribute.

Map<TextAttribute, Object> attributes = new HashMap<>();

attributes.put(TextAttribute.FAMILY, currentFont.getFamily());
attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_SEMIBOLD);
attributes.put(TextAttribute.SIZE, (int) (currentFont.getSize() * 1.4));
myFont = Font.getFont(attributes);

g.setFont(myFont);

The TextAttribute method often gives one even greater flexibility. For example, you can set the weight to semi-bold, as in the example above.

One last suggestion... Because the resolution of monitors can be different and continues to increase with technology, avoid adding a specific amount (such as getSize()+2 or getSize()+4) and consider multiplying instead. This way, your new font is consistently proportional to the "current" font (getSize() * 1.4), and you won't be editing your code when you get one of those nice 4K monitors.

OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this?

Is canny your own function? Do you use Canny from OpenCV inside it? If yes check if you feed suitable argument for Canny - first Canny argument should meet following criteria:

  • type: <type 'numpy.ndarray'>
  • dtype: dtype('uint8')
  • being single channel or simplyfing: grayscale, that is 2D array, i.e. its shape should be 2-tuple of ints (tuple containing exactly 2 integers)

You can check it by printing respectively

type(variable_name)
variable_name.dtype
variable_name.shape

Replace variable_name with name of variable you feed as first argument to Canny.

Use ffmpeg to add text subtitles

ffmpeg supports the mov_text subtitle encoder which is about the only one supported in an MP4 container and playable by iTunes, Quicktime, iOS etc.

Your line would read:

ffmpeg -i input.mp4 -i input.srt -map 0:0 -map 0:1 -map 1:0 -c:s mov_text output.mp4

How can I autoplay a video using the new embed code style for Youtube?

YouTube Help says that &autoplay=1 has to be after the video ID - I assume, immediately after.

If conditions in a Makefile, inside a target

You can simply use shell commands. If you want to suppress echoing the output, use the "@" sign. For example:

clean:
    @if [ "test" = "test" ]; then\
        echo "Hello world";\
    fi

Note that the closing ";" and "\" are necessary.

Outlets cannot be connected to repeating content iOS

Create a table view cell subclass and set it as the class of the prototype. Add the outlets to that class and connect them. Now when you configure the cell you can access the outlets.

How to take character input in java

you can use a Scanner to read from input :

Scanner scanner = new Scanner(System.in); 
char c = scanner.next().charAt(0); //charAt() method returns the character at the specified index in a string. The index of the first character is 0, the second character is 1, and so on.