Programs & Examples On #Windows virtual pc

How to prevent a click on a '#' link from jumping to top of page?

So this is old but... just in case someone finds this in a search.

Just use "#/" instead of "#" and the page won't jump.

What's the syntax for mod in java

if (a % 2 == 0) {
} else {
}

How to convert hex to rgb using Java?

Convert it to an integer, then divmod it twice by 16, 256, 4096, or 65536 depending on the length of the original hex string (3, 6, 9, or 12 respectively).

Redirect output of mongo query to a csv file

Have a look at this

for outputing from mongo shell to file. There is no support for outputing csv from mongos shell. You would have to write the javascript yourself or use one of the many converters available. Google "convert json to csv" for example.

Java: print contents of text file to screen

Every example here shows a solution using the FileReader. It is convenient if you do not need to care about a file encoding. If you use some other languages than english, encoding is quite important. Imagine you have file with this text

Príliš žlutoucký kun
úpel dábelské ódy

and the file uses windows-1250 format. If you use FileReader you will get this result:

P??li? ?lu?ou?k? k??
?p?l ??belsk? ?dy

So in this case you would need to specify encoding as Cp1250 (Windows Eastern European) but the FileReader doesn't allow you to do so. In this case you should use InputStreamReader on a FileInputStream.

Example:

String encoding = "Cp1250";
File file = new File("foo.txt");

if (file.exists()) {
    try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding))) {
        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
else {
    System.out.println("file doesn't exist");
}

In case you want to read the file character after character do not use BufferedReader.

try (InputStreamReader isr = new InputStreamReader(new FileInputStream(file), encoding)) {
    int data = isr.read();
    while (data != -1) {
        System.out.print((char) data);
        data = isr.read();
    }
} catch (IOException e) {
    e.printStackTrace();
}

How to get number of rows using SqlDataReader in C#

There are only two options:

  • Find out by reading all rows (and then you might as well store them)

  • run a specialized SELECT COUNT(*) query beforehand.

Going twice through the DataReader loop is really expensive, you would have to re-execute the query.

And (thanks to Pete OHanlon) the second option is only concurrency-safe when you use a transaction with a Snapshot isolation level.

Since you want to end up storing all rows in memory anyway the only sensible option is to read all rows in a flexible storage (List<> or DataTable) and then copy the data to any format you want. The in-memory operation will always be much more efficient.

Is it better to use std::memcpy() or std::copy() in terms to performance?

My rule is simple. If you are using C++ prefer C++ libraries and not C :)

scipy.misc module has no attribute imread?

Imread uses PIL library, if the library is installed use : "from scipy.ndimage import imread"

Source: http://docs.scipy.org/doc/scipy-0.17.0/reference/generated/scipy.ndimage.imread.html

Format specifier %02x

%x is a format specifier that format and output the hex value. If you are providing int or long value, it will convert it to hex value.

%02x means if your provided value is less than two digits then 0 will be prepended.

You provided value 16843009 and it has been converted to 1010101 which a hex value.

TypeError: window.initMap is not a function

I had a similar error. The answers here helped me figure out what to do.

index.html

 <!--The div element for the map -->
 <div id="map"></div>

<!--The link to external javascript file that has initMap() function-->
 <script src="main.js">

<!--Google api, this calls initMap() function-->
 <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEYWY&callback=initMap">
</script>

main.js // This gives error


// The initMap function has not been executed
const initMap = () => {
const mapDisplayElement = document.getElementById('map');
  // The address is Uluru
const address = {lat: -25.344, lng: 131.036};
  // The zoom property specifies the zoom level for the map. Zoom: 0 is the lowest zoom,and displays the entire earth.
const map = new google.maps.Map(mapDisplayElement, { zoom: 4, center: address });
const marker = new google.maps.Marker({ position: address, map });
};

The answers here helped me figure out a solution. I used an immediately invoked the function (IIFE ) to work around it.

The error is as at the time of calling the google maps api the initMap() function has not executed.

main.js // This works

const mapDisplayElement = document.getElementById('map');
// The address is Uluru
// Run the initMap() function imidiately, 
(initMap = () => {
  const address = {lat: -25.344, lng: 131.036};
  // The zoom property specifies the zoom level for the map. Zoom: 0 is the lowest zoom,and displays the entire earth.
  const map = new google.maps.Map(mapDisplayElement, { zoom: 4, center: address });
  const marker = new google.maps.Marker({ position: address, map });
})();

Cast from VARCHAR to INT - MySQL

For casting varchar fields/values to number format can be little hack used:

SELECT (`PROD_CODE` * 1) AS `PROD_CODE` FROM PRODUCT`

Difference between jQuery parent(), parents() and closest() functions

from http://api.jquery.com/closest/

The .parents() and .closest() methods are similar in that they both traverse up the DOM tree. The differences between the two, though subtle, are significant:

.closest()

  • Begins with the current element
  • Travels up the DOM tree until it finds a match for the supplied selector
  • The returned jQuery object contains zero or one element

.parents()

  • Begins with the parent element
  • Travels up the DOM tree to the document's root element, adding each ancestor element to a temporary collection; it then filters that collection based on a selector if one is supplied
  • The returned jQuery object contains zero, one, or multiple elements

.parent()

  • Given a jQuery object that represents a set of DOM elements, the .parent() method allows us to search through the parents of these elements in the DOM tree and construct a new jQuery object from the matching elements.

Note: The .parents() and .parent() methods are similar, except that the latter only travels a single level up the DOM tree. Also, $("html").parent() method returns a set containing document whereas $("html").parents() returns an empty set.

Here are related threads:

I ran into a merge conflict. How can I abort the merge?

If you end up with merge conflict and doesn't have anything to commit, but still a merge error is being displayed. After applying all the below mentioned commands,

git reset --hard HEAD
git pull --strategy=theirs remote_branch
git fetch origin
git reset --hard origin

Please remove

.git\index.lock

File [cut paste to some other location in case of recovery] and then enter any of below command depending on which version you want.

git reset --hard HEAD
git reset --hard origin

Hope that helps!!!

Apple Mach-O Linker Error when compiling for device

I got the same issue when i export FMDB module in xcode 4.6. Later i found a fmdb.m in my my file list which was causing this issue. After i removed from the project it works fine

How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption

Errors: "Bad encrypt / decrypt" "gitencrypt_smudge: FAILURE: openssl error decrypting file"

There are various error strings that are thrown from openssl, depending on respective versions, and scenarios. Below is the checklist I use in case of openssl related issues:

  1. Ideally, openssl is able to encrypt/decrypt using same key (+ salt) & enc algo only.
  2. Ensure that openssl versions (used to encrypt/decrypt), are compatible. For eg. the hash used in openssl changed at version 1.1.0 from MD5 to SHA256. This produces a different key from the same password. Fix: add "-md md5" in 1.1.0 to decrypt data from lower versions, and add "-md sha256 in lower versions to decrypt data from 1.1.0

  3. Ensure that there is a single openssl version installed in your machine. In case there are multiple versions installed simultaneously (in my machine, these were installed :- 'LibreSSL 2.6.5' and 'openssl 1.1.1d'), make the sure that only the desired one appears in your PATH variable.

Secure FTP using Windows batch script

First, make sure you understand, if you need to use Secure FTP (=FTPS, as per your text) or SFTP (as per tag you have used).

Neither is supported by Windows command-line ftp.exe. As you have suggested, you can use WinSCP. It supports both FTPS and SFTP.

Using WinSCP, your batch file would look like (for SFTP):

echo open sftp://ftp_user:[email protected] -hostkey="server's hostkey" >> ftpcmd.dat
echo put c:\directory\%1-export-%date%.csv >> ftpcmd.dat
echo exit >> ftpcmd.dat
winscp.com /script=ftpcmd.dat
del ftpcmd.dat

And the batch file:

winscp.com /log=ftpcmd.log /script=ftpcmd.dat /parameter %1 %date%

Though using all capabilities of WinSCP (particularly providing commands directly on command-line and the %TIMESTAMP% syntax), the batch file simplifies to:

winscp.com /log=ftpcmd.log /command ^
    "open sftp://ftp_user:[email protected] -hostkey=""server's hostkey""" ^
    "put c:\directory\%1-export-%%TIMESTAMP#yyyymmdd%%.csv" ^
    "exit"

For the purpose of -hostkey switch, see verifying the host key in script.

Easier than assembling the script/batch file manually is to setup and test the connection settings in WinSCP GUI and then have it generate the script or batch file for you:

Generate batch file

All you need to tweak is the source file name (use the %TIMESTAMP% syntax as shown previously) and the path to the log file.


For FTPS, replace the sftp:// in the open command with ftpes:// (explicit TLS/SSL) or ftps:// (implicit TLS/SSL). Remove the -hostkey switch.

winscp.com /log=ftpcmd.log /command ^
    "open ftps://ftp_user:[email protected] -explicit" ^
    "put c:\directory\%1-export-%%TIMESTAMP#yyyymmdd%%.csv" ^
    "exit"

You may need to add the -certificate switch, if your server's certificate is not issued by a trusted authority.

Again, as with the SFTP, easier is to setup and test the connection settings in WinSCP GUI and then have it generate the script or batch file for you.


See a complete conversion guide from ftp.exe to WinSCP.

You should also read the Guide to automating file transfers to FTP server or SFTP server.


Note to using %TIMESTAMP#yyyymmdd% instead of %date%: A format of %date% variable value is locale-specific. So make sure you test the script on the same locale you are actually going to use the script on. For example on my Czech locale the %date% resolves to ct 06. 11. 2014, what might be problematic when used as a part of a file name.

For this reason WinSCP supports (locale-neutral) timestamp formatting natively. For example %TIMESTAMP#yyyymmdd% resolves to 20170515 on any locale.

(I'm the author of WinSCP)

Edittext change border color with shape.xml

i use as following for over come this matter

edittext_style.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:thickness="0dp"
android:shape="rectangle">
<stroke android:width="1dp"
        android:color="#c8c8c8"/>
<corners android:radius="0dp" />

And applied as bellow

<EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:ems="10"
            android:id="@+id/editTextName"
            android:background="@drawable/edit_text_style"/>

try like this..

How to disable text selection using jQuery?

In jQuery 1.8, this can be done as follows:

(function($){
    $.fn.disableSelection = function() {
        return this
                 .attr('unselectable', 'on')
                 .css('user-select', 'none')
                 .on('selectstart', false);
    };
})(jQuery);

Username and password in command for git push

Git will not store the password when you use URLs like that. Instead, it will just store the username, so it only needs to prompt you for the password the next time. As explained in the manual, to store the password, you should use an external credential helper. For Windows, you can use the Windows Credential Store for Git. This helper is also included by default in GitHub for Windows.

When using it, your password will automatically be remembered, so you only need to enter it once. So when you clone, you will be asked for your password, and then every further communication with the remote will not prompt you for your password again. Instead, the credential helper will provide Git with the authentication.

This of course only works for authentication via https; for ssh access ([email protected]/repository.git) you use SSH keys and those you can remember using ssh-agent (or PuTTY’s pageant if you’re using plink).

How to append a date in batch files

@SETLOCAL ENABLEDELAYEDEXPANSION

@REM Use WMIC to retrieve date and time
@echo off
FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
    IF NOT "%%~F"=="" (
        SET /A SortDate = 10000 * %%F + 100 * %%D + %%A
        set YEAR=!SortDate:~0,4!
        set MON=!SortDate:~4,2!
        set DAY=!SortDate:~6,2!
        @REM Add 1000000 so as to force a prepended 0 if hours less than 10
        SET /A SortTime = 1000000 + 10000 * %%B + 100 * %%C + %%E
        set HOUR=!SortTime:~1,2!
        set MIN=!SortTime:~3,2!
        set SEC=!SortTime:~5,2!
    )
)
@echo on
@echo DATE=%DATE%, TIME=%TIME%
@echo HOUR=!HOUR! MIN=!MIN! SEC=!SEC!
@echo YR=!YEAR! MON=!MON! DAY=!DAY! 
@echo DATECODE= '!YEAR!!MON!!DAY!!HOUR!!MIN!' 

Output:

DATE=2015-05-20, TIME= 1:30:38.59
HOUR=01 MIN=30 SEC=38
YR=2015 MON=05 DAY=20
DATECODE= '201505200130'

Match multiline text using regular expression

First, you're using the modifiers under an incorrect assumption.

Pattern.MULTILINE or (?m) tells Java to accept the anchors ^ and $ to match at the start and end of each line (otherwise they only match at the start/end of the entire string).

Pattern.DOTALL or (?s) tells Java to allow the dot to match newline characters, too.

Second, in your case, the regex fails because you're using the matches() method which expects the regex to match the entire string - which of course doesn't work since there are some characters left after (\\W)*(\\S)* have matched.

So if you're simply looking for a string that starts with User Comments:, use the regex

^\s*User Comments:\s*(.*)

with the Pattern.DOTALL option:

Pattern regex = Pattern.compile("^\\s*User Comments:\\s+(.*)", Pattern.DOTALL);
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
    ResultString = regexMatcher.group(1);
} 

ResultString will then contain the text after User Comments:

Access parent URL from iframe

You're correct. Subdomains are still considered separate domains when using iframes. It's possible to pass messages using postMessage(...), but other JS APIs are intentionally made inaccessible.

It's also still possible to get the URL depending on the context. See other answers for more details.

calling another method from the main method in java

Check out for the static before the main method, this declares the method as a class method, which means it needs no instance to be called. So as you are going to call a non static method, Java complains because you are trying to call a so called "instance method", which, of course needs an instance first ;)

If you want a better understanding about classes and instances, create a new class with instance and class methods, create a object in your main loop and call the methods!

 class Foo{

    public static void main(String[] args){
       Bar myInstance = new Bar();
       myInstance.do(); // works!
       Bar.do(); // doesn't work!

       Bar.doSomethingStatic(); // works!
    }
 }

class Bar{

   public do() {
   // do something
   }

   public static doSomethingStatic(){
   }
}

Also remember, classes in Java should start with an uppercase letter.

C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H

I think your problem is that you assume that the bytes that represent the utf8 string will result in the same string when interpreted as something else (iso-8859-1). And that is simply just not the case. I recommend that you read this excellent article by Joel spolsky.

Read int values from a text file in C

A simple solution using fscanf:

void read_ints (const char* file_name)
{
  FILE* file = fopen (file_name, "r");
  int i = 0;

  fscanf (file, "%d", &i);    
  while (!feof (file))
    {  
      printf ("%d ", i);
      fscanf (file, "%d", &i);      
    }
  fclose (file);        
}

How to determine the Boost version on a system?

If one installed boost on macOS via Homebrew, one is likely to see the installed boost version(s) with:

ls /usr/local/Cellar/boost*

Trim Cells using VBA in Excel

This works well for me. It uses an array so you aren't looping through each cell. Runs much faster over large worksheet sections.

Sub Trim_Cells_Array_Method()

Dim arrData() As Variant
Dim arrReturnData() As Variant
Dim rng As Excel.Range
Dim lRows As Long
Dim lCols As Long
Dim i As Long, j As Long

  lRows = Selection.Rows.count
  lCols = Selection.Columns.count

  ReDim arrData(1 To lRows, 1 To lCols)
  ReDim arrReturnData(1 To lRows, 1 To lCols)

  Set rng = Selection
  arrData = rng.value

  For j = 1 To lCols
    For i = 1 To lRows
      arrReturnData(i, j) = Trim(arrData(i, j))
    Next i
  Next j

  rng.value = arrReturnData

  Set rng = Nothing
End Sub

Php artisan make:auth command is not defined

Checkout your laravel/framework version on your composer.json file,

If it's either "^6.0" or higher than "^5.9",

you have to use php artisan ui:auth instead of php artisan make:auth.

Before using that you have to install new dependencies by calling composer require laravel/ui --dev in the current directory.

Hide a EditText & make it visible by clicking a menu

Try phoneNumber.setVisibility(View.GONE);

C compile error: "Variable-sized object may not be initialized"

int size=5;
int ar[size ]={O};

/* This  operation gives an error -  
variable sized array may not be 
initialised.  Then just try this. 
*/
int size=5,i;
int ar[size];
for(i=0;i<size;i++)
{
    ar[i]=0;
}

Draw horizontal rule in React Native

import { View, Dimensions } from 'react-native'

var { width, height } = Dimensions.get('window')

// Create Component

<View style={{
   borderBottomColor: 'black', 
   borderBottomWidth: 0.5, 
   width: width - 20,}}>
</View>

How do you extract classes' source code from a dll file?

You can use Reflector and also use Add-In FileGenerator to extract source code into a project.

select and echo a single field from mysql db using PHP

Try this:

echo mysql_result($result, 0);

This is enough because you are only fetching one field of one row.

React "after render" code?

There is actually a lot simpler and cleaner version than using request animationframe or timeouts. Iam suprised no one brought it up: the vanilla-js onload handler. If you can, use component did mount, if not, simply bind a function on the onload hanlder of the jsx component. If you want the function to run every render, also execute it before returning you results in the render function. the code would look like this:

_x000D_
_x000D_
runAfterRender = () => _x000D_
{_x000D_
  const myElem = document.getElementById("myElem")_x000D_
  if(myElem)_x000D_
  {_x000D_
    //do important stuff_x000D_
  }_x000D_
}_x000D_
_x000D_
render()_x000D_
{_x000D_
  this.runAfterRender()_x000D_
  return (_x000D_
    <div_x000D_
      onLoad = {this.runAfterRender}_x000D_
    >_x000D_
      //more stuff_x000D_
    </div>_x000D_
  )_x000D_
}
_x000D_
_x000D_
_x000D_

}

How to use jQuery to get the current value of a file input field

I've tried this and it works:

 yourelement.next().val();

yourelement could be:

$('#elementIdName').next().val();

good luck!

Is there a way to get a list of column names in sqlite?

I like the answer by @thebeancounter, but prefer to parameterize the unknowns, the only problem being a vulnerability to exploits on the table name. If you're sure it's okay, then this works:

def get_col_names(cursor, tablename):
    """Get column names of a table, given its name and a cursor
       (or connection) to the database.
    """
    reader=cursor.execute("SELECT * FROM {}".format(tablename))
    return [x[0] for x in reader.description] 

If it's a problem, you could add code to sanitize the tablename.

How to get the number of threads in a Java process

ManagementFactory.getThreadMXBean().getThreadCount() doesn't limit itself to thread groups as Thread.activeCount() does.

How to use cookies in Python Requests

You can use a session object. It stores the cookies so you can make requests, and it handles the cookies for you

s = requests.Session() 
# all cookies received will be stored in the session object

s.post('http://www...',data=payload)
s.get('http://www...')

Docs: https://requests.readthedocs.io/en/master/user/advanced/#session-objects

You can also save the cookie data to an external file, and then reload them to keep session persistent without having to login every time you run the script:

How to save requests (python) cookies to a file?

redistributable offline .NET Framework 3.5 installer for Windows 8

Looks like you need the package from the installation media if you're you're offline (located at D:\sources\sxs) You could copy this to each machine that you require .NET 3.5 on (so technically you only need the installation media once to get the package) and get each machine to run the command:

Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:c:\dotnet35 /LimitAccess

There's a guide on MSDN.

Removing html5 required attribute with jQuery

_x000D_
_x000D_
$('#id').removeAttr('required');?????
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Spark SQL: apply aggregate functions to a list of columns

Current answers are perfectly correct on how to create the aggregations, but none actually address the column alias/renaming that is also requested in the question.

Typically, this is how I handle this case:

val dimensionFields = List("col1")
val metrics = List("col2", "col3", "col4")
val columnOfInterests = dimensions ++ metrics

val df = spark.read.table("some_table"). 
    .select(columnOfInterests.map(c => col(c)):_*)
    .groupBy(dimensions.map(d => col(d)): _*)
    .agg(metrics.map( m => m -> "sum").toMap)
    .toDF(columnOfInterests:_*)    // that's the interesting part

The last line essentially renames every columns of the aggregated dataframe to the original fields, essentially changing sum(col2) and sum(col3) to simply col2 and col3.

Can I use GDB to debug a running process?

If one want to attach a process, this process must have the same owner. The root is able to attach to any process.

Convert java.time.LocalDate into java.util.Date type

    LocalDate date = LocalDate.now();
    DateFormat formatter = new SimpleDateFormat("dd-mm-yyyy");
    try {
        Date utilDate= formatter.parse(date.toString());
    } catch (ParseException e) {
        // handle exception
    }

How do I change a single value in a data.frame?

Suppose your dataframe is df and you want to change gender from 2 to 1 in participant id 5 then you should determine the row by writing "==" as you can see

 df["rowName", "columnName"] <- value
 df[df$serial.id==5, "gender"] <- 1

Setting format and value in input type="date"

What you want to do is fetch the value from the input and assign it to a new Date instance.

let date = document.getElementById('dateInput');

let formattedDate = new Date(date.value);

console.log(formattedDate);

Convert a RGB Color Value to a Hexadecimal String

You can use

String hex = String.format("#%02x%02x%02x", r, g, b);  

Use capital X's if you want your resulting hex-digits to be capitalized (#FFFFFF vs. #ffffff).

How to install xgboost in Anaconda Python (Windows platform)?

  1. Download package from this website. I downloaded xgboost-0.6-cp36-cp36m-win_amd64.whl for anaconda 3 (python 3.6)
  2. Put the package in directory C:\
  3. Open anaconda 3 prompt
  4. Type cd C:\
  5. Type pip install C:\xgboost-0.6-cp36-cp36m-win_amd64.whl
  6. Type conda update scikit-learn

Javascript Uncaught Reference error Function is not defined

If you are using Angular.js then functions imbedded into HTML, such as onclick="function()" or onchange="function()". They will not register. You need to make the change events in the javascript. Such as:

$('#exampleBtn').click(function() {
  function();
});

Bootstrap fixed header and footer with scrolling body-content area in fluid-container

Add the following css to disable the default scroll:

body {
    overflow: hidden;
}

And change the #content css to this to make the scroll only on content body:

#content {
    max-height: calc(100% - 120px);
    overflow-y: scroll;
    padding: 0px 10%;
    margin-top: 60px;
}

See fiddle here.


Edit:

Actually, I'm not sure what was the issue you were facing, since it seems that your css is working. I have only added the HTML and the header css statement:

_x000D_
_x000D_
html {_x000D_
  height: 100%;_x000D_
}_x000D_
html body {_x000D_
  height: 100%;_x000D_
  overflow: hidden;_x000D_
}_x000D_
html body .container-fluid.body-content {_x000D_
  position: absolute;_x000D_
  top: 50px;_x000D_
  bottom: 30px;_x000D_
  right: 0;_x000D_
  left: 0;_x000D_
  overflow-y: auto;_x000D_
}_x000D_
header {_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    right: 0;_x000D_
    top: 0;_x000D_
    background-color: #4C4;_x000D_
    height: 50px;_x000D_
}_x000D_
footer {_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    right: 0;_x000D_
    bottom: 0;_x000D_
    background-color: #4C4;_x000D_
    height: 30px;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<header></header>_x000D_
<div class="container-fluid body-content">_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
</div>_x000D_
<footer></footer>
_x000D_
_x000D_
_x000D_

Getting DOM elements by classname

There is also another approach without the use of DomXPath or Zend_Dom_Query.

Based on dav's original function, I wrote the following function that returns all the children of the parent node whose tag and class match the parameters.

function getElementsByClass(&$parentNode, $tagName, $className) {
    $nodes=array();

    $childNodeList = $parentNode->getElementsByTagName($tagName);
    for ($i = 0; $i < $childNodeList->length; $i++) {
        $temp = $childNodeList->item($i);
        if (stripos($temp->getAttribute('class'), $className) !== false) {
            $nodes[]=$temp;
        }
    }

    return $nodes;
}

suppose you have a variable $html the following HTML:

<html>
 <body>
  <div id="content_node">
    <p class="a">I am in the content node.</p>
    <p class="a">I am in the content node.</p>
    <p class="a">I am in the content node.</p>    
  </div>
  <div id="footer_node">
    <p class="a">I am in the footer node.</p>
  </div>
 </body>
</html>

use of getElementsByClass is as simple as:

$dom = new DOMDocument('1.0', 'utf-8');
$dom->loadHTML($html);
$content_node=$dom->getElementById("content_node");

$div_a_class_nodes=getElementsByClass($content_node, 'div', 'a');//will contain the three nodes under "content_node".

ASP.NET / C#: DropDownList SelectedIndexChanged in server control not firing

First, I would like to clarify something. Is this a post back (trip back to server) never occur, or is it the post back occurs, but it never gets into the ddlCountry_SelectedIndexChanged event handler?

I am not sure which case you are having, but if it is the second case, I can offer some suggestion. If it is the first case, then the following is FYI.

For the second case (event handler never fires even though request made), you may want to try the following suggestions:

  1. Query the Request.Params[ddlCountries.UniqueID] and see if it has value. If it has, manually fire the event handler.
  2. As long as view state is on, only bind the list data when it is not a post back.
  3. If view state has to be off, then put the list data bind in OnInit instead of OnLoad.

Beware that when calling Control.DataBind(), view state and post back information would no longer be available from the control. In the case of view state is on, between post back, values of the DropDownList would be kept intact (the list does not to be rebound). If you issue another DataBind in OnLoad, it would clear out its view state data, and the SelectedIndexChanged event would never be fired.

In the case of view state is turned off, you have no choice but to rebind the list every time. When a post back occurs, there are internal ASP.NET calls to populate the value from Request.Params to the appropriate controls, and I suspect happen at the time between OnInit and OnLoad. In this case, restoring the list values in OnInit will enable the system to fire events correctly.

Thanks for your time reading this, and welcome everyone to correct if I am wrong.

How can I check if mysql is installed on ubuntu?

With this command:

 dpkg -s mysql-server | grep Status

how to get value of selected item in autocomplete

When autocomplete changes a value, it fires a autocompletechange event, not the change event

$(document).ready(function () {
    $('#tags').on('autocompletechange change', function () {
        $('#tagsname').html('You selected: ' + this.value);
    }).change();
});

Demo: Fiddle

Another solution is to use select event, because the change event is triggered only when the input is blurred

$(document).ready(function () {
    $('#tags').on('change', function () {
        $('#tagsname').html('You selected: ' + this.value);
    }).change();
    $('#tags').on('autocompleteselect', function (e, ui) {
        $('#tagsname').html('You selected: ' + ui.item.value);
    });
});

Demo: Fiddle

how to make a new line in a jupyter markdown cell

The double space generally works well. However, sometimes the lacking newline in the PDF still occurs to me when using four pound sign sub titles #### in Jupyter Notebook, as the next paragraph is put into the subtitle as a single paragraph. No amount of double spaces and returns fixed this, until I created a notebook copy 'v. PDF' and started using a single backslash '\' which also indents the next paragraph nicely:

#### 1.1 My Subtitle  \

1.1 My Subtitle
    Next paragraph text.

An alternative to this, is to upgrade the level of your four # titles to three # titles, etc. up the title chain, which will remove the next paragraph indent and format the indent of the title itself (#### My Subtitle ---> ### My Subtitle).

### My Subtitle


1.1 My Subtitle

Next paragraph text.

SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch

Once you have established that they don't match, you still have a problem -- what to do about it. Often, the certificate may merely be assembled incorrectly. When a CA signs your certificate, they send you a block that looks something like

-----BEGIN CERTIFICATE-----
MIIAA-and-a-buncha-nonsense-that-is-your-certificate
-and-a-buncha-nonsense-that-is-your-certificate-and-
a-buncha-nonsense-that-is-your-certificate-and-a-bun
cha-nonsense-that-is-your-certificate-and-a-buncha-n
onsense-that-is-your-certificate-AA+
-----END CERTIFICATE-----

they'll also send you a bundle (often two certificates) that represent their authority to grant you a certificate. this will look something like

-----BEGIN CERTIFICATE-----
MIICC-this-is-the-certificate-that-signed-your-request
-this-is-the-certificate-that-signed-your-request-this
-is-the-certificate-that-signed-your-request-this-is-t
he-certificate-that-signed-your-request-this-is-the-ce
rtificate-that-signed-your-request-A
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIICC-this-is-the-certificate-that-signed-for-that-one
-this-is-the-certificate-that-signed-for-that-one-this
-is-the-certificate-that-signed-for-that-one-this-is-t
he-certificate-that-signed-for-that-one-this-is-the-ce
rtificate-that-signed-for-that-one-this-is-the-certifi
cate-that-signed-for-that-one-AA
-----END CERTIFICATE-----

except that unfortunately, they won't be so clearly labeled.

a common practice, then, is to bundle these all up into one file -- your certificate, then the signing certificates. But since they aren't easily distinguished, it sometimes happens that someone accidentally puts them in the other order -- signing certs, then the final cert -- without noticing. In that case, your cert will not match your key.

You can test to see what the cert thinks it represents by running

openssl x509 -noout -text -in yourcert.cert

Near the top, you should see "Subject:" and then stuff that looks like your data. If instead it lookslike your CA, your bundle is probably in the wrong order; you might try making a backup, and then moving the last cert to the beginning, hoping that is the one that is your cert.

If this doesn't work, you might just have to get the cert re-issued. When I make a CSR, I like to clearly label what server it's for (instead of just ssl.key or server.key) and make a copy of it with the date in the name, like mydomain.20150306.key etc. that way they private and public key pairs are unlikely to get mixed up with another set.

How to auto adjust the div size for all mobile / tablet display formats?

Whilst I was looking for my answer for the same question, I found this:

<img src="img.png" style=max-
width:100%;overflow:hidden;border:none;padding:0;margin:0 auto;display:block;" marginheight="0" marginwidth="0">

You can use it inside a tag (iframe or img) the image will adjust based on it's device.

Convert a binary NodeJS Buffer to JavaScript ArrayBuffer

I tried the above for a Float64Array and it just did not work.

I ended up realising that really the data needed to be read 'INTO' the view in correct chunks. This means reading 8 bytes at a time from the source Buffer.

Anyway this is what I ended up with...

var buff = new Buffer("40100000000000004014000000000000", "hex");
var ab = new ArrayBuffer(buff.length);
var view = new Float64Array(ab);

var viewIndex = 0;
for (var bufferIndex=0;bufferIndex<buff.length;bufferIndex=bufferIndex+8)            {

    view[viewIndex] = buff.readDoubleLE(bufferIndex);
    viewIndex++;
}

Unable to install packages in latest version of RStudio and R Version.3.1.1

My solution that worked was to open R studio options and select global miror (the field was empty before) and the error went away.

What's better at freeing memory with PHP: unset() or $var = null

It works in a different way for variables copied by reference:

$a = 5;
$b = &$a;
unset($b); // just say $b should not point to any variable
print $a; // 5

$a = 5;
$b = &$a;
$b = null; // rewrites value of $b (and $a)
print $a; // nothing, because $a = null

IntelliJ and Tomcat.. Howto..?

You can also debug tomcat using the community edition (Unlike what is said above).

Start tomcat in debug mode, for example like this: .\catalina.bat jpda run

In intellij: Run > Edit Configurations > +

Select "Remote" Name the connection: "somename" Set "Port:" 8000 (default 5005)

Select Run > Debug "somename"

Converting newline formatting from Mac to Windows

In Xcode 9 in the left panel open/choose your file in project navigator. If file is not there, drug-and-drop it into the project navigator.

On right panel find Text Settings and change Line Endings to Windows (CRLF) .

XCode screendumpscreendump from XCode

SQLite with encryption/password protection

Keep in mind, the following is not intended to be a substitute for a proper security solution.

After playing around with this for four days, I've put together a solution using only the open source System.Data.SQLite package from NuGet. I don't know how much protection this provides. I'm only using it for my own course of study. This will create the DB, encrypt it, create a table, and add data.

using System.Data.SQLite;

namespace EncryptDB
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = @"C:\Programming\sqlite3\db.db";
            string passwordString = "password";
            byte[] passwordBytes = GetBytes(passwordString);
            SQLiteConnection.CreateFile(connectionString);
            SQLiteConnection conn = new SQLiteConnection("Data Source=" + connectionString + ";Version=3;");
            conn.SetPassword(passwordBytes);
            conn.Open();
            SQLiteCommand sqlCmd = new SQLiteCommand("CREATE TABLE data(filename TEXT, filepath TEXT, filelength INTEGER, directory TEXT)", conn);
            sqlCmd.ExecuteNonQuery();
            sqlCmd = new SQLiteCommand("INSERT INTO data VALUES('name', 'path', 200, 'dir')", conn);
            sqlCmd.ExecuteNonQuery();
            conn.Close();
        }
        static byte[] GetBytes(string str)
        {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            bytes = System.Text.Encoding.Default.GetBytes(str);
            return bytes;
        }
    }
}

Optionally, you can remove conn.SetPassword(passwordBytes);, and replace it with conn.ChangePassword("password"); which needs to be placed after conn.Open(); instead of before. Then you won't need the GetBytes method.

To decrypt, it's just a matter of putting the password in your connection string before the call to open.

        string filename = @"C:\Programming\sqlite3\db.db";
        string passwordString = "password";
        SQLiteConnection conn = new SQLiteConnection("Data Source=" + filename + ";Version=3;Password=" + passwordString + ";");
        conn.Open();

Global javascript variable inside document.ready

You can define the variable inside the document ready function without var to make it a global variable. In javascript any variable declared without var automatically becomes a global variable

$(document).ready(function() {
    intro =  "something";
});

although you cant use the variable immediately, but it would be accessible to other functions

How do I execute a MS SQL Server stored procedure in java/jsp, returning table data?

Thank to Brian for the code. I was trying to connect to the sql server with {call spname(?,?)} and I got errors, but when I change my code to exec sp... it works very well.

I post my code in hope this helps others with problems like mine:

ResultSet rs = null;
PreparedStatement cs=null;
Connection conn=getJNDIConnection();

try {
    cs=conn.prepareStatement("exec sp_name ?,?,?,?,?,?,?");
    cs.setEscapeProcessing(true);
    cs.setQueryTimeout(90);

    cs.setString(1, "valueA");

    cs.setString(2, "valueB");

    cs.setString(3, "0418");

    //commented, because no need to register parameters out!, I got results from the resultset. 
    //cs.registerOutParameter(1, Types.VARCHAR);
    //cs.registerOutParameter(2, Types.VARCHAR);

    rs = cs.executeQuery();
    ArrayList<ObjectX> listaObjectX = new ArrayList<ObjectX>();
    while (rs.next()) {

        ObjectX to = new ObjectX();
        to.setFecha(rs.getString(1));
        to.setRefId(rs.getString(2));
        to.setRefNombre(rs.getString(3));
        to.setUrl(rs.getString(4));

        listaObjectX.add(to);

    }
    return listaObjectX;
     } catch (SQLException se) {
        System.out.println("Error al ejecutar SQL"+ se.getMessage());
        se.printStackTrace();
        throw new IllegalArgumentException("Error al ejecutar SQL: " + se.getMessage());

    } finally {

        try {

            rs.close();
            cs.close();
          con.close();

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

Javascript - sort array based on another array

Case 1: Original Question (No Libraries)

Plenty of other answers that work. :)

Case 2: Original Question (Lodash.js or Underscore.js)

var groups = _.groupBy(itemArray, 1);
var result = _.map(sortArray, function (i) { return groups[i].shift(); });

Case 3: Sort Array1 as if it were Array2

I'm guessing that most people came here looking for an equivalent to PHP's array_multisort (I did) so I thought I'd post that answer as well. There are a couple options:

1. There's an existing JS implementation of array_multisort(). Thanks to @Adnan for pointing it out in the comments. It is pretty large, though.

2. Write your own. (JSFiddle demo)

function refSort (targetData, refData) {
  // Create an array of indices [0, 1, 2, ...N].
  var indices = Object.keys(refData);

  // Sort array of indices according to the reference data.
  indices.sort(function(indexA, indexB) {
    if (refData[indexA] < refData[indexB]) {
      return -1;
    } else if (refData[indexA] > refData[indexB]) {
      return 1;
    }
    return 0;
  });

  // Map array of indices to corresponding values of the target array.
  return indices.map(function(index) {
    return targetData[index];
  });
}

3. Lodash.js or Underscore.js (both popular, smaller libraries that focus on performance) offer helper functions that allow you to do this:

    var result = _.chain(sortArray)
      .pairs()
      .sortBy(1)
      .map(function (i) { return itemArray[i[0]]; })
      .value();

...Which will (1) group the sortArray into [index, value] pairs, (2) sort them by the value (you can also provide a callback here), (3) replace each of the pairs with the item from the itemArray at the index the pair originated from.

The network adapter could not establish the connection - Oracle 11g

First check your listener is on or off. Go to net manager then Local -> service naming -> orcl. Then change your HOST NAME and put your PC name. Now go to LISTENER and change the HOST and put your PC name.

How do I obtain a Query Execution Plan in SQL Server?

There are a number of methods of obtaining an execution plan, which one to use will depend on your circumstances. Usually you can use SQL Server Management Studio to get a plan, however if for some reason you can't run your query in SQL Server Management Studio then you might find it helpful to be able to obtain a plan via SQL Server Profiler or by inspecting the plan cache.

Method 1 - Using SQL Server Management Studio

SQL Server comes with a couple of neat features that make it very easy to capture an execution plan, simply make sure that the "Include Actual Execution Plan" menu item (found under the "Query" menu) is ticked and run your query as normal.

Include Action Execution Plan menu item

If you are trying to obtain the execution plan for statements in a stored procedure then you should execute the stored procedure, like so:

exec p_Example 42

When your query completes you should see an extra tab entitled "Execution plan" appear in the results pane. If you ran many statements then you may see many plans displayed in this tab.

Screenshot of an Execution Plan

From here you can inspect the execution plan in SQL Server Management Studio, or right click on the plan and select "Save Execution Plan As ..." to save the plan to a file in XML format.

Method 2 - Using SHOWPLAN options

This method is very similar to method 1 (in fact this is what SQL Server Management Studio does internally), however I have included it for completeness or if you don't have SQL Server Management Studio available.

Before you run your query, run one of the following statements. The statement must be the only statement in the batch, i.e. you cannot execute another statement at the same time:

SET SHOWPLAN_TEXT ON
SET SHOWPLAN_ALL ON
SET SHOWPLAN_XML ON
SET STATISTICS PROFILE ON
SET STATISTICS XML ON -- The is the recommended option to use

These are connection options and so you only need to run this once per connection. From this point on all statements run will be acompanied by an additional resultset containing your execution plan in the desired format - simply run your query as you normally would to see the plan.

Once you are done you can turn this option off with the following statement:

SET <<option>> OFF

Comparison of execution plan formats

Unless you have a strong preference my recommendation is to use the STATISTICS XML option. This option is equivalent to the "Include Actual Execution Plan" option in SQL Server Management Studio and supplies the most information in the most convenient format.

  • SHOWPLAN_TEXT - Displays a basic text based estimated execution plan, without executing the query
  • SHOWPLAN_ALL - Displays a text based estimated execution plan with cost estimations, without executing the query
  • SHOWPLAN_XML - Displays an XML based estimated execution plan with cost estimations, without executing the query. This is equivalent to the "Display Estimated Execution Plan..." option in SQL Server Management Studio.
  • STATISTICS PROFILE - Executes the query and displays a text based actual execution plan.
  • STATISTICS XML - Executes the query and displays an XML based actual execution plan. This is equivalent to the "Include Actual Execution Plan" option in SQL Server Management Studio.

Method 3 - Using SQL Server Profiler

If you can't run your query directly (or your query doesn't run slowly when you execute it directly - remember we want a plan of the query performing badly), then you can capture a plan using a SQL Server Profiler trace. The idea is to run your query while a trace that is capturing one of the "Showplan" events is running.

Note that depending on load you can use this method on a production environment, however you should obviously use caution. The SQL Server profiling mechanisms are designed to minimize impact on the database but this doesn't mean that there won't be any performance impact. You may also have problems filtering and identifying the correct plan in your trace if your database is under heavy use. You should obviously check with your DBA to see if they are happy with you doing this on their precious database!

  1. Open SQL Server Profiler and create a new trace connecting to the desired database against which you wish to record the trace.
  2. Under the "Events Selection" tab check "Show all events", check the "Performance" -> "Showplan XML" row and run the trace.
  3. While the trace is running, do whatever it is you need to do to get the slow running query to run.
  4. Wait for the query to complete and stop the trace.
  5. To save the trace right click on the plan xml in SQL Server Profiler and select "Extract event data..." to save the plan to file in XML format.

The plan you get is equivalent to the "Include Actual Execution Plan" option in SQL Server Management Studio.

Method 4 - Inspecting the query cache

If you can't run your query directly and you also can't capture a profiler trace then you can still obtain an estimated plan by inspecting the SQL query plan cache.

We inspect the plan cache by querying SQL Server DMVs. The following is a basic query which will list all cached query plans (as xml) along with their SQL text. On most database you will also need to add additional filtering clauses to filter the results down to just the plans you are interested in.

SELECT UseCounts, Cacheobjtype, Objtype, TEXT, query_plan
FROM sys.dm_exec_cached_plans 
CROSS APPLY sys.dm_exec_sql_text(plan_handle)
CROSS APPLY sys.dm_exec_query_plan(plan_handle)

Execute this query and click on the plan XML to open up the plan in a new window - right click and select "Save execution plan as..." to save the plan to file in XML format.

Notes:

Because there are so many factors involved (ranging from the table and index schema down to the data stored and the table statistics) you should always try to obtain an execution plan from the database you are interested in (normally the one that is experiencing a performance problem).

You can't capture an execution plan for encrypted stored procedures.

"actual" vs "estimated" execution plans

An actual execution plan is one where SQL Server actually runs the query, whereas an estimated execution plan SQL Server works out what it would do without executing the query. Although logically equivalent, an actual execution plan is much more useful as it contains additional details and statistics about what actually happened when executing the query. This is essential when diagnosing problems where SQL Servers estimations are off (such as when statistics are out of date).

How do I interpret a query execution plan?

This is a topic worthy enough for a (free) book in its own right.

See also:

NameError: name 'self' is not defined

Default argument values are evaluated at function define-time, but self is an argument only available at function call time. Thus arguments in the argument list cannot refer each other.

It's a common pattern to default an argument to None and add a test for that in code:

def p(self, b=None):
    if b is None:
        b = self.a
    print b

Angular2 - Radio Button Binding

Here is the best way to use radio buttons in Angular2. There is no need to use the (click) event or a RadioControlValueAccessor to change the binded property value, setting [checked] property does the trick.

<input name="options" type="radio" [(ngModel)]="model.options" [value]="1"
       [checked]="model.options==1" /><br/>
<input name="options" type="radio"  [(ngModel)]="model.options" [value]="2"
       [checked]="model.options==2" /><br/>

I published an example of using radio buttons: Angular 2: how to create radio buttons from enum and add two-way binding? It works from at least Angular 2 RC5.

C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?

For languages not specifying a memory model, you are writing code for the language and the memory model specified by the processor architecture. The processor may choose to re-order memory accesses for performance. So, if your program has data races (a data race is when it's possible for multiple cores / hyper-threads to access the same memory concurrently) then your program is not cross platform because of its dependence on the processor memory model. You may refer to the Intel or AMD software manuals to find out how the processors may re-order memory accesses.

Very importantly, locks (and concurrency semantics with locking) are typically implemented in a cross platform way... So if you are using standard locks in a multithreaded program with no data races then you don't have to worry about cross platform memory models.

Interestingly, Microsoft compilers for C++ have acquire / release semantics for volatile which is a C++ extension to deal with the lack of a memory model in C++ http://msdn.microsoft.com/en-us/library/12a04hfd(v=vs.80).aspx. However, given that Windows runs on x86 / x64 only, that's not saying much (Intel and AMD memory models make it easy and efficient to implement acquire / release semantics in a language).

The request was rejected because no multipart boundary was found in springboot

When I use postman to send a file which is 5.6M to an external network, I faced the same issue. The same action is succeeded on my own computer and local testing environment.

After checking all the server configs and HTTP headers, I found that the reason is Postman may have some trouble simulating requests to external HTTP requests. Finally, I did the sendfile request on the chrome HTML page successfully. Just as a reference :)

HTTP post XML data in C#

In General:

An example of an easy way to post XML data and get the response (as a string) would be the following function:

public string postXMLData(string destinationUrl, string requestXml)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
    byte[] bytes;
    bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
    request.ContentType = "text/xml; encoding='utf-8'";
    request.ContentLength = bytes.Length;
    request.Method = "POST";
    Stream requestStream = request.GetRequestStream();
    requestStream.Write(bytes, 0, bytes.Length);
    requestStream.Close();
    HttpWebResponse response;
    response = (HttpWebResponse)request.GetResponse();
    if (response.StatusCode == HttpStatusCode.OK)
    {
        Stream responseStream = response.GetResponseStream();
        string responseStr = new StreamReader(responseStream).ReadToEnd();
        return responseStr;
    }
    return null;
}

In your specific situation:

Instead of:

request.ContentType = "application/x-www-form-urlencoded";

use:

request.ContentType = "text/xml; encoding='utf-8'";

Also, remove:

string postData = "XMLData=" + Sendingxml;

And replace:

byte[] byteArray = Encoding.UTF8.GetBytes(postData);

with:

byte[] byteArray = Encoding.UTF8.GetBytes(Sendingxml.ToString());

Remove all child nodes from a parent?

You can use .empty(), like this:

$("#foo").empty();

From the docs:

Remove all child nodes of the set of matched elements from the DOM.

JSON and XML comparison

Faster is not an attribute of JSON or XML or a result that a comparison between those would yield. If any, then it is an attribute of the parsers or the bandwidth with which you transmit the data.

Here is (the beginning of) a list of advantages and disadvantages of JSON and XML:


JSON

Pro:

  • Simple syntax, which results in less "markup" overhead compared to XML.
  • Easy to use with JavaScript as the markup is a subset of JS object literal notation and has the same basic data types as JavaScript.
  • JSON Schema for description and datatype and structure validation
  • JsonPath for extracting information in deeply nested structures

Con:

  • Simple syntax, only a handful of different data types are supported.

  • No support for comments.


XML

Pro:

  • Generalized markup; it is possible to create "dialects" for any kind of purpose
  • XML Schema for datatype, structure validation. Makes it also possible to create new datatypes
  • XSLT for transformation into different output formats
  • XPath/XQuery for extracting information in deeply nested structures
  • built in support for namespaces

Con:

  • Relatively wordy compared to JSON (results in more data for the same amount of information).

So in the end you have to decide what you need. Obviously both formats have their legitimate use cases. If you are mostly going to use JavaScript then you should go with JSON.

Please feel free to add pros and cons. I'm not an XML expert ;)

Declare variable in SQLite and use it

Herman's solution works, but it can be simplified because Sqlite allows to store any value type on any field.

Here is a simpler version that uses one Value field declared as TEXT to store any value:

CREATE TEMP TABLE IF NOT EXISTS Variables (Name TEXT PRIMARY KEY, Value TEXT);

INSERT OR REPLACE INTO Variables VALUES ('VarStr', 'Val1');
INSERT OR REPLACE INTO Variables VALUES ('VarInt', 123);
INSERT OR REPLACE INTO Variables VALUES ('VarBlob', x'12345678');

SELECT Value
  FROM Variables
 WHERE Name = 'VarStr'
UNION ALL
SELECT Value
  FROM Variables
 WHERE Name = 'VarInt'
UNION ALL
SELECT Value
  FROM Variables
 WHERE Name = 'VarBlob';

Write HTML to string

I was looking for something that looked like jquery for generating dom in C# (I don't need to parse). Unfortunately no luck in finding a lightweight solution so I created this simple class that is inherited from System.Xml.Linq.XElement. The key feature is that you can chain the operator like when using jquery in javascript so it's more fluent. It's not fully featured but it does what I need and if there is interest I can start a git.

public class DomElement : XElement
{
    public DomElement(string name) : base(name)
    {
    }

    public DomElement(string name, string value) : base(name, value)
    {
    }

    public DomElement Css(string style, string value)
    {
        style = style.Trim();
        value = value.Trim();
        var existingStyles = new Dictionary<string, string>();
        var xstyle = this.Attribute("style");
        if (xstyle != null)
        {
            foreach (var s in xstyle.Value.Split(';'))
            {
                var keyValue = s.Split(':');
                existingStyles.Add(keyValue[0], keyValue.Length < 2 ? null : keyValue[1]);
            }
        }

        if (existingStyles.ContainsKey(style))
        {
            existingStyles[style] = value;
        }
        else
        {
            existingStyles.Add(style, value);
        }

        var styleString = string.Join(";", existingStyles.Select(s => $"{s.Key}:{s.Value}"));
        this.SetAttributeValue("style", styleString);

        return this;
    }

    public DomElement AddClass(string cssClass)
    {
        var existingClasses = new List<string>();
        var xclass = this.Attribute("class");
        if (xclass != null)
        {
            existingClasses.AddRange(xclass.Value.Split());
        }

        var addNewClasses = cssClass.Split().Where(e => !existingClasses.Contains(e));
        existingClasses.AddRange(addNewClasses);

        this.SetAttributeValue("class", string.Join(" ", existingClasses));
        return this;
    }

    public DomElement Text(string text)
    {
        this.Value = text;
        return this;
    }

    public DomElement Append(string text)
    {
        this.Add(text);
        return this;
    }

    public DomElement Append(DomElement child)
    {
        this.Add(child);
        return this;
    }
}

Sample:

void Main()
{
    var html = new DomElement("html")
        .Append(new DomElement("head"))
        .Append(new DomElement("body")
            .Append(new DomElement("p")
                .Append("This paragraph contains")
                .Append(new DomElement("b", "bold"))
                .Append(" text.")
                )
            .Append(new DomElement("p").Text("This paragraph has just plain text"))
            )
        ;

    html.ToString().Dump();

    var table = new DomElement("table").AddClass("table table-sm").AddClass("table-striped")
            .Append(new DomElement("thead")
                .Append(new DomElement("tr")
                    .Append(new DomElement("td").Css("padding-left", "15px").Css("color", "red").Css("color", "blue")
                        .AddClass("from-now")
                        .Append(new DomElement("div").Text("Hi there"))
                        .Append(new DomElement("div").Text("Hey there"))
                        .Append(new DomElement("div", "Yo there"))
                        )
                )
            )
        ;
    table.ToString().Dump();
}

output from above code:

<html>
  <head />
  <body>
    <p>This paragraph contains<b>bold</b> text.</p>
    <p>This paragraph has just plain text</p>
  </body>
</html>
<table class="table table-sm table-striped">
  <thead>
    <tr>
      <td style="padding-left:15px;color:blue" class="from-now">
        <div>Hi there</div>
        <div>Hey there</div>
        <div>Yo there</div>
      </td>
    </tr>
  </thead>
</table>

Creating a triangle with for loops

private static void printStar(int x) {
    int i, j;
    for (int y = 0; y < x; y++) { // number of row of '*'

        for (i = y; i < x - 1; i++)
            // number of space each row
            System.out.print(' ');

        for (j = 0; j < y * 2 + 1; j++)
            // number of '*' each row
            System.out.print('*');

        System.out.println();
    }
}

How to properly export an ES6 class in Node 4?

class expression can be used for simplicity.

 // Foo.js
'use strict';

// export default class Foo {}
module.exports = class Foo {}

-

// main.js
'use strict';

const Foo = require('./Foo.js');

let Bar = new class extends Foo {
  constructor() {
    super();
    this.name = 'bar';
  }
}

console.log(Bar.name);

How to Create a Form Dynamically Via Javascript

some thing as follows ::

Add this After the body tag

This is a rough sketch, you will need to modify it according to your needs.

<script>
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");

var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");

var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");

f.appendChild(i);
f.appendChild(s);

//and some more input elements here
//and dont forget to add a submit button

document.getElementsByTagName('body')[0].appendChild(f);

</script>

Linux - Install redis-cli only

To install 3.0 which is the latest stable version:

$ git clone http://github.com/antirez/redis.git 
$ cd redis && git checkout 3.0 
$ make redis-cli 

Optionally, you can put the compiled executable in your load path for convenience:

$ ln -s src/redis-cli /usr/local/bin/redis-cli

C++ - Decimal to binary converting

Here is modern variant that can be used for ints of different sizes.

#include <type_traits>
#include <bitset>

template<typename T>
std::enable_if_t<std::is_integral_v<T>,std::string>
encode_binary(T i){
    return std::bitset<sizeof(T) * 8>(i).to_string();
}

TypeError: 'NoneType' object is not iterable in Python

You're calling write_file with arguments like this:

write_file(foo, bar)

But you haven't defined 'foo' correctly, or you have a typo in your code so that it's creating a new empty variable and passing it in.

Fastest way to check if a file exist using standard C++/C++11/C?

It depends on where the files reside. For instance, if they are all supposed to be in the same directory, you can read all the directory entries into a hash table and then check all the names against the hash table. This might be faster on some systems than checking each file individually. The fastest way to check each file individually depends on your system ... if you're writing ANSI C, the fastest way is fopen because it's the only way (a file might exist but not be openable, but you probably really want openable if you need to "do something on it"). C++, POSIX, Windows all offer additional options.

While I'm at it, let me point out some problems with your question. You say that you want the fastest way, and that you have thousands of files, but then you ask for the code for a function to test a single file (and that function is only valid in C++, not C). This contradicts your requirements by making an assumption about the solution ... a case of the XY problem. You also say "in standard c++11(or)c++(or)c" ... which are all different, and this also is inconsistent with your requirement for speed ... the fastest solution would involve tailoring the code to the target system. The inconsistency in the question is highlighted by the fact that you accepted an answer that gives solutions that are system-dependent and are not standard C or C++.

Convert long/lat to pixel x/y on a given picture

my approach works without a library and with cropped maps. Means it works with just parts from a Mercator image. Maybe it helps somebody: https://stackoverflow.com/a/10401734/730823

How to get df linux command output always in GB

You can use the -B option.

Man page of df:

-B, --block-size=SIZE use SIZE-byte blocks

All together,

df -BG

What is the difference between `throw new Error` and `throw someObject`?

TLDR: they are equivalent Error(x) === new Error(x).

// this:
const x = Error('I was created using a function call!');
????// has the same functionality as this:
const y = new Error('I was constructed via the "new" keyword!');

source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

throw and throw Error will are functionally equivalent. But when you catch them and serialize them to console.log they are not serialized exactly the same way:

throw 'Parameter is not a number!';
throw new Error('Parameter is not a number!');
throw Error('Parameter is not a number!');

Console.log(e) of the above will produce 2 different results:

Parameter is not a number!
Error: Parameter is not a number!
Error: Parameter is not a number!

git rebase merge conflict

Rebasing can be a real headache. You have to resolve the merge conflicts and continue rebasing. For example you can use the merge tool (which differs depending on your settings)

git mergetool

Then add your changes and go on

git rebase --continue

Good luck

jQuery - how to check if an element exists?

You can use length to see if your selector matched anything.

if ($('#MyId').length) {
    // do your stuff
}

How to install PostgreSQL's pg gem on Ubuntu?

Need to add package

sudo apt-get install libpq-dev

to install pg gem in RoR

Using putty to scp from windows to Linux

You need to tell scp where to send the file. In your command that is not working:

scp C:\Users\Admin\Desktop\WMU\5260\A2.c ~

You have not mentioned a remote server. scp uses : to delimit the host and path, so it thinks you have asked it to download a file at the path \Users\Admin\Desktop\WMU\5260\A2.c from the host C to your local home directory.

The correct upload command, based on your comments, should be something like:

C:\> pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:

If you are running the command from your home directory, you can use a relative path:

C:\Users\Admin> pscp Desktop\WMU\5260\A2.c [email protected]:

You can also mention the directory where you want to this folder to be downloaded to at the remote server. i.e by just adding a path to the folder as below:

C:/> pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:/home/path_to_the_folder/

Get the value of checked checkbox?

None of the above worked for me but simply use this:

document.querySelector('.messageCheckbox').checked;

Happy coding.

Reset auto increment counter in postgres

To get sequence id use

SELECT pg_get_serial_sequence('tableName', 'ColumnName');

This will gives you sequesce id as tableName_ColumnName_seq

To Get Last seed number use

select currval(pg_get_serial_sequence('tableName', 'ColumnName'));

or if you know sequence id already use it directly.

select currval(tableName_ColumnName_seq);

It will gives you last seed number

To Reset seed number use

ALTER SEQUENCE tableName_ColumnName_seq RESTART WITH 45

How to log a method's execution time exactly in milliseconds?

I use this:

clock_t start, end;
double elapsed;
start = clock();

//Start code to time

//End code to time

end = clock();
elapsed = ((double) (end - start)) / CLOCKS_PER_SEC;
NSLog(@"Time: %f",elapsed);

But I'm not sure about CLOCKS_PER_SEC on the iPhone. You might want to leave it off.

Format date in a specific timezone

.zone() has been deprecated, and you should use utcOffset instead:

// for a timezone that is +7 UTC hours
moment(1369266934311).utcOffset(420).format('YYYY-MM-DD HH:mm')

How to get the next auto-increment id in mysql

SELECT id FROM `table` ORDER BY id DESC LIMIT 1

Although I doubt in its productiveness but it's 100% reliable

How to save S3 object to a file using boto3

When you want to read a file with a different configuration than the default one, feel free to use either mpu.aws.s3_download(s3path, destination) directly or the copy-pasted code:

def s3_download(source, destination,
                exists_strategy='raise',
                profile_name=None):
    """
    Copy a file from an S3 source to a local destination.

    Parameters
    ----------
    source : str
        Path starting with s3://, e.g. 's3://bucket-name/key/foo.bar'
    destination : str
    exists_strategy : {'raise', 'replace', 'abort'}
        What is done when the destination already exists?
    profile_name : str, optional
        AWS profile

    Raises
    ------
    botocore.exceptions.NoCredentialsError
        Botocore is not able to find your credentials. Either specify
        profile_name or add the environment variables AWS_ACCESS_KEY_ID,
        AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN.
        See https://boto3.readthedocs.io/en/latest/guide/configuration.html
    """
    exists_strategies = ['raise', 'replace', 'abort']
    if exists_strategy not in exists_strategies:
        raise ValueError('exists_strategy \'{}\' is not in {}'
                         .format(exists_strategy, exists_strategies))
    session = boto3.Session(profile_name=profile_name)
    s3 = session.resource('s3')
    bucket_name, key = _s3_path_split(source)
    if os.path.isfile(destination):
        if exists_strategy is 'raise':
            raise RuntimeError('File \'{}\' already exists.'
                               .format(destination))
        elif exists_strategy is 'abort':
            return
    s3.Bucket(bucket_name).download_file(key, destination)

from collections import namedtuple

S3Path = namedtuple("S3Path", ["bucket_name", "key"])


def _s3_path_split(s3_path):
    """
    Split an S3 path into bucket and key.

    Parameters
    ----------
    s3_path : str

    Returns
    -------
    splitted : (str, str)
        (bucket, key)

    Examples
    --------
    >>> _s3_path_split('s3://my-bucket/foo/bar.jpg')
    S3Path(bucket_name='my-bucket', key='foo/bar.jpg')
    """
    if not s3_path.startswith("s3://"):
        raise ValueError(
            "s3_path is expected to start with 's3://', " "but was {}"
            .format(s3_path)
        )
    bucket_key = s3_path[len("s3://"):]
    bucket_name, key = bucket_key.split("/", 1)
    return S3Path(bucket_name, key)

Can't pickle <type 'instancemethod'> when using multiprocessing Pool.map()

In this simple case, where someClass.f is not inheriting any data from the class and not attaching anything to the class, a possible solution would be to separate out f, so it can be pickled:

import multiprocessing


def f(x):
    return x*x


class someClass(object):
    def __init__(self):
        pass

    def go(self):
        pool = multiprocessing.Pool(processes=4)       
        print pool.map(f, range(10))

How can I make a weak protocol reference in 'pure' Swift (without @objc)

AnyObject is the official way to use a weak reference in Swift.

class MyClass {
    weak var delegate: MyClassDelegate?
}

protocol MyClassDelegate: AnyObject {
}

From Apple:

To prevent strong reference cycles, delegates should be declared as weak references. For more information about weak references, see Strong Reference Cycles Between Class Instances. Marking the protocol as class-only will later allow you to declare that the delegate must use a weak reference. You mark a protocol as being class-only by inheriting from AnyObject, as discussed in Class-Only Protocols.

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html#//apple_ref/doc/uid/TP40014097-CH25-ID276

How to remove trailing whitespaces with sed?

At least on Mountain Lion, Viktor's answer will also remove the character 't' when it is at the end of a line. The following fixes that issue:

sed -i '' -e's/[[:space:]]*$//' "$1"

How to parse dates in multiple formats using SimpleDateFormat

If working in Java 1.8 you can leverage the DateTimeFormatterBuilder

public static boolean isTimeStampValid(String inputString)
{
    DateTimeFormatterBuilder dateTimeFormatterBuilder = new DateTimeFormatterBuilder()
            .append(DateTimeFormatter.ofPattern("" + "[yyyy-MM-dd'T'HH:mm:ss.SSSZ]" + "[yyyy-MM-dd]"));

    DateTimeFormatter dateTimeFormatter = dateTimeFormatterBuilder.toFormatter();

    try {
        dateTimeFormatter.parse(inputString);
        return true;
    } catch (DateTimeParseException e) {
        return false;
    }
}

See post: Java 8 Date equivalent to Joda's DateTimeFormatterBuilder with multiple parser formats?

Java: Check if command line arguments are null

If you don't pass any argument then even in that case args gets initialized but without any item/element. Try the following one, you will get the same effect:

 
public static void main(String[] args) throws InterruptedException {
        String [] dummy= new String [] {};
        if(dummy[0] == null)
        {
            System.out.println("Proper Usage is: java program filename");
            System.exit(0);
        }

    }

pandas DataFrame: replace nan values with average of columns

If you want to impute missing values with mean and you want to go column by column, then this will only impute with the mean of that column. This might be a little more readable.

sub2['income'] = sub2['income'].fillna((sub2['income'].mean()))

Setting the focus to a text field

I have toyed with this for forever, and finally found something that seems to always work!

textField = new JTextField() {

    public void addNotify() {
        super.addNotify();
        requestFocus();
    }
};

How can I pass an argument to a PowerShell script?

Let PowerShell analyze and decide the data type. It internally uses a 'Variant' for this.

And generally it does a good job...

param($x)
$iTunes = New-Object -ComObject iTunes.Application
if ($iTunes.playerstate -eq 1)
{
    $iTunes.PlayerPosition = $iTunes.PlayerPosition + $x
}

Or if you need to pass multiple parameters:

param($x1, $x2)
$iTunes = New-Object -ComObject iTunes.Application
if ($iTunes.playerstate -eq 1)
{
    $iTunes.PlayerPosition = $iTunes.PlayerPosition + $x1
    $iTunes.<AnyProperty>  = $x2
}

Get a list of dates between two dates

We had a similar problem with BIRT reports in that we wanted to report on those days that had no data. Since there were no entries for those dates, the easiest solution for us was to create a simple table that stored all dates and use that to get ranges or join to get zero values for that date.

We have a job that runs every month to ensure that the table is populated 5 years out into the future. The table is created thus:

create table all_dates (
    dt date primary key
);

No doubt there are magical tricky ways to do this with different DBMS' but we always opt for the simplest solution. The storage requirements for the table are minimal and it makes the queries so much simpler and portable. This sort of solution is almost always better from a performance point-of-view since it doesn't require per-row calculations on the data.

The other option (and we've used this before) is to ensure there's an entry in the table for every date. We swept the table periodically and added zero entries for dates and/or times that didn't exist. This may not be an option in your case, it depends on the data stored.

If you really think it's a hassle to keep the all_dates table populated, a stored procedure is the way to go which will return a dataset containing those dates. This will almost certainly be slower since you have to calculate the range every time it's called rather than just pulling pre-calculated data from a table.

But, to be honest, you could populate the table out for 1000 years without any serious data storage problems - 365,000 16-byte (for example) dates plus an index duplicating the date plus 20% overhead for safety, I'd roughly estimate at about 14M [365,000 * 16 * 2 * 1.2 = 14,016,000 bytes]), a minuscule table in the scheme of things.

R data formats: RData, Rda, Rds etc

In addition to @KenM's answer, another important distinction is that, when loading in a saved object, you can assign the contents of an Rds file. Not so for Rda

> x <- 1:5
> save(x, file="x.Rda")
> saveRDS(x, file="x.Rds")
> rm(x)

## ASSIGN USING readRDS
> new_x1 <- readRDS("x.Rds")
> new_x1
[1] 1 2 3 4 5

## 'ASSIGN' USING load -- note the result
> new_x2 <- load("x.Rda")
loading in to  <environment: R_GlobalEnv> 
> new_x2
[1] "x"
# NOTE: `load()` simply returns the name of the objects loaded. Not the values. 
> x
[1] 1 2 3 4 5

How to resize an Image C#

Note: this will not work with ASP.Net Core because WebImage depends on System.Web, but on previous versions of ASP.Net I used this snippet many times and was useful.

String ThumbfullPath = Path.GetFileNameWithoutExtension(file.FileName) + "80x80.jpg";
var ThumbfullPath2 = Path.Combine(ThumbfullPath, fileThumb);
using (MemoryStream stream = new MemoryStream(System.IO.File.ReadAllBytes(fullPath)))
{
      var thumbnail = new WebImage(stream).Resize(80, 80);
      thumbnail.Save(ThumbfullPath2, "jpg");
}

Populating a dictionary using for loops (python)

dicts = {}
keys = range(4)
values = ["Hi", "I", "am", "John"]
for i in keys:
        dicts[i] = values[i]
print(dicts)

alternatively

In [7]: dict(list(enumerate(values)))
Out[7]: {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}

memory error in python

Using python 64 bit solves lot of problems.

How do I get rid of the "cannot empty the clipboard" error?

If you can't find the clipboard, then close that excel sheet and reopen it again. This will solve your problem.

Where is nodejs log file?

There is no log file. Each node.js "app" is a separate entity. By default it will log errors to STDERR and output to STDOUT. You can change that when you run it from your shell to log to a file instead.

node my_app.js > my_app_log.log 2> my_app_err.log

Alternatively (recommended), you can add logging inside your application either manually or with one of the many log libraries:

Trim spaces from end of a NSString

let string = " Test Trimmed String "

For Removing white Space and New line use below code :-

let str_trimmed = yourString.trimmingCharacters(in: .whitespacesAndNewlines)

For Removing only Spaces from string use below code :-

let str_trimmed = yourString.trimmingCharacters(in: .whitespaces)

pandas dataframe columns scaling with sklearn

As it is being mentioned in pir's comment - the .apply(lambda el: scale.fit_transform(el)) method will produce the following warning:

DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and will raise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.

Converting your columns to numpy arrays should do the job (I prefer StandardScaler):

from sklearn.preprocessing import StandardScaler
scale = StandardScaler()

dfTest[['A','B','C']] = scale.fit_transform(dfTest[['A','B','C']].as_matrix())

-- Edit Nov 2018 (Tested for pandas 0.23.4)--

As Rob Murray mentions in the comments, in the current (v0.23.4) version of pandas .as_matrix() returns FutureWarning. Therefore, it should be replaced by .values:

from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()

scaler.fit_transform(dfTest[['A','B']].values)

-- Edit May 2019 (Tested for pandas 0.24.2)--

As joelostblom mentions in the comments, "Since 0.24.0, it is recommended to use .to_numpy() instead of .values."

Updated example:

import pandas as pd
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
dfTest = pd.DataFrame({
               'A':[14.00,90.20,90.95,96.27,91.21],
               'B':[103.02,107.26,110.35,114.23,114.68],
               'C':['big','small','big','small','small']
             })
dfTest[['A', 'B']] = scaler.fit_transform(dfTest[['A','B']].to_numpy())
dfTest
      A         B      C
0 -1.995290 -1.571117    big
1  0.436356 -0.603995  small
2  0.460289  0.100818    big
3  0.630058  0.985826  small
4  0.468586  1.088469  small

IF EXIST C:\directory\ goto a else goto b problems windows XP batch files

Use parentheses to group the individual branches:

IF EXIST D:\RPS_BACKUP\backups_to_zip\ (goto zipexist) else goto zipexistcontinue

In your case the parser won't ever see the else belonging to the if because goto will happily accept everything up to the end of the command. You can see a similar issue when using echo instead of goto.

Also using parentheses will allow you to use the statements directly without having to jump around (although I wasn't able to rewrite your code to actually use structured programming techniques; maybe it's too early or it doesn't lend itself well to block structures as the code is right now).

Can you "compile" PHP code and upload a binary-ish file, which will just be run by the byte code interpreter?

In php 7 there is the php ini option opcache.file_cache that saves the bytecode in a specific folder. In could be useful to in php cli script that are "compiled" and saved in a specific folder for a optimized reuse.

Opcache it is not compiling but is something similar.

Get height of div with no height set in css

Also make sure the div is currently appended to the DOM and visible.

Safari 3rd party cookie iframe trick no longer working?

In your Ruby on Rails controller you can use:

private

before_filter :safari_cookie_fix

def safari_cookie_fix
  user_agent = UserAgent.parse(request.user_agent) # Uses useragent gem!
  if user_agent.browser == 'Safari' # we apply the fix..
    return if session[:safari_cookie_fixed] # it is already fixed.. continue
    if params[:safari_cookie_fix].present? # we should be top window and able to set cookies.. so fix the issue :)
      session[:safari_cookie_fixed] = true
      redirect_to params[:return_to]
    else
      # Redirect the top frame to your server..
      render :text => "<script>alert('start redirect');top.window.location='?safari_cookie_fix=true&return_to=#{set_your_return_url}';</script>"
    end
  end
end

Java : How to determine the correct charset encoding of a stream

An alternative to TikaEncodingDetector is to use Tika AutoDetectReader.

Charset charset = new AutoDetectReader(new FileInputStream(file)).getCharset();

Use a LIKE statement on SQL Server XML Datatype

This is what I am going to use based on marc_s answer:

SELECT 
SUBSTRING(DATA.value('(/PAGECONTENT/TEXT)[1]', 'VARCHAR(100)'),PATINDEX('%NORTH%',DATA.value('(/PAGECONTENT/TEXT)[1]', 'VARCHAR(100)')) - 20,999)

FROM WEBPAGECONTENT 
WHERE COALESCE(PATINDEX('%NORTH%',DATA.value('(/PAGECONTENT/TEXT)[1]', 'VARCHAR(100)')),0) > 0

Return a substring on the search where the search criteria exists

Find and replace with a newline in Visual Studio Code

In the local searchbox (ctrl + f) you can insert newlines by pressing ctrl + enter.

Image of multiline search in local search

If you use the global search (ctrl + shift + f) you can insert newlines by pressing shift + enter.

Image of multiline search in global search

If you want to search for multilines by the character literal, remember to check the rightmost regex icon.

Image of regex mode in search replace


In previous versions of Visual Studio code this was difficult or impossible. Older versions require you to use the regex mode, older versions yet did not support newline search whatsoever.

HTTP Error 404 when running Tomcat from Eclipse

Another way to fix this would be to go to the properties of the server on eclipse (right click on server -> properties) In general tab you would see location as workspace.metadata. Click on switch location.

Reading an Excel file in python using pandas

Loading an excel file without explicitly naming a sheet but instead giving the number of the sheet order (often one will simply load the first sheet) goes like:

import pandas as pd
myexcel = pd.ExcelFile("C:/filename.xlsx")
myexcel = myexcel.parse(myexcel.sheet_names[0])

Since .sheet_names returns a list of sheet names, it is easy to load one or more sheets by simply calling the list element(s).

Remove folder and its contents from git/GitHub's history

I find that the --tree-filter option used in other answers can be very slow, especially on larger repositories with lots of commits.

Here is the method I use to completely remove a directory from the git history using the --index-filter option, which runs much quicker:

# Make a fresh clone of YOUR_REPO
git clone YOUR_REPO
cd YOUR_REPO

# Create tracking branches of all branches
for remote in `git branch -r | grep -v /HEAD`; do git checkout --track $remote ; done

# Remove DIRECTORY_NAME from all commits, then remove the refs to the old commits
# (repeat these two commands for as many directories that you want to remove)
git filter-branch --index-filter 'git rm -rf --cached --ignore-unmatch DIRECTORY_NAME/' --prune-empty --tag-name-filter cat -- --all
git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d

# Ensure all old refs are fully removed
rm -Rf .git/logs .git/refs/original

# Perform a garbage collection to remove commits with no refs
git gc --prune=all --aggressive

# Force push all branches to overwrite their history
# (use with caution!)
git push origin --all --force
git push origin --tags --force

You can check the size of the repository before and after the gc with:

git count-objects -vH

Ansible date variable

The command ansible localhost -m setup basically says "run the setup module against localhost", and the setup module gathers the facts that you see in the output.

When you run the echo command these facts don't exist since the setup module wasn't run. A better method to testing things like this would be to use ansible-playbook to run a playbook that looks something like this:

- hosts: localhost
  tasks:
      - debug: var=ansible_date_time

      - debug: msg="the current date is {{ ansible_date_time.date }}"

Because this runs as a playbook facts for localhost are gathered before the tasks are run. The output of the above playbook will be something like this:

PLAY [localhost] **************************************************

GATHERING FACTS ***************************************************************
ok: [localhost]

TASK: [debug var=ansible_date_time] *******************************************
ok: [localhost] => {
    "ansible_date_time": {
        "date": "2015-07-09",
        "day": "09",
        "epoch": "1436461166",
        "hour": "16",
        "iso8601": "2015-07-09T16:59:26Z",
        "iso8601_micro": "2015-07-09T16:59:26.896629Z",
        "minute": "59",
        "month": "07",
        "second": "26",
        "time": "16:59:26",
        "tz": "UTC",
        "tz_offset": "+0000",
        "weekday": "Thursday",
        "year": "2015"
    }
}

TASK: [debug msg="the current date is {{ ansible_date_time.date }}"] **********
ok: [localhost] => {
    "msg": "the current date is 2015-07-09"
}

PLAY RECAP ********************************************************************
localhost      : ok=3    changed=0    unreachable=0    failed=0

MSSQL Error 'The underlying provider failed on Open'

This can also happen if you restore a database and the user already exists with different schema, leaving you unable to assign the correct permissions.

To correct this run:

USE your_database
EXEC sp_change_users_login 'Auto_Fix', 'user', NULL, 'cf'
GO
EXEC sp_change_users_login 'update_one', 'user', 'user'
GO

not:first-child selector

As I used ul:not(:first-child) is a perfect solution.

div ul:not(:first-child) {
    background-color: #900;
}

Why is this a perfect because by using ul:not(:first-child), we can apply CSS on inner elements. Like li, img, span, a tags etc.

But when used others solutions:

div ul + ul {
  background-color: #900;
}

and

div li~li {
    color: red;
}

and

ul:not(:first-of-type) {}

and

div ul:nth-child(n+2) {
    background-color: #900;
}

These restrict only ul level CSS. Suppose we cannot apply CSS on li as `div ul + ul li'.

For inner level elements the first Solution works perfectly.

div ul:not(:first-child) li{
        background-color: #900;
    }

and so on ...

SHA-256 or MD5 for file integrity

To 1): Yes, on most CPUs, SHA-256 is about only 40% as fast as MD5.

To 2): I would argue for a different algorithm than MD5 in such a case. I would definitely prefer an algorithm that is considered safe. However, this is more a feeling. Cases where this matters would be rather constructed than realistic, e.g. if your backup system encounters an example case of an attack on an MD5-based certificate, you are likely to have two files in such an example with different data, but identical MD5 checksums. For the rest of the cases, it doesn't matter, because MD5 checksums have a collision (= same checksums for different data) virtually only when provoked intentionally. I'm not an expert on the various hashing (checksum generating) algorithms, so I can not suggest another algorithm. Hence this part of the question is still open. Suggested further reading is Cryptographic Hash Function - File or Data Identifier on Wikipedia. Also further down on that page there is a list of cryptographic hash algorithms.

To 3): MD5 is an algorithm to calculate checksums. A checksum calculated using this algorithm is then called an MD5 checksum.

mysqldump & gzip commands to properly create a compressed file of a MySQL database using crontab

Besides the solution of m79lkm above, my 2 cents on this topic is not to directly pipe the result in gzip but first dump it as a .sql file, and then gzip it. (Use && instead of | )

The dump itself will be faster. (for what I tested it was double as fast)

Otherwise you tables will be locked longer and the downtime/slow-responding of your application can bother the users. The mysqldump command is taking a lot of resources from your server.

So I would go for "&& gzip" instead of "| gzip"

Important: check for free disk space first with df -h since you will need more then piping | gzip.

mysqldump -u user -p[user_password] [database_name] > dumpfilename.sql && gzip dumpfilename.sql

-> which will also result in 1 file called dumpfilename.sql.gz

Furthermore the option --single-transaction prevents the tables being locked but still result in a solid backup. So you might consider to use that option. See docs here

mysqldump --single-transaction -u user -p[user_password] [database_name] > dumpfilename.sql && gzip dumpfilename.sql

How to delete multiple values from a vector?

q <- c(1,1,2,2,3,3,3,4,4,5,5,7,7)
rm <- q[11]
remove(rm)
q
q[13] = NaN
q
q %in% 7

This sets the 13 in a vector to not a number(NAN) it shows false remove(q[c(11,12,13)]) if you try this you will see that remove function don't work on vector number. you remove entire vector but maybe not a single element.

Can't open and lock privilege tables: Table 'mysql.user' doesn't exist

The mysql_install_db script also needs the datadir parameter:

mysql_install_db --user=root --datadir=$db_datapath

On Maria DB you use the install script mysql_install_db to install and initialize. In my case I use an environment variable for the data path. Not only does mysqld need to know where the data is (specified via commandline), but so does the install script.

Format numbers in JavaScript similar to C#

You can do it in the following way: So you will not only format the number but you can also pass as a parameter how many decimal digits to display, you set a custom decimal and mile separator.

function format(number, decimals = 2, decimalSeparator = '.', thousandsSeparator = ',') {
    const roundedNumber = number.toFixed(decimals);
    let integerPart = '', fractionalPart = '';
    if (decimals == 0) {
        integerPart = roundedNumber;
        decimalSeparator = '';
    } else {
        let numberParts = roundedNumber.split('.');
        integerPart = numberParts[0];
        fractionalPart = numberParts[1];
    }
    integerPart = integerPart.replace(/(\d)(?=(\d{3})+(?!\d))/g, `$1${thousandsSeparator}`);
    return `${integerPart}${decimalSeparator}${fractionalPart}`;
}

Use:

let min = 1556454.0001;
let max = 15556982.9999;
console.time('number format');
for (let i = 0; i < 15000; i++) {
    let randomNumber = Math.random() * (max - min) + min;

    let formated = format(randomNumber, 4, ',', '.'); // formated number

    console.debug('number: ', randomNumber, 'formated: ', formated);
}
console.timeEnd('number format');

Highlight Bash/shell code in Markdown files

If you are looking to highlight a shell session command sequence as it looks to the user (with prompts, not just as contents of a hypothetical script file), then the right identifier to use at the moment is console:

```console
foo@bar:~$ whoami
foo
```

GitHub Markdown preview tab screenshot

Setting SMTP details for php mail () function

Under Windows only: You may try to use ini_set() functionDocs for the SMTPDocs and smtp_portDocs settings:

ini_set('SMTP', 'mysmtphost'); 
ini_set('smtp_port', 25); 

Beamer: How to show images as step-by-step images

This is a sample code I used to counter the problem.

\begin{frame}{Topic 1}
Topic of the figures
\begin{figure}
\captionsetup[subfloat]{position=top,labelformat=empty}
\only<1>{\subfloat[Fig. 1]{\includegraphics{figure1.jpg}}}
\only<2>{\subfloat[Fig. 2]{\includegraphics{figure2.jpg}}}
\only<3>{\subfloat[Fig. 3]{\includegraphics{figure3.jpg}}}
\end{figure}
\end{frame}

Rotating a point about another point (2D)

First subtract the pivot point (cx,cy), then rotate it, then add the point again.

Untested:

POINT rotate_point(float cx,float cy,float angle,POINT p)
{
  float s = sin(angle);
  float c = cos(angle);

  // translate point back to origin:
  p.x -= cx;
  p.y -= cy;

  // rotate point
  float xnew = p.x * c - p.y * s;
  float ynew = p.x * s + p.y * c;

  // translate point back:
  p.x = xnew + cx;
  p.y = ynew + cy;
  return p;
}

Creating email templates with Django

I like using this tool to permit easily to send email HTML and TXT with easy context processing: https://github.com/divio/django-emailit

How to create .ipa file using Xcode?

Here is the steps I followed to export the .ipa

  • Validate the archive
  • Click on on distribute the app
  • Click the distribution method
  • Choose the export in the next screen (The screen shown only if the archive is validated)

How to edit a text file in my terminal

Try this command:

sudo gedit helloWorld.txt

it, will open up a text editor to edit your file.

OR

sudo nano helloWorld.txt

Here, you can edit your file in the terminal window.

Conversion from 12 hours time to 24 hours time in java

java.time

In Java 8 and later it could be done in one line using class java.time.LocalTime.

In the formatting pattern, lowercase hh means 12-hour clock while uppercase HH means 24-hour clock.

Code example:

String result =                                       // Text representing the value of our date-time object.
    LocalTime.parse(                                  // Class representing a time-of-day value without a date and without a time zone.
        "03:30 PM" ,                                  // Your `String` input text.
        DateTimeFormatter.ofPattern(                  // Define a formatting pattern to match your input text.
            "hh:mm a" ,
            Locale.US                                 // `Locale` determines the human language and cultural norms used in localization. Needed here to translate the `AM` & `PM` value.
        )                                             // Returns a `DateTimeFormatter` object.
    )                                                 // Return a `LocalTime` object.
    .format( DateTimeFormatter.ofPattern("HH:mm") )   // Generate text in a specific format. Returns a `String` object.
;

See this code run live at IdeOne.com.

15:30

See Oracle Tutorial.

postgreSQL - psql \i : how to execute script in a given path

Have you tried using Unix style slashes (/ instead of \)?

\ is often an escape or command character, and may be the source of confusion. I have never had issues with this, but I also do not have Windows, so I cannot test it.

Additionally, the permissions may be based on the user running psql, or maybe the user executing the postmaster service, check that both have read to that file in that directory.

Installation of VB6 on Windows 7 / 8 / 10

I've installed and use VB6 for legacy projects many times on Windows 7.

What I have done and never came across any issues, is to install VB6, ignore the errors and then proceed to install the latest service pack, currently SP6.

Download here: http://www.microsoft.com/en-us/download/details.aspx?id=5721

Bonus: Also once you install it and realize that scrolling doesn't work, use the below: http://www.joebott.com/vb6scrollwheel.htm

import .css file into .less file

If you want your CSS to be copied into the output without being processed, you can use the (inline) directive. e.g.,

@import (inline) '../timepicker/jquery.ui.timepicker.css';

How to set 24-hours format for date on java?

You can do it like this:

Date d=new Date(new Date().getTime()+28800000);
String s=new SimpleDateFormat("dd/MM/yyyy kk:mm:ss").format(d);

here 'kk:mm:ss' is right answer, I confused with Oracle database, sorry.

What is __stdcall?

It has to do with how the function is called- basically the order in which things are put on the the stack and who is responsible for cleanup.

Here's the documentation, but it doesn't mean much unless you understand the first part:
http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx

make *** no targets specified and no makefile found. stop

Delete your source tree that was gunzipped or gzipped and extracted to folder and reextract again. Supply your options again

./configure --with-option=/path/etc ...

Then if all libs are present, your make should succeed.

writing to existing workbook using xlwt

I had the same problem. My customer ordered me Python 3.4 script that updates XLS (not XLSX) Excel files.

The 1st package xlrd was installed by "pip install" without problems in my Python home.

The 2nd one xlwt needed to say "pip install xlwt-future" to be compatible.

The 3rd one xlutils has no support for Python 3, but I adapted it a little bit and now it works at least for dummy script:

#!C:\Python343\python
from xlutils.copy import copy # http://pypi.python.org/pypi/xlutils
from xlrd import open_workbook # http://pypi.python.org/pypi/xlrd
from xlwt import easyxf # http://pypi.python.org/pypi/xlwt

file_path = 'C:\Dev\Test_upd.xls'
rb = open_workbook('C:\Dev\Test.xls',formatting_info=True)
r_sheet = rb.sheet_by_index(0) # read only copy to introspect the file
wb = copy(rb) # a writable copy (I can't read values out of this, only write to it)
w_sheet = wb.get_sheet(0) # the sheet to write to within the writable copy
w_sheet.write(1, 1, 'Value')
wb.save(file_path)

I attached the file here: http://ifolder.su/43507580

Write to [email protected] if it got expired.

P.S.: Some functions are not called in the dummy example, so maybe they will need for an adaptation also. Who wants to do it, fix exceptions one-by-one with a google help. It's not a very difficult task, because the package code is small...

What is a file with extension .a?

.a files are created with the ar utility, and they are libraries. To use it with gcc, collect all .a files in a lib/ folder and then link with -L lib/ and -l<name of specific library>.

Collection of all .a files into lib/ is optional. Doing so makes for better looking directories with nice separation of code and libraries, IMHO.

JQuery DatePicker ReadOnly

During initialization you have to set to false the option enableOnReadonly which by default is true.

$('#datepicker').datepicker({
    enableOnReadonly: false
});

Then, you need to make the field readonly

$('#datepicker').prop('readonly', true);

See https://bootstrap-datepicker.readthedocs.io/en/latest/options.html#enableonreadonly

How to sort an ArrayList in Java

Try BeanComparator from Apache Commons.

import org.apache.commons.beanutils.BeanComparator;


BeanComparator fieldComparator = new BeanComparator("fruitName");
Collections.sort(fruits, fieldComparator);

PHP foreach change original array values

In PHP, passing by reference (&) is ... controversial. I recommend not using it unless you know why you need it and test the results.

I would recommend doing the following:

foreach ($fields as $key => $field) {
    if ($field['required'] && strlen($_POST[$field['name']]) <= 0) {
        $fields[$key]['value'] = "Some error";
    }
}

So basically use $field when you need the values, and $fields[$key] when you need to change the data.

Add IIS 7 AppPool Identities as SQL Server Logons

CREATE LOGIN [IIS APPPOOL\MyAppPool] FROM WINDOWS;
CREATE USER MyAppPoolUser FOR LOGIN [IIS APPPOOL\MyAppPool];

How to compile C programming in Windows 7?

MinGW uses a fairly old version of GCC (3.4.5, I believe), and hasn't been updated in a while. If you're already comfortable with the GCC toolset and just looking to get your feet wet in Windows programming, this may be a good option for you. There are lots of great IDEs available that use this compiler.

Edit: Apparently I was wrong; that's what I get for talking about something I know very little about. Tauran points out that there is a project that aims to provide the MinGW toolkit with the current version of GCC. You can download it from their website.


However, I'm not sure that I can recommend it for serious Windows development. If you're not a idealistic fanboy who can't stomach the notion of ever using Microsoft software, I highly recommend investigating Visual Studio, which comes bundled with Microsoft's C/C++ compiler. The Express version (which includes the same compiler as all the paid-for editions) is absolutely free for download. In addition to the compiler, Visual Studio also provides a world-class IDE that makes developing Windows-specific applications much easier. Yes, detractors will ramble on about the fact that it's not fully standards-compliant, but such is the world of writing Windows applications. They're never going to be truly portable once you include windows.h, so most of the idealistic dedication just ends up being a waste of time.

ConfigurationManager.AppSettings - How to modify and save?

I know I'm late :) But this how i do it:

public static void AddOrUpdateAppSettings(string key, string value)
{
    try
    {
        var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var settings = configFile.AppSettings.Settings;
        if (settings[key] == null)
        {
            settings.Add(key, value);
        }
        else
        {
            settings[key].Value = value;
        }
        configFile.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
    }
    catch (ConfigurationErrorsException)
    {
        Console.WriteLine("Error writing app settings");
    }
}

For more information look at MSDN

Adding multiple class using ng-class

To apply different classes when different expressions evaluate to true:

<div ng-class="{class1 : expression1, class2 : expression2}">
    Hello World!
</div>

To apply multiple classes when an expression holds true:

<!-- notice expression1 used twice -->
<div ng-class="{class1 : expression1, class2 : expression1}">
    Hello World!
</div>

or quite simply:

<div ng-class="{'class1 class2' : expression1}">
    Hello World!
</div>

Notice the single quotes surrounding css classes.

How do I use a third-party DLL file in Visual Studio C++?

As everyone else says, LoadLibrary is the hard way to do it, and is hardly ever necessary.

The DLL should have come with a .lib file for linking, and one or more header files to #include into your sources. The header files will define the classes and function prototypes that you can use from the DLL. You will need this even if you use LoadLibrary.

To link with the library, you might have to add the .lib file to the project configuration under Linker/Input/Additional Dependencies.

Regular expression for exact match of a string

You may also try appending a space at the start and end of keyword: /\s+123456\s+/i.

Variable name as a string in Javascript

Probably pop would be better than indexing with [0], for safety (variable might be null).

const myFirstName = 'John'
const variableName = Object.keys({myFirstName}).pop();
console.log(`Variable ${variableName} with value '${variable}'`);

// returns "Variable myFirstName with value 'John'"

Make xargs handle filenames that contain spaces

xargs on MacOS doesn't have -d option, so this solution uses -0 instead.

Get ls to output one file per line, then translate newlines into nulls and tell xargs to use nulls as the delimiter:

ls -1 *mp3 | tr "\n" "\0" | xargs -0 mplayer

Copy/Paste from Excel to a web page

The same idea as Tatu(thanks I'll need it soon in our project), but with a regular expression.
Which may be quicker for large dataset.

<html>
<head>
    <title>excelToTable</title>
    <script src="../libs/jquery.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
    <textarea>a1    a2  a3
b1  b2  b3</textarea>
    <div></div>
    <input type="button" onclick="convert()" value="convert"/>
    <script>
        function convert(){
            var xl = $('textarea').val();
            $('div').html( 
                '<table><tr><td>' + 
                xl.replace(/\n+$/i, '').replace(/\n/g, '</tr><tr><td>').replace(/\t/g, '</td><td>') + 
                '</tr></table>'
            )
        }
    </script>
</body>
</html>

Change a Django form field to a hidden field

This may also be useful: {{ form.field.as_hidden }}

Anaconda / Python: Change Anaconda Prompt User Path

In Windows, if you have the shortcut in your taskbar, right-click the "Anaconda Prompt" icon, you'll see:

  • Anaconda Prompt
  • Unpin from taskbar (if pinned)
  • Close window

Right-click on "Anaconda Prompt" again.

Click "Properties"

Add the path you want your anaconda prompt to open up into in the "Start In:" section.

Note - you can also do this by searching for "Anaconda Prompt" in the Start Menu. The directions above are specifically for the shortcut.

How should the ViewModel close the form?

Here's what I initially did, which does work, however it seems rather long-winded and ugly (global static anything is never good)

1: App.xaml.cs

public partial class App : Application
{
    // create a new global custom WPF Command
    public static readonly RoutedUICommand LoggedIn = new RoutedUICommand();
}

2: LoginForm.xaml

// bind the global command to a local eventhandler
<CommandBinding Command="client:App.LoggedIn" Executed="OnLoggedIn" />

3: LoginForm.xaml.cs

// implement the local eventhandler in codebehind
private void OnLoggedIn( object sender, ExecutedRoutedEventArgs e )
{
    DialogResult = true;
    Close();
}

4: LoginFormViewModel.cs

// fire the global command from the viewmodel
private void OnRemoteServerReturnedSuccess()
{
    App.LoggedIn.Execute(this, null);
}

I later on then removed all this code, and just had the LoginFormViewModel call the Close method on it's view. It ended up being much nicer and easier to follow. IMHO the point of patterns is to give people an easier way to understand what your app is doing, and in this case, MVVM was making it far harder to understand than if I hadn't used it, and was now an anti-pattern.

Maven Java EE Configuration Marker with Java Server Faces 1.2

I had the same problem. After adding velocity dependencies in my maven project i was getting the same error in marker tab. Then I noticed that the web.xml file that maven project creates has servlet2.3 schema. When i changed it to servlet 3.0 schema and save the project then this error gone. Here is the web.xml file that maven creates

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>
</web-app>

Change it to

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
                        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
                        version="3.0">
    <display-name>Archetype Created Web Application</display-name>

</web-app>

save the project, and your error would gone.

After that if markers tab is still showing message then Select the project. Do mouse right click. Select Maven --> Update Project.

Hopefully error would be gone then.

Thanks

Getting the class name from a static method in Java

So, we have a situation when we need to statically get class object or a class full/simple name without an explicit usage of MyClass.class syntax.

It can be really handy in some cases, e.g. logger instance for the upper-level functions (in this case kotlin creates a static Java class not accessible from the kotlin code).

We have a few different variants for getting this info:

  1. new Object(){}.getClass().getEnclosingClass();
    noted by Tom Hawtin - tackline

  2. getClassContext()[0].getName(); from the SecurityManager
    noted by Christoffer

  3. new Throwable().getStackTrace()[0].getClassName();
    by count ludwig

  4. Thread.currentThread().getStackTrace()[1].getClassName();
    from Keksi

  5. and finally awesome
    MethodHandles.lookup().lookupClass();
    from Rein


I've prepared a benchmark for all variants and results are:

# Run complete. Total time: 00:04:18

Benchmark                                                      Mode  Cnt      Score     Error  Units
StaticClassLookup.MethodHandles_lookup_lookupClass             avgt   30      3.630 ±   0.024  ns/op
StaticClassLookup.AnonymousObject_getClass_enclosingClass      avgt   30    282.486 ±   1.980  ns/op
StaticClassLookup.SecurityManager_classContext_1               avgt   30    680.385 ±  21.665  ns/op
StaticClassLookup.Thread_currentThread_stackTrace_1_className  avgt   30  11179.460 ± 286.293  ns/op
StaticClassLookup.Throwable_stackTrace_0_className             avgt   30  10221.209 ± 176.847  ns/op


Conclusions

  1. Best variant to use, rather clean and monstrously fast.
    Available only since Java 7 and Android API 26!
 MethodHandles.lookup().lookupClass();
  1. In case you need this functionality for Android or Java 6, you can use the second best variant. It's rather fast too, but creates an anonymous class in each place of usage :(
 new Object(){}.getClass().getEnclosingClass();
  1. If you need it in many places and don't want your bytecode to bloat due to tons of anonymous classes – SecurityManager is your friend (third best option).

    But you can't just call getClassContext() – it's protected in the SecurityManager class. You will need some helper class like this:

 // Helper class
 public final class CallerClassGetter extends SecurityManager
 {
    private static final CallerClassGetter INSTANCE = new CallerClassGetter();
    private CallerClassGetter() {}

    public static Class<?> getCallerClass() {
        return INSTANCE.getClassContext()[1];
    }
 }

 // Usage example:
 class FooBar
 {
    static final Logger LOGGER = LoggerFactory.getLogger(CallerClassGetter.getCallerClass())
 }
  1. You probably don't ever need to use last two variants based on the getStackTrace() from exception or the Thread.currentThread(). Very inefficient and can return only the class name as a String, not the Class<*> instance.


P.S.

If you want to create a logger instance for static kotlin utils (like me :), you can use this helper:

import org.slf4j.Logger
import org.slf4j.LoggerFactory

// Should be inlined to get an actual class instead of the one where this helper declared
// Will work only since Java 7 and Android API 26!
@Suppress("NOTHING_TO_INLINE")
inline fun loggerFactoryStatic(): Logger
    = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass())

Usage example:

private val LOGGER = loggerFactoryStatic()

/**
 * Returns a pseudo-random, uniformly distributed value between the
 * given least value (inclusive) and bound (exclusive).
 *
 * @param min the least value returned
 * @param max the upper bound (exclusive)
 *
 * @return the next value
 * @throws IllegalArgumentException if least greater than or equal to bound
 * @see java.util.concurrent.ThreadLocalRandom.nextDouble(double, double)
 */
fun Random.nextDouble(min: Double = .0, max: Double = 1.0): Double {
    if (min >= max) {
        if (min == max) return max
        LOGGER.warn("nextDouble: min $min > max $max")
        return min
    }
    return nextDouble() * (max - min) + min
}

How can I see function arguments in IPython Notebook Server 3?

In 1.0, the functionality was bound to ( and tab and shift-tab, in 2.0 tab was deprecated but still functional in some unambiguous cases completing or inspecting were competing in many cases. Recommendation was to always use shift-Tab. ( was also added as deprecated as confusing in Haskell-like syntax to also push people toward Shift-Tab as it works in more cases. in 3.0 the deprecated bindings have been remove in favor of the official, present for 18+ month now Shift-Tab.

So press Shift-Tab.

How to select id with max date group by category in PostgreSQL?

This is a perfect use-case for DISTINCT ON - a Postgres specific extension of the standard DISTINCT:

SELECT DISTINCT ON (category)
       id  -- , category, date  -- any other column (expression) from the same row
FROM   tbl
ORDER  BY category, date DESC;

Careful with descending sort order. If the column can be NULL, you may want to add NULLS LAST:

DISTINCT ON is simple and fast. Detailed explanation in this related answer:

For big tables with many rows per category consider an alternative approach:

How can I clone an SQL Server database on the same server in SQL Server 2008 Express?

Using MS SQL Server 2012, you need to perform 3 basic steps:

  1. First, generate .sql file containing only the structure of the source DB

    • right click on the source DB and then Tasks then Generate Scripts
    • follow the wizard and save the .sql file locally
  2. Second, replace the source DB with the destination one in the .sql file

    • Right click on the destination file, select New Query and Ctrl-H or (Edit - Find and replace - Quick replace)
  3. Finally, populate with data

    • Right click on the destination DB, then select Tasks and Import Data
    • Data source drop down set to ".net framework data provider for SQL server" + set the connection string text field under DATA ex: Data Source=Mehdi\SQLEXPRESS;Initial Catalog=db_test;User ID=sa;Password=sqlrpwrd15
    • do the same with the destination
    • check the table you want to transfer or check box besides "source: ..." to check all of them

You are done.

programming a servo thru a barometer

You could define a mapping of air pressure to servo angle, for example:

def calc_angle(pressure, min_p=1000, max_p=1200):     return 360 * ((pressure - min_p) / float(max_p - min_p))  angle = calc_angle(pressure) 

This will linearly convert pressure values between min_p and max_p to angles between 0 and 360 (you could include min_a and max_a to constrain the angle, too).

To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:

d = {1000:0, 1001: 1.8, ...}  angle = d[pressure] 

but this would be rather time-consuming to type out!

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

Did you try:

<Directory /path/to/your/wp-admin>
Order allow,deny
Allow from all
</Directory>

What is the "continue" keyword and how does it work in Java?

Generally, I see continue (and break) as a warning that the code might use some refactoring, especially if the while or for loop declaration isn't immediately in sight. The same is true for return in the middle of a method, but for a slightly different reason.

As others have already said, continue moves along to the next iteration of the loop, while break moves out of the enclosing loop.

These can be maintenance timebombs because there is no immediate link between the continue/break and the loop it is continuing/breaking other than context; add an inner loop or move the "guts" of the loop into a separate method and you have a hidden effect of the continue/break failing.

IMHO, it's best to use them as a measure of last resort, and then to make sure their use is grouped together tightly at the start or end of the loop so that the next developer can see the "bounds" of the loop in one screen.

continue, break, and return (other than the One True Return at the end of your method) all fall into the general category of "hidden GOTOs". They place loop and function control in unexpected places, which then eventually causes bugs.

What's the best way to center your HTML email content in the browser window (or email client preview pane)?

Align the table to center.

<table width="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
        <td align="center">
            Your Content
        </td>
    </tr>
</table>

Where you have "your content" if it is a table, set it to the desired width and you will have centred content.

HTML Image not displaying, while the src url works

The simple solution is:

1.keep the image file and HTML file in the same folder.

2.code: <img src="Desert.png">// your image name.

3.keep the folder in D drive.

Keeping the folder on the desktop(which is c drive) you can face the issue of permission.

How can I find last row that contains data in a specific column?

You should use the .End(xlup) but instead of using 65536 you might want to use:

sheetvar.Rows.Count

That way it works for Excel 2007 which I believe has more than 65536 rows

How to convert a Java 8 Stream to an Array?

you can use the collector like this

  Stream<String> io = Stream.of("foo" , "lan" , "mql");
  io.collect(Collectors.toCollection(ArrayList<String>::new));

Print a variable in hexadecimal in Python

Convert the string to an integer base 16 then to hexadecimal.

print hex(int(string, base=16))

These are built-in functions.

http://docs.python.org/2/library/functions.html#int

Example

>>> string = 'AA'
>>> _int = int(string, base=16)
>>> _hex = hex(_int)
>>> print _int
170
>>> print _hex
0xaa
>>> 

php multidimensional array get values

This is the way to iterate on this array:

foreach($hotels as $row) {
       foreach($row['rooms'] as $k) {
             echo $k['boards']['board_id'];
             echo $k['boards']['price'];
       }
}

You want to iterate on the hotels and the rooms (the ones with numeric indexes), because those seem to be the "collections" in this case. The other arrays only hold and group properties.

How to deserialize xml to object

The comments above are correct. You're missing the decorators. If you want a generic deserializer you can use this.

public static T DeserializeXMLFileToObject<T>(string XmlFilename)
{
    T returnObject = default(T);
    if (string.IsNullOrEmpty(XmlFilename)) return default(T);

    try
    {
        StreamReader xmlStream = new StreamReader(XmlFilename);
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        returnObject = (T)serializer.Deserialize(xmlStream);
    }
    catch (Exception ex)
    {
        ExceptionLogger.WriteExceptionToConsole(ex, DateTime.Now);
    }
    return returnObject;
}

Then you'd call it like this:

MyObjType MyObj = DeserializeXMLFileToObject<MyObjType>(FilePath);

Send a base64 image in HTML email

Support, unfortunately, is brutal at best. Here's a post on the topic:

https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/

And the post content: enter image description here

Class name does not name a type in C++

The problem is that you need to include B.h in your A.h file. The problem is that in the definition of A, the compiler still doesn't know what B is. You should include all the definitions of all the types you are using.

What's the equivalent of Java's Thread.sleep() in JavaScript?

You can either write a spin loop (a loop that just loops for a long period of time performing some sort of computation to delay the function) or use:

setTimeout("Func1()", 3000);

This will call 'Func1()' after 3 seconds.

Edit:

Credit goes to the commenters, but you can pass anonymous functions to setTimeout.

setTimeout(function() {
   //Do some stuff here
}, 3000);

This is much more efficient and does not invoke javascript's eval function.

SQL query for extracting year from a date

just pass the columnName as parameter of YEAR

SELECT YEAR(ASOFDATE) from PSASOFDATE;

another is to use DATE_FORMAT

SELECT DATE_FORMAT(ASOFDATE, '%Y') from PSASOFDATE;

UPDATE 1

I bet the value is varchar with the format MM/dd/YYYY, it that's the case,

SELECT YEAR(STR_TO_DATE('11/15/2012', '%m/%d/%Y'));

LAST RESORT if all the queries fail

use SUBSTRING

SELECT SUBSTRING('11/15/2012', 7, 4)

How to allow <input type="file"> to accept only image files?

i know i'm late but this might help. you can add specific type of image or other file type and do validation in your code :

<input style="margin-left: 10px; margin-top: 5px;" type="file" accept="image/x-png,image/jpeg,application/pdf" (change)="handleFileInput($event,'creditRatingFile')" name="creditRatingFile" id="creditRatingFile">

      handleFileInput(event) {
    console.log(event);
    const file = event.target.files[0];
    if (file.size > 2097152) {
        throw err;
    } else if (
      file.type !== "application/pdf"  &&
      file.type !== "application/wps-office.pdf"   && 
      file.type !== 'application/pdf'  && file.type !== 'image/jpg'  && file.type !== 'image/jpeg'  && file.type !== "image/png"
    ) {
throw err;
    } else {
      
        console.log('file valid')
    }
  }

How to output to the console in C++/Windows

You don't necessarily need to make any changes to your code (nor to change the SUBSYSTEM type). If you wish, you also could simply pipe stdout and stderr to a console application (a Windows version of cat works well).

How do I install Python libraries in wheel format?

Simple steps to install python in Ubuntu:

  1. Download Python

    $ cd /usr/src 
    $ wget  https://www.python.org/ftp/python/3.6.0/Python-3.6.0.tgz
    
  2. Extract the downloaded package

    $ sudo tar xzf Python-3.6.0.tgz
    
  3. Compile Python source

    $ cd Python-3.6.0
    $ sudo ./configure
    $ sudo make altinstall 
    

    Note make altinstall is used to prevent replacing the default python binary file /usr/bin/python.

  4. check the python version

    # python3.6 -V
    

Finding the indices of matching elements in list in Python

You are using .index() which will only find the first occurrence of your value in the list. So if you have a value 1.0 at index 2, and at index 9, then .index(1.0) will always return 2, no matter how many times 1.0 occurs in the list.

Use enumerate() to add indices to your loop instead:

def find(lst, a, b):
    result = []
    for i, x in enumerate(lst):
        if x<a or x>b:
            result.append(i)
    return result

You can collapse this into a list comprehension:

def find(lst, a, b):
    return [i for i, x in enumerate(lst) if x<a or x>b]

Reading binary file and looping over each byte

After trying all the above and using the answer from @Aaron Hall, I was getting memory errors for a ~90 Mb file on a computer running Window 10, 8 Gb RAM and Python 3.5 32-bit. I was recommended by a colleague to use numpy instead and it works wonders.

By far, the fastest to read an entire binary file (that I have tested) is:

import numpy as np

file = "binary_file.bin"
data = np.fromfile(file, 'u1')

Reference

Multitudes faster than any other methods so far. Hope it helps someone!

EF Core add-migration Build Failed

Try these steps:

  1. Clean the solution.

  2. Build every project separately.

  3. Resolve any errors if found (sometimes, VS is not showing errors until you build it separately).

  4. Then try to run migration again.

How to stop mongo DB in one command

in the terminal window on your mac, press control+c

"%%" and "%/%" for the remainder and the quotient

In R, you can assign your own operators using %[characters]%. A trivial example:

'%p%' <- function(x, y){x^2 + y}

2 %p% 3 # result: 7

While I agree with BlueTrin that %% is pretty standard, I have a suspicion %/% may have something to do with the sort of operator definitions I showed above - perhaps it was easier to implement, and makes sense: %/% means do a special sort of division (integer division)

Convert array values from string to int?

Keep it simple...

$intArray = array ();
$strArray = explode(',', $string);
foreach ($strArray as $value)
$intArray [] = intval ($value);

Why are you looking for other ways? Looping does the job without pain. If performance is your concern, you can go with json_decode (). People have posted how to use that, so I am not including it here.

Note: When using == operator instead of === , your string values are automatically converted into numbers (e.g. integer or double) if they form a valid number without quotes. For example:

$str = '1';
($str == 1) // true but
($str === 1) //false

Thus, == may solve your problem, is efficient, but will break if you use === in comparisons.

Why did I get the compile error "Use of unassigned local variable"?

IEnumerable<DateTime?> _getCurrentHolidayList; //this will not initailize

Assign value(_getCurrentHolidayList) inside the loop

foreach (HolidaySummaryList _holidayItem in _holidayDetailsList)
{
                            if (_holidayItem.CountryId == Countryid)
                                _getCurrentHolidayList = _holidayItem.Holiday;                                                   
}

After your are passing the local varibale to another method like below. It throw error(use of unassigned variable). eventhough nullable mentioned in time of decalration.

var cancelRescheduleCondition = GetHolidayDays(_item.ServiceDateFrom, _getCurrentHolidayList);

if you mentioned like below, It will not throw any error.

IEnumerable<DateTime?> _getCurrentHolidayList =null;

What is the difference between server side cookie and client side cookie?

HTTP COOKIES

Cookies are key/value pairs used by websites to store state information on the browser. Say you have a website (example.com), when the browser requests a webpage the website can send cookies to store information on the browser.

Browser request example:

GET /index.html HTTP/1.1
Host: www.example.com

Example answer from the server:

HTTP/1.1 200 OK
Content-type: text/html
Set-Cookie: foo=10
Set-Cookie: bar=20; Expires=Fri, 30 Sep 2011 11:48:00 GMT
... rest  of the response

Here two cookies foo=10 and bar=20 are stored on the browser. The second one will expire on 30 September. In each subsequent request the browser will send the cookies back to the server.

GET /spec.html HTTP/1.1
Host: www.example.com
Cookie: foo=10; bar=20
Accept: */*

SESSIONS: Server side cookies

Server side cookies are known as "sessions". The website in this case stores a single cookie on the browser containing a unique Session Identifier. Status information (foo=10 and bar=20 above) are stored on the server and the Session Identifier is used to match the request with the data stored on the server.

Examples of usage

You can use both sessions and cookies to store: authentication data, user preferences, the content of a chart in an e-commerce website, etc...

Pros and Cons

Below pros and cons of the solutions. These are the first that comes to my mind, there are surely others.

Cookie Pros:

  • scalability: all the data is stored in the browser so each request can go through a load balancer to different webservers and you have all the information needed to fullfill the request;
  • they can be accessed via javascript on the browser;
  • not being on the server they will survive server restarts;
  • RESTful: requests don't depend on server state

Cookie Cons:

Session Pros:

  • generally easier to use, in PHP there's probably not much difference.
  • unlimited storage

Session Cons:

  • more difficult to scale
  • on web server restarts you can lose all sessions or not depending on the implementation
  • not RESTful

Add timestamp column with default NOW() for new rows only

For example, I will create a table called users as below and give a column named date a default value NOW()

create table users_parent (
    user_id     varchar(50),
    full_name   varchar(240),
    login_id_1  varchar(50),
    date        timestamp NOT NULL DEFAULT NOW()
);

Thanks

How to disable the ability to select in a DataGridView?

you have to create a custom DataGridView

`

namespace System.Windows.Forms
{
    class MyDataGridView : DataGridView
    {
        public bool PreventUserClick = false;

        public MyDataGridView()
        {

        }
        protected override void OnMouseDown(MouseEventArgs e)
        {
            if (PreventUserClick) return;

            base.OnMouseDown(e);
        }
    }
}

` note that you have to first compile the program once with the added class, before you can use the new control.

then go to The .Designer.cs and change the old DataGridView to the new one without having to mess up you previous code.

private System.Windows.Forms.DataGridView dgv; // found close to the bottom

private void InitializeComponent() {
    ...
    this.dgv = new System.Windows.Forms.DataGridView();
    ...
}

to (respective)

private System.Windows.Forms.MyDataGridView dgv;

this.dgv = new System.Windows.Forms.MyDataGridView();

Wildcard string comparison in Javascript

I think you meant something like "*" (star) as a wildcard for example:

  • "a*b" => everything that starts with "a" and ends with "b"
  • "a*" => everything that starts with "a"
  • "*b" => everything that ends with "b"
  • "*a*" => everything that has an "a" in it
  • "*a*b*"=> everything that has an "a" in it, followed by anything, followed by a "b", followed by anything

or in your example: "bird*" => everything that starts with bird

I had a similar problem and wrote a function with RegExp:

_x000D_
_x000D_
//Short code_x000D_
function matchRuleShort(str, rule) {_x000D_
  var escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");_x000D_
  return new RegExp("^" + rule.split("*").map(escapeRegex).join(".*") + "$").test(str);_x000D_
}_x000D_
_x000D_
//Explanation code_x000D_
function matchRuleExpl(str, rule) {_x000D_
  // for this solution to work on any string, no matter what characters it has_x000D_
  var escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");_x000D_
_x000D_
  // "."  => Find a single character, except newline or line terminator_x000D_
  // ".*" => Matches any string that contains zero or more characters_x000D_
  rule = rule.split("*").map(escapeRegex).join(".*");_x000D_
_x000D_
  // "^"  => Matches any string with the following at the beginning of it_x000D_
  // "$"  => Matches any string with that in front at the end of it_x000D_
  rule = "^" + rule + "$"_x000D_
_x000D_
  //Create a regular expression object for matching string_x000D_
  var regex = new RegExp(rule);_x000D_
_x000D_
  //Returns true if it finds a match, otherwise it returns false_x000D_
  return regex.test(str);_x000D_
}_x000D_
_x000D_
//Examples_x000D_
alert(_x000D_
    "1. " + matchRuleShort("bird123", "bird*") + "\n" +_x000D_
    "2. " + matchRuleShort("123bird", "*bird") + "\n" +_x000D_
    "3. " + matchRuleShort("123bird123", "*bird*") + "\n" +_x000D_
    "4. " + matchRuleShort("bird123bird", "bird*bird") + "\n" +_x000D_
    "5. " + matchRuleShort("123bird123bird123", "*bird*bird*") + "\n" +_x000D_
    "6. " + matchRuleShort("s[pe]c 3 re$ex 6 cha^rs", "s[pe]c*re$ex*cha^rs") + "\n" +_x000D_
    "7. " + matchRuleShort("should not match", "should noo*oot match") + "\n"_x000D_
);
_x000D_
_x000D_
_x000D_


If you want to read more about the used functions:

img onclick call to JavaScript function

This should work(with or without 'javascript:' part):

<img onclick="javascript:exportToForm('1.6','55','10','50','1')" src="China-Flag-256.png" />
<script>
function exportToForm(a, b, c, d, e) {
     alert(a, b);
 }
</script>