Programs & Examples On #Pkcs#1

PKCS #1 is a standard that defines the RSA algorithm and padding schemes.

Converting PKCS#12 certificate into PEM using OpenSSL

I had a PFX file and needed to create KEY file for NGINX, so I did this:

openssl pkcs12 -in file.pfx -out file.key -nocerts -nodes

Then I had to edit the KEY file and remove all content up to -----BEGIN PRIVATE KEY-----. After that NGINX accepted the KEY file.

Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

This is possible with a bit of format conversion.

To extract the private key in a format openssh can use:

openssl pkcs12 -in pkcs12.pfx -nocerts -nodes | openssl rsa > id_rsa

To convert the private key to a public key:

openssl rsa -in id_rsa -pubout | ssh-keygen -f /dev/stdin -i -m PKCS8

To extract the public key in a format openssh can use:

openssl pkcs12 -in pkcs12.pfx -clcerts -nokeys | openssl x509 -pubkey -noout | ssh-keygen -f /dev/stdin -i -m PKCS8

Java HTTPS client certificate authentication

They JKS file is just a container for certificates and key pairs. In a client-side authentication scenario, the various parts of the keys will be located here:

  • The client's store will contain the client's private and public key pair. It is called a keystore.
  • The server's store will contain the client's public key. It is called a truststore.

The separation of truststore and keystore is not mandatory but recommended. They can be the same physical file.

To set the filesystem locations of the two stores, use the following system properties:

-Djavax.net.ssl.keyStore=clientsidestore.jks

and on the server:

-Djavax.net.ssl.trustStore=serversidestore.jks

To export the client's certificate (public key) to a file, so you can copy it to the server, use

keytool -export -alias MYKEY -file publicclientkey.cer -store clientsidestore.jks

To import the client's public key into the server's keystore, use (as the the poster mentioned, this has already been done by the server admins)

keytool -import -file publicclientkey.cer -store serversidestore.jks

Switching from zsh to bash on OSX, and back again?

You can easily switch back to bash by using command "bye"

How to write a switch statement in Ruby

It's critical to emphasize the comma (,) in a when clause. It acts as an || of an if statement, that is, it does an OR comparison and not an AND comparison between the delimited expressions of the when clause. See the following case statement:

x = 3
case x
  when 3, x < 2 then 'apple'
  when 3, x > 2 then 'orange'
end
 => "apple"

x is not less than 2, yet the return value is "apple". Why? Because x was 3 and since ',`` acts as an||, it did not bother to evaluate the expressionx < 2'.

You might think that to perform an AND, you can do something like this below, but it doesn't work:

case x
  when (3 && x < 2) then 'apple'
  when (3 && x > 2) then 'orange'
end
 => nil 

It doesn't work because (3 && x > 2) evaluates to true, and Ruby takes the True value and compares it to x with ===, which is not true, since x is 3.

To do an && comparison, you will have to treat case like an if/else block:

case
  when x == 3 && x < 2 then 'apple'
  when x == 3 && x > 2 then 'orange'
end

In the Ruby Programming Language book, Matz says this latter form is the simple (and infrequently used) form, which is nothing more than an alternative syntax for if/elsif/else. However, whether it is infrequently used or not, I do not see any other way to attach multiple && expressions for a given when clause.

powershell - extract file name and extension

If is from a text file and and presuming name file are surrounded by white spaces this is a way:

$a = get-content c:\myfile.txt

$b = $a | select-string -pattern "\s.+\..{3,4}\s" | select -ExpandProperty matches | select -ExpandProperty value

$b | % {"File name:{0} - Extension:{1}" -f $_.substring(0, $_.lastindexof('.')) , $_.substring($_.lastindexof('.'), ($_.length - $_.lastindexof('.'))) }

If is a file you can use something like this based on your needs:

$a = dir .\my.file.xlsx # or $a = get-item c:\my.file.xlsx 

$a
    Directory: Microsoft.PowerShell.Core\FileSystem::C:\ps


Mode           LastWriteTime       Length Name
----           -------------       ------ ----
-a---      25/01/10    11.51          624 my.file.xlsx


$a.BaseName
my.file
$a.Extension
.xlsx

How to check if a value is not null and not empty string in JS

I got so fed up with checking for null and empty strings specifically, that I now usually just write and call a small function to do it for me.

/**
 * Test if the given value equals null or the empty string.
 * 
 * @param {string} value
**/
const isEmpty = (value) => value === null || value === '';

// Test:
isEmpty('');        // true
isEmpty(null);      // true
isEmpty(1);         // false
isEmpty(0);         // false
isEmpty(undefined); // false

Collectors.toMap() keyMapper -- more succinct expression?

We can use an optional merger function also in case of same key collision. For example, If two or more persons have the same getLast() value, we can specify how to merge the values. If we not do this, we could get IllegalStateException. Here is the example to achieve this...

Map<String, Person> map = 
roster
    .stream()
    .collect(
        Collectors.toMap(p -> p.getLast(),
                         p -> p,
                         (person1, person2) -> person1+";"+person2)
    );

Best way to work with dates in Android SQLite

"SELECT  "+_ID+" ,  "+_DESCRIPTION +","+_CREATED_DATE +","+_DATE_TIME+" FROM "+TBL_NOTIFICATION+" ORDER BY "+"strftime(%s,"+_DATE_TIME+") DESC";

Change URL and redirect using jQuery

If you really want to do this with jQuery (why?) you should get the DOM window.location object to use its functions:

$(window.location)[0].replace("https://www.google.it");

Note that [0] says to jQuery to use directly the DOM object and not the $(window.location) jQuery object incapsulating the DOM object.

increase legend font size ggplot2

theme(plot.title = element_text(size = 12, face = "bold"),
    legend.title=element_text(size=10), 
    legend.text=element_text(size=9))

LINQ to SQL - Left Outer Join with multiple join conditions

I know it's "a bit late" but just in case if anybody needs to do this in LINQ Method syntax (which is why I found this post initially), this would be how to do that:

var results = context.Periods
    .GroupJoin(
        context.Facts,
        period => period.id,
        fk => fk.periodid,
        (period, fact) => fact.Where(f => f.otherid == 17)
                              .Select(fact.Value)
                              .DefaultIfEmpty()
    )
    .Where(period.companyid==100)
    .SelectMany(fact=>fact).ToList();

How to calculate difference between two dates in oracle 11g SQL

You can not use DATEDIFF but you can use this (if columns are not date type):

SELECT 
to_date('2008-08-05','YYYY-MM-DD')-to_date('2008-06-05','YYYY-MM-DD') 
AS DiffDate from dual

you can see the sample

http://sqlfiddle.com/#!4/d41d8/34609

Vue template or render function not defined yet I am using neither?

I cannot believe how did I fix the issue! weird solution!
I kept the app running then I removed all template tags and again I returned them back and it worked! but I don't understand what happened.

Plugin is too old, please update to a more recent version, or set ANDROID_DAILY_OVERRIDE environment variable to

This issue occurs because of the Gradle version changes, since your application uses old version of gradle, you need to update to new version.

This changes needs to be done in build.gradle file, have look at this link http://www.feelzdroid.com/2015/11/android-plugin-too-old-update-recent-version.html. to know how to update the gradle and detailed steps are provided. there.

Thans

Image.open() cannot identify image file - Python?

For me it was fixed by downloading the image data set I was using again (in fact I forwarded the copy I had locally using vs-code's SFTP). Here is the jupyter notebook I used (in vscode) with it's output:

from pathlib import Path

import PIL
import PIL.Image as PILI
#from PIL import Image

print(PIL.__version__)

img_path = Path('PATH_UR_DATASET/miniImagenet/train/n03998194/n0399819400000585.jpg')
print(img_path.exists())
img = PILI.open(img_path).convert('RGB')

print(img)

output:

7.0.0
True
<PIL.Image.Image image mode=RGB size=158x160 at 0x7F4AD0A1E050>

note that open always opens in r mode and even has a check to throw an error if that mode is changed.

Converts scss to css

If you click on the title CSS (SCSS) in CodePen (don't change the pre-processor with the gear) it will switch to the compiled CSS view.

Codepen Screenshot of Compiled Preview

How to set xampp open localhost:8080 instead of just localhost

you can get loccalhost page by writing localhost/xampp or by writing http://127.0.0.1 you will get the local host page. After starting the apache serve that can be from wamp, xamp or lamp.

C++ passing an array pointer as a function argument

You're over-complicating it - it just needs to be:

void generateArray(int *a, int si)
{
    for (int j = 0; j < si; j++)
        a[j] = rand() % 9;
}

int main()
{
    const int size=5;
    int a[size];

    generateArray(a, size);

    return 0;
}

When you pass an array as a parameter to a function it decays to a pointer to the first element of the array. So there is normally never a need to pass a pointer to an array.

Replace specific characters within strings

You do not need to create data frame from vector of strings, if you want to replace some characters in it. Regular expressions is good choice for it as it has been already mentioned by @Andrie and @Dirk Eddelbuettel.

Pay attention, if you want to replace special characters, like dots, you should employ full regular expression syntax, as shown in example below:

ctr_names <- c("Czech.Republic","New.Zealand","Great.Britain")
gsub("[.]", " ", ctr_names)

this will produce

[1] "Czech Republic" "New Zealand"    "Great Britain" 

Find a row in dataGridView based on column and value

This builds on the above answer from Gordon--not all of it is my original work. What I did was add a more generic method to my static utility class.

public static int MatchingRowIndex(DataGridView dgv, string columnName, string searchValue)
        {
        int rowIndex = -1;
        bool tempAllowUserToAddRows = dgv.AllowUserToAddRows;

        dgv.AllowUserToAddRows = false; // Turn off or .Value below will throw null exception
        if (dgv.Rows.Count > 0 && dgv.Columns.Count > 0 && dgv.Columns[columnName] != null)
            {
            DataGridViewRow row = dgv.Rows
                .Cast<DataGridViewRow>()
                .FirstOrDefault(r => r.Cells[columnName].Value.ToString().Equals(searchValue));

            rowIndex = row.Index;
            }
        dgv.AllowUserToAddRows = tempAllowUserToAddRows;
        return rowIndex;
        }

Then in whatever form I want to use it, I call the method passing the DataGridView, column name and search value. For simplicity I am converting everything to strings for the search, though it would be easy enough to add overloads for specifying the data types.

private void UndeleteSectionInGrid(string sectionLetter)
        {
        int sectionRowIndex = UtilityMethods.MatchingRowIndex(dgvSections, "SectionLetter", sectionLetter);
        dgvSections.Rows[sectionRowIndex].Cells["DeleteSection"].Value = false;
        }

Set padding for UITextField with UITextBorderStyleNone

  1. Create a textfield Custom

PaddingTextField.swift

import UIKit
class PaddingTextField: UITextField {

@IBInspectable var paddingLeft: CGFloat = 0
@IBInspectable var paddingRight: CGFloat = 0

override func textRectForBounds(bounds: CGRect) -> CGRect {
    return CGRectMake(bounds.origin.x + paddingLeft, bounds.origin.y,
        bounds.size.width - paddingLeft - paddingRight, bounds.size.height);
}

override func editingRectForBounds(bounds: CGRect) -> CGRect {
    return textRectForBounds(bounds)
}}
  1. Set your textfield class is PaddingTextField and custom your padding as you want enter image description here enter image description here

  2. Enjoy it

final

Kotlin Ternary Conditional Operator

Remember Ternary operator and Elvis operator hold separate meanings in Kotlin unlike in many popular languages. Doing expression? value1: value2 would give you bad words by the Kotlin compiler, unlike any other language as there is no ternary operator in Kotlin as mentioned in the official docs. The reason is that the if, when and try-catch statements themselves return values.

So, doing expression? value1: value2 can be replaced by

val max = if (a > b) print("Choose a") else print("Choose b")

The Elvis operator that Kotlin has, works only in the case of nullable variables ex.:

If I do something like value3 = value1 ?: value2 then if value1 is null then value2 would be returned otherwise value1 would be returned.

A more clear understanding can be achieved from these answers.

SQL query to make all data in a column UPPER CASE?

Permanent:

UPDATE
  MyTable
SET
  MyColumn = UPPER(MyColumn)

Temporary:

SELECT
  UPPER(MyColumn) AS MyColumn
FROM
  MyTable

Pass values of checkBox to controller action in asp.net mvc4

try using form collection

<input id="responsable" value="True" name="checkResp" type="checkbox" /> 

[HttpPost]
public ActionResult Index(FormCollection collection)
{
     if(!string.IsNullOrEmpty(collection["checkResp"])
     {
        string checkResp=collection["checkResp"];
        bool checkRespB=Convert.ToBoolean(checkResp);
     }

}

Explain ExtJS 4 event handling

Just wanted to add a couple of pence to the excellent answers above: If you are working on pre Extjs 4.1, and don't have application wide events but need them, I've been using a very simple technique that might help: Create a simple object extending Observable, and define any app wide events you might need in it. You can then fire those events from anywhere in your app, including actual html dom element and listen to them from any component by relaying the required elements from that component.

Ext.define('Lib.MessageBus', {
    extend: 'Ext.util.Observable',

    constructor: function() {
        this.addEvents(
            /*
             * describe the event
             */
                  "eventname"

            );
        this.callParent(arguments);
    }
});

Then you can, from any other component:

 this.relayEvents(MesageBus, ['event1', 'event2'])

And fire them from any component or dom element:

 MessageBus.fireEvent('event1', somearg);

 <input type="button onclick="MessageBus.fireEvent('event2', 'somearg')">

Vba macro to copy row from table if value in table meets condition

That is exactly what you do with an advanced filter. If it's a one shot, you don't even need a macro, it is available in the Data menu.

Sheets("Sheet1").Range("A1:D17").AdvancedFilter Action:=xlFilterCopy, _
    CriteriaRange:=Sheets("Sheet1").Range("G1:G2"), CopyToRange:=Range("A1:D1") _
    , Unique:=False

Include of non-modular header inside framework module

Make sure the header files are publicly available as part of the framework's public headers.

Goto Framework -> Target -> Build Phases and drag to move the relevant header files from Project to Public. Hope that helps!

Screenshot

Count number of rows matching a criteria

With dplyr package, Use

 nrow(filter(mydata, sCode == "CA")),

All the solutions provided here gave me same error as multi-sam but that one worked.

How can I pass a parameter to a setTimeout() callback?

The easiest cross browser solution for supporting parameters in setTimeout:

setTimeout(function() {
    postinsql(topicId);
}, 4000)

If you don't mind not supporting IE 9 and lower:

setTimeout(postinsql, 4000, topicId);

setTimeout desktop browser compatibility

setTimeout mobile browser compatibility

https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout

What are the differences between the urllib, urllib2, urllib3 and requests module?

You should generally use urllib2, since this makes things a bit easier at times by accepting Request objects and will also raise a URLException on protocol errors. With Google App Engine though, you can't use either. You have to use the URL Fetch API that Google provides in its sandboxed Python environment.

Getting unix timestamp from Date()

To get a timestamp from Date(), you'll need to divide getTime() by 1000, i.e. :

Date currentDate = new Date();
currentDate.getTime() / 1000;
// 1397132691

or simply:

long unixTime = System.currentTimeMillis() / 1000L;

How do I clear inner HTML

const destroy = container => {
  document.getElementById(container).innerHTML = '';
};

Faster previous

const destroyFast = container => {
  const el = document.getElementById(container);
  while (el.firstChild) el.removeChild(el.firstChild);
};

Facebook Open Graph Error - Inferred Property

UPD 2020: "Open Graph Object Debugger" has been discontinued. Use Sharing Debugger to refresh Facebook cache.


There is some confusion about tons of Facebook Tools and Documentation. So many people probably use the Sharing Debugger tool to check their OpenGraph markup: https://developers.facebook.com/tools/debug/sharing/

But it only retrieves the information about your site from the Facebook cache. This means that after you change the ogp-markup on your site, the Sharing Debugger will still be using the old cached data. Moreover, if there is no cached data on the Facebook server then the Sharing Debugger will show you the error: This URL hasn't been shared on Facebook before.

So, the solution is to use another tool – Open Graph Object Debugger: https://developers.facebook.com/tools/debug/og/object/

It allows you to Fetch new scrape information and refresh the Facebook cache:

Open Graph Object Debugger

Honestly, I don't know how to find this tool exploring the Tools & Support section of developers.facebook.com – I cannot find any links and mentions. I only have this tool in my bookmarks. That's Facebook :)


Use 'property'-attrs

I also noted that some developers use the name attribute instead of property. Many parsers probably will process such tags properly, but according to The Open Graph protocol, we should use property, not name:

<meta property="og:url" content="http://www.mywebaddress.com"/>

Use full URLs

The last recommendation is to specify full URLs. For example, Facebook complains when you use relative URL in og:image. So use the full one:

<meta property="og:image" content="http://www.mywebaddress.com/myimage.jpg"/>

Communication between tabs or windows

For those searching for a solution not based on jQuery, this is a plain JavaScript version of the solution provided by Thomas M:

window.addEventListener("storage", message_receive);

function message_broadcast(message) {
    localStorage.setItem('message',JSON.stringify(message));
}

function message_receive(ev) {
    if (ev.key == 'message') {
        var message=JSON.parse(ev.newValue);
    }
}

WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server

You have to just check whether your WAMP server is online or not.

To put your WAMP server online, follow these steps.

  1. Go to your WAMP server notification icon (in the task bar).
  2. Single click on the WAMP server icon.
  3. Select last option from the menu, that is, Put Online
  4. Your server will restart automatically (in the latest versions only). Otherwise, you have to restart your server manually.

And you are DONE...

How do I fix "for loop initial declaration used outside C99 mode" GCC error?

I'd try to declare i outside of the loop!

Good luck on solving 3n+1 :-)

Here's an example:

#include <stdio.h>

int main() {

   int i;

   /* for loop execution */
   for (i = 10; i < 20; i++) {
       printf("i: %d\n", i);
   }   

   return 0;
}

Read more on for loops in C here.

Correct use for angular-translate in controllers

Recommended: don't translate in the controller, translate in your view

I'd recommend to keep your controller free from translation logic and translate your strings directly inside your view like this:

<h1>{{ 'TITLE.HELLO_WORLD' | translate }}</h1>

Using the provided service

Angular Translate provides the $translate service which you can use in your Controllers.

An example usage of the $translate service can be:

.controller('TranslateMe', ['$scope', '$translate', function ($scope, $translate) {
    $translate('PAGE.TITLE')
        .then(function (translatedValue) {
            $scope.pageTitle = translatedValue;
        });
});

The translate service also has a method for directly translating strings without the need to handle a promise, using $translate.instant():

.controller('TranslateMe', ['$scope', '$translate', function ($scope, $translate) {
    $scope.pageTitle = $translate.instant('TITLE.DASHBOARD'); // Assuming TITLE.DASHBOARD is defined
});

The downside with using $translate.instant() could be that the language file isn't loaded yet if you are loading it async.

Using the provided filter

This is my preferred way since I don't have to handle promises this way. The output of the filter can be directly set to a scope variable.

.controller('TranslateMe', ['$scope', '$filter', function ($scope, $filter) {
    var $translate = $filter('translate');

    $scope.pageTitle = $translate('TITLE.DASHBOARD'); // Assuming TITLE.DASHBOARD is defined
});

Using the provided directive

Since @PascalPrecht is the creator of this awesome library, I'd recommend going with his advise (see his answer below) and use the provided directive which seems to handle translations very intelligent.

The directive takes care of asynchronous execution and is also clever enough to unwatch translation ids on the scope if the translation has no dynamic values.

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its dependencies could not be resolved

I was able to solve the same problem with different solution.

The solution that worked for me was to Right click project "pom.xml" in eclipse and select "Maven Install".

When is null or undefined used in JavaScript?

I might be missing something, but afaik, you get undefined only

Update: Ok, I missed a lot, trying to complete:

You get undefined...

... when you try to access properties of an object that don't exist:

var a = {}
a.foo // undefined

... when you have declared a variable but not initialized it:

var a;
// a is undefined

... when you access a parameter for which no value was passed:

function foo (a, b) {
    // something
}

foo(42); // b inside foo is undefined

... when a function does not return a value:

function foo() {};
var a = foo(); // a is undefined

It might be that some built-in functions return null on some error, but if so, then it is documented. null is a concrete value in JavaScript, undefined is not.


Normally you don't need to distinguish between those. Depending on the possible values of a variable, it is sufficient to use if(variable) to test whether a value is set or not (both, null and undefined evaluate to false).

Also different browsers seem to be returning these differently.

Please give a concrete example.

Generate Row Serial Numbers in SQL Query

select 
  ROW_NUMBER() Over (Order by CustomerID) As [S.N.], 
  CustomerID , 
  CustomerName, 
  Address, 
  City, 
  State, 
  ZipCode  
from Customers;

SQL How to Select the most recent date item

Select * 
FROM test_table 
WHERE user_id = value 
AND date_added = (select max(date_added) 
   from test_table 
   where user_id = value)

How can I cast int to enum?

From an int:

YourEnum foo = (YourEnum)yourInt;

From a string:

YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);

// The foo.ToString().Contains(",") check is necessary for enumerations marked with an [Flags] attribute
if (!Enum.IsDefined(typeof(YourEnum), foo) && !foo.ToString().Contains(","))
{
    throw new InvalidOperationException($"{yourString} is not an underlying value of the YourEnum enumeration.")
}

Update:

From number you can also

YourEnum foo = (YourEnum)Enum.ToObject(typeof(YourEnum) , yourInt);

How to remove item from a JavaScript object

_x000D_
_x000D_
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
_x000D_
_x000D_

this deletes test.blue

How do I create an Android Spinner as a popup?

android:spinnerMode="dialog"

// Creating adapter for spinner

ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, categories);

// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);

Could not open ServletContext resource [/WEB-INF/applicationContext.xml]

Update: This will create a second context same as in applicationContext.xml

or you can add this code snippet to your web.xml

<servlet>
    <servlet-name>spring-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

instead of

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

Changing three.js background to transparent or other color

A full answer: (Tested with r71)

To set a background color use:

renderer.setClearColor( 0xffffff ); // white background - replace ffffff with any hex color

If you want a transparent background you will have to enable alpha in your renderer first:

renderer = new THREE.WebGLRenderer( { alpha: true } ); // init like this
renderer.setClearColor( 0xffffff, 0 ); // second param is opacity, 0 => transparent

View the docs for more info.

jQuery checkbox check/uncheck

Use .prop() instead and if we go with your code then compare like this:

Look at the example jsbin:

  $("#news_list tr").click(function () {
    var ele = $(this).find(':checkbox');
    if ($(':checked').length) {
      ele.prop('checked', false);
      $(this).removeClass('admin_checked');
    } else {
      ele.prop('checked', true);
      $(this).addClass('admin_checked');
    }
 });

Changes:

  1. Changed input to :checkbox.
  2. Comparing the length of the checked checkboxes.

Tool for comparing 2 binary files in Windows

If you want to find out only whether or not the files are identical, you can use the Windows fc command in binary mode:

fc.exe /b file1 file2

For details, see the reference for fc

Normalizing images in OpenCV

The other answers normalize an image based on the entire image. But if your image has a predominant color (such as black), it will mask out the features that you're trying to enhance since it will not be as pronounced. To get around this limitation, we can normalize the image based on a subsection region of interest (ROI). Essentially we will normalize based on the section of the image that we want to enhance instead of equally treating each pixel with the same weight. Take for instance this earth image:

Input image -> Normalization based on entire image

If we want to enhance the clouds by normalizing based on the entire image, the result will not be very sharp and will be over saturated due to the black background. The features to enhance are lost. So to obtain a better result we can crop a ROI, normalize based on the ROI, and then apply the normalization back onto the original image. Say we crop the ROI highlighted in green:

This gives us this ROI

The idea is to calculate the mean and standard deviation of the ROI and then clip the frame based on the lower and upper range. In addition, we could use an offset to dynamically adjust the clip intensity. From here we normalize the original image to this new range. Here's the result:

Before -> After

Code

import cv2
import numpy as np

# Load image as grayscale and crop ROI
image = cv2.imread('1.png', 0)
x, y, w, h = 364, 633, 791, 273
ROI = image[y:y+h, x:x+w]

# Calculate mean and STD
mean, STD  = cv2.meanStdDev(ROI)

# Clip frame to lower and upper STD
offset = 0.2
clipped = np.clip(image, mean - offset*STD, mean + offset*STD).astype(np.uint8)

# Normalize to range
result = cv2.normalize(clipped, clipped, 0, 255, norm_type=cv2.NORM_MINMAX)

cv2.imshow('image', image)
cv2.imshow('ROI', ROI)
cv2.imshow('result', result)
cv2.waitKey()

The difference between normalizing based on the entire image vs a specific section of the ROI can be visualized by applying a heatmap to the result. Notice the difference on how the clouds are defined.

Input image -> heatmap

Normalized on entire image -> heatmap

Normalized on ROI -> heatmap

Heatmap code

import matplotlib.pyplot as plt
import numpy as np
import cv2

image = cv2.imread('result.png', 0)
colormap = plt.get_cmap('inferno')
heatmap = (colormap(image) * 2**16).astype(np.uint16)[:,:,:3]
heatmap = cv2.cvtColor(heatmap, cv2.COLOR_RGB2BGR)

cv2.imshow('image', image)
cv2.imshow('heatmap', heatmap)
cv2.waitKey()

Note: The ROI bounding box coordinates were obtained using how to get ROI Bounding Box Coordinates without Guess & Check and heatmap code was from how to convert a grayscale image to heatmap image with Python OpenCV

Invoking a PHP script from a MySQL trigger

A cronjob could monitor this log and based on events created by your trigger it could invoke a php script. That is if you absolutely have no control over you insertion.. If you have transaction logs in you MySQL, you can create a trigger for purpose of a log instance creation.

Print values for multiple variables on the same line from within a for-loop

As an additional note, there is no need for the for loop because of R's vectorization.

This:

P <- 243.51
t <- 31 / 365
n <- 365

for (r in seq(0.15, 0.22, by = 0.01))    
     A <- P * ((1 + (r/ n))^ (n * t))
     interest <- A - P
}

is equivalent to:

P <- 243.51
t <- 31 / 365
n <- 365
r <- seq(0.15, 0.22, by = 0.01)
A <- P * ((1 + (r/ n))^ (n * t))
interest <- A - P

Because r is a vector, the expression above containing it is performed for all values of the vector.

Wait for page load in Selenium

Use implicitly wait for wait of every element on page till given time.

driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

this wait for every element on page for 30 sec.

Another wait is Explicitly wait or conditional wait in this wait until given condition.

WebDriverWait wait = new WebDriverWait(driver, 40);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));

In id give static element id which is diffidently display on the page, as soon as page is load.

navigator.geolocation.getCurrentPosition sometimes works sometimes doesn't

This library adds a desiredAccuracy and maxWait option to geolocation calls, which means it will keep trying to get a position until the accuracy is within a specified range.

How to "select distinct" across multiple data frame columns in pandas?

I think use drop duplicate sometimes will not so useful depending dataframe.

I found this:

[in] df['col_1'].unique()
[out] array(['A', 'B', 'C'], dtype=object)

And work for me!

https://riptutorial.com/pandas/example/26077/select-distinct-rows-across-dataframe

How to get back Lost phpMyAdmin Password, XAMPP

The question may be getting old, but I've struggled with the same issue just now.

After deleting passwords with resetroot.bat, as instructed by Nedshed, you can choose another password by going to http://localhost/security/index.php

Specifying content of an iframe instead of the src attribute to a page

In combination with what Guffa described, you could use the technique described in Explanation of <script type = "text/template"> ... </script> to store the HTML document in a special script element (see the link for an explanation on how this works). That's a lot easier than storing the HTML document in a string.

How do you use MySQL's source command to import large files in windows

use mysql source command to avoid redirection failures, especially on windows.

mysql [-u <username>] [-p<password>] <databasename> -e "source /path/to/dump.sql"

where e for "Execute command"

On Windows, please remember to use double quote for sql command.

However, either backslash \ or slash / will work on Windows.

iPad/iPhone hover problem causes the user to double click a link

With inspiration from MacFreak, I put together something that works for me.

This js method prevents hover from sticking on an ipad, and prevents the click registering as two clicks in some cases. In CSS, if you have any :hover psudo classes in your css, change them to .hover For example .some-class:hover to .some-class.hover

Test this code on an ipad to see how css and js hover method behave differently (in hover effect only). The CSS button doesn't have a fancy click alert. http://jsfiddle.net/bensontrent/ctgr6stm/

_x000D_
_x000D_
function clicker(id, doStuff) {_x000D_
  id.on('touchstart', function(e) {_x000D_
    id.addClass('hover');_x000D_
  }).on('touchmove', function(e) {_x000D_
    id.removeClass('hover');_x000D_
  }).mouseenter(function(e) {_x000D_
    id.addClass('hover');_x000D_
  }).mouseleave(function(e) {_x000D_
    id.removeClass('hover');_x000D_
  }).click(function(e) {_x000D_
    id.removeClass('hover');_x000D_
    //It's clicked. Do Something_x000D_
    doStuff(id);_x000D_
  });_x000D_
}_x000D_
_x000D_
function doStuff(id) {_x000D_
  //Do Stuff_x000D_
  $('#clicked-alert').fadeIn(function() {_x000D_
    $(this).fadeOut();_x000D_
  });_x000D_
}_x000D_
clicker($('#unique-id'), doStuff);
_x000D_
button {_x000D_
  display: block;_x000D_
  margin: 20px;_x000D_
  padding: 10px;_x000D_
  -webkit-appearance: none;_x000D_
  touch-action: manipulation;_x000D_
}_x000D_
.hover {_x000D_
  background: yellow;_x000D_
}_x000D_
.btn:active {_x000D_
  background: red;_x000D_
}_x000D_
.cssonly:hover {_x000D_
  background: yellow;_x000D_
}_x000D_
.cssonly:active {_x000D_
  background: red;_x000D_
}_x000D_
#clicked-alert {_x000D_
  display: none;_x000D_
}
_x000D_
<button id="unique-id" class="btn">JS Hover for Mobile devices<span id="clicked-alert"> Clicked</span>_x000D_
_x000D_
</button>_x000D_
<button class="cssonly">CSS Only Button</button>_x000D_
<br>This js method prevents hover from sticking on an ipad, and prevents the click registering as two clicks. In CSS, if you have any :hover in your css, change them to .hover For example .some-class:hover to .some-class.hover
_x000D_
_x000D_
_x000D_

Maximum value of maxRequestLength?

These two settings worked for me to upload 1GB mp4 videos.

<system.web>
    <httpRuntime maxRequestLength="2097152" requestLengthDiskThreshold="2097152" executionTimeout="240"/>
</system.web>
<system.webServer>
    <security>
        <requestFiltering>
            <requestLimits maxAllowedContentLength="2147483648" />
        </requestFiltering>
    </security>
</system.webServer>

Show datalist labels but submit the actual value

The solution I use is the following:

<input list="answers" id="answer">
<datalist id="answers">
  <option data-value="42" value="The answer">
</datalist>

Then access the value to be sent to the server using JavaScript like this:

var shownVal = document.getElementById("answer").value;
var value2send = document.querySelector("#answers option[value='"+shownVal+"']").dataset.value;


Hope it helps.

Proxy setting for R

Simplest way to get everything working in RStudio under Windows 10:

Open up Internet Explorer, select Internet Options:

enter image description here


Open editor for Environment variables:

enter image description here


Add a variable HTTP_PROXY in form:

HTTP_PROXY=http://username:password@localhost:port/

Example:

HTTP_PROXY=http://John:JohnPassword@localhost:8080/    

enter image description here


RStudio should work:

enter image description here

Java Inheritance - calling superclass method

You can't call alpha's alphaMethod1() by using beta's object But you have two solutions:

solution 1: call alpha's alphaMethod1() from beta's alphaMethod1()

class Beta extends Alpha
{
  public void alphaMethod1()
  {
    super.alphaMethod1();
  }
}

or from any other method of Beta like:

class Beta extends Alpha
{
  public void foo()
  {
     super.alphaMethod1();
  }
}

class Test extends Beta 
{
   public static void main(String[] args)
   {
      Beta beta = new Beta();
      beta.foo();
   }
}

solution 2: create alpha's object and call alpha's alphaMethod1()

class Test extends Beta
{
   public static void main(String[] args)
   {
      Alpha alpha = new Alpha();
      alpha.alphaMethod1();
   }
}

@Autowired - No qualifying bean of type found for dependency

You should autowire interface AbstractManager instead of class MailManager. If you have different implemetations of AbstractManager you can write @Component("mailService") and then @Autowired @Qualifier("mailService") combination to autowire specific class.

This is due to the fact that Spring creates and uses proxy objects based on the interfaces.

How do I import a namespace in Razor View Page?

One issue that you must know is that when you import a namespace via web.config in Views folder, that namespace is imported JUST for views in that folder. Means if you want to import a namespace in an area views, you must also import that namespace, in that area's web.config file, located in area's Views folder;

JCheckbox - ActionListener and ItemListener?

The difference is that ActionEvent is fired when the action is performed on the JCheckBox that is its state is changed either by clicking on it with the mouse or with a space bar or a mnemonic. It does not really listen to change events whether the JCheckBox is selected or deselected.

For instance, if JCheckBox c1 (say) is added to a ButtonGroup. Changing the state of other JCheckBoxes in the ButtonGroup will not fire an ActionEvent on other JCheckBox, instead an ItemEvent is fired.

Final words: An ItemEvent is fired even when the user deselects a check box by selecting another JCheckBox (when in a ButtonGroup), however ActionEvent is not generated like that instead ActionEvent only listens whether an action is performed on the JCheckBox (to which the ActionListener is registered only) or not. It does not know about ButtonGroup and all other selection/deselection stuff.

Accessing elements of Python dictionary by index

Simple Example to understand how to access elements in the dictionary:-

Create a Dictionary

d = {'dog' : 'bark', 'cat' : 'meow' } 
print(d.get('cat'))
print(d.get('lion'))
print(d.get('lion', 'Not in the dictionary'))
print(d.get('lion', 'NA'))
print(d.get('dog', 'NA'))

Explore more about Python Dictionaries and learn interactively here...

Static Initialization Blocks

static int B,H;
static boolean flag = true;
static{
    Scanner scan = new Scanner(System.in);
    B = scan.nextInt();
    scan.nextLine();
    H = scan.nextInt();

    if(B < 0 || H < 0){
        flag = false;
        System.out.println("java.lang.Exception: Breadth and height must be positive");
    } 
}

How to open Emacs inside Bash

In the spirit of providing functionality, go to your .profile or .bashrc file located at /home/usr/ and at the bottom add the line:

alias enw='emacs -nw'

Now each time you open a terminal session you just type, for example, enw and you have the Emacs no-window option with three letters :).

MySQL select 10 random rows from 600K rows fast

Its very simple and single line query.

SELECT * FROM Table_Name ORDER BY RAND() LIMIT 0,10;

File Explorer in Android Studio

Device Explorer path for Emulator in Mac

/Users/"UserName"/Documents/AndroidStudio/DeviceExplorer/...

Logs File path for Emulator in Mac

/Users/"UserName"/Documents/AndroidStudio/DeviceExplorer/"EmulatorName"/storage/emulated/0/Android/data/com.app.domain/files/LogFiles/

Shared Preferences File path for Emulator in Mac

/Users/"UserName"/Documents/AndroidStudio/DeviceExplorer/"EmulatorName"/data/data/com.app.domain/shared_prefs/

Undoing a git rebase

It annoys me to no end that none of these answers is fully automatic, despite the fact that it should be automatable (at least mostly). I created a set of aliases to try to remedy this:

# Useful commands
#################

# Undo the last rebase
undo-rebase = "! f() { : git reset ; PREV_COMMIT=`git x-rev-before-rebase` && git reset --merge \"$PREV_COMMIT\" \"$@\";}; f"

# See what changed since the last rebase
rdiff = "!f() { : git diff ; git diff `git x-rev-before-rebase` "$@";}; f"

# Helpers
########
# Get the revision before the last rebase started
x-rev-before-rebase = !git reflog --skip=1 -1 \"`git x-start-of-rebase`\" --format=\"%gD\"

# Get the revision that started the rebase
x-start-of-rebase = reflog --grep-reflog '^rebase (start)' -1 --format="%gD"

You should be able to tweak this to allow going back an arbitrary number of rebases pretty easily (juggling the args is the trickiest part), which can be useful if you do a number of rebases in quick succession and mess something up along the way.

Caveats

It will get confused if any commit messages begin with "rebase (start)" (please don't do this). You could make the regex more resilient to improve the situation by matching something like this for your regex:

--grep-reflog "^rebase (start): checkout " 

WARNING: not tested (regex may need adjustments)

The reason I haven't done this is because I'm not 100% that a rebase always begins with a checkout. Can anyone confirm this?

[If you're curious about the null (:) commands at the beginning of the function, that's a way of setting up bash completions for the aliases]

How to drop unique in MySQL?

There is a better way which don't need you to alter the table:

mysql> DROP INDEX email ON fuinfo;

where email is the name of unique key (index).

You can also bring it back like that:

mysql> CREATE UNIQUE INDEX email ON fuinfo(email);

where email after IDEX is the name of the index and it's not optional. You can use KEY instead of INDEX.

Also it's possible to create (remove) multicolumn unique indecies like that:

mysql> CREATE UNIQUE INDEX email_fid ON fuinfo(email, fid);
mysql> DROP INDEX email_fid ON fuinfo;

If you didn't specify the name of multicolumn index you can remove it like that:

mysql> DROP INDEX email ON fuinfo;

where email is the column name.

Prime numbers between 1 to 100 in C Programming Language

#include<stdio.h>
int main()
{
    int a,b,i,c,j;
    printf("\n Enter the two no. in between you want to check:");
    scanf("%d%d",&a,&c);
    printf("%d-%d\n",a,c);
    for(j=a;j<=c;j++)
    {
        b=0;
        for(i=1;i<=c;i++)
        {
            if(j%i==0)
            {
                 b++;
            }
        }
        if(b==2)
        {
            printf("\nPrime number:%d\n",j);
        }
        else
        {
            printf("\n\tNot prime:%d\n",j);
        }
    }
}

Word-wrap in an HTML table

Workaround that uses overflow-wrap and works fine with normal table layout + table width 100%

https://jsfiddle.net/krf0v6pw/

HTML

<table>
  <tr>
    <td class="overflow-wrap-hack">
      <div class="content">
        wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
      </div>
    </td>
  </tr>
</table>

CSS

.content{
  word-wrap:break-word; /*old browsers*/
  overflow-wrap:break-word;
}

table{
  width:100%; /*must be set (to any value)*/
}

.overflow-wrap-hack{
  max-width:1px;
}

Benefits:

  • Uses overflow-wrap:break-word instead of word-break:break-all. Which is better because it tries to break on spaces first, and cuts the word off only if the word is bigger than it's container.
  • No table-layout:fixed needed. Use your regular auto-sizing.
  • Not needed to define fixed width or fixed max-width in pixels. Define % of the parent if needed.

Tested in FF57, Chrome62, IE11, Safari11

return error message with actionResult

Inside Controller Action you can access HttpContext.Response. There you can set the response status as in the following listing.

[HttpPost]
public ActionResult PostViaAjax()
{
    var body = Request.BinaryRead(Request.TotalBytes);

    var result = Content(JsonError(new Dictionary<string, string>()
    {
        {"err", "Some error!"}
    }), "application/json; charset=utf-8");
    HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
    return result;
}

PHP Warning: PHP Startup: ????????: Unable to initialize module

In my case, with Windows Server 2008, I had to change the PATH variable. The former version of PHP (VC9) was inside it.

I have changed it with the newer version of PHP (VC11).

After a restart of Apache, it was okay.

Displaying all table names in php from MySQL database

you need to assign the mysql_query to a variable (eg $result), then display this variable as you would a normal result from the database.

Calling a method every x minutes

var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromMinutes(5);

var timer = new System.Threading.Timer((e) =>
{
    MyMethod();   
}, null, startTimeSpan, periodTimeSpan);

Elegant ways to support equivalence ("equality") in Python classes

The 'is' test will test for identity using the builtin 'id()' function which essentially returns the memory address of the object and therefore isn't overloadable.

However in the case of testing the equality of a class you probably want to be a little bit more strict about your tests and only compare the data attributes in your class:

import types

class ComparesNicely(object):

    def __eq__(self, other):
        for key, value in self.__dict__.iteritems():
            if (isinstance(value, types.FunctionType) or 
                    key.startswith("__")):
                continue

            if key not in other.__dict__:
                return False

            if other.__dict__[key] != value:
                return False

         return True

This code will only compare non function data members of your class as well as skipping anything private which is generally what you want. In the case of Plain Old Python Objects I have a base class which implements __init__, __str__, __repr__ and __eq__ so my POPO objects don't carry the burden of all that extra (and in most cases identical) logic.

How to do a for loop in windows command line?

You might also consider adding ".

For example for %i in (*.wav) do opusenc "%~ni.wav" "%~ni.opus" is very good idea.

Read/write to file using jQuery

No, JavaScript doesn't have access to writing files as this would be a huge security risk to say the least. If you wanted to get/store information server-side, though, you can certainly make an Ajax call to a PHP/ASP/Python/etc. script that can then get/store the data in the server. If you meant store data on the client machine, this is impossible with JavaScript alone. I suspect Flash/Java may be able to, but I am not sure.

If you are only trying to store a small amount of information for an unreliable period of time regarding a specific user, I think you want Web Storage API or cookies. I am not sure from your question what you are trying to accomplish, though.

iOS download and save image inside app

You cannot save anything inside the app's bundle, but you can use +[NSData dataWithContentsOfURL:] to store the image in your app's documents directory, e.g.:

NSData *imageData = [NSData dataWithContentsOfURL:myImageURL];
NSString *imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"/myImage.png"];
[imageData writeToFile:imagePath atomically:YES];

Not exactly permanent, but it stays there at least until the user deletes the app.

How to calculate the sum of the datatable column in asp.net?

You Can use Linq by Name Grouping

  var allEntries = from r in dt.AsEnumerable()
                            select r["Amount"];

using name space using System.Linq;

You can find the sample total,subtotal,grand total in datatable using c# at Myblog

How to verify a Text present in the loaded page through WebDriver

Note: Not in boolean

WebDriver driver=new FirefoxDriver();
driver.get("http://www.gmail.com");

if(driver.getPageSource().contains("Ur message"))
  {
    System.out.println("Pass");
  }
else
  {
    System.out.println("Fail");
  }

Picasso v/s Imageloader v/s Fresco vs Glide

I am one of the engineers on the Fresco project. So obviously I'm biased.

But you don't have to take my word for it. We've released a sample app that allows you to compare the performance of five libraries - Fresco, Picasso, UIL, Glide, and Volley Image Loader - side by side. You can get it at our GitHub repo.

I should also point out that Fresco is available on Maven Central, as com.facebook.fresco:fresco.

Fresco offers features that Picasso, UIL, and Glide do not yet have:

  1. Images aren't stored in the Java heap, but in the ashmem heap. Intermediate byte buffers are also stored in the native heap. This leaves a lot more memory available for applications to use. It reduces the risk of OutOfMemoryErrors. It also reduces the amount of garbage collection apps have to do, leading to better performance.
  2. Progressive JPEG images can be streamed, just like in a web browser.
  3. Images can be cropped around any point, not just the center.
  4. JPEG images can be resized natively. This avoids the problem of OOMing while trying to downsize an image.

There are many others (see our documentation), but these are the most important.

Fatal error: Call to undefined function imap_open() in PHP

if you are on linux, edit the /etc/php/php.ini (or you will have to create a new extension import file at /etc/php5/cli/conf.d) file so that you add the imap shared object file and then, restart the apache server. Uncomment

;extension=imap.so

so that it becomes like this:

extension=imap.so

Then, restart the apache by

# /etc/rc.d/httpd restart

How can I remove the last character of a string in python?

As you say, you don't need to use a regex for this. You can use rstrip.

my_file_path = my_file_path.rstrip('/')

If there is more than one / at the end, this will remove all of them, e.g. '/file.jpg//' -> '/file.jpg'. From your question, I assume that would be ok.

How do I get multiple subplots in matplotlib?

  • You can also unpack the axes in the subplots call

  • And set whether you want to share the x and y axes between the subplots

Like this:

import matplotlib.pyplot as plt
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True)
ax1.plot(range(10), 'r')
ax2.plot(range(10), 'b')
ax3.plot(range(10), 'g')
ax4.plot(range(10), 'k')
plt.show()

enter image description here

Division in Python 2.7. and 3.3

"/" is integer division in python 2 so it is going to round to a whole number. If you would like a decimal returned, just change the type of one of the inputs to float:

float(20)/15 #1.33333333

How to declare a global variable in a .js file

The recommended approach is:

window.greeting = "Hello World!"

You can then access it within any function:

function foo() {

   alert(greeting); // Hello World!
   alert(window["greeting"]); // Hello World!
   alert(window.greeting); // Hello World! (recommended)

}

This approach is preferred for two reasons.

  1. The intent is explicit. The use of the var keyword can easily lead to declaring global vars that were intended to be local or vice versa. This sort of variable scoping is a point of confusion for a lot of Javascript developers. So as a general rule, I make sure all variable declarations are preceded with the keyword var or the prefix window.

  2. You standardize this syntax for reading the variables this way as well which means that a locally scoped var doesn't clobber the global var or vice versa. For example what happens here is ambiguous:

 

 greeting = "Aloha";

 function foo() {
     greeting = "Hello"; // overrides global!
 }

 function bar(greeting) {
   alert(greeting);
 }

 foo();
 bar("Howdy"); // does it alert "Hello" or "Howdy" ?

However, this is much cleaner and less error prone (you don't really need to remember all the variable scoping rules):

 function foo() {
     window.greeting = "Hello";
 }

 function bar(greeting) {
   alert(greeting);
 }

 foo();
 bar("Howdy"); // alerts "Howdy"

Combating AngularJS executing controller twice

Just want to add one more case when controller can init twice (this is actual for angular.js 1.3.1):

<div ng-if="loading">Loading...</div>
<div ng-if="!loading">
    <div ng-view></div>
</div>

In this case $route.current will be already set when ng-view will init. That cause double initialization.

To fix it just change ng-if to ng-show/ng-hide and all will work well.

Printing 2D array in matrix format

I wrote extension method

public static string ToMatrixString<T>(this T[,] matrix, string delimiter = "\t")
{
    var s = new StringBuilder();

    for (var i = 0; i < matrix.GetLength(0); i++)
    {
        for (var j = 0; j < matrix.GetLength(1); j++)
        {
            s.Append(matrix[i, j]).Append(delimiter);
        }

        s.AppendLine();
    }

    return s.ToString();
}

To use just call the method

results.ToMatrixString();

Django ManyToMany filter()

Note that if the user may be in multiple zones used in the query, you may probably want to add .distinct(). Otherwise you get one user multiple times:

users_in_zones = User.objects.filter(zones__in=[zone1, zone2, zone3]).distinct()

Laravel Eloquent: How to get only certain columns from joined tables

Using Model:

Model::where('column','value')->get(['column1','column2','column3',...]);

Using Query Builder:

DB::table('table_name')->where('column','value')->get(['column1','column2','column3',...]);

Java Long primitive type maximum limit

Exceding the maximum value of a long doesnt throw an exception, instead it cicles back. If you do this:

Long.MAX_VALUE + 1

you will notice that the result is the equivalent to Long.MIN_VALUE.

From here: java number exceeds long.max_value - how to detect?

What does $1 [QSA,L] mean in my .htaccess file?

This will capture requests for files like version, release, and README.md, etc. which should be treated either as endpoints, if defined (as in the case of /release), or as "not found."

Number of rows affected by an UPDATE in PL/SQL

Use the Count(*) analytic function OVER PARTITION BY NULL This will count the total # of rows

jquery remove "selected" attribute of option?

This works:

$("#myselect").find('option').removeAttr("selected");

or

$("#myselect").find('option:selected').removeAttr("selected");

jsFiddle

Changing password with Oracle SQL Developer

The correct syntax for updating the password using SQL Developer is:

alter user user_name identified by new_password replace old_password ;

You can check more options for this command here: ALTER USER-Oracle DOCS

What is a race condition?

A race condition is an undesirable situation that occurs when two or more process can access and change the shared data at the same time.It occurred because there were conflicting accesses to a resource . Critical section problem may cause race condition. To solve critical condition among the process we have take out only one process at a time which execute the critical section.

Line Break in XML?

If you are using CSS to style (Not recommended.) you can use display:block;, however, this will only give you line breaks before and after the styled element.

Linq on DataTable: select specific column into datatable, not whole table

If you already know beforehand how many columns your new DataTable would have, you can do something like this:

DataTable matrix = ... // get matrix values from db

DataTable newDataTable = new DataTable();
newDataTable.Columns.Add("c_to", typeof(string));
newDataTable.Columns.Add("p_to", typeof(string));

var query = from r in matrix.AsEnumerable()
            where r.Field<string>("c_to") == "foo" &&
                    r.Field<string>("p_to") == "bar"
            let objectArray = new object[]
            {
                r.Field<string>("c_to"), r.Field<string>("p_to")
            }
            select objectArray;

foreach (var array in query)
{
    newDataTable.Rows.Add(array);
}

PDO Prepared Inserts multiple rows in single query

Most of the solutions given here to create the prepared query are more complex that they need to be. Using PHP's built in functions you can easily creare the SQL statement without significant overhead.

Given $records, an array of records where each record is itself an indexed array (in the form of field => value), the following function will insert the records into the given table $table, on a PDO connection $connection, using only a single prepared statement. Note that this is a PHP 5.6+ solution because of the use of argument unpacking in the call to array_push:

private function import(PDO $connection, $table, array $records)
{
    $fields = array_keys($records[0]);
    $placeHolders = substr(str_repeat(',?', count($fields)), 1);
    $values = [];
    foreach ($records as $record) {
        array_push($values, ...array_values($record));
    }

    $query = 'INSERT INTO ' . $table . ' (';
    $query .= implode(',', $fields);
    $query .= ') VALUES (';
    $query .= implode('),(', array_fill(0, count($records), $placeHolders));
    $query .= ')';

    $statement = $connection->prepare($query);
    $statement->execute($values);
}

How to delete the contents of a folder?

To delete all the files inside the directory as well as its sub-directories, without removing the folders themselves, simply do this:

import os
mypath = "my_folder" #Enter your path here
for root, dirs, files in os.walk(mypath):
    for file in files:
        os.remove(os.path.join(root, file))

Get IFrame's document, from JavaScript in main document

You should be able to access the document in the IFRAME using the following code:

document.getElementById('myframe').contentWindow.document

However, you will not be able to do this if the page in the frame is loaded from a different domain (such as google.com). THis is because of the browser's Same Origin Policy.

php: check if an array has duplicates

? PERFORMANCE SOLUTION ?

If you care about performance and micro-optimizations check this one-liner:

function no_dupes(array $input_array) {
    return count($input_array) === count(array_flip($input_array));
}

Description:

Function compares number of array elements in $input_array with array_flip'ed elements. Values become keys and guess what - keys must be unique in associative arrays so not unique values are lost and final number of elements is lower than original.

As said in manual array keys can be only type of int or string so this is what you can have in original array values to compare, otherwise PHP will start casting with unexpected results.

PROOF FOR 10M RECORDS ARRAY

  • Most voted solution: 14.187316179276s
  • Accepted solution: 2.0736091136932s
  • This answer solution: 0.14155888557434s /10

Test case:

<?php

$elements = array_merge(range(1,10000000),[1]);

$time = microtime(true);
accepted_solution($elements);
echo 'Accepted solution: ', (microtime(true) - $time), 's', PHP_EOL;

$time = microtime(true);
most_voted_solution($elements);
echo 'Most voted solution: ', (microtime(true) - $time), 's', PHP_EOL;

$time = microtime(true);
this_answer_solution($elements);
echo 'This answer solution: ', (microtime(true) - $time), 's', PHP_EOL;

function accepted_solution($array){
 $dupe_array = array();
 foreach($array as $val){
  // sorry, but I had to add below line to remove millions of notices
  if(!isset($dupe_array[$val])){$dupe_array[$val]=0;}
  if(++$dupe_array[$val] > 1){
   return true;
  }
 }
 return false;
}

function most_voted_solution($array) {
   return count($array) !== count(array_unique($array));
}

function this_answer_solution(array $input_array) {
    return count($input_array) === count(array_flip($input_array));
}

Notice that accepted solution might be faster in certain condition when not unique values are near the beginning of huge array.

Selenium WebDriver can't find element by link text

This doesn't seem to have <a> </a> tags so selenium might not be able to detect it as a link.

You may try and use

driver.findElement(By.xpath("//*[@class='ng-binding']")).click();

if this is the only element in that page with this class .

Redirecting Output from within Batch file

@echo OFF
[your command] >> [Your log file name].txt

I used the command above in my batch file and it works. In the log file, it shows the results of my command.

Why does Java have an "unreachable statement" compiler error?

It is Nanny. I feel .Net got this one right - it raises a warning for unreachable code, but not an error. It is good to be warned about it, but I see no reason to prevent compilation (especially during debugging sessions where it is nice to throw a return in to bypass some code).

How do you render primitives as wireframes in OpenGL?

You can use glut libraries like this:

  1. for a sphere:

    glutWireSphere(radius,20,20);
    
  2. for a Cylinder:

    GLUquadric *quadratic = gluNewQuadric();
    gluQuadricDrawStyle(quadratic,GLU_LINE);
    gluCylinder(quadratic,1,1,1,12,1);
    
  3. for a Cube:

    glutWireCube(1.5);
    

In C#, why is String a reference type that behaves like a value type?

The distinction between reference types and value types are basically a performance tradeoff in the design of the language. Reference types have some overhead on construction and destruction and garbage collection, because they are created on the heap. Value types on the other hand have overhead on method calls (if the data size is larger than a pointer), because the whole object is copied rather than just a pointer. Because strings can be (and typically are) much larger than the size of a pointer, they are designed as reference types. Also, as Servy pointed out, the size of a value type must be known at compile time, which is not always the case for strings.

The question of mutability is a separate issue. Both reference types and value types can be either mutable or immutable. Value types are typically immutable though, since the semantics for mutable value types can be confusing.

Reference types are generally mutable, but can be designed as immutable if it makes sense. Strings are defined as immutable because it makes certain optimizations possible. For example, if the same string literal occurs multiple times in the same program (which is quite common), the compiler can reuse the same object.

So why is "==" overloaded to compare strings by text? Because it is the most useful semantics. If two strings are equal by text, they may or may not be the same object reference due to the optimizations. So comparing references are pretty useless, while comparing text are almost always what you want.

Speaking more generally, Strings has what is termed value semantics. This is a more general concept than value types, which is a C# specific implementation detail. Value types have value semantics, but reference types may also have value semantics. When a type have value semantics, you can't really tell if the underlying implementation is a reference type or value type, so you can consider that an implementation detail.

Safely override C++ virtual functions

Since g++ 4.7 it does understand the new C++11 override keyword:

class child : public parent {
    public:
      // force handle_event to override a existing function in parent
      // error out if the function with the correct signature does not exist
      void handle_event(int something) override;
};

Select by partial string from a pandas DataFrame

Using contains didn't work well for my string with special characters. Find worked though.

df[df['A'].str.find("hello") != -1]

Use of min and max functions in C++

As you noted yourself, fmin and fmax were introduced in C99. Standard C++ library doesn't have fmin and fmax functions. Until C99 standard library gets incorporated into C++ (if ever), the application areas of these functions are cleanly separated. There's no situation where you might have to "prefer" one over the other.

You just use templated std::min/std::max in C++, and use whatever is available in C.

Could not find a version that satisfies the requirement tensorflow

As of October 2020:

  • Tensorflow only supports the 64-bit version of Python

  • Tensorflow only supports Python 3.5 to 3.8

So, if you're using an out-of-range version of Python (older or newer) or a 32-bit version, then you'll need to use a different version.

If else embedding inside html

In @Patrick McMahon's response, the second comment here ( $first_condition is false and $second_condition is true ) is not entirely accurate:

<?php if($first_condition): ?>
  /*$first_condition is true*/
  <div class="first-condition-true">First Condition is true</div>
<?php elseif($second_condition): ?>
  /*$first_condition is false and $second_condition is true*/
  <div class="second-condition-true">Second Condition is true</div>
<?php else: ?>
  /*$first_condition and $second_condition are false*/
  <div class="first-and-second-condition-false">Conditions are false</div>
<?php endif; ?>

Elseif fires whether $first_condition is true or false, as do additional elseif statements, if there are multiple.

I am no PHP expert, so I don't know whether that's the correct way to say IF this OR that ELSE that or if there is another/better way to code it in PHP, but this would be an important distinction to those looking for OR conditions versus ELSE conditions.

Source is w3schools.com and my own experience.

How do I pass variables and data from PHP to JavaScript?

Let's say your variable is always integer. In that case this is easier:

<?PHP
    $number = 4;

    echo '<script>';
    echo 'var number = ' . $number . ';';
    echo 'alert(number);';
    echo '</script>';
?>

Output:

<script>var number = 4;alert(number);</script>

Let's say your variable is not an integer, but if you try above method you will get something like this:

<script>var number = abcd;alert(number);</script>

But in JavaScript this is a syntax error.

So in PHP we have a function call json_encode that encode string to a JSON object.

<?PHP
    $number = 'abcd';

    echo '<script>';
    echo 'var number = ' . json_encode($number) . ';';
    echo 'alert(number);';
    echo '</script>';
?>

Since abcd in JSON is "abcd", it looks like this:

<script>var number = "abcd";alert(number);</script>

You can use same method for arrays:

<?PHP
    $details = [
    'name' => 'supun',
    'age' => 456,
    'weight' => '55'
    ];

    echo '<script>';
    echo 'var details = ' . json_encode($details) . ';';
    echo 'alert(details);';
    echo 'console.log(details);';
    echo '</script>';
?>

And your JavaScript code looks like this:

<script>var details = {"name":"supun","age":456,"weight":"55"};alert(details);console.log(details);</script>

Console output

Enter image description here

How do I write a for loop in bash

I commonly like to use a slight variant on the standard for loop. I often use this to run a command on a series of remote hosts. I take advantage of bash's brace expansion to create for loops that allow me to create non-numerical for-loops.

Example:

I want to run the uptime command on frontend hosts 1-5 and backend hosts 1-3:

% for host in {frontend{1..5},backend{1..3}}.mycompany.com
    do ssh $host "echo -n $host; uptime"
  done

I typically run this as a single-line command with semicolons on the ends of the lines instead of the more readable version above. The key usage consideration are that braces allow you to specify multiple values to be inserted into a string (e.g. pre{foo,bar}post results in prefoopost, prebarpost) and allow counting/sequences by using the double periods (you can use a..z etc.). However, the double period syntax is a new feature of bash 3.0; earlier versions will not support this.

PDO closing connection

Its more than just setting the connection to null. That may be what the documentation says, but that is not the truth for mysql. The connection will stay around for a bit longer (Ive heard 60s, but never tested it)

If you want to here the full explanation see this comment on the connections https://www.php.net/manual/en/pdo.connections.php#114822

To force the close the connection you have to do something like

$this->connection = new PDO();
$this->connection->query('KILL CONNECTION_ID()');
$this->connection = null;

New line in JavaScript alert box

_x000D_
_x000D_
 alert("some text\nmore text in a new line");
_x000D_
_x000D_
_x000D_

Output:

some text
more text in a new line

Finish all activities at a time

There is a finishAffinity() method in Activity that will finish the current activity and all parent activities, but it works only in Android 4.1 or higher.

For API 16+, use

finishAffinity();

For lower (Android 4.1 lower), use

ActivityCompat.finishAffinity(YourActivity.this);

How to work with complex numbers in C?

This code will help you, and it's fairly self-explanatory:

#include <stdio.h>      /* Standard Library of Input and Output */
#include <complex.h>    /* Standard Library of Complex Numbers */

int main() {

    double complex z1 = 1.0 + 3.0 * I;
    double complex z2 = 1.0 - 4.0 * I;

    printf("Working with complex numbers:\n\v");

    printf("Starting values: Z1 = %.2f + %.2fi\tZ2 = %.2f %+.2fi\n", creal(z1), cimag(z1), creal(z2), cimag(z2));

    double complex sum = z1 + z2;
    printf("The sum: Z1 + Z2 = %.2f %+.2fi\n", creal(sum), cimag(sum));

    double complex difference = z1 - z2;
    printf("The difference: Z1 - Z2 = %.2f %+.2fi\n", creal(difference), cimag(difference));

    double complex product = z1 * z2;
    printf("The product: Z1 x Z2 = %.2f %+.2fi\n", creal(product), cimag(product));

    double complex quotient = z1 / z2;
    printf("The quotient: Z1 / Z2 = %.2f %+.2fi\n", creal(quotient), cimag(quotient));

    double complex conjugate = conj(z1);
    printf("The conjugate of Z1 = %.2f %+.2fi\n", creal(conjugate), cimag(conjugate));

    return 0;
}

  with:

creal(z1): get the real part (for float crealf(z1), for long double creall(z1))

cimag(z1): get the imaginary part (for float cimagf(z1), for long double cimagl(z1))

Another important point to remember when working with complex numbers is that functions like cos(), exp() and sqrt() must be replaced with their complex forms, e.g. ccos(), cexp(), csqrt().

"ImportError: no module named 'requests'" after installing with pip

In Windows it worked for me only after trying the following: 1. Open cmd inside the folder where "requests" is unpacked. (CTRL+SHIFT+right mouse click, choose the appropriate popup menu item) 2. (Here is the path to your pip3.exe)\pip3.exe install requests Done

Swift how to sort array of custom objects by property value

Two alternatives

1) Ordering the original array with sortInPlace

self.assignments.sortInPlace({ $0.order < $1.order })
self.printAssignments(assignments)

2) Using an alternative array to store the ordered array

var assignmentsO = [Assignment] ()
assignmentsO = self.assignments.sort({ $0.order < $1.order })
self.printAssignments(assignmentsO)

How to add `style=display:"block"` to an element using jQuery?

There are multiple function to do this work that wrote in bottom based on priority.

Set one or more CSS properties for the set of matched elements.

$("div").css("display", "block")
// Or add multiple CSS properties
$("div").css({
  display: "block",
  color: "red",
  ...
})

Display the matched elements and is roughly equivalent to calling .css("display", "block")

You can display element using .show() instead

$("div").show()

Set one or more attributes for the set of matched elements.

If target element hasn't style attribute, you can use this method to add inline style to element.

$("div").attr("style", "display:block")
// Or add multiple CSS properties
$("div").attr("style", "display:block; color:red")

  • JavaScript

You can add specific CSS property to element using pure javascript, if you don't want to use jQuery.

var div = document.querySelector("div");
// One property
div.style.display = "block";
// Multiple properties
div.style.cssText = "display:block; color:red"; 
// Multiple properties
div.setAttribute("style", "display:block; color:red");

How to use ADB in Android Studio to view an SQLite DB

Depending on devices you might not find sqlite3 command in adb shell. In that case you might want to follow this :

adb shell

$ run-as package.name
$ cd ./databases/
$ ls -l #Find the current permissions - r=4, w=2, x=1
$ chmod 666 ./dbname.db
$ exit
$ exit
adb pull /data/data/package.name/databases/dbname.db ~/Desktop/
adb push ~/Desktop/dbname.db /data/data/package.name/databases/dbname.db
adb shell
$ run-as package.name
$ chmod 660 ./databases/dbname.db #Restore original permissions
$ exit
$ exit

for reference go to https://stackoverflow.com/a/17177091/3758972.

There might be cases when you get "remote object not found" after following above procedure. Then change permission of your database folder to 755 in adb shell.

$ chmod 755 databases/

But please mind that it'll work only on android version < 21.

How to do relative imports in Python?

You have to append the module’s path to PYTHONPATH:

export PYTHONPATH="${PYTHONPATH}:/path/to/your/module/"

CSS-Only Scrollable Table with fixed headers

As I was recently in need of this, I will share a solution that uses 3 tables, but does not require JavaScript.

Table 1 (parent) contains two rows. The first row contains table 2 (child 1) for the column headers. The second row contains table 3 (child 2) for the scrolling content.

It must be noted the childTbl must be 25px shorter than the parentTbl for the scroller to appear properly.

This is the source, where I got the idea from. I made it HTML5-friendly without the deprecated tags and the inline CSS.

_x000D_
_x000D_
.parentTbl table {_x000D_
  border-spacing: 0;_x000D_
  border-collapse: collapse;_x000D_
  border: 0;_x000D_
  width: 690px;_x000D_
}_x000D_
.childTbl table {_x000D_
  border-spacing: 0;_x000D_
  border-collapse: collapse;_x000D_
  border: 1px solid #d7d7d7;_x000D_
  width: 665px;_x000D_
}_x000D_
.childTbl th,_x000D_
.childTbl td {_x000D_
  border: 1px solid #d7d7d7;_x000D_
}_x000D_
.scrollData {_x000D_
  width: 690;_x000D_
  height: 150px;_x000D_
  overflow-x: hidden;_x000D_
}
_x000D_
<div class="parentTbl">_x000D_
  <table>_x000D_
    <tr>_x000D_
      <td>_x000D_
        <div class="childTbl">_x000D_
          <table class="childTbl">_x000D_
            <tr>_x000D_
              <th>Header 1</th>_x000D_
              <th>Header 2</th>_x000D_
              <th>Header 3</th>_x000D_
              <th>Header 4</th>_x000D_
              <th>Header 5</th>_x000D_
              <th>Header 6</th>_x000D_
            </tr>_x000D_
          </table>_x000D_
        </div>_x000D_
      </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>_x000D_
        <div class="scrollData childTbl">_x000D_
          <table>_x000D_
            <tr>_x000D_
              <td>Table Data 1</td>_x000D_
              <td>Table Data 2</td>_x000D_
              <td>Table Data 3</td>_x000D_
              <td>Table Data 4</td>_x000D_
              <td>Table Data 5</td>_x000D_
              <td>Table Data 6</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Table Data 1</td>_x000D_
              <td>Table Data 2</td>_x000D_
              <td>Table Data 3</td>_x000D_
              <td>Table Data 4</td>_x000D_
              <td>Table Data 5</td>_x000D_
              <td>Table Data 6</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Table Data 1</td>_x000D_
              <td>Table Data 2</td>_x000D_
              <td>Table Data 3</td>_x000D_
              <td>Table Data 4</td>_x000D_
              <td>Table Data 5</td>_x000D_
              <td>Table Data 6</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Table Data 1</td>_x000D_
              <td>Table Data 2</td>_x000D_
              <td>Table Data 3</td>_x000D_
              <td>Table Data 4</td>_x000D_
              <td>Table Data 5</td>_x000D_
              <td>Table Data 6</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Table Data 1</td>_x000D_
              <td>Table Data 2</td>_x000D_
              <td>Table Data 3</td>_x000D_
              <td>Table Data 4</td>_x000D_
              <td>Table Data 5</td>_x000D_
              <td>Table Data 6</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Table Data 1</td>_x000D_
              <td>Table Data 2</td>_x000D_
              <td>Table Data 3</td>_x000D_
              <td>Table Data 4</td>_x000D_
              <td>Table Data 5</td>_x000D_
              <td>Table Data 6</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Table Data 1</td>_x000D_
              <td>Table Data 2</td>_x000D_
              <td>Table Data 3</td>_x000D_
              <td>Table Data 4</td>_x000D_
              <td>Table Data 5</td>_x000D_
              <td>Table Data 6</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Table Data 1</td>_x000D_
              <td>Table Data 2</td>_x000D_
              <td>Table Data 3</td>_x000D_
              <td>Table Data 4</td>_x000D_
              <td>Table Data 5</td>_x000D_
              <td>Table Data 6</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Table Data 1</td>_x000D_
              <td>Table Data 2</td>_x000D_
              <td>Table Data 3</td>_x000D_
              <td>Table Data 4</td>_x000D_
              <td>Table Data 5</td>_x000D_
              <td>Table Data 6</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Table Data 1</td>_x000D_
              <td>Table Data 2</td>_x000D_
              <td>Table Data 3</td>_x000D_
              <td>Table Data 4</td>_x000D_
              <td>Table Data 5</td>_x000D_
              <td>Table Data 6</td>_x000D_
            </tr>_x000D_
          </table>_x000D_
        </div>_x000D_
      </td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This is reliable on different browsers, the downside would be having to hard code the table widths.

Could not load file or assembly 'System.Net.Http.Formatting' or one of its dependencies. The system cannot find the path specified

I found an extra

  <dependentAssembly>
    <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-2.2.28.0" newVersion="2.2.28.0" />
  </dependentAssembly>

in my web.config. removed that to get it to work. some other package I installed, and then removed caused the issue.

How do I do redo (i.e. "undo undo") in Vim?

In command mode, use the U key to undo and Ctrl + r to redo. Have a look at http://www.vim.org/htmldoc/undo.html.

Have a fixed position div that needs to scroll if content overflows

The solutions here didn't work for me as I'm styling react components.

What worked though for the sidebar was

.sidebar{
position: sticky;
top: 0;
}

Hope this helps someone.

How do I select and store columns greater than a number in pandas?

Sample DF:

In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))

In [80]: df
Out[80]:
    a   b   c
0   6  11  11
1  14   7   8
2  13   5  11
3  13   7  11
4  13   5   9
5   5  11   9
6   9   8   6
7   5  11  10
8   8  10  14
9   7  14  13

present only those rows where b > 10

In [81]: df[df.b > 10]
Out[81]:
   a   b   c
0  6  11  11
5  5  11   9
7  5  11  10
9  7  14  13

Minimums (for all columns) for the rows satisfying b > 10 condition

In [82]: df[df.b > 10].min()
Out[82]:
a     5
b    11
c     9
dtype: int32

Minimum (for the b column) for the rows satisfying b > 10 condition

In [84]: df.loc[df.b > 10, 'b'].min()
Out[84]: 11

UPDATE: starting from Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.

Google Play Services Library update and missing symbol @integer/google_play_services_version

Please note that this fix may only apply to IntelliJ users!! (More information at the bottom of this post that should apply to everyone.)

Fixed this problem! I use IntelliJ and it turns out I just had misconfigured the way I was including the google-play-services_lib module as a dependency.

As I fixed this entirely through GUI and not at all by editing any files, here's a couple of screenshots:

Step 1 - Initial Project Structure So my Project Structure started off looking like this...

Step 2 - Removed google-play-services library Then I removed the google-play-services library from my dependencies list by selecting it and then clicking the minus button at the bottom. Notice the error at the bottom of the dialog, as my project absolutely does require this library. But don't worry, we'll re-add it soon!

Step 3 - Added google-play-services as a module dependency Next I added google-play-services_lib as a module dependency instead of a library dependency. Then I hit the up arrow button at the bottom a couple times to move this dependency to the top of the list. But notice the error at the bottom (we're still not done yet!)

Step 4 - Click the lightbulb to add the google-play-services library as a dependency I then clicked the lightbulb at the bottom of the dialog in the error message area to bring up this little small popup that gives two choices (Add to dependencies... or Remove Library). Click the Add to dependencies... option!

Step 5 - Add the library to the google-play-services_lib module A new small dialog window should have popped up. It gave me two choices, one for my main project (it's name is blurred out), and then another for the google-play-services_lib project. Yours may have a bunch more depending on your project (like you may see actionbarsherlock, stuff like that). Select google-play-services_lib and click okay!

And finally, you're done! I hope this helps someone else out there!

Further info

I believe the reason that this issue was happening to begin with is because I thought that I had properly included the entire google-play-services_lib project into my overall project... but I actually had not, and had instead only properly included its jar file (google-play-services_lib/libs/google-play-services.jar). That jar file only includes code, not Android resources values, and so as such the @integer/google_play_services_version value was never really in my project. But the code was able to be used in my project, and so that made it seem like everything was fine.

And as a side note, fixing this issue also seems to have fixed the GooglePlayServicesUtil.getErrorDialog(...).show() crash that I used to have. But that could also have been fixed by the update, not really 100% sure there.

Assigning strings to arrays of characters

You can use this:

yylval.sval=strdup("VHDL + Volcal trance...");

Where yylval is char*. strdup from does the job.

@RequestParam vs @PathVariable

it may be that the application/x-www-form-urlencoded midia type convert space to +, and the reciever will decode the data by converting the + to space.check the url for more info.http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1

How to launch PowerShell (not a script) from the command line

If you go to C:\Windows\system32\Windowspowershell\v1.0 (and C:\Windows\syswow64\Windowspowershell\v1.0 on x64 machines) in Windows Explorer and double-click powershell.exe you will see that it opens PowerShell with a black background. The PowerShell console shows up as blue when opened from the start menu because the console properties for shortcuts to powershell.exe can be set independently from the default properties.

To set the default options, font, colors and layout, open a PowerShell console, type Alt-Space, and select the Defaults menu option.

Running start powershell from cmd.exe should start a new console with your default settings.

How to print / echo environment variables?

On windows, you can print with this command in your CLI C:\Users\dir\env | more

You can view all environment variables set on your system with the env command. The list is long, so pipe the output through more to make it easier to read.

python xlrd unsupported format, or corrupt file.

Worked on the same issue , finally done this is top for the question so just putting what i did.

Observation - 1 -The file was not actually XLS i renamed to txt and noticed HTML text in file.

2 - Renamed the file to html and tried reading pd.read_html, Failed.

3- Added as it was not there in txt file, removed style to ensure that table is displaying in browser from local, and WORKED.

Below is the code may help someone..

import pandas as pd
import os
import shutil
import html5lib
import requests
from bs4 import BeautifulSoup
import re
import time

shutil.copy('your.xls','file.html')
shutil.copy('file.html','file.txt')
time.sleep(2)

txt = open('file.txt','r').read()

# Modify the text to ensure the data display in html page, delete style

txt = str(txt).replace('<style> .text { mso-number-format:\@; } </script>','')

# Add head and body if it is not there in HTML text

txt_with_head = '<html><head></head><body>'+txt+'</body></html>'

# Save the file as HTML

html_file = open('output.html','w')
html_file.write(txt_with_head)

# Use beautiful soup to read

url = r"C:\Users\hitesh kumar\PycharmProjects\OEM ML\output.html"
page = open(url)
soup = BeautifulSoup(page.read(), features="lxml")
my_table = soup.find("table",attrs={'border': '1'})

frame = pd.read_html(str(my_table))[0]
print(frame.head())
frame.to_excel('testoutput.xlsx',sheet_name='sheet1', index=False)

Can CSS force a line break after each word in an element?

You can't target each word in CSS. However, with a bit of jQuery you probably could.

With jQuery you can wrap each word in a <span> and then CSS set span to display:block which would put it on its own line.

In theory of course :P

Superscript in markdown (Github flavored)?

<sup> and <sub> tags work and are your only good solution for arbitrary text. Other solutions include:

Unicode

If the superscript (or subscript) you need is of a mathematical nature, Unicode may well have you covered.

I've compiled a list of all the Unicode super and subscript characters I could identify in this gist. Some of the more common/useful ones are:

  • ° SUPERSCRIPT ZERO (U+2070)
  • ¹ SUPERSCRIPT ONE (U+00B9)
  • ² SUPERSCRIPT TWO (U+00B2)
  • ³ SUPERSCRIPT THREE (U+00B3)
  • n SUPERSCRIPT LATIN SMALL LETTER N (U+207F)

People also often reach for <sup> and <sub> tags in an attempt to render specific symbols like these:

  • TRADE MARK SIGN (U+2122)
  • ® REGISTERED SIGN (U+00AE)
  • ? SERVICE MARK (U+2120)

Assuming your editor supports Unicode, you can copy and paste the characters above directly into your document.

Alternatively, you could use the hex values above in an HTML character escape. Eg, &#x00B2; instead of ². This works with GitHub (and should work anywhere else your Markdown is rendered to HTML) but is less readable when presented as raw text/Markdown.

Images

If your requirements are especially unusual, you can always just inline an image. The GitHub supported syntax is:

![Alt text goes here, if you'd like](path/to/image.png) 

You can use a full path (eg. starting with https:// or http://) but it's often easier to use a relative path, which will load the image from the repo, relative to the Markdown document.

If you happen to know LaTeX (or want to learn it) you could do just about any text manipulation imaginable and render it to an image. Sites like Quicklatex make this quite easy.

Disable LESS-CSS Overwriting calc()

Here's a cross-browser less mixin for using CSS's calc with any property:

.calc(@prop; @val) {
  @{prop}: calc(~'@{val}');
  @{prop}: -moz-calc(~'@{val}');
  @{prop}: -webkit-calc(~'@{val}');
  @{prop}: -o-calc(~'@{val}');
}

Example usage:

.calc(width; "100% - 200px");

And the CSS that's output:

width: calc(100% - 200px);
width: -moz-calc(100% - 200px);
width: -webkit-calc(100% - 200px);
width: -o-calc(100% - 200px);

A codepen of this example: http://codepen.io/patrickberkeley/pen/zobdp

When to use IList and when to use List

Microsoft guidelines as checked by FxCop discourage use of List<T> in public APIs - prefer IList<T>.

Incidentally, I now almost always declare one-dimensional arrays as IList<T>, which means I can consistently use the IList<T>.Count property rather than Array.Length. For example:

public interface IMyApi
{
    IList<int> GetReadOnlyValues();
}

public class MyApiImplementation : IMyApi
{
    public IList<int> GetReadOnlyValues()
    {
        List<int> myList = new List<int>();
        ... populate list
        return myList.AsReadOnly();
    }
}
public class MyMockApiImplementationForUnitTests : IMyApi
{
    public IList<int> GetReadOnlyValues()
    {
        IList<int> testValues = new int[] { 1, 2, 3 };
        return testValues;
    }
}

Bootstrap onClick button event

If, like me, you had dynamically created buttons on your page, the

$("#your-bs-button's-id").on("click", function(event) {
                       or
$(".your-bs-button's-class").on("click", function(event) {

methods won't work because they only work on current elements (not future elements). Instead you need to reference a parent item that existed at the initial loading of the web page.

$(document).on("click", "#your-bs-button's-id", function(event) {
                       or more generally
$("#pre-existing-element-id").on("click", ".your-bs-button's-class", function(event) {

There are many other references to this issue on stack overflow here and here.

PHP, getting variable from another php-file

using include 'page1.php' in second page is one option but it can generate warnings and errors of undefined variables.
Three methods by which you can use variables of one php file in another php file:

  • use session to pass variable from one page to another
    method:
    first you have to start the session in both the files using php command

    sesssion_start();
    then in first file consider you have one variable
    $x='var1';

    now assign value of $x to a session variable using this:
    $_SESSION['var']=$x;
    now getting value in any another php file:
    $y=$_SESSION['var'];//$y is any declared variable

  • using get method and getting variables on clicking a link
    method

    <a href="page2.php?variable1=value1&variable2=value2">clickme</a>
    getting values in page2.php file by $_GET function:
    $x=$_GET['variable1'];//value1 be stored in $x
    $y=$_GET['variable2'];//vale2 be stored in $y

  • if you want to pass variable value using button then u can use it by following method:

    $x='value1'
    <input type="submit" name='btn1' value='.$x.'/>
    in second php
    $var=$_POST['btn1'];

Stash only one file out of multiple files that have changed with Git?

Use git stash push, like this:

git stash push [--] [<pathspec>...]

For example:

git stash push -- my/file.sh

This is available since Git 2.13, released in spring 2017.

How can I get a specific parameter from location.search?

Grab the params from location.search with one line:

const params = new Map(this.props.location.search.slice(1).split('&').map(param => param.split('=')))

Then, simply:

if(params.get("year")){
  //year exists. do something...
} else {
  //year doesn't exist. do something else...
}

HTTP 401 - what's an appropriate WWW-Authenticate header value?

When indicating HTTP Basic Authentication we return something like:

WWW-Authenticate: Basic realm="myRealm"

Whereas Basic is the scheme and the remainder is very much dependent on that scheme. In this case realm just provides the browser a literal that can be displayed to the user when prompting for the user id and password.

You're obviously not using Basic however since there is no point having session expiry when Basic Auth is used. I assume you're using some form of Forms based authentication.

From recollection, Windows Challenge Response uses a different scheme and different arguments.

The trick is that it's up to the browser to determine what schemes it supports and how it responds to them.

My gut feel if you are using forms based authentication is to stay with the 200 + relogin page but add a custom header that the browser will ignore but your AJAX can identify.

For a really good User + AJAX experience, get the script to hang on to the AJAX request that found the session expired, fire off a relogin request via a popup, and on success, resubmit the original AJAX request and carry on as normal.

Avoid the cheat that just gets the script to hit the site every 5 mins to keep the session alive cause that just defeats the point of session expiry.

The other alternative is burn the AJAX request but that's a poor user experience.

Import / Export database with SQL Server Server Management Studio

I wanted to share with you my solution to export a database with Microsoft SQL Server Management Studio.

To Export your database

  1. Open a new request
  2. Copy paste this script
DECLARE @BackupFile NVARCHAR(255);
SET @BackupFile = 'c:\database-backup_2020.07.22.bak';
PRINT @BackupFile;
BACKUP DATABASE [%databaseName%] TO DISK = @BackupFile;

Don't forget to replace %databaseName% with the name of the database you want to export.

Note that this method gives a lighter file than from the menu.

To import this file from SQL Server Management Studio. Don't forget to delete your database beforehand.

  1. Click restore database

Click restore database

  1. Add the backup file Add the backup file

  2. Validate

Enjoy! :) :)

SCRIPT5: Access is denied in IE9 on xmlhttprequest

On IE7, IE8, and IE9 just go to Settings->Internet Options->Security->Custom Level and change security settings under "Miscellaneous" set "Access data sources across domains" to Enable.

Android: how to refresh ListView contents?

Another easy way:

//In your ListViewActivity:
public void refreshListView() {
    listAdapter = new ListAdapter(this);
    setListAdapter(listAdapter);
}

Align HTML input fields by :

in my case i always put these stuffs in a p tag like

<p> name : < input type=text /> </p>

and so on and then applying the css like

p {
  text-align:left;
}

p input {
  float:right;
}

You need to specify the width of the p tag.because the input tags will float all the way right.

This css will also affect the submit button. You need to override the rule for this tag.

SQL Server r2 installation error .. update Visual Studio 2008 to SP1

Finally, I solved it. Even though the solution is a bit lengthy, I think its the simplest. The solution is as follows:

  1. Install Visual Studio 2008
  2. Install the service Package 1 (SP1)
  3. Install SQL Server 2008 r2

Create two-dimensional arrays and access sub-arrays in Ruby

I'm quite sure this can be very simple

2.0.0p247 :032 > list = Array.new(5)

 => [nil, nil, nil, nil, nil] 

2.0.0p247 :033 > list.map!{ |x| x = [0] }

 => [[0], [0], [0], [0], [0]] 

2.0.0p247 :034 > list[0][0]

  => 0

Abstraction VS Information Hiding VS Encapsulation

Encapsulation: binding data and the methods that act on it. this allows the hiding of data from all other methods in other classes. example: MyList class that can add an item, remove an item, and remove all items the methods add, remove, and removeAll act on the list(a private array) that can not be accessed directly from the outside.

Abstraction: is hiding the non relevant behavior and data. How the items are actually stored, added, or deleted is hidden (abstracted). My data may be held in simple array, ArrayList, LinkedList, and so on. Also, how the methods are implemented is hidden from the outside.

Func vs. Action vs. Predicate

Action is a delegate (pointer) to a method, that takes zero, one or more input parameters, but does not return anything.

Func is a delegate (pointer) to a method, that takes zero, one or more input parameters, and returns a value (or reference).

Predicate is a special kind of Func often used for comparisons.

Though widely used with Linq, Action and Func are concepts logically independent of Linq. C++ already contained the basic concept in form of typed function pointers.

Here is a small example for Action and Func without using Linq:

class Program
{
    static void Main(string[] args)
    {
        Action<int> myAction = new Action<int>(DoSomething);
        myAction(123);           // Prints out "123"
                                 // can be also called as myAction.Invoke(123);

        Func<int, double> myFunc = new Func<int, double>(CalculateSomething);
        Console.WriteLine(myFunc(5));   // Prints out "2.5"
    }

    static void DoSomething(int i)
    {
        Console.WriteLine(i);
    }

    static double CalculateSomething(int i)
    {
        return (double)i/2;
    }
}

Producing a new line in XSLT

I have found a difference between literal newlines in <xsl:text> and literal newlines using &#xA;.

While literal newlines worked fine in my environment (using both Saxon and the default Java XSLT processor) my code failed when it was executed by another group running in a .NET environment.

Changing to entities (&#xA;) got my file generation code running consistently on both Java and .NET.

Also, literal newlines are vulnerable to being reformatted by IDEs and can inadvertently get lost when the file is maintained by someone 'not in the know'.

Passing data to a bootstrap modal

Here is a cleaner way to do it if you are using Bootstrap 3.2.0.

Link HTML

<a href="#my_modal" data-toggle="modal" data-book-id="my_id_value">Open Modal</a>

Modal JavaScript

//triggered when modal is about to be shown
$('#my_modal').on('show.bs.modal', function(e) {

    //get data-id attribute of the clicked element
    var bookId = $(e.relatedTarget).data('book-id');

    //populate the textbox
    $(e.currentTarget).find('input[name="bookId"]').val(bookId);
});

http://jsfiddle.net/k7FC2/

How to list AD group membership for AD users using input list?

The below code will return username group membership using the samaccountname. You can modify it to get input from a file or change the query to get accounts with non expiring passwords etc

$location = "c:\temp\Peace2.txt"
$users = (get-aduser -filter *).samaccountname
$le = $users.length
for($i = 0; $i -lt $le; $i++){
  $output = (get-aduser $users[$i] | Get-ADPrincipalGroupMembership).name
  $users[$i] + " " + $output 
  $z =  $users[$i] + " " + $output 
  add-content $location $z
}

Sample Output:

Administrator Domain Users Administrators Schema Admins Enterprise Admins Domain Admins Group Policy Creator Owners
Guest Domain Guests Guests
krbtgt Domain Users Denied RODC Password Replication Group
Redacted Domain Users CompanyUsers Production
Redacted Domain Users CompanyUsers Production
Redacted Domain Users CompanyUsers Production

Script to Change Row Color when a cell changes text

//Sets the row color depending on the value in the "Status" column.
function setRowColors() {
  var range = SpreadsheetApp.getActiveSheet().getDataRange();
  var statusColumnOffset = getStatusColumnOffset();

  for (var i = range.getRow(); i < range.getLastRow(); i++) {
    rowRange = range.offset(i, 0, 1);
    status = rowRange.offset(0, statusColumnOffset).getValue();
    if (status == 'Completed') {
      rowRange.setBackgroundColor("#99CC99");
    } else if (status == 'In Progress') {
      rowRange.setBackgroundColor("#FFDD88");    
    } else if (status == 'Not Started') {
      rowRange.setBackgroundColor("#CC6666");          
    }
  }
}

//Returns the offset value of the column titled "Status"
//(eg, if the 7th column is labeled "Status", this function returns 6)
function getStatusColumnOffset() {
  lastColumn = SpreadsheetApp.getActiveSheet().getLastColumn();
  var range = SpreadsheetApp.getActiveSheet().getRange(1,1,1,lastColumn);

  for (var i = 0; i < range.getLastColumn(); i++) {
    if (range.offset(0, i, 1, 1).getValue() == "Status") {
      return i;
    } 
  }
}

How do you explicitly set a new property on `window` in TypeScript?

After finding answers around, I think this page might be helpful. https://www.typescriptlang.org/docs/handbook/declaration-merging.html#global-augmentation Not sure about the history of declaration merging, but it explains why the following could work.

declare global {
    interface Window { MyNamespace: any; }
}

window.MyNamespace = window.MyNamespace || {};

Array of strings in groovy

Most of the time you would create a list in groovy rather than an array. You could do it like this:

names = ["lucas", "Fred", "Mary"]

Alternately, if you did not want to quote everything like you did in the ruby example, you could do this:

names = "lucas Fred Mary".split()

How can I create a temp file with a specific extension with .NET?

Try this function ...

public static string GetTempFilePathWithExtension(string extension) {
  var path = Path.GetTempPath();
  var fileName = Guid.NewGuid().ToString() + extension;
  return Path.Combine(path, fileName);
}

It will return a full path with the extension of your choice.

Note, it's not guaranteed to produce a unique file name since someone else could have technically already created that file. However the chances of someone guessing the next guid produced by your app and creating it is very very low. It's pretty safe to assume this will be unique.

How do I disable the resizable property of a textarea?

To disable resize for all textareas:

textarea {
    resize: none;
}

To disable resize for a specific textarea, add an attribute, name, or an id and set it to something. In this case, it is named noresize

HTML

<textarea name='noresize' id='noresize'> </textarea>

CSS

/* Using the attribute name */
textarea[name=noresize] {
    resize: none;
}
/* Or using the id */

#noresize {
    resize: none;
}

MySQL JOIN ON vs USING?

It is mostly syntactic sugar, but a couple differences are noteworthy:

ON is the more general of the two. One can join tables ON a column, a set of columns and even a condition. For example:

SELECT * FROM world.City JOIN world.Country ON (City.CountryCode = Country.Code) WHERE ...

USING is useful when both tables share a column of the exact same name on which they join. In this case, one may say:

SELECT ... FROM film JOIN film_actor USING (film_id) WHERE ...

An additional nice treat is that one does not need to fully qualify the joining columns:

SELECT film.title, film_id -- film_id is not prefixed
FROM film
JOIN film_actor USING (film_id)
WHERE ...

To illustrate, to do the above with ON, we would have to write:

SELECT film.title, film.film_id -- film.film_id is required here
FROM film
JOIN film_actor ON (film.film_id = film_actor.film_id)
WHERE ...

Notice the film.film_id qualification in the SELECT clause. It would be invalid to just say film_id since that would make for an ambiguity:

ERROR 1052 (23000): Column 'film_id' in field list is ambiguous

As for select *, the joining column appears in the result set twice with ON while it appears only once with USING:

mysql> create table t(i int);insert t select 1;create table t2 select*from t;
Query OK, 0 rows affected (0.11 sec)

Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

Query OK, 1 row affected (0.19 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> select*from t join t2 on t.i=t2.i;
+------+------+
| i    | i    |
+------+------+
|    1 |    1 |
+------+------+
1 row in set (0.00 sec)

mysql> select*from t join t2 using(i);
+------+
| i    |
+------+
|    1 |
+------+
1 row in set (0.00 sec)

mysql>

How to load a text file into a Hive table stored as sequence files

You cannot directly create a table stored as a sequence file and insert text into it. You must do this:

  1. Create a table stored as text
  2. Insert the text file into the text table
  3. Do a CTAS to create the table stored as a sequence file.
  4. Drop the text table if desired

Example:

CREATE TABLE test_txt(field1 int, field2 string)
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t';

LOAD DATA INPATH '/path/to/file.tsv' INTO TABLE test_txt;

CREATE TABLE test STORED AS SEQUENCEFILE
AS SELECT * FROM test_txt;

DROP TABLE test_txt;

How to compile and run C files from within Notepad++ using NppExec plugin?

For perl,

To run perl script use this procedure

Requirement: You need to setup classpath variable.

Go to plugins->NppExec->Execute

In command section, type this

cmd /c cd "$(CURRENT_DIRECTORY)"&&"$(FULL_CURRENT_PATH)"

Save it and give name to it.(I give Perl).

Press OK. If editor wants to restart, do it first.

Now press F6 and you will find your Perl script output on below side.

Note: Not required seperate config for seperate files.

For java,

Requirement: You need to setup JAVA_HOME and classpath variable.

Go to plugins->NppExec->Execute

In command section, type this

cmd /c cd "$(CURRENT_DIRECTORY)"&&"%JAVA_HOME%\bin\javac""$(FULL_CURRENT_PATH)"

your *.class will generate on location of current folder; despite of programming error.

For Python,

Use this Plugin Python Plugin

Go to plugins->NppExec-> Run file in Python intercative

By using this you can run scripts within Notepad++.

For PHP,

No need for different configuration just download this plugin.

PHP Plugin and done.

For C language,

Requirement: You need to setup classpath variable.
I am using MinGW compiler.

Go to plugins->NppExec->Execute

paste this into there

   NPP_SAVE

   CD $(CURRENT_DIRECTORY)

   C:\MinGW32\bin\gcc.exe -g "$(FILE_NAME)" 

   a

(Remember to give above four lines separate lines.)

Now, give name, save and ok.

Restart Npp.

Go to plugins->NppExec->Advanced options.

Menu Item->Item Name (I have C compiler)

Associated Script-> from combo box select the above name of script.

Click on Add/modify and Ok.

Now assign shortcut key as given in first answer.

Press F6 and select script or just press shortcut(I assigned Ctrl+2).

For C++,

Only change g++ instead of gcc and *.cpp instead on *.c

That's it!!

Does bootstrap have builtin padding and margin classes?

I would like to give an example which I tried by understanding above documentation and works correctly. If you wish to apply 25% padding on left and right sides medium screen size then please use px-md-1. It works as desired and can similarly follow for other screen sizes. :)

How to split a data frame?

You could also use

data2 <- data[data$sum_points == 2500, ]

This will make a dataframe with the values where sum_points = 2500

It gives :

airfoils sum_points field_points   init_t contour_t   field_t
...
491        5       2500         5625 0.000086  0.004272  6.321774
498        5       2500         5625 0.000087  0.004507  6.325083
504        5       2500         5625 0.000088  0.004370  6.336034
603        5        250        10000 0.000072  0.000525  1.111278
577        5        250        10000 0.000104  0.000559  1.111431
587        5        250        10000 0.000072  0.000528  1.111524
606        5        250        10000 0.000079  0.000538  1.111685
....
> data2 <- data[data$sum_points == 2500, ]
> data2
airfoils sum_points field_points   init_t contour_t   field_t
108        5       2500          625 0.000082  0.004329  0.733109
106        5       2500          625 0.000102  0.004564  0.733243
117        5       2500          625 0.000087  0.004321  0.733274
112        5       2500          625 0.000081  0.004428  0.733587

How can I calculate the time between 2 Dates in typescript

This is how it should be done in typescript:

(new Date()).valueOf() - (new Date("2013-02-20T12:01:04.753Z")).valueOf()

Better readability:

      var eventStartTime = new Date(event.startTime);
      var eventEndTime = new Date(event.endTime);
      var duration = eventEndTime.valueOf() - eventStartTime.valueOf();

Obtaining ExitCode using Start-Process and WaitForExit instead of -Wait

There are two things to remember here. One is to add the -PassThru argument and two is to add the -Wait argument. You need to add the wait argument because of this defect: http://connect.microsoft.com/PowerShell/feedback/details/520554/start-process-does-not-return-exitcode-property

-PassThru [<SwitchParameter>]
    Returns a process object for each process that the cmdlet started. By d
    efault, this cmdlet does not generate any output.

Once you do this a process object is passed back and you can look at the ExitCode property of that object. Here is an example:

$process = start-process ping.exe -windowstyle Hidden -ArgumentList "-n 1 -w 127.0.0.1" -PassThru -Wait
$process.ExitCode

# This will print 1

If you run it without -PassThru or -Wait, it will print out nothing.

The same answer is here: How do I run a Windows installer and get a succeed/fail value in PowerShell?

Shell equality operators (=, ==, -eq)

== is a bash-specific alias for = and it performs a string (lexical) comparison instead of a numeric comparison. eq being a numeric comparison of course.

Finally, I usually prefer to use the form if [ "$a" == "$b" ]

Formula to determine brightness of RGB color

I was solving a similar task today in javascript. I've settled on this getPerceivedLightness(rgb) function for a HEX RGB color. It deals with Helmholtz-Kohlrausch effect via Fairchild and Perrotta formula for luminance correction.

/**
 * Converts RGB color to CIE 1931 XYZ color space.
 * https://www.image-engineering.de/library/technotes/958-how-to-convert-between-srgb-and-ciexyz
 * @param  {string} hex
 * @return {number[]}
 */
export function rgbToXyz(hex) {
    const [r, g, b] = hexToRgb(hex).map(_ => _ / 255).map(sRGBtoLinearRGB)
    const X =  0.4124 * r + 0.3576 * g + 0.1805 * b
    const Y =  0.2126 * r + 0.7152 * g + 0.0722 * b
    const Z =  0.0193 * r + 0.1192 * g + 0.9505 * b
    // For some reason, X, Y and Z are multiplied by 100.
    return [X, Y, Z].map(_ => _ * 100)
}

/**
 * Undoes gamma-correction from an RGB-encoded color.
 * https://en.wikipedia.org/wiki/SRGB#Specification_of_the_transformation
 * https://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color
 * @param  {number}
 * @return {number}
 */
function sRGBtoLinearRGB(color) {
    // Send this function a decimal sRGB gamma encoded color value
    // between 0.0 and 1.0, and it returns a linearized value.
    if (color <= 0.04045) {
        return color / 12.92
    } else {
        return Math.pow((color + 0.055) / 1.055, 2.4)
    }
}

/**
 * Converts hex color to RGB.
 * https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
 * @param  {string} hex
 * @return {number[]} [rgb]
 */
function hexToRgb(hex) {
    const match = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
    if (match) {
        match.shift()
        return match.map(_ => parseInt(_, 16))
    }
}

/**
 * Converts CIE 1931 XYZ colors to CIE L*a*b*.
 * The conversion formula comes from <http://www.easyrgb.com/en/math.php>.
 * https://github.com/cangoektas/xyz-to-lab/blob/master/src/index.js
 * @param   {number[]} color The CIE 1931 XYZ color to convert which refers to
 *                           the D65/2° standard illuminant.
 * @returns {number[]}       The color in the CIE L*a*b* color space.
 */
// X, Y, Z of a "D65" light source.
// "D65" is a standard 6500K Daylight light source.
// https://en.wikipedia.org/wiki/Illuminant_D65
const D65 = [95.047, 100, 108.883]
export function xyzToLab([x, y, z]) {
  [x, y, z] = [x, y, z].map((v, i) => {
    v = v / D65[i]
    return v > 0.008856 ? Math.pow(v, 1 / 3) : v * 7.787 + 16 / 116
  })
  const l = 116 * y - 16
  const a = 500 * (x - y)
  const b = 200 * (y - z)
  return [l, a, b]
}

/**
 * Converts Lab color space to Luminance-Chroma-Hue color space.
 * http://www.brucelindbloom.com/index.html?Eqn_Lab_to_LCH.html
 * @param  {number[]}
 * @return {number[]}
 */
export function labToLch([l, a, b]) {
    const c = Math.sqrt(a * a + b * b)
    const h = abToHue(a, b)
    return [l, c, h]
}

/**
 * Converts a and b of Lab color space to Hue of LCH color space.
 * https://stackoverflow.com/questions/53733379/conversion-of-cielab-to-cielchab-not-yielding-correct-result
 * @param  {number} a
 * @param  {number} b
 * @return {number}
 */
function abToHue(a, b) {
    if (a >= 0 && b === 0) {
        return 0
    }
    if (a < 0 && b === 0) {
        return 180
    }
    if (a === 0 && b > 0) {
        return 90
    }
    if (a === 0 && b < 0) {
        return 270
    }
    let xBias
    if (a > 0 && b > 0) {
        xBias = 0
    } else if (a < 0) {
        xBias = 180
    } else if (a > 0 && b < 0) {
        xBias = 360
    }
    return radiansToDegrees(Math.atan(b / a)) + xBias
}

function radiansToDegrees(radians) {
    return radians * (180 / Math.PI)
}

function degreesToRadians(degrees) {
    return degrees * Math.PI / 180
}

/**
 * Saturated colors appear brighter to human eye.
 * That's called Helmholtz-Kohlrausch effect.
 * Fairchild and Pirrotta came up with a formula to
 * calculate a correction for that effect.
 * "Color Quality of Semiconductor and Conventional Light Sources":
 * https://books.google.ru/books?id=ptDJDQAAQBAJ&pg=PA45&lpg=PA45&dq=fairchild+pirrotta+correction&source=bl&ots=7gXR2MGJs7&sig=ACfU3U3uIHo0ZUdZB_Cz9F9NldKzBix0oQ&hl=ru&sa=X&ved=2ahUKEwi47LGivOvmAhUHEpoKHU_ICkIQ6AEwAXoECAkQAQ#v=onepage&q=fairchild%20pirrotta%20correction&f=false
 * @return {number}
 */
function getLightnessUsingFairchildPirrottaCorrection([l, c, h]) {
    const l_ = 2.5 - 0.025 * l
    const g = 0.116 * Math.abs(Math.sin(degreesToRadians((h - 90) / 2))) + 0.085
    return l + l_ * g * c
}

export function getPerceivedLightness(hex) {
    return getLightnessUsingFairchildPirrottaCorrection(labToLch(xyzToLab(rgbToXyz(hex))))
}

JavaScript + Unicode regexes

As mentioned in other answers, JavaScript regexes have no support for Unicode character classes. However, there is a library that does provide this: Steven Levithan's excellent XRegExp and its Unicode plug-in.

Removing whitespace between HTML elements when using line breaks

Sorry if this is old but I just found a solution.

Try setting the font-size to 0. Thus the white-spaces in between the images will be 0 in width, and the images won't be affected.

Don't know if this works in all browsers, but I tried it with Chromium and some <li> elements with display: inline-block;.

Error: Cannot Start Container: stat /bin/sh: no such file or directory"

I had a similar problem:

docker: Error response from daemon: OCI runtime create failed: container_linux.go:346: starting container process caused "exec: \"sh\": executable file not found in $PATH": unknown.

In my case, I know the image works in other places, then was a corrupted local image. I solved the issue removing the image (docker rmi <imagename>) and pulling it again(docker pull <imagename>).

I did a docker system prune too, but I think it's not mandatory.

How to use onClick event on react Link component?

You are passing hello() as a string, also hello() means execute hello immediately.

try

onClick={hello}

How to get min, seconds and milliseconds from datetime.now() in python?

if you want your datetime.now() precise till the minute , you can use

datetime.strptime(datetime.now().strftime('%Y-%m-%d %H:%M'), '%Y-%m-%d %H:%M')

similarly for hour it will be

datetime.strptime(datetime.now().strftime('%Y-%m-%d %H'), '%Y-%m-%d %H')

It is kind of a hack, if someone has a better solution, I am all ears

IntelliJ: Never use wildcard imports

This applies for "Intellij Idea- 2020.1.2" on window

Navigate to "IntelliJ IDEA->File->Settings->Editor->Code Style->java".

enter image description here

Reading a text file using OpenFileDialog in windows forms

Here's one way:

Stream myStream = null;
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = @"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
    try
    {
        if ((myStream = theDialog.OpenFile()) != null)
        {
            using (myStream)
            {
                // Insert code to read the stream here.
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
    }
}

Modified from here:MSDN OpenFileDialog.OpenFile

EDIT Here's another way more suited to your needs:

private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
    OpenFileDialog theDialog = new OpenFileDialog();
    theDialog.Title = "Open Text File";
    theDialog.Filter = "TXT files|*.txt";
    theDialog.InitialDirectory = @"C:\";
    if (theDialog.ShowDialog() == DialogResult.OK)
    {
        string filename = theDialog.FileName;

        string[] filelines = File.ReadAllLines(filename);

        List<Employee> employeeList = new List<Employee>();
        int linesPerEmployee = 4;
        int currEmployeeLine = 0;
        //parse line by line into instance of employee class
        Employee employee = new Employee();
        for (int a = 0; a < filelines.Length; a++)
        {

            //check if to move to next employee
            if (a != 0 && a % linesPerEmployee == 0)
            {
                employeeList.Add(employee);
                employee = new Employee();
                currEmployeeLine = 1;
            }

            else
            {
                currEmployeeLine++;
            }
            switch (currEmployeeLine)
            {
                case 1:
                    employee.EmployeeNum = Convert.ToInt32(filelines[a].Trim());
                    break;
                case 2:
                    employee.Name = filelines[a].Trim();
                    break;
                case 3:
                    employee.Address = filelines[a].Trim();
                    break;
                case 4:
                    string[] splitLines = filelines[a].Split(' ');

                    employee.Wage = Convert.ToDouble(splitLines[0].Trim());
                    employee.Hours = Convert.ToDouble(splitLines[1].Trim());
                    break;


            }

        }
        //Test to see if it works
        foreach (Employee emp in employeeList)
        {
            MessageBox.Show(emp.EmployeeNum + Environment.NewLine +
                emp.Name + Environment.NewLine +
                emp.Address + Environment.NewLine +
                emp.Wage + Environment.NewLine +
                emp.Hours + Environment.NewLine);
        }
    }
}

HTML5 Canvas 100% Width Height of Viewport?

You can try viewport units (CSS3):

canvas { 
  height: 100vh; 
  width: 100vw; 
  display: block;
}

In Python How can I declare a Dynamic Array

Here's a great method I recently found on a different stack overflow post regarding multi-dimensional arrays, but the answer works beautifully for single dimensional arrays as well:

# Create an 8 x 5 matrix of 0's:
w, h = 8, 5;
MyMatrix = [ [0 for x in range( w )] for y in range( h ) ]  

# Create an array of objects:
MyList = [ {} for x in range( n ) ]

I love this because you can specify the contents and size dynamically, in one line!

One more for the road:

# Dynamic content initialization:
MyFunkyArray = [ x * a + b for x in range ( n ) ]

How can I change the Java Runtime Version on Windows (7)?

Update your environment variables

Ensure the reference to java/bin is up to date in 'Path'; This may be automatic if you have JAVA_HOME or equivalent set. If JAVA_HOME is set, simply update it to refer to the older JRE installation.

ORACLE IIF Statement

Oracle doesn't provide such IIF Function. Instead, try using one of the following alternatives:

DECODE Function:

SELECT DECODE(EMP_ID, 1, 'True', 'False') from Employee

CASE Function:

SELECT CASE WHEN EMP_ID = 1 THEN 'True' ELSE 'False' END from Employee

How to create an alert message in jsp page after submit process is complete

in your servlet

 request.setAttribute("submitDone","done");
 return mapping.findForward("success");

In your jsp

<c:if test="${not empty submitDone}">
  <script>alert("Form submitted");
</script></c:if>

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

It's possible that you're creating your controls on the wrong thread. Consider the following documentation from MSDN:

This means that InvokeRequired can return false if Invoke is not required (the call occurs on the same thread), or if the control was created on a different thread but the control's handle has not yet been created.

In the case where the control's handle has not yet been created, you should not simply call properties, methods, or events on the control. This might cause the control's handle to be created on the background thread, isolating the control on a thread without a message pump and making the application unstable.

You can protect against this case by also checking the value of IsHandleCreated when InvokeRequired returns false on a background thread. If the control handle has not yet been created, you must wait until it has been created before calling Invoke or BeginInvoke. Typically, this happens only if a background thread is created in the constructor of the primary form for the application (as in Application.Run(new MainForm()), before the form has been shown or Application.Run has been called.

Let's see what this means for you. (This would be easier to reason about if we saw your implementation of SafeInvoke also)

Assuming your implementation is identical to the referenced one with the exception of the check against IsHandleCreated, let's follow the logic:

public static void SafeInvoke(this Control uiElement, Action updater, bool forceSynchronous)
{
    if (uiElement == null)
    {
        throw new ArgumentNullException("uiElement");
    }

    if (uiElement.InvokeRequired)
    {
        if (forceSynchronous)
        {
            uiElement.Invoke((Action)delegate { SafeInvoke(uiElement, updater, forceSynchronous); });
        }
        else
        {
            uiElement.BeginInvoke((Action)delegate { SafeInvoke(uiElement, updater, forceSynchronous); });
        }
    }
    else
    {    
        if (uiElement.IsDisposed)
        {
            throw new ObjectDisposedException("Control is already disposed.");
        }

        updater();
    }
}

Consider the case where we're calling SafeInvoke from the non-gui thread for a control whose handle has not been created.

uiElement is not null, so we check uiElement.InvokeRequired. Per the MSDN docs (bolded) InvokeRequired will return false because, even though it was created on a different thread, the handle hasn't been created! This sends us to the else condition where we check IsDisposed or immediately proceed to call the submitted action... from the background thread!

At this point, all bets are off re: that control because its handle has been created on a thread that doesn't have a message pump for it, as mentioned in the second paragraph. Perhaps this is the case you're encountering?

ASP.Net MVC Redirect To A Different View

The simplest way is use return View.

return View("ViewName");

Remember, the physical name of the "ViewName" should be something like ViewName.cshtml in your project, if your are using MVC C# / .NET.

How to shutdown my Jenkins safely?

You can also look in the init script area (e.g. centos vi /etc/init.d/jenkins ) for details on how the service is actually started and stopped.

ASP.NET Core configuration for .NET Core console application

You can use LiteWare.Configuration library for that. It is very similar to .NET Framework original ConfigurationManager and works for .NET Core/Standard. Code-wise, you'll end up with something like:

string cacheDirectory = ConfigurationManager.AppSettings.GetValue<string>("CacheDirectory");
ulong cacheFileSize = ConfigurationManager.AppSettings.GetValue<ulong>("CacheFileSize");

Disclaimer: I am the author of LiteWare.Configuration.

104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?

I've had this problem. See The Python "Connection Reset By Peer" Problem.

You have (most likely) run afoul of small timing issues based on the Python Global Interpreter Lock.

You can (sometimes) correct this with a time.sleep(0.01) placed strategically.

"Where?" you ask. Beats me. The idea is to provide some better thread concurrency in and around the client requests. Try putting it just before you make the request so that the GIL is reset and the Python interpreter can clear out any pending threads.

Embed Youtube video inside an Android app

Embedding the YouTube player in Android is very simple & it hardly takes you 10 minutes,

1) Enable YouTube API from Google API console
2) Download YouTube player Jar file
3) Start using it in Your app

Here are the detailed steps http://www.feelzdroid.com/2017/01/embed-youtube-video-player-android-app-example.html.

Just refer it & if you face any problem, let me know, ill help you

Search text in fields in every table of a MySQL database

You could do an SQLDump of the database (and its data) then search that file.

Check if a path represents a file or a folder

public static boolean isDirectory(String path) {
    return path !=null && new File(path).isDirectory();
}

To answer the question directly.

Check whether a path is valid

You could try using Path.IsPathRooted() in combination with Path.GetInvalidFileNameChars() to make sure the path is half-way okay.

Python reshape list to ndim array

You can specify the interpretation order of the axes using the order parameter:

np.reshape(arr, (2, -1), order='F')

How can I set a DateTimePicker control to a specific date?

You can set the "value" property

dateTimePicker1.Value = DateTime.Today;

Simplest way to read json from a URL in java

Here are couple of alternatives versions with Jackson (since there are more than one ways you might want data as):

  ObjectMapper mapper = new ObjectMapper(); // just need one
  // Got a Java class that data maps to nicely? If so:
  FacebookGraph graph = mapper.readValue(url, FaceBookGraph.class);
  // Or: if no class (and don't need one), just map to Map.class:
  Map<String,Object> map = mapper.readValue(url, Map.class);

And specifically the usual (IMO) case where you want to deal with Java objects, can be made one liner:

FacebookGraph graph = new ObjectMapper().readValue(url, FaceBookGraph.class);

Other libs like Gson also support one-line methods; why many examples show much longer sections is odd. And even worse is that many examples use obsolete org.json library; it may have been the first thing around, but there are half a dozen better alternatives so there is very little reason to use it.

Why can't I call a public method in another class?

It sounds like you're not instantiating your class. That's the primary reason I get the "an object reference is required" error.

MyClass myClass = new MyClass();

once you've added that line you can then call your method

myClass.myMethod();

Also, are all of your classes in the same namespace? When I was first learning c# this was a common tripping point for me.

How to use onClick with divs in React.js

Whilst this can be done with react, be aware that using onClicks with divs (instead of Buttons or Anchors, and others which already have behaviours for click events) is bad practice and should be avoided whenever it can be.

Python circular importing?

I was able to import the module within the function (only) that would require the objects from this module:

def my_func():
    import Foo
    foo_instance = Foo()

"npm config set registry https://registry.npmjs.org/" is not working in windows bat file

  1. Set npm registry globally

    use the below command to modify the .npmrc config file for the logged in user

    npm config set registry <registry url>

    Example: npm config set registry https://registry.npmjs.org/


  1. Set npm registry Scope

    Scopes allow grouping of related packages together. Scoped packages will be installed in a sub-folder under node_modules folder.

    Example: node_modules/@my-org/packagaename

    To set the scope registry use: npm config set @my-org:registry http://example.reg-org.com

    To install packages using scope use: npm install @my-org/mypackage

    whenever you install any packages from scope @my-org npm will search in the registry setting linked to scope @my-org for the registry url.


  1. Set npm registry locally for a project

    To modify the npm registry only for the current project. create a file inside the root folder of the project as .npmrc

    Add the below contents in the file

   registry = 'https://registry.npmjs.org/'