Programs & Examples On #Tstringgrid

TStringGrid is VCL grid control designed to manage the handling of strings and associated objects in Delphi and related development tools. It is defined in the Grids.pas (or VCL.Grids.pas starting with Delphi XE2 version) unit.

How to remove certain characters from a string in C++?

I'm new, but some of the answers above are insanely complicated, so here's an alternative.

NOTE: As long as 0-9 are contiguous (which they should be according to the standard), this should filter out all other characters but numbers and ' '. Knowing 0-9 should be contiguous and a char is really an int, we can do the below.

EDIT: I didn't notice the poster wanted spaces too, so I altered it...

#include <cstdio>
#include <cstring>

void numfilter(char * buff, const char * string)
{
  do
  { // According to standard, 0-9 should be contiguous in system int value.
    if ( (*string >= '0' && *string <= '9') || *string == ' ')
      *buff++ = *string;
  } while ( *++string );
  *buff++ = '\0'; // Null terminate
}

int main()
{
  const char *string = "(555) 555-5555";
  char buff[ strlen(string) + 1 ];

  numfilter(buff, string);
  printf("%s\n", buff);

return 0;
}

Below is to filter supplied characters.

#include <cstdio>
#include <cstring>

void cfilter(char * buff, const char * string, const char * toks)
{
  const char * tmp;  // So we can keep toks pointer addr.
  do
  {
    tmp = toks;
    *buff++ = *string; // Assume it's correct and place it.
    do                 // I can't think of a faster way.
    {
      if (*string == *tmp)
      {
        buff--;  // Not correct, pull back and move on.
        break;
      }
    }while (*++tmp);
  }while (*++string);

  *buff++ = '\0';  // Null terminate
}

int main()
{
  char * string = "(555) 555-5555";
  char * toks = "()-";
  char buff[ strlen(string) + 1 ];

  cfilter(buff, string, toks);
  printf("%s\n", buff);

  return 0;
}

Float a div above page content

give z-index:-1 to flash and give z-index:100 to div..

Regex to replace multiple spaces with a single space

I have this method, I call it the Derp method for lack of a better name.

while (str.indexOf("  ") !== -1) {
    str = str.replace(/  /g, " ");
}

Running it in JSPerf gives some surprising results.

How can I catch an error caused by mail()?

PHPMailer handles errors nicely, also a good script to use for sending mail via SMTP...

if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
} else {
  echo "Message sent!";
}

Is it possible to ignore one single specific line with Pylint?

Checkout the files in https://github.com/PyCQA/pylint/tree/master/pylint/checkers. I haven't found a better way to obtain the error name from a message than either Ctrl + F-ing those files or using the GitHub search feature:

If the message is "No name ... in module ...", use the search:

No name %r in module %r repo:PyCQA/pylint/tree/master path:/pylint/checkers

Or, to get fewer results:

"No name %r in module %r" repo:PyCQA/pylint/tree/master path:/pylint/checkers

GitHub will show you:

"E0611": (
    "No name %r in module %r",
    "no-name-in-module",
    "Used when a name cannot be found in a module.",

You can then do:

from collections import Sequence # pylint: disable=no-name-in-module

Compare two List<T> objects for equality, ignoring order

If you don't care about the number of occurrences, I would approach it like this. Using hash sets will give you better performance than simple iteration.

var set1 = new HashSet<MyType>(list1);
var set2 = new HashSet<MyType>(list2);
return set1.SetEquals(set2);

This will require that you have overridden .GetHashCode() and implemented IEquatable<MyType> on MyType.

Match whitespace but not newlines

The below regex would match white spaces but not of a new line character.

(?:(?!\n)\s)

DEMO

If you want to add carriage return also then add \r with the | operator inside the negative lookahead.

(?:(?![\n\r])\s)

DEMO

Add + after the non-capturing group to match one or more white spaces.

(?:(?![\n\r])\s)+

DEMO

I don't know why you people failed to mention the POSIX character class [[:blank:]] which matches any horizontal whitespaces (spaces and tabs). This POSIX chracter class would work on BRE(Basic REgular Expressions), ERE(Extended Regular Expression), PCRE(Perl Compatible Regular Expression).

DEMO

Find Java classes implementing an interface

In full generality, this functionality is impossible. The Java ClassLoader mechanism guarantees only the ability to ask for a class with a specific name (including pacakge), and the ClassLoader can supply a class, or it can state that it does not know that class.

Classes can be (and frequently are) loaded from remote servers, and they can even be constructed on the fly; it is not difficult at all to write a ClassLoader that returns a valid class that implements a given interface for any name you ask from it; a List of the classes that implement that interface would then be infinite in length.

In practice, the most common case is an URLClassLoader that looks for classes in a list of filesystem directories and JAR files. So what you need is to get the URLClassLoader, then iterate through those directories and archives, and for each class file you find in them, request the corresponding Class object and look through the return of its getInterfaces() method.

How do I set cell value to Date and apply default Excel date format?

http://poi.apache.org/spreadsheet/quick-guide.html#CreateDateCells

CellStyle cellStyle = wb.createCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(
    createHelper.createDataFormat().getFormat("m/d/yy h:mm"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);

How to decorate a class?

There's actually a pretty good implementation of a class decorator here:

https://github.com/agiliq/Django-parsley/blob/master/parsley/decorators.py

I actually think this is a pretty interesting implementation. Because it subclasses the class it decorates, it will behave exactly like this class in things like isinstance checks.

It has an added benefit: it's not uncommon for the __init__ statement in a custom django Form to make modifications or additions to self.fields so it's better for changes to self.fields to happen after all of __init__ has run for the class in question.

Very clever.

However, in your class you actually want the decoration to alter the constructor, which I don't think is a good use case for a class decorator.

Printing long int value in C

You must use %ld to print a long int, and %lld to print a long long int.

Note that only long long int is guaranteed to be large enough to store the result of that calculation (or, indeed, the input values you're using).

You will also need to ensure that you use your compiler in a C99-compatible mode (for example, using the -std=gnu99 option to gcc). This is because the long long int type was not introduced until C99; and although many compilers implement long long int in C90 mode as an extension, the constant 2147483648 may have a type of unsigned int or unsigned long in C90. If this is the case in your implementation, then the value of -2147483648 will also have unsigned type and will therefore be positive, and the overall result will be not what you expect.

Linker Error C++ "undefined reference "

Your error shows you are not compiling file with the definition of the insert function. Update your command to include the file which contains the definition of that function and it should work.

Add image to layout in ruby on rails

Anything in the public folder is accessible at the root path (/) so change your img tag to read:

<img src="/images/rss.jpg" alt="rss feed" />

If you wanted to use a rails tag, use this:

<%= image_tag("rss.jpg", :alt => "rss feed") %>

Setting action for back button in navigation controller

The solution I have found so far is not very nice, but it works for me. Taking this answer, I also check whether I'm popping programmatically or not:

- (void)viewWillDisappear:(BOOL)animated {
  [super viewWillDisappear:animated];

  if ((self.isMovingFromParentViewController || self.isBeingDismissed)
      && !self.isPoppingProgrammatically) {
    // Do your stuff here
  }
}

You have to add that property to your controller and set it to YES before popping programmatically:

self.isPoppingProgrammatically = YES;
[self.navigationController popViewControllerAnimated:YES];

Loop through all the resources in a .resx file

Using LINQ to SQL:

XDocument
        .Load(resxFileName)
        .Descendants()
        .Where(_ => _.Name == "data")
        .Select(_ => $"{ _.Attributes().First(a => a.Name == "name").Value} - {_.Value}");

Unsigned values in C

When you initialize unsigned int a to -1; it means that you are storing the 2's complement of -1 into the memory of a.
Which is nothing but 0xffffffff or 4294967295.

Hence when you print it using %x or %u format specifier you get that output.

By specifying signedness of a variable to decide on the minimum and maximum limit of value that can be stored.

Like with unsigned int: the range is from 0 to 4,294,967,295 and int: the range is from -2,147,483,648 to 2,147,483,647

For more info on signedness refer this

How do I write a backslash (\) in a string?

even though this post is quite old I tried something that worked for my case .

I wanted to create a string variable with the value below:

21541_12_1_13\":null

so my approach was like that:

  • build the string using verbatim

    string substring = @"21541_12_1_13\"":null";

  • and then remove the unwanted backslashes using Remove function

    string newsubstring = substring.Remove(13, 1);

Hope that helps. Cheers

List distinct values in a vector in R

Do you mean unique:

R> x = c(1,1,2,3,4,4,4)
R> x
[1] 1 1 2 3 4 4 4
R> unique(x)
[1] 1 2 3 4

Change background color on mouseover and remove it after mouseout

Set the original background-color in you CSS file:

.forum{
    background-color:#f0f;
}?

You don't have to capture the original color in jQuery. Remember that jQuery will alter the style INLINE, so by setting the background-color to null you will get the same result.

$(function() {
    $(".forum").hover(
    function() {
        $(this).css('background-color', '#ff0')
    }, function() {
        $(this).css('background-color', '')
    });
});?

Can I use library that used android support with Androidx projects.

I had a problem like this before, it was the gradle.properties file doesn't exist, only the gradle.properties.txt , so i went to my project folder and i copied & pasted the gradle.properties.txt file but without .txt extension then it finally worked.

phpmysql error - #1273 - #1273 - Unknown collation: 'utf8mb4_general_ci'

You can fix this issue by deleting browser cookie from the begining of time. I have tried this and it is working fine for me.

To delete only cookies:

  1. hold down ctrl+shift+delete
  2. remove all check boxes except for cookies of course
  3. use the drop down on top to select "from the beginning of time
  4. click clear browsing data

How do I remove my IntelliJ license in 2019.3?

For Windows : Using batch program.

Write this code in a text file and save it.

REM Delete eval folder with licence key and options.xml which contains a reference  to it
for %%I in ("WebStorm", "IntelliJ", "CLion", "Rider", "GoLand", "PhpStorm") do (
  for /d %%a in ("%USERPROFILE%\.%%I*") do (
    rd /s /q "%%a/config/eval"
    del /q "%%a\config\options\other.xml"
  )
)

REM Delete registry key and jetbrains folder (not sure if needet but however)
rmdir /s /q "%APPDATA%\JetBrains"
reg delete "HKEY_CURRENT_USER\Software\JavaSoft" /f

Now rename the file fileName.txt to fileName.bat

Close phpstorm if running. Disconnect internet. Then run the file. Open phpstorm again. If nothing goes wrong you will see the magic.

worst case : If phpstorm still shows "License Expired", at first uninstall and then apply the above technique.

Changing .gitconfig location on Windows

If you are on windows and having problem either changing environment variables or mklink because of insufficient privileges, an easy solution to your problem is to start git batch in another location.

Just right click on Git Bash.exe, click properties and change the "Start in" property to c:\my_configuration_files\.

Get value of multiselect box using jQuery or pure JS

According to the widget's page, it should be:

var myDropDownListValues = $("#myDropDownList").multiselect("getChecked").map(function()
{
    return this.value;    
}).get();

It works for me :)

In C#, how to check if a TCP port is available?

    public static bool TestOpenPort(int Port)
    {
        var tcpListener = default(TcpListener);

        try
        {
            var ipAddress = Dns.GetHostEntry("localhost").AddressList[0];

            tcpListener = new TcpListener(ipAddress, Port);
            tcpListener.Start();

            return true;
        }
        catch (SocketException)
        {
        }
        finally
        {
            if (tcpListener != null)
                tcpListener.Stop();
        }

        return false;
    }

How to determine SSL cert expiration date from a PEM encoded certificate?

Same as accepted answer, But note that it works even with .crt file and not just .pem file, just in case if you are not able to find .pem file location.

openssl x509 -enddate -noout -in e71c8ea7fa97ad6c.crt

Result:

notAfter=Mar 29 06:15:00 2020 GMT

How to forward declare a template class in namespace std?

there is a limited alternative you can use

header:

class std_int_vector;

class A{
    std_int_vector* vector;
public:
    A();
    virtual ~A();
};

cpp:

#include "header.h"
#include <vector>
class std_int_vector: public std::vectror<int> {}

A::A() : vector(new std_int_vector()) {}
[...]

not tested in real programs, so expect it to be non-perfect.

PHP Remove elements from associative array

I kinda disagree with the accepted answer. Sometimes an application architecture doesn't want you to mess with the array id, or makes it inconvenient. For instance, I use CakePHP quite a lot, and a database query returns the primary key as a value in each record, very similar to the above.

Assuming the array is not stupidly large, I would use array_filter. This will create a copy of the array, minus the records you want to remove, which you can assign back to the original array variable.

Although this may seem inefficient it's actually very much in vogue these days to have variables be immutable, and the fact that most php array functions return a new array rather than futzing with the original implies that PHP kinda wants you to do this too. And the more you work with arrays, and realize how difficult and annoying the unset() function is, this approach makes a lot of sense.

Anyway:

$my_array = array_filter($my_array, 
                         function($el) { 
                            return $el["value"]!="Completed" && $el!["value"]!="Marked as Spam"; 
                         });

You can use whatever inclusion logic (eg. your id field) in the embedded function that you want.

UIView Infinite 360 degree rotation animation?

Nate's answer above is ideal for stop and start animation and gives a better control. I was intrigued why yours didn't work and his does. I wanted to share my findings here and a simpler version of the code that would animate a UIView continuously without stalling.

This is the code I used,

- (void)rotateImageView
{
    [UIView animateWithDuration:1 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        [self.imageView setTransform:CGAffineTransformRotate(self.imageView.transform, M_PI_2)];
    }completion:^(BOOL finished){
        if (finished) {
            [self rotateImageView];
        }
    }];
}

I used 'CGAffineTransformRotate' instead of 'CGAffineTransformMakeRotation' because the former returns the result which is saved as the animation proceeds. This will prevent the jumping or resetting of the view during the animation.

Another thing is not to use 'UIViewAnimationOptionRepeat' because at the end of the animation before it starts repeating, it resets the transform making the view jump back to its original position. Instead of a repeat, you recurse so that the transform is never reset to the original value because the animation block virtually never ends.

And the last thing is, you have to transform the view in steps of 90 degrees (M_PI / 2) instead of 360 or 180 degrees (2*M_PI or M_PI). Because transformation occurs as a matrix multiplication of sine and cosine values.

t' =  [ cos(angle) sin(angle) -sin(angle) cos(angle) 0 0 ] * t

So, say if you use 180-degree transformation, the cosine of 180 yields -1 making the view transform in opposite direction each time (Note-Nate's answer will also have this issue if you change the radian value of transformation to M_PI). A 360-degree transformation is simply asking the view to remain where it was, hence you don't see any rotation at all.

Two Decimal places using c#

here is another approach

decimal decimalRounded = Decimal.Parse(Debitvalue.ToString("0.00"));

Swap DIV position with CSS only

This solution worked for me:

Using a parent element like:

.parent-div {
    display:flex;
    flex-direction: column-reverse;
}

In my case I didn't have to change the css of the elements that I needed to switch.

Is there an addHeaderView equivalent for RecyclerView?

Native API doesn't have such "addHeader" feature, but has the concept of "addItem".

I was able to include this specific feature of headers and extends for footers as well in my FlexibleAdapter project. I called it Scrollable Headers and Footers.

Here how they work:

Scrollable Headers and Footers are special items that scroll along with all others, but they don't belongs to main items (business items) and they are always handled by the adapter beside the main items. Those items are persistently located at the first and last positions.

enter image description here

There's a lot to say about them, better to read the detailed wiki page.

Moreover the FlexibleAdapter allows you to create headers/sections, also you can have them sticky and tens of others features like expandable items, endless scroll, UI extensions etc... all in one library!

Is there any standard for JSON API response format?

For those coming later, in addition to the accepted answer that includes HAL, JSend, and JSON API, I would add a few other specifications worth looking into:

  • JSON-LD, which is a W3C Recommendation and specifies how to build interoperable Web Services in JSON
  • Ion Hypermedia Type for REST, which claims itself as a "a simple and intuitive JSON-based hypermedia type for REST"

remove objects from array by object property

Check this out using Set and ES6 filter.

  let result = arrayOfObjects.filter( el => (-1 == listToDelete.indexOf(el.id)) );
  console.log(result);

Here is JsFiddle: https://jsfiddle.net/jsq0a0p1/1/

Line Break in XML?

If you use CDATA, you could embed the line breaks directly into the XML I think. Example:

<song>
    <title>Song Title</title>
    <lyric><![CDATA[Line 1
Line 2
Line 3]]></lyric>
</song>

How to show shadow around the linearlayout in Android?

Well, this is easy to achieve .

Just build a GradientDrawable that comes from black and goes to a transparent color, than use parent relationship to place your shape close to the View that you want to have a shadow, then you just have to give any values to height or width .

Here is an example, this file have to be created inside res/drawable , I name it as shadow.xml :

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <gradient
        android:startColor="#9444"
        android:endColor="#0000"
        android:type="linear"
        android:angle="90"> <!-- Change this value to have the correct shadow angle, must be multiple from 45 -->
    </gradient>

</shape>

Place the following code above from a LinearLayout , for example, set the android:layout_width and android:layout_height to fill_parent and 2.3dp, you'll have a nice shadow effect on your LinearLayout .

<View
    android:id="@+id/shadow"
    android:layout_width="fill_parent"
    android:layout_height="2.3dp"  
    android:layout_above="@+id/id_from_your_LinearLayout" 
    android:background="@drawable/shadow">
</View>

Note 1: If you increase android:layout_height more shadow will be shown .

Note 2: Use android:layout_above="@+id/id_from_your_LinearLayout" attribute if you are placing this code inside a RelativeLayout, otherwise ignore it.

Hope it help someone.

MySQL delete multiple rows in one query conditions unique to each row

You were very close, you can use this:

DELETE FROM table WHERE (col1,col2) IN ((1,2),(3,4),(5,6))

Please see this fiddle.

PHP random string generator

PHP 7+ Generate cryptographically secure random bytes using random_bytes function.

$bytes = random_bytes(16);
echo bin2hex($bytes);

Possible output

da821217e61e33ed4b2dd96f8439056c


PHP 5.3+ Generate pseudo-random bytes using openssl_random_pseudo_bytes function.

$bytes = openssl_random_pseudo_bytes(16);
echo bin2hex($bytes);

Possible output

e2d1254506fbb6cd842cd640333214ad


The best use case could be

function getRandomBytes($length = 16)
{
    if (function_exists('random_bytes')) {
        $bytes = random_bytes($length / 2);
    } else {
        $bytes = openssl_random_pseudo_bytes($length / 2);
    }
    return bin2hex($bytes);
}
echo getRandomBytes();

Possible output

ba8cc342bdf91143

android - save image into gallery

 String filePath="/storage/emulated/0/DCIM"+app_name;
    File dir=new File(filePath);
    if(!dir.exists()){
        dir.mkdir();
    }

This code is in onCreate method.This code is for creating a directory of app_name. Now,this directory can be accessed using default file manager app in android. Use this string filePath wherever required to set your destination folder. I am sure this method works on Android 7 too because I tested on it.Hence,it can work on other versions of android too.

How do I delete everything below row X in VBA/Excel?

Any Reference to 'Row' should use 'long' not 'integer' else it will overflow if the spreadsheet has a lot of data.

How to focus on a form input text field on page load using jQuery?

Why is everybody using jQuery for something simple as this.

<body OnLoad="document.myform.mytextfield.focus();">

How to start nginx via different port(other than 80)

Follow this: Open your config file

vi /etc/nginx/conf.d/default.conf

Change port number on which you are listening;

listen       81;
server_name  localhost;

Add a rule to iptables

 vi /etc/sysconfig/iptables 
-A INPUT -m state --state NEW -m tcp -p tcp --dport 81 -j ACCEPT

Restart IPtables

 service iptables restart;

Restart the nginx server

service nginx restart

Access yr nginx server files on port 81

jQuery - Trigger event when an element is removed from the DOM

This.

$.each(
  $('#some-element'), 
        function(i, item){
            item.addEventListener('DOMNodeRemovedFromDocument',
                function(e){ console.log('I has been removed'); console.log(e);
                })
         })

Comparing two arrays & get the values which are not common

Try:

$a1=@(1,2,3,4,5)
$b1=@(1,2,3,4,5,6)
(Compare-Object $a1 $b1).InputObject

Or, you can use:

(Compare-Object $b1 $a1).InputObject

The order doesn't matter.

Checking if a number is an Integer in Java

One example more :)

double a = 1.00

if(floor(a) == a) {
   // a is an integer
} else {
   //a is not an integer.
}

In this example, ceil can be used and have the exact same effect.

Play local (hard-drive) video file with HTML5 video tag?

That will be possible only if the HTML file is also loaded with the file protocol from the local user's harddisk.

If the HTML page is served by HTTP from a server, you can't access any local files by specifying them in a src attribute with the file:// protocol as that would mean you could access any file on the users computer without the user knowing which would be a huge security risk.

As Dimitar Bonev said, you can access a file if the user selects it using a file selector on their own. Without that step, it's forbidden by all browsers for good reasons. Thus, while his answer might prove useful for many people, it loosens the requirement from the code in the original question.

PHP XML how to output nice format

This is a slight variation of the above theme but I'm putting here in case others hit this and cannot make sense of it ...as I did.

When using saveXML(), preserveWhiteSpace in the target DOMdocument does not apply to imported nodes (as at PHP 5.6).

Consider the following code:

$dom = new DOMDocument();                               //create a document
$dom->preserveWhiteSpace = false;                       //disable whitespace preservation
$dom->formatOutput = true;                              //pretty print output
$documentElement = $dom->createElement("Entry");        //create a node
$dom->appendChild ($documentElement);                   //append it 
$message = new DOMDocument();                           //create another document
$message->loadXML($messageXMLtext);                     //populate the new document from XML text
$node=$dom->importNode($message->documentElement,true); //import the new document content to a new node in the original document
$documentElement->appendChild($node);                   //append the new node to the document Element
$dom->saveXML($dom->documentElement);                   //print the original document

In this context, the $dom->saveXML(); statement will NOT pretty print the content imported from $message, but content originally in $dom will be pretty printed.

In order to achieve pretty printing for the entire $dom document, the line:

$message->preserveWhiteSpace = false; 

must be included after the $message = new DOMDocument(); line - ie. the document/s from which the nodes are imported must also have preserveWhiteSpace = false.

Dictionary with list of strings as value

I'd wrap the dictionary in another class:

public class MyListDictionary
{

    private Dictionary<string, List<string>> internalDictionary = new Dictionary<string,List<string>>();

    public void Add(string key, string value)
    {
        if (this.internalDictionary.ContainsKey(key))
        {
            List<string> list = this.internalDictionary[key];
            if (list.Contains(value) == false)
            {
                list.Add(value);
            }
        }
        else
        {
            List<string> list = new List<string>();
            list.Add(value);
            this.internalDictionary.Add(key, list);
        }
    }

}

python: how to send mail with TO, CC and BCC?

As of Python 3.2, released Nov 2011, the smtplib has a new function send_message instead of just sendmail, which makes dealing with To/CC/BCC easier. Pulling from the Python official email examples, with some slight modifications, we get:

# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.message import EmailMessage

# Open the plain text file whose name is in textfile for reading.
with open(textfile) as fp:
    # Create a text/plain message
    msg = EmailMessage()
    msg.set_content(fp.read())

# me == the sender's email address
# you == the recipient's email address
# them == the cc's email address
# they == the bcc's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you
msg['Cc'] = them
msg['Bcc'] = they


# Send the message via our own SMTP server.
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()

Using the headers work fine, because send_message respects BCC as outlined in the documentation:

send_message does not transmit any Bcc or Resent-Bcc headers that may appear in msg


With sendmail it was common to add the CC headers to the message, doing something such as:

msg['Bcc'] = [email protected]

Or

msg = "From: [email protected]" +
      "To: [email protected]" +
      "BCC: [email protected]" +
      "Subject: You've got mail!" +
      "This is the message body"

The problem is, the sendmail function treats all those headers the same, meaning they'll get sent (visibly) to all To: and BCC: users, defeating the purposes of BCC. The solution, as shown in many of the other answers here, was to not include BCC in the headers, and instead only in the list of emails passed to sendmail.

The caveat is that send_message requires a Message object, meaning you'll need to import a class from email.message instead of merely passing strings into sendmail.

Re-order columns of table in Oracle

Look at the package DBMS_Redefinition. It will rebuild the table with the new ordering. It can be done with the table online.

As Phil Brown noted, think carefully before doing this. However there is overhead in scanning the row for columns and moving data on update. Column ordering rules I use (in no particular order):

  • Group related columns together.
  • Not NULL columns before null-able columns.
  • Frequently searched un-indexed columns first.
  • Rarely filled null-able columns last.
  • Static columns first.
  • Updateable varchar columns later.
  • Indexed columns after other searchable columns.

These rules conflict and have not all been tested for performance on the latest release. Most have been tested in practice, but I didn't document the results. Placement options target one of three conflicting goals: easy to understand column placement; fast data retrieval; and minimal data movement on updates.

How to count the NaN values in a column in pandas DataFrame

import pandas as pd
import numpy as np

# example DataFrame
df = pd.DataFrame({'a':[1,2,np.nan], 'b':[np.nan,1,np.nan]})

# count the NaNs in a column
num_nan_a = df.loc[ (pd.isna(df['a'])) , 'a' ].shape[0]
num_nan_b = df.loc[ (pd.isna(df['b'])) , 'b' ].shape[0]

# summarize the num_nan_b
print(df)
print(' ')
print(f"There are {num_nan_a} NaNs in column a")
print(f"There are {num_nan_b} NaNs in column b")

Gives as output:

     a    b
0  1.0  NaN
1  2.0  1.0
2  NaN  NaN

There are 1 NaNs in column a
There are 2 NaNs in column b

Pandas df.to_csv("file.csv" encode="utf-8") still gives trash characters for minus sign

Your "bad" output is UTF-8 displayed as CP1252.

On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:

df.to_csv('file.csv',encoding='utf-8-sig')

That encoder will add the BOM.

Determining Referer in PHP

We have only single option left after reading all the fake referrer problems: i.e. The page we desire to track as referrer should be kept in session, and as ajax called then checking in session if it has referrer page value and doing the action other wise no action.

While on the other hand as he request any different page then make the referrer session value to null.

Remember that session variable is set on desire page request only.

How to get Map data using JDBCTemplate.queryForMap

queryForMap is appropriate if you want to get a single row. You are selecting without a where clause, so you probably want to queryForList. The error is probably indicative of the fact that queryForMap wants one row, but you query is retrieving many rows.

Check out the docs. There is a queryForList that takes just sql; the return type is a

List<Map<String,Object>>.

So once you have the results, you can do what you are doing. I would do something like

List results = template.queryForList(sql);

for (Map m : results){
   m.get('userid');
   m.get('username');
} 

I'll let you fill in the details, but I would not iterate over keys in this case. I like to explicit about what I am expecting.

If you have a User object, and you actually want to load User instances, you can use the queryForList that takes sql and a class type

queryForList(String sql, Class<T> elementType)

(wow Spring has changed a lot since I left Javaland.)

How to enable DataGridView sorting when user clicks on the column header?

If you get an error message like

An unhandled exception of type 'System.NullReferenceException' occurred in System.Windows.Forms.dll

if you work with SortableBindingList, your code probably uses some loops over DataGridView rows and also try to access the empty last row! (BindingSource = null)

If you don't need to allow the user to add new rows directly in the DataGridView this line of code easily solve the issue:

InitializeComponent();
m_dataGridView.AllowUserToAddRows = false; // after components initialized
...

How to get every first element in 2 dimensional list

Compared the 3 methods

  1. 2D list: 5.323603868484497 seconds
  2. Numpy library : 0.3201274871826172 seconds
  3. Zip (Thanks to Joran Beasley) : 0.12395167350769043 seconds
D2_list=[list(range(100))]*100
t1=time.time()
for i in range(10**5):
    for j in range(10):
        b=[k[j] for k in D2_list]
D2_list_time=time.time()-t1

array=np.array(D2_list)
t1=time.time()        
for i in range(10**5):
    for j in range(10):
        b=array[:,j]        
Numpy_time=time.time()-t1

D2_trans = list(zip(*D2_list)) 
t1=time.time()        
for i in range(10**5):
    for j in range(10):
        b=D2_trans[j]
Zip_time=time.time()-t1

print ('2D List:',D2_list_time)
print ('Numpy:',Numpy_time)
print ('Zip:',Zip_time)

The Zip method works best. It was quite useful when I had to do some column wise processes for mapreduce jobs in the cluster servers where numpy was not installed.

What is the keyguard in Android?

In a nutshell, it is your lockscreen.

PIN, pattern, face, password locks or the default lock (slide to unlock), but it is your lock screen.

ASP.net page without a code behind

I thought you could deploy just your .aspx page without the .aspx.cs so long as the DLL was in your bin. Part of the issue here is how visual studio .net works with .aspx pages.

Check it out here: Working with Single-File Web Forms Pages in Visual Studio .NET

I know for sure that VS2008 with asp.net MVC RC you don't have code-behind files for your views.

Should I use encodeURI or encodeURIComponent for encoding URLs?

Here is a summary.

  1. escape() will not encode @ * _ + - . /

    Do not use it.

  2. encodeURI() will not encode A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #

    Use it when your input is a complete URL like 'https://searchexample.com/search?q=wiki'

  3. encodeURIComponent() will not encode A-Z a-z 0-9 - _ . ! ~ * ' ( ) Use it when your input is part of a complete URL e.g const queryStr = encodeURIComponent(someString)

How can I update a single row in a ListView?

I found the answer, thanks to your information Michelle. You can indeed get the right view using View#getChildAt(int index). The catch is that it starts counting from the first visible item. In fact, you can only get the visible items. You solve this with ListView#getFirstVisiblePosition().

Example:

private void updateView(int index){
    View v = yourListView.getChildAt(index - 
        yourListView.getFirstVisiblePosition());

    if(v == null)
       return;

    TextView someText = (TextView) v.findViewById(R.id.sometextview);
    someText.setText("Hi! I updated you manually!");
}

Should I use @EJB or @Inject

Update: This answer may be incorrect or out of date. Please see comments for details.

I switched from @Inject to @EJB because @EJB allows circular injection whereas @Inject pukes on it.

Details: I needed @PostConstruct to call an @Asynchronous method but it would do so synchronously. The only way to make the asynchronous call was to have the original call a method of another bean and have it call back the method of the original bean. To do this each bean needed a reference to the other -- thus circular. @Inject failed for this task whereas @EJB worked.

How to get current url in view in asp.net core 1.0

You can consider to use this extension method (from Microsoft.AspNetCore.Http.Extensions namespace:

@Context.Request.GetDisplayUrl()

For some my projects i prefer more flexible solution. There are two extensions methods.

1) First method creates Uri object from incoming request data (with some variants through optional parameters). 2) Second method receives Uri object and returns string in following format (with no trailing slash): Scheme_Host_Port

public static Uri GetUri(this HttpRequest request, bool addPath = true, bool addQuery = true)
    {
        var uriBuilder = new UriBuilder
        {
            Scheme = request.Scheme,
            Host = request.Host.Host,
            Port = request.Host.Port.GetValueOrDefault(80),
            Path = addPath ? request.Path.ToString() : default(string),
            Query = addQuery ? request.QueryString.ToString() : default(string)
        };
        return uriBuilder.Uri;
    }

    public static string HostWithNoSlash(this Uri uri)
    {
        return uri.GetComponents(UriComponents.SchemeAndServer, UriFormat.UriEscaped);
    }

Usage:

//before >> https://localhost:44304/information/about?param1=a&param2=b
        Request.GetUri(addQuery: false);
        //after >> https://localhost:44304/information/about

        //before >> https://localhost:44304/information/about?param1=a&param2=b
        new Uri("https://localhost:44304/information/about?param1=a&param2=b").GetHostWithNoSlash();
        //after >> https://localhost:44304

Using pickle.dump - TypeError: must be str, not bytes

Just had same issue. In Python 3, Binary modes 'wb', 'rb' must be specified whereas in Python 2x, they are not needed. When you follow tutorials that are based on Python 2x, that's why you are here.

import pickle

class MyUser(object):
    def __init__(self,name):
        self.name = name

user = MyUser('Peter')

print("Before serialization: ")
print(user.name)
print("------------")
serialized = pickle.dumps(user)
filename = 'serialized.native'

with open(filename,'wb') as file_object:
    file_object.write(serialized)

with open(filename,'rb') as file_object:
    raw_data = file_object.read()

deserialized = pickle.loads(raw_data)


print("Loading from serialized file: ")
user2 = deserialized
print(user2.name)
print("------------")

.keyCode vs. .which

jQuery normalises event.which depending on whether event.which, event.keyCode or event.charCode is supported by the browser:

// Add which for key events
if ( event.which == null && (event.charCode != null || event.keyCode != null) ) {
   event.which = event.charCode != null ? event.charCode : event.keyCode;
}

An added benefit of .which is that jQuery does it for mouse clicks too:

// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && event.button !== undefined ) {
    event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
}

Difference between onCreate() and onStart()?

Take a look on life cycle of Activity enter image description here

Where

***onCreate()***

Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one. Always followed by onStart().

***onStart()***

Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.

And you can write your simple class to take a look when these methods call

public class TestActivity extends Activity {
    /** Called when the activity is first created. */

    private final static String TAG = "TestActivity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.i(TAG, "On Create .....");
    }
    /* (non-Javadoc)
    * @see android.app.Activity#onDestroy()
    */
    @Override
    protected void onDestroy() { 
        super.onDestroy();
        Log.i(TAG, "On Destroy .....");
    }
    /* (non-Javadoc)
    * @see android.app.Activity#onPause()
    */
    @Override
    protected void onPause() { 
        super.onPause();
        Log.i(TAG, "On Pause .....");
    }

    /* (non-Javadoc)
    * @see android.app.Activity#onRestart()
    */
    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "On Restart .....");
    }

    /* (non-Javadoc)
    * @see android.app.Activity#onResume()
    */
    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "On Resume .....");
    }

    /* (non-Javadoc)
    * @see android.app.Activity#onStart()
    */
    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "On Start .....");
    }
    /* (non-Javadoc)
    * @see android.app.Activity#onStop()
    */
    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, "On Stop .....");
    }
}

Hope this will clear your confusion.

And take a look here for details.

Lifecycle Methods in Details is a very good example and demo application, which is a very good article to understand the life cycle.

How do you make Vim unhighlight what you searched for?

:noh (short for nohighlight) will do the trick.

opening html from google drive

Steps:

  1. Upload html file to the google drive and share it as "Public on the web" after uploading just make sure that the content of your html is not modified in the drive.
  2. Right click on the shared file and click on 'Get link' and save it to notepad it will look something like 'https://drive.google.com/open?id=0B55nkHvMDw18T3VaYjY3NEE4SEE'
  3. Take the code (about 28 character alphanumeric) after '=' sign from the above link and paste it after 'https://googledrive.com/host/' now 'https://googledrive.com/host/0B55nkHvMDw18T3VaYjY3NEE4SEE' is your actual sharable url link, open the html file from address bar of the browser using this url.

Unable to compile simple Java 10 / Java 11 project with Maven

As of 30Jul, 2018 to fix the above issue, one can configure the java version used within maven to any up to JDK/11 and make use of the maven-compiler-plugin:3.8.0 to specify a release of either 9,10,11 without any explicit dependencies.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.0</version>
    <configuration>
        <release>11</release>  <!--or <release>10</release>-->
    </configuration>
</plugin>

Note:- The default value for source/target has been lifted from 1.5 to 1.6 with this version. -- release notes.


Edit [30.12.2018]

In fact, you can make use of the same version of maven-compiler-plugin while compiling the code against JDK/12 as well.

More details and a sample configuration in how to Compile and execute a JDK preview feature with Maven.

Parsing JSON object in PHP using json_decode

You have to make sure first that your server allow remote connection so that the function file_get_contents($url) works fine , most server disable this feature for security reason.

Location for session files in Apache/PHP

Non of the above worked for me using the IUS repo for CentOS 7 with PHP 7.2:

php -v
> PHP 7.2.30 (cli) (built: Apr 19 2020 00:32:29) ( NTS )

php -r 'echo session_save_path(), "\n";
> 

php -r 'echo sys_get_temp_dir(), "\n";'
> /tmp

However, sessions weren't saved in the /tmp folder, but in the /var/lib/php/mod_php/session/ folder:

ls /var/lib/php/mod_php/session/
> sess_3cebqoq314pcnc2jgqiu840h0k  sess_ck5dtaerol28fpctj6nutbn6fn  sess_i24lgt2v2l58op5kfmj1k6qb3h  sess_nek5q1alop8fkt84gliie91703
> sess_9ff74f4q5ihccnv6com2a8409t  sess_dvrt9fmfuolr8bqt9efdpcbj0d  sess_igdaksn26hm1s5nfvtjfb53pl7  sess_tgf5b7gkgno8kuvl966l9ce7nn

Char to int conversion in C

int i = c - '0';

You should be aware that this doesn't perform any validation against the character - for example, if the character was 'a' then you would get 91 - 48 = 49. Especially if you are dealing with user or network input, you should probably perform validation to avoid bad behavior in your program. Just check the range:

if ('0' <= c &&  c <= '9') {
    i = c - '0';
} else {
    /* handle error */
}

Note that if you want your conversion to handle hex digits you can check the range and perform the appropriate calculation.

if ('0' <= c && c <= '9') {
    i = c - '0';
} else if ('a' <= c && c <= 'f') {
    i = 10 + c - 'a';
} else if ('A' <= c && c <= 'F') {
    i = 10 + c - 'A';
} else {
    /* handle error */
}

That will convert a single hex character, upper or lowercase independent, into an integer.

validate natural input number with ngpattern

The problem is that your REGX pattern will only match the input "0-9".

To meet your requirement (0-9999999), you should rewrite your regx pattern:

ng-pattern="/^[0-9]{1,7}$/"

My example:

HTML:

<div ng-app ng-controller="formCtrl">
  <form name="myForm" ng-submit="onSubmit()">
    <input type="number" ng-model="price" name="price_field" 
           ng-pattern="/^[0-9]{1,7}$/" required>
    <span ng-show="myForm.price_field.$error.pattern">Not a valid number!</span>
    <span ng-show="myForm.price_field.$error.required">This field is required!</span>
    <input type="submit" value="submit"/>
  </form>
</div>

JS:

function formCtrl($scope){
  $scope.onSubmit = function(){
    alert("form submitted");
  }
}

Here is a jsFiddle demo.

load external URL into modal jquery ui dialog

var page = "http://somurl.com/asom.php.aspx";

var $dialog = $('<div></div>')
               .html('<iframe style="border: 0px; " src="' + page + '" width="100%" height="100%"></iframe>')
               .dialog({
                   autoOpen: false,
                   modal: true,
                   height: 625,
                   width: 500,
                   title: "Some title"
               });
$dialog.dialog('open');

Use this inside a function. This is great if you really want to load an external URL as an IFRAME. Also make sure that in you custom jqueryUI you have the dialog.

How do I conditionally apply CSS styles in AngularJS?

I have found problems when applying classes inside table elements when I had one class already applied to the whole table (for example, a color applied to the odd rows <myClass tbody tr:nth-child(even) td>). It seems that when you inspect the element with Developer Tools, the element.style has no style assigned. So instead of using ng-class, I have tried using ng-style, and in this case, the new CSS attribute does appear inside element.style. This code works great for me:

<tr ng-repeat="element in collection">

    [...amazing code...]

    <td ng-style="myvar === 0 && {'background-color': 'red'} ||
                  myvar === 1 && {'background-color': 'green'} ||
                  myvar === 2 && {'background-color': 'yellow'}">{{ myvar }}</td>

    [...more amazing code...]

</tr>

Myvar is what I am evaluating, and in each case I apply a style to each <td> depending on myvar value, that overwrites the current style applied by the CSS class for the whole table.

UPDATE

If you want to apply a class to the table for example, when visiting a page or in other cases, you can use this structure:

<li ng-class="{ active: isActive('/route_a') || isActive('/route_b')}">

Basically, what we need to activate a ng-class is the class to apply and a true or false statement. True applies the class and false doesn't. So here we have two checks of the route of the page and an OR between them, so if we are in /route_a OR we are in route_b, the active class will be applied.

This works just having a logic function on the right that returns true or false.

So in the first example, ng-style is conditioned by three statements. If all of them are false, no style is applied, but following our logic, at least one is going to be applied, so, the logic expression will check which variable comparison is true and because a non empty array is always true, that will left an array as return and with only one true, considering we are using OR for the whole response, the style remaining will be applied.

By the way, I forgot to give you the function isActive():

$rootScope.isActive = function(viewLocation) {
    return viewLocation === $location.path();
};

NEW UPDATE

Here you have something I find really useful. When you need to apply a class depending on the value of a variable, for example, an icon depending on the contents of the div, you can use the following code (very useful in ng-repeat):

<i class="fa" ng-class="{ 'fa-github'   : type === 0,
                          'fa-linkedin' : type === 1,
                          'fa-skype'    : type === 2,
                          'fa-google'   : type === 3 }"></i>

Icons from Font Awesome

Where is database .bak file saved from SQL Server Management Studio?

As said by Faiyaz, to get default backup location for the instance, you cannot get it into msdb, but you have to look into Registry. You can get it in T-SQL in using xp_instance_regread stored procedure like this:

EXEC  master.dbo.xp_instance_regread 
      N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQLServer',N'BackupDirectory'

The double backslash (\\) is because the spaces into that key name part (Microsoft SQL Server). The "MSSQL12.MSSQLSERVER" part is for default instance name for SQL 2014. You have to adapt to put your own instance name (look into Registry).

How to unpack an .asar file?

https://www.electronjs.org/apps/asarui

UI for Asar, Extract All, or drag extract file/directory

How to configure the web.config to allow requests of any length

Something else to check: if your site is using MVC, this can happen if you added [Authorize] to your login controller class. It can't access the login method because it's not authorized so it redirects to the login method --> boom.

Set up an HTTP proxy to insert a header

If you have ruby on your system, how about a small Ruby Proxy using Sinatra (make sure to install the Sinatra Gem). This should be easier than setting up apache. The code can be found here.

argparse module How to add option without any argument?

To create an option that needs no value, set the action [docs] of it to 'store_const', 'store_true' or 'store_false'.

Example:

parser.add_argument('-s', '--simulate', action='store_true')

Goal Seek Macro with Goal as a Formula

GoalSeek will throw an "Invalid Reference" error if the GoalSeek cell contains a value rather than a formula or if the ChangingCell contains a formula instead of a value or nothing.

The GoalSeek cell must contain a formula that refers directly or indirectly to the ChangingCell; if the formula doesn't refer to the ChangingCell in some way, GoalSeek either may not converge to an answer or may produce a nonsensical answer.

I tested your code with a different GoalSeek formula than yours (I wasn't quite clear whether some of the terms referred to cells or values).

For the test, I set:

  the GoalSeek cell  H18 = (G18^3)+(3*G18^2)+6
  the Goal cell      H32 =  11
  the ChangingCell   G18 =  0 

The code was:

Sub GSeek()
    With Worksheets("Sheet1")
        .Range("H18").GoalSeek _
        Goal:=.Range("H32").Value, _
        ChangingCell:=.Range("G18")
    End With
End Sub

And the code produced the (correct) answer of 1.1038, the value of G18 at which the formula in H18 produces the value of 11, the goal I was seeking.

How to set locale in DatePipe in Angular 2?

I've had a look in date_pipe.ts and it has two bits of info which are of interest. near the top are the following two lines:

// TODO: move to a global configurable location along with other i18n components.
var defaultLocale: string = 'en-US';

Near the bottom is this line:

return DateFormatter.format(value, defaultLocale, pattern);

This suggests to me that the date pipe is currently hard-coded to be 'en-US'.

Please enlighten me if I am wrong.

How can I make a JPA OneToOne relation lazy

First off, some clarifications to KLE's answer:

  1. Unconstrained (nullable) one-to-one association is the only one that can not be proxied without bytecode instrumentation. The reason for this is that owner entity MUST know whether association property should contain a proxy object or NULL and it can't determine that by looking at its base table's columns due to one-to-one normally being mapped via shared PK, so it has to be eagerly fetched anyway making proxy pointless. Here's a more detailed explanation.

  2. many-to-one associations (and one-to-many, obviously) do not suffer from this issue. Owner entity can easily check its own FK (and in case of one-to-many, empty collection proxy is created initially and populated on demand), so the association can be lazy.

  3. Replacing one-to-one with one-to-many is pretty much never a good idea. You can replace it with unique many-to-one but there are other (possibly better) options.

Rob H. has a valid point, however you may not be able to implement it depending on your model (e.g. if your one-to-one association is nullable).

Now, as far as original question goes:

A) @ManyToOne(fetch=FetchType.LAZY) should work just fine. Are you sure it's not being overwritten in the query itself? It's possible to specify join fetch in HQL and / or explicitly set fetch mode via Criteria API which would take precedence over class annotation. If that's not the case and you're still having problems, please post your classes, query and resulting SQL for more to-the-point conversation.

B) @OneToOne is trickier. If it's definitely not nullable, go with Rob H.'s suggestion and specify it as such:

@OneToOne(optional = false, fetch = FetchType.LAZY)

Otherwise, if you can change your database (add a foreign key column to owner table), do so and map it as "joined":

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name="other_entity_fk")
public OtherEntity getOther()

and in OtherEntity:

@OneToOne(mappedBy = "other")
public OwnerEntity getOwner()

If you can't do that (and can't live with eager fetching) bytecode instrumentation is your only option. I have to agree with CPerkins, however - if you have 80!!! joins due to eager OneToOne associations, you've got bigger problems then this :-)

Git checkout - switching back to HEAD

You can stash (save the changes in temporary box) then, back to master branch HEAD.

$ git add .
$ git stash
$ git checkout master

Jump Over Commits Back and Forth:

  • Go to a specific commit-sha.

      $ git checkout <commit-sha>
    
  • If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.

      # checkout a new branch, add, commit, push
      $ git checkout -b <branch-name>
      $ git add .
      $ git commit -m 'Commit message'
      $ git push origin HEAD          # push the current branch to remote 
    
      $ git checkout master           # back to master branch now
    
  • If you have changes in the specific commit and don't want to keep the changes, you can do stash or reset then checkout to master (or, any other branch).

      # stash
      $ git add -A
      $ git stash
      $ git checkout master
    
      # reset
      $ git reset --hard HEAD
      $ git checkout master
    
  • After checking out a specific commit if you have no uncommitted change(s) then, just back to master or other branch.

      $ git status          # see the changes
      $ git checkout master
    
      # or, shortcut
      $ git checkout -      # back to the previous state
    

How to set size for local image using knitr for markdown?

Here's some options that keep the file self-contained without retastering the image:

Wrap the image in div tags

<div style="width:300px; height:200px">
![Image](path/to/image)
</div>

Use a stylesheet

test.Rmd

---
title: test
output: html_document
css: test.css
---

## Page with an image {#myImagePage}

![Image](path/to/image)

test.css

#myImagePage img {
  width: 400px;
  height: 200px;
}

If you have more than one image you might need to use the nth-child pseudo-selector for this second option.

How to monitor SQL Server table changes by using c#?

In the interests of completeness there are a couple of other solutions which (in my opinion) are more orthodox than solutions relying on the SqlDependency (and SqlTableDependency) classes. SqlDependency was originally designed to make refreshing distributed webserver caches easier, and so was built to a different set of requirements than if it were designed as an event producer.

There are broadly four options, some of which have not been covered here already:

  • Change Tracking
  • CDC
  • Triggers to queues
  • CLR

Change tracking

Source: https://docs.microsoft.com/en-us/sql/relational-databases/track-changes/about-change-tracking-sql-server

Change tracking is a lightweight notification mechanism in SQL server. Basically, a database-wide version number is incremented with every change to any data. The version number is then written to the change tracking tables with a bit mask including the names of the columns which were changed. Note, the actual change is not persisted. The notification only contains the information that a particular data entity has changed. Further, because the change table versioning is cumulative, change notifications on individual items are not preserved and are overwritten by newer notifications. This means that if an entity changes twice, change tracking will only know about the most recent change.

In order to capture these changes in c#, polling must be used. The change tracking tables can be polled and each change inspected to see if is of interest. If it is of interest, it is necessary to then go directly to the data to retrieve the current state.

Change Data Capture

Source: https://technet.microsoft.com/en-us/library/bb522489(v=sql.105).aspx

Change data capture (CDC) is more powerful but most costly than change tracking. Change data capture will track and notify changes based on monitoring the database log. Because of this CDC has access to the actual data which has been changed, and keeps a record of all individual changes.

Similarly to change tracking, in order to capture these changes in c#, polling must be used. However, in the case of CDC, the polled information will contain the change details, so it's not strictly necessary to go back to the data itself.

Triggers to queues

Source: https://code.msdn.microsoft.com/Service-Broker-Message-e81c4316

This technique depends on triggers on the tables from which notifications are required. Each change will fire a trigger, and the trigger will write this information to a service broker queue. The queue can then be connected to via C# using the Service Broker Message Processor (sample in the link above).

Unlike change tracking or CDC, triggers to queues do not rely on polling and thereby provides realtime eventing.

CLR

This is a technique I have seen used, but I would not recommend it. Any solution which relies on the CLR to communicate externally is a hack at best. The CLR was designed to make writing complex data processing code easier by leveraging C#. It was not designed to wire in external dependencies like messaging libraries. Furthermore, CLR bound operations can break in clustered environments in unpredictable ways.

This said, it is fairly straightforward to set up, as all you need to do is register the messaging assembly with CLR and then you can call away using triggers or SQL jobs.

In summary...

It has always been a source of amazement to me that Microsoft has steadfastly refused to address this problem space. Eventing from database to code should be a built-in feature of the database product. Considering that Oracle Advanced Queuing combined with the ODP.net MessageAvailable event provided reliable database eventing to C# more than 10 years ago, this is woeful from MS.

The upshot of this is that none of the solutions listed to this question are very nice. They all have technical drawbacks and have a significant setup cost. Microsoft if you're listening, please sort out this sorry state of affairs.

Matplotlib scatter plot with different text at each data point

I would love to add that you can even use arrows /text boxes to annotate the labels. Here is what I mean:

import random
import matplotlib.pyplot as plt


y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199]
z = [0.15, 0.3, 0.45, 0.6, 0.75]
n = [58, 651, 393, 203, 123]

fig, ax = plt.subplots()
ax.scatter(z, y)

ax.annotate(n[0], (z[0], y[0]), xytext=(z[0]+0.05, y[0]+0.3), 
    arrowprops=dict(facecolor='red', shrink=0.05))

ax.annotate(n[1], (z[1], y[1]), xytext=(z[1]-0.05, y[1]-0.3), 
    arrowprops = dict(  arrowstyle="->",
                        connectionstyle="angle3,angleA=0,angleB=-90"))

ax.annotate(n[2], (z[2], y[2]), xytext=(z[2]-0.05, y[2]-0.3), 
    arrowprops = dict(arrowstyle="wedge,tail_width=0.5", alpha=0.1))

ax.annotate(n[3], (z[3], y[3]), xytext=(z[3]+0.05, y[3]-0.2), 
    arrowprops = dict(arrowstyle="fancy"))

ax.annotate(n[4], (z[4], y[4]), xytext=(z[4]-0.1, y[4]-0.2),
    bbox=dict(boxstyle="round", alpha=0.1), 
    arrowprops = dict(arrowstyle="simple"))

plt.show()

Which will generate the following graph: enter image description here

When to use references vs. pointers

My rule of thumb is:

  • Use pointers for outgoing or in/out parameters. So it can be seen that the value is going to be changed. (You must use &)
  • Use pointers if NULL parameter is acceptable value. (Make sure it's const if it's an incoming parameter)
  • Use references for incoming parameter if it cannot be NULL and is not a primitive type (const T&).
  • Use pointers or smart pointers when returning a newly created object.
  • Use pointers or smart pointers as struct or class members instead of references.
  • Use references for aliasing (eg. int &current = someArray[i])

Regardless which one you use, don't forget to document your functions and the meaning of their parameters if they are not obvious.

Chain-calling parent initialisers in python

You can simply write :

class A(object):

    def __init__(self):
        print "Initialiser A was called"

class B(A):

    def __init__(self):
        A.__init__(self)
        # A.__init__(self,<parameters>) if you want to call with parameters
        print "Initialiser B was called"

class C(B):

    def __init__(self):
        # A.__init__(self) # if you want to call most super class...
        B.__init__(self)
        print "Initialiser C was called"

What is the Auto-Alignment Shortcut Key in Eclipse?

auto-alignment shortcut key Ctrl+Shift+F

to change the shortcut keys Goto Window > Preferences > Java > Editor > Save Actions

What are the use cases for selecting CHAR over VARCHAR in SQL?

In some SQL databases, VARCHAR will be padded out to its maximum size in order to optimize the offsets, This is to speed up full table scans and indexes.

Because of this, you do not have any space savings by using a VARCHAR(200) compared to a CHAR(200)

Javascript select onchange='this.form.submit()'

Use :

<select onchange="myFunction()">

    function myFunction() {
        document.querySelectorAll("input[type=submit]")[0].click();
    }

How to execute UNION without sorting? (SQL)

You can do something like this.

Select distinct name from  (SELECT r.name FROM outsider_role_mapping orm1 
    union all
SELECT r.name FROM user_role_mapping orm2
) tmp;

EXCEL VBA Check if entry is empty or not 'space'

A common trick is to check like this:

trim(TextBox1.Value & vbnullstring) = vbnullstring

this will work for spaces, empty strings, and genuine null values

How to extract HTTP response body from a Python requests call?

Your code is correct. I tested:

r = requests.get("http://www.google.com")
print(r.content)

And it returned plenty of content. Check the url, try "http://www.google.com". Cheers!

Invalid http_host header

settings.py

ALLOWED_HOSTS = ['*']

Selecting only first-level elements in jquery

You might want to try this if results still flows down to children, in many cases JQuery will still apply to children.

$("ul.rootlist > li > a")

Using this method: E > F Matches any F element that is a child of an element E.

Tells JQuery to look only for explicit children. http://www.w3.org/TR/CSS2/selector.html

What is the best way to ensure only one instance of a Bash script is running?

Ubuntu/Debian distros have the start-stop-daemon tool which is for the same purpose you describe. See also /etc/init.d/skeleton to see how it is used in writing start/stop scripts.

-- Noah

How to hide TabPage from TabControl

I realize the question is old, and the accepted answer is old, but ...

At least in .NET 4.0 ...

To hide a tab:

tabControl.TabPages.Remove(tabPage);

To put it back:

tabControl.TabPages.Insert(index, tabPage);

TabPages works so much better than Controls for this.

Converting list to *args when calling function

*args just means that the function takes a number of arguments, generally of the same type.

Check out this section in the Python tutorial for more info.

What is ViewModel in MVC?

A view model is a conceptual model of data. Its use is to for example either get a subset or combine data from different tables.

You might only want specific properties, so this allows you to only load those and not additional unneccesary properties

How to install easy_install in Python 2.7.1 on Windows 7

I know this isn't a direct answer to your question but it does offer one solution to your problem. Python 2.7.9 includes PIP and SetupTools, if you update to this version you will have one solution to your problem.

Change mysql user password using command line

In windows 10, just exit out of current login and run this on command line

--> mysqladmin -u root password “newpassword”

where instead of root could be any user.

How to check if an object is a certain type

Some more details in relation with the response from Cody Gray. As it took me some time to digest it I though it might be usefull to others.

First, some definitions:

  1. There are TypeNames, which are string representations of the type of an object, interface, etc. For example, Bar is a TypeName in Public Class Bar, or in Dim Foo as Bar. TypeNames could be seen as "labels" used in the code to tell the compiler which type definition to look for in a dictionary where all available types would be described.
  2. There are System.Type objects which contain a value. This value indicates a type; just like a String would take some text or an Int would take a number, except we are storing types instead of text or numbers. Type objects contain the type definitions, as well as its corresponding TypeName.

Second, the theory:

  1. Foo.GetType() returns a Type object which contains the type for the variable Foo. In other words, it tells you what Foo is an instance of.
  2. GetType(Bar) returns a Type object which contains the type for the TypeName Bar.
  3. In some instances, the type an object has been Cast to is different from the type an object was first instantiated from. In the following example, MyObj is an Integer cast into an Object:

    Dim MyVal As Integer = 42 Dim MyObj As Object = CType(MyVal, Object)

So, is MyObj of type Object or of type Integer? MyObj.GetType() will tell you it is an Integer.

  1. But here comes the Type Of Foo Is Bar feature, which allows you to ascertain a variable Foo is compatible with a TypeName Bar. Type Of MyObj Is Integer and Type Of MyObj Is Object will both return True. For most cases, TypeOf will indicate a variable is compatible with a TypeName if the variable is of that Type or a Type that derives from it. More info here: https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/typeof-operator#remarks

The test below illustrate quite well the behaviour and usage of each of the mentionned keywords and properties.

Public Sub TestMethod1()

    Dim MyValInt As Integer = 42
    Dim MyValDble As Double = CType(MyValInt, Double)
    Dim MyObj As Object = CType(MyValDble, Object)

    Debug.Print(MyValInt.GetType.ToString) 'Returns System.Int32
    Debug.Print(MyValDble.GetType.ToString) 'Returns System.Double
    Debug.Print(MyObj.GetType.ToString) 'Returns System.Double

    Debug.Print(MyValInt.GetType.GetType.ToString) 'Returns System.RuntimeType
    Debug.Print(MyValDble.GetType.GetType.ToString) 'Returns System.RuntimeType
    Debug.Print(MyObj.GetType.GetType.ToString) 'Returns System.RuntimeType

    Debug.Print(GetType(Integer).GetType.ToString) 'Returns System.RuntimeType
    Debug.Print(GetType(Double).GetType.ToString) 'Returns System.RuntimeType
    Debug.Print(GetType(Object).GetType.ToString) 'Returns System.RuntimeType

    Debug.Print(MyValInt.GetType = GetType(Integer)) '# Returns True
    Debug.Print(MyValInt.GetType = GetType(Double)) 'Returns False
    Debug.Print(MyValInt.GetType = GetType(Object)) 'Returns False

    Debug.Print(MyValDble.GetType = GetType(Integer)) 'Returns False
    Debug.Print(MyValDble.GetType = GetType(Double)) '# Returns True
    Debug.Print(MyValDble.GetType = GetType(Object)) 'Returns False

    Debug.Print(MyObj.GetType = GetType(Integer)) 'Returns False
    Debug.Print(MyObj.GetType = GetType(Double)) '# Returns True
    Debug.Print(MyObj.GetType = GetType(Object)) 'Returns False

    Debug.Print(TypeOf MyObj Is Integer) 'Returns False
    Debug.Print(TypeOf MyObj Is Double) '# Returns True
    Debug.Print(TypeOf MyObj Is Object) '# Returns True


End Sub

EDIT

You can also use Information.TypeName(Object) to get the TypeName of a given object. For example,

Dim Foo as Bar
Dim Result as String
Result = TypeName(Foo)
Debug.Print(Result) 'Will display "Bar"

Error With Port 8080 already in use

It has been long time, but I faced the same Issue, and solved it as follow: 1. tried shutting down the application server using the shutdown.bat/.bash which might be in your application Server / bin/shutdown..

  1. My Issue, was that more than 1 instance of java was running, I was changing ports, and not looking back, so it kept running other java processes, with that specific port. for windows users, : ALT+Shift+Esc, and end java processes that you are not using and now you should be able to re-use your port 8080

How to receive JSON as an MVC 5 action method parameter

You are sending a array of string

var usersRoles = [];
jQuery("#dualSelectRoles2 option").each(function () {
    usersRoles.push(jQuery(this).val());
});   

So change model type accordingly

 public ActionResult AddUser(List<string> model)
 {
 }

Replace the single quote (') character from a string

Here are a few ways of removing a single ' from a string in python.

  • str.replace

    replace is usually used to return a string with all the instances of the substring replaced.

    "A single ' char".replace("'","")
    
  • str.translate

    In Python 2

    To remove characters you can pass the first argument to the funstion with all the substrings to be removed as second.

    "A single ' char".translate(None,"'")
    

    In Python 3

    You will have to use str.maketrans

    "A single ' char".translate(str.maketrans({"'":None}))
    
  • re.sub

    Regular Expressions using re are even more powerful (but slow) and can be used to replace characters that match a particular regex rather than a substring.

    re.sub("'","","A single ' char")
    

Other Ways

There are a few other ways that can be used but are not at all recommended. (Just to learn new ways). Here we have the given string as a variable string.

Another final method can be used also (Again not recommended - works only if there is only one occurrence )

  • Using list call along with remove and join.

    x = list(string)
    x.remove("'")
    ''.join(x)
    

crop text too long inside div

.crop { 
  overflow:hidden; 
  white-space:nowrap; 
  text-overflow:ellipsis; 
  width:100px; 
}?

http://jsfiddle.net/hT3YA/

Simple way to transpose columns and rows in SQL?

Adding to @Paco Zarate's terrific answer above, if you want to transpose a table which has multiple types of columns, then add this to the end of line 39, so it only transposes int columns:

and C.system_type_id = 56   --56 = type int

Here is the full query that is being changed:

select @colsUnpivot = stuff((select ','+quotename(C.name)
from sys.columns as C
where C.object_id = object_id(@tableToPivot) and
      C.name <> @columnToPivot and C.system_type_id = 56    --56 = type int
for xml path('')), 1, 1, '')

To find other system_type_id's, run this:

select name, system_type_id from sys.types order by name

What is the difference between "word-break: break-all" versus "word-wrap: break-word" in CSS

With word-break, a very long word starts at the point it should start and it is being broken as long as required

[X] I am a text that 0123
4567890123456789012345678
90123456789 want to live 
inside this narrow paragr
aph.

However, with word-wrap, a very long word WILL NOT start at the point it should start. it wrap to next line and then being broken as long as required

[X] I am a text that 
012345678901234567890123
4567890123456789 want to
live inside this narrow 
paragraph.

How do I close an open port from the terminal on the Mac?

  1. First find out the Procees id (pid) which has occupied the required port.(e.g 5434)

    ps aux | grep 5434

2.kill that process

   kill -9 <pid>

Multiple INSERT statements vs. single INSERT with multiple VALUES

The issue probably has to do with the time it takes to compile the query.

If you want to speed up the inserts, what you really need to do is wrap them in a transaction:

BEGIN TRAN;
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age) 
   VALUES ('6f3f7257-a3d8-4a78-b2e1-c9b767cfe1c1', 'First 0', 'Last 0', 0);
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age) 
   VALUES ('32023304-2e55-4768-8e52-1ba589b82c8b', 'First 1', 'Last 1', 1);
...
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age) 
   VALUES ('f34d95a7-90b1-4558-be10-6ceacd53e4c4', 'First 999', 'Last 999', 999);
COMMIT TRAN;

From C#, you might also consider using a table valued parameter. Issuing multiple commands in a single batch, by separating them with semicolons, is another approach that will also help.

Calling another different view from the controller using ASP.NET MVC 4

To return a different view, you can specify the name of the view you want to return and model as follows:

return View("ViewName", yourModel);

if the view is in different folder under Views folder then use below absolute path:

return View("~/Views/FolderName/ViewName.aspx");

Add my custom http header to Spring RestTemplate request / extend RestTemplate

Add a "User-Agent" header to your request.

Some servers attempt to block spidering programs and scrapers from accessing their server because, in earlier days, requests did not send a user agent header.

You can either try to set a custom user agent value or use some value that identifies a Browser like "Mozilla/5.0 Firefox/26.0"

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();

headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("user-agent", "Mozilla/5.0 Firefox/26.0");
headers.set("user-key", "your-password-123"); // optional - in case you auth in headers
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<Game[]> respEntity = restTemplate.exchange(url, HttpMethod.GET, entity, Game[].class);

logger.info(respEntity.toString());

Getting a directory name from a filename

There is a standard Windows function for this, PathRemoveFileSpec. If you only support Windows 8 and later, it is highly recommended to use PathCchRemoveFileSpec instead. Among other improvements, it is no longer limited to MAX_PATH (260) characters.

show validation error messages on submit in angularjs

There are two simple & elegant ways to do it.

Pure CSS:

After first form submission, despite the form validity, Angular will add a ng-submitted class to all form elements inside the form just submitted.

We can use .ng-submitted to controller our element via CSS.

if you want to display an error text only when user have submitted e.g.

.error { display: none }
.ng-submitted .error {
     display: block;
}

Using a value from Scope:
After first form submission, despite the form validity, Angular will set [your form name].$submitted to true. Thus, we can use that value to control elements.

<div ng-show="yourFormName.$submitted">error message</div>
<form name="yourFormName"></form>

Update Eclipse with Android development tools v. 23

There are many possible answers to this question. I think it all depends on what your environment and installation procedure is. I'm running into the same issue as stated multiple times above. I cannot install ADT 23 because of a conflict dependency.

This is my environment:

I'm running Windows 7 64-bit with Eclipse 4.2.2. I installed ADT through menu Help ? Install New Software.

My solution:

Menu Help ? About Eclipse ? Uninstall ? ALL_ANDROID. Then I simply installed each of the ADT 23 tools through the "Install New Software".

Note: This is with the LATEST ADT release.

How do I set up the database.yml file in Rails?

The database.yml is the file where you set up all the information to connect to the database. It differs depending on the kind of DB you use. You can find more information about this in the Rails Guide or any tutorial explaining how to setup a rails project.

The information in the database.yml file is scoped by environment, allowing you to get a different setting for testing, development or production. It is important that you keep those distinct if you don't want the data you use for development deleted by mistake while running your test suite.

Regarding source control, you should not commit this file but instead create a template file for other developers (called database.yml.template). When deploying, the convention is to create this database.yml file in /shared/config directly on the server.

With SVN: svn propset svn:ignore config "database.yml"

With Git: Add config/database.yml to the .gitignore file or with git-extra git ignore config/database.yml


... and now, some examples:

SQLite

adapter: sqlite3
database: db/db_dev_db.sqlite3
pool: 5
timeout: 5000

MYSQL

adapter: mysql
database: my_db
hostname: 127.0.0.1
username: root
password: 
socket: /tmp/mysql.sock
pool: 5
timeout: 5000

MongoDB with MongoID (called mongoid.yml, but basically the same thing)

host: <%= ENV['MONGOID_HOST'] %>
port: <%= ENV['MONGOID_PORT'] %>
username: <%= ENV['MONGOID_USERNAME'] %>
password: <%= ENV['MONGOID_PASSWORD'] %>
database: <%= ENV['MONGOID_DATABASE'] %>
# slaves:
#   - host: slave1.local
#     port: 27018
#   - host: slave2.local
#     port: 27019

How to update json file with python

def updateJsonFile():
    jsonFile = open("replayScript.json", "r") # Open the JSON file for reading
    data = json.load(jsonFile) # Read the JSON into the buffer
    jsonFile.close() # Close the JSON file

    ## Working with buffered content
    tmp = data["location"] 
    data["location"] = path
    data["mode"] = "replay"

    ## Save our changes to JSON file
    jsonFile = open("replayScript.json", "w+")
    jsonFile.write(json.dumps(data))
    jsonFile.close()

Does a VPN Hide my Location on Android?

Your question can be conveniently divided into several parts:

Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.

How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.

You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):

  1. Download and install a trusted VPN.

  2. Install the VPN on your Android device.

  3. Open the application and connect to a server in a different country.

  4. Your Android location will now be successfully changed!

Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.

Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.

How do I change Eclipse to use spaces instead of tabs?

Just a quick tip for people stumbling across this thread; there is one more place where this setting can also be set, in your project!

Eclipse supports project-specific settings, and some projects will use their own, un-managed tabs/spaces settings, which won't show up anywhere except the current project Properties.

This can be managed through:

  • Right-Click current Project in Package Explorer
  • Properties » Java Code Style
  • Turn off all the project-specific options

This will generally only be an issue if you import someone else's code into your Eclipse.

get all the images from a folder in php

You can simply show your actual image directory(less secure). By just 2 line of code.

 $dir = base_url()."photos/";

echo"<a href=".$dir.">Photo Directory</a>";

Concatenating multiple text files into a single file in Bash

the most pragmatic way with the shell is the cat command. other ways include,

awk '1' *.txt > all.txt
perl -ne 'print;' *.txt > all.txt

In Bash, how to add "Are you sure [Y/n]" to any command or alias?

Well, here's my version of confirm, modified from James' one:

function confirm() {
  local response msg="${1:-Are you sure} (y/[n])? "; shift
  read -r $* -p "$msg" response || echo
  case "$response" in
  [yY][eE][sS]|[yY]) return 0 ;;
  *) return 1 ;;
  esac
}

These changes are:

  1. use local to prevent variable names from colliding
  2. read use $2 $3 ... to control its action, so you may use -n and -t
  3. if read exits unsuccessfully, echo a line feed for beauty
  4. my Git on Windows only has bash-3.1 and has no true or false, so use return instead. Of course, this is also compatible with bash-4.4 (the current one in Git for Windows).
  5. use IPython-style "(y/[n])" to clearly indicate that "n" is the default.

How to link 2 cell of excel sheet?

The simplest solution is to select the second cell, and press =. This will begin the fomula creation process. Now either type in the 1st cell reference (eg, A1) or click on the first cell and press enter. This should make the second cell reference the value of the first cell.

To read up more on different options for referencing see - This Article.

AWS : The config profile (MyName) could not be found

Was facing similar issue and found below link more helpful then the answers provided here. I guess this is due to the updates to AWS CLI since the answers are provided.

https://serverfault.com/questions/792937/the-config-profile-adminuser-could-not-be-found

Essentially it helps to create two different files (i.e. one for the general config related information and the second for the credentials related information).

Replacing backslashes with forward slashes with str_replace() in php

You need to escape backslash with a \

  $str = str_replace ("\\", "/", $str);

What is a stored procedure?

Think of a situation like this,

  • You have a database with data.
  • There are a number of different applications needed to access that central database, and in the future some new applications too.
  • If you are going to insert the inline database queries to access the central database, inside each application's code individually, then probably you have to duplicate the same query again and again inside different applications' code.
  • In that kind of a situation, you can use stored procedures (SPs). With stored procedures, you are writing number of common queries (procedures) and store them with the central database.
  • Now the duplication of work will never happen as before and the data access and the maintenance will be done centrally.

NOTE:

  • In the above situation, you may wonder "Why cannot we introduce a central data access server to interact with all the applications? Yes. That will be a possible alternative. But,
  • The main advantage with SPs over that approach is, unlike your data-access-code with inline queries, SPs are pre-compiled statements, so they will execute faster. And communication costs (over networks) will be at a minimum.
  • Opposite to that, SPs will add some more load to the database server. If that would be a concern according to the situation, a centralized data access server with inline queries will be a better choice.

Html code as IFRAME source rather than a URL

According to W3Schools, HTML 5 lets you do this using a new "srcdoc" attribute, but the browser support seems very limited.

How to create folder with PHP code?

... You can then use copy() to duplicate a PHP file, although this sounds incredibly inefficient.

Adding text to a cell in Excel using VBA

You could do

[A1].Value = "'O1/01/13 00:00"

if you really mean to add it as text (note the apostrophe as the first character).

The [A1].Value is VBA shorthand for Range("A1").Value.

If you want to enter a date, you could instead do (edited order with thanks to @SiddharthRout):

[A1].NumberFormat = "mm/dd/yyyy hh:mm;@"
[A1].Value = DateValue("01/01/2013 00:00")

Using LINQ to concatenate strings

Real example from my code:

return selected.Select(query => query.Name).Aggregate((a, b) => a + ", " + b);

A query is an object that has a Name property which is a string, and I want the names of all the queries on the selected list, separated by commas.

Display PDF within web browser

I use Google Docs embeddable PDF viewer. The docs don't have to be uploaded to Google Docs, but they do have to be available online.

<iframe src="http://docs.google.com/gview?url=http://path.com/to/your/pdf.pdf&embedded=true" 
style="width:600px; height:500px;" frameborder="0"></iframe>

Vuex - passing multiple parameters to mutation

i think this can be as simple let as assume that you are going to pass multiple parameters to you action as you read up there actions accept only two parameters context and payload which is your data you want to pass in action so let take an example

Setting up Action

instead of

actions: {
        authenticate: ({ commit }, token, expiration) => commit('authenticate', token, expiration)
    }

do

actions: {
        authenticate: ({ commit }, {token, expiration}) => commit('authenticate', token, expiration)
    }

Calling (dispatching) Action

instead of

this.$store.dispatch({
                  type: 'authenticate',
                  token: response.body.access_token,
                  expiration: response.body.expires_in + Date.now()
              })

do

this.$store.dispatch('authenticate',{
                  token: response.body.access_token,
                  expiration: response.body.expires_in + Date.now()
              })

hope this gonna help

How can I restart a Java application?

Similar to Yoda's 'improved' answer, but with further improvements (both functional, readability, and testability). It's now safe to run, and restarts for as as many times as the amount of program arguments given.

  • No accumulation of JAVA_TOOL_OPTIONS options.
  • Automatically finds main class.
  • Inherits current stdout/stderr.

public static void main(String[] args) throws Exception {
    if (args.length == 0)
        return;
    else
        args = Arrays.copyOf(args, args.length - 1);

    List<String> command = new ArrayList<>(32);
    appendJavaExecutable(command);
    appendVMArgs(command);
    appendClassPath(command);
    appendEntryPoint(command);
    appendArgs(command, args);

    System.out.println(command);
    try {
        new ProcessBuilder(command).inheritIO().start();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

private static void appendJavaExecutable(List<String> cmd) {
    cmd.add(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java");
}

private static void appendVMArgs(Collection<String> cmd) {
    Collection<String> vmArguments = ManagementFactory.getRuntimeMXBean().getInputArguments();

    String javaToolOptions = System.getenv("JAVA_TOOL_OPTIONS");
    if (javaToolOptions != null) {
        Collection<String> javaToolOptionsList = Arrays.asList(javaToolOptions.split(" "));
        vmArguments = new ArrayList<>(vmArguments);
        vmArguments.removeAll(javaToolOptionsList);
    }

    cmd.addAll(vmArguments);
}

private static void appendClassPath(List<String> cmd) {
    cmd.add("-cp");
    cmd.add(ManagementFactory.getRuntimeMXBean().getClassPath());
}

    private static void appendEntryPoint(List<String> cmd) {
    StackTraceElement[] stackTrace          = new Throwable().getStackTrace();
    StackTraceElement   stackTraceElement   = stackTrace[stackTrace.length - 1];
    String              fullyQualifiedClass = stackTraceElement.getClassName();
    String              entryMethod         = stackTraceElement.getMethodName();
    if (!entryMethod.equals("main"))
        throw new AssertionError("Entry point is not a 'main()': " + fullyQualifiedClass + '.' + entryMethod);

    cmd.add(fullyQualifiedClass);
}

private static void appendArgs(List<String> cmd, String[] args) {
    cmd.addAll(Arrays.asList(args));
}

V1.1 Bugfix: null pointer if JAVA_TOOL_OPTIONS is not set


Example:

$ java -cp Temp.jar Temp a b c d e
[/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java, -cp, Temp.jar, Temp, a, b, c, d]
[/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java, -cp, Temp.jar, Temp, a, b, c]
[/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java, -cp, Temp.jar, Temp, a, b]
[/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java, -cp, Temp.jar, Temp, a]
[/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java, -cp, Temp.jar, Temp]
$

How to efficiently change image attribute "src" from relative URL to absolute using jQuery?

Instead of below code:

$(this).attr("src").replace(urlRelative, urlAbsolute);

Use this:

$(this).attr("src",urlAbsolute);

How to remove border from specific PrimeFaces p:panelGrid?

Please try this too

.ui-panelgrid tr, .ui-panelgrid td {
border:0 !important;
}

Django - after login, redirect user to his custom page --> mysite.com/username

Yes! In your settings.py define the following

LOGIN_REDIRECT_URL = '/your-path'

And have '/your-path' be a simple View that looks up self.request.user and does whatever logic it needs to return a HttpResponseRedirect object.

A better way might be to define a simple URL like '/simple' that does the lookup logic there. The URL looks more beautiful, saves you some work, etc.

C++ Boost: undefined reference to boost::system::generic_category()

You could come across another problem. After installing Boost on the Linux Mint I've had the same problem. Linking -lboost_system or -lboost_system-mt haven't worked because library have had name libboost_system.so.1.54.0.

So the solution is to create symbolic link to the original file. In my case

sudo ln -s /usr/lib/x86_64-linux-gnu/libboost_system.so.1.54.0 /usr/lib/libboost_system.so

For more information see this question.

Difference between 'struct' and 'typedef struct' in C++?

Struct is to create a data type. The typedef is to set a nickname for a data type.

Convert Map to JSON using Jackson

You should prefer Object Mapper instead. Here is the link for the same : Object Mapper - Spring MVC way of Obect to JSON

How to format a number as percentage in R?

This function could transform the data to percentages by columns

percent.colmns = function(base, columnas = 1:ncol(base), filas = 1:nrow(base)){
    base2 = base
    for(j in columnas){
        suma.c = sum(base[,j])
        for(i in filas){
            base2[i,j] = base[i,j]*100/suma.c
        }
    }
    return(base2)
}

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

How to delete projects in Intellij IDEA 14?

Deleting and Recreating a project with same name is tricky. If you try to follow above suggested steps and try to create a project with same name as the one you just deleted, you will run into error like

'C:/xxxxxx/pom.xml' already exists in VFS

Here is what I found would work.

  1. Remove module
  2. File -> Invalidate Cache (at this point the Intelli IDEA wants to restart)
  3. Close project
  4. Delete the folder form system explorer.
  5. Now you can create a project with same name as before.

How to store date/time and timestamps in UTC time zone with JPA and Hibernate

To the best of my knowledge, you need to put your entire Java app in UTC timezone (so that Hibernate will store dates in UTC), and you'll need to convert to whatever timezone desired when you display stuff (at least we do it this way).

At startup, we do:

TimeZone.setDefault(TimeZone.getTimeZone("Etc/UTC"));

And set the desired timezone to the DateFormat:

fmt.setTimeZone(TimeZone.getTimeZone("Europe/Budapest"))

Read an Excel file directly from a R script

library(RODBC)
file.name <- "file.xls"
sheet.name <- "Sheet Name"

## Connect to Excel File Pull and Format Data
excel.connect <- odbcConnectExcel(file.name)
dat <- sqlFetch(excel.connect, sheet.name, na.strings=c("","-"))
odbcClose(excel.connect)

Personally, I like RODBC and can recommend it.

Interop type cannot be embedded

Here's where to set the Embed Interop in Visual Studio 2012

enter image description here

Jquery split function

Javascript String objects have a split function, doesn't really need to be jQuery specific

 var str = "nice.test"
 var strs = str.split(".")

strs would be

 ["nice", "test"]

I'd be tempted to use JSON in your example though. The php could return the JSON which could easily be parsed

 success: function(data) {
   var items = JSON.parse(data)
 }

Updating a local repository with changes from a GitHub repository

This should work for every default repo:

git pull origin master

If your default branch is different than master, you will need to specify the branch name:

git pull origin my_default_branch_name

How to make a flat list out of list of lists?

Here is a general approach that applies to numbers, strings, nested lists and mixed containers.

Code

#from typing import Iterable 
from collections import Iterable                            # < py38


def flatten(items):
    """Yield items from any nested iterable; see Reference."""
    for x in items:
        if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
            for sub_x in flatten(x):
                yield sub_x
        else:
            yield x

Notes:

  • In Python 3, yield from flatten(x) can replace for sub_x in flatten(x): yield sub_x
  • In Python 3.8, abstract base classes are moved from collection.abc to the typing module.

Demo

lst = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
list(flatten(lst))                                         # nested lists
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

mixed = [[1, [2]], (3, 4, {5, 6}, 7), 8, "9"]              # numbers, strs, nested & mixed
list(flatten(mixed))
# [1, 2, 3, 4, 5, 6, 7, 8, '9']

Reference

  • This solution is modified from a recipe in Beazley, D. and B. Jones. Recipe 4.14, Python Cookbook 3rd Ed., O'Reilly Media Inc. Sebastopol, CA: 2013.
  • Found an earlier SO post, possibly the original demonstration.

How do I retrieve a textbox value using JQuery?

You need to use the val() function to get the textbox value. text does not exist as a property only as a function and even then its not the correct function to use in this situation.

var from = $("input#fromAddress").val()

val() is the standard function for getting the value of an input.

How can I set a website image that will show as preview on Facebook?

1. Include the Open Graph XML namespace extension to your HTML declaration

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:fb="http://ogp.me/ns/fb#">

2. Inside your <head></head> use the following meta tag to define the image you want to use

<meta property="og:image" content="fully_qualified_image_url_here" />

Read more about open graph protocol here.

After doing the above, use the Facebook "Object Debugger" if the image does not show up correctly. Also note the first time shared it still won't show up unless height and width are also specified, see Share on Facebook - Thumbnail not showing for the first time

Prevent flex items from overflowing a container

I know this is really late, but for me, I found that applying flex-basis: 0; to the element prevented it from overflowing.

How to fix 'sudo: no tty present and no askpass program specified' error?

This error may also arise when you are trying to run a terminal command (that requires root password) from some non-shell script, eg sudo ls (in backticks) from a Ruby program. In this case, you can use Expect utility (http://en.wikipedia.org/wiki/Expect) or its alternatives.
For example, in Ruby to execute sudo ls without getting sudo: no tty present and no askpass program specified, you can run this:

require 'ruby_expect'

exp = RubyExpect::Expect.spawn('sudo ls', :debug => true)
exp.procedure do
    each do
        expect "[sudo] password for _your_username_:" do
            send _your_password_
        end
    end
end

[this uses one of the alternatives to Expect TCL extension: ruby_expect gem].

How to remove a web site from google analytics

You can also do in this way : select your profile then go to admin => in admin second column "Property" select the site you want to remove => go to third column "view settings" clic => on the right bottom you ll see delete the view => confirm and it s done , have a nice day all

CSS content generation before or after 'input' elements

This is not due to input tags not having any content per-se, but that their content is outside the scope of CSS.

input elements are a special type called replaced elements, these do not support :pseudo selectors like :before and :after.

In CSS, a replaced element is an element whose representation is outside the scope of CSS. These are kind of external objects whose representation is independent of the CSS. Typical replaced elements are <img>, <object>, <video> or form elements like <textarea> and <input>. Some elements, like <audio> or <canvas> are replaced elements only in specific cases. Objects inserted using the CSS content properties are anonymous replaced elements.

Note that this is even referred to in the spec:

This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML).

And more explicitly:

Replaced elements do not have ::before and ::after pseudo-elements

Check if a Python list item contains a string inside another string

If you only want to check for the presence of abc in any string in the list, you could try

some_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
if any("abc" in s for s in some_list):
    # whatever

If you really want to get all the items containing abc, use

matching = [s for s in some_list if "abc" in s]

bower proxy configuration

Add the below entry to your .bowerrc:

{
  "proxy":"http://<user>:<password>@<host>:<port>",
  "https-proxy":"http://<user>:<password>@<host>:<port>"
}

Also if your password contains any special character URL-encode it Eg: replace the @ character with %40

Convert a Unicode string to an escaped ASCII string

A small patch to @Adam Sills's answer which solves FormatException on cases where the input string like "c:\u00ab\otherdirectory\" plus RegexOptions.Compiled makes the Regex compilation much faster:

    private static Regex DECODING_REGEX = new Regex(@"\\u(?<Value>[a-fA-F0-9]{4})", RegexOptions.Compiled);
    private const string PLACEHOLDER = @"#!#";
    public static string DecodeEncodedNonAsciiCharacters(this string value)
    {
        return DECODING_REGEX.Replace(
            value.Replace(@"\\", PLACEHOLDER),
            m => { 
                return ((char)int.Parse(m.Groups["Value"].Value, NumberStyles.HexNumber)).ToString(); })
            .Replace(PLACEHOLDER, @"\\");
    }

ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

In my case, the problem was I didn't had a Tomcat server separately installed in my eclipse. I assumed my Springboot will start the server automatically within itself.

Since my main class extends SpringBootServletInitializer and override configure method, I definitely need a Tomcat server installed in my IDE.

To install, first download Apachce Tomcat (version 9 in my case) and create server using Servers tab.

After installation, run the main class on server.

Run As -> Run on Server

"make_sock: could not bind to address [::]:443" when restarting apache (installing trac and mod_wsgi)

I'm adding another answer to this as I had the same problem and solved it the same way: I had installed SSL on apache2 using a2enmod ssl, which seems to have added an extra configuration in /etc/apache2/ports.conf:

NameVirtualHost *:80
Listen 80

NameVirtualHost *:443
Listen 443

<IfModule mod_ssl.c>
    Listen 443
</IfModule>

<IfModule mod_gnutls.c>
    Listen 443
</IfModule>

I had to comment out the first Listen 443 after the NameVirtualHost *:443 directive:

NameVirtualHost *:443
#Listen 443

But I'm thinking I can as well let it and comment the others. Anyway, thank you for the solution :)

Determine the size of an InputStream

I just wanted to add, Apache Commons IO has stream support utilities to perform the copy. (Btw, what do you mean by placing the file into an inputstream? Can you show us your code?)

Edit:

Okay, what do you want to do with the contents of the item? There is an item.get() which returns the entire thing in a byte array.

Edit2

item.getSize() will return the uploaded file size.

AngularJS $http, CORS and http authentication

No you don't have to put credentials, You have to put headers on client side eg:

 $http({
        url: 'url of service',
        method: "POST",
        data: {test :  name },
        withCredentials: true,
        headers: {
                    'Content-Type': 'application/json; charset=utf-8'
        }
    });

And and on server side you have to put headers to this is example for nodejs:

/**
 * On all requests add headers
 */
app.all('*', function(req, res,next) {


    /**
     * Response settings
     * @type {Object}
     */
    var responseSettings = {
        "AccessControlAllowOrigin": req.headers.origin,
        "AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5,  Date, X-Api-Version, X-File-Name",
        "AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
        "AccessControlAllowCredentials": true
    };

    /**
     * Headers
     */
    res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
    res.header("Access-Control-Allow-Origin",  responseSettings.AccessControlAllowOrigin);
    res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
    res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);

    if ('OPTIONS' == req.method) {
        res.send(200);
    }
    else {
        next();
    }


});

Which MIME type to use for a binary file that's specific to my program?

mimetype headers are recognised by the browser for the purpose of a (fast) possible identifying a handler to use the downloaded file as target, for example, PDF would be downloaded and your Adobe Reader program would be executed with the path of the PDF file as an argument,

If your needs are to write a browser extension to handle your downloaded file, through your operation-system, or you simply want to make you project a more 'professional looking' go ahead and select a unique mimetype for you to use, it would make no difference since the operation-system would have no handle to open it with (some browsers has few bundled-plugins, for example new Google Chrome versions has a built-in PDF-reader),

if you want to make sure the file would be downloaded have a look at this answer: https://stackoverflow.com/a/34758866/257319

if you want to make your file type especially organised, it might be worth adding a few letters in the first few bytes of the file, for example, every JPG has this at it's file start:

if you can afford a jump of 4 or 8 bytes it could be very helpful for you in the rest of the way

:)

C# List of objects, how do I get the sum of a property

Another alternative:

myPlanetsList.Select(i => i.Moons).Sum();

How do I print out the value of this boolean? (Java)

System.out.println(isLeapYear);

should work just fine.

Incidentally, in

else if ((year % 4 == 0) && (year % 100 == 0))
    isLeapYear = false;

else if ((year % 4 == 0) && (year % 100 == 0) && (year % 400 == 0))
    isLeapYear = true;

the year % 400 part will never be reached because if (year % 4 == 0) && (year % 100 == 0) && (year % 400 == 0) is true, then (year % 4 == 0) && (year % 100 == 0) must have succeeded.

Maybe swap those two conditions or refactor them:

else if ((year % 4 == 0) && (year % 100 == 0))
    isLeapYear = (year % 400 == 0);

The type or namespace name 'DbContext' could not be found

For step-by-step instructions, see this new MVC / EF tutorial series: http://www.asp.net/entity-framework/tutorials/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application The tutorial assumes you have installed the latest MVC 3 Tools Update and provides a link in case you haven't.

Resource files not found from JUnit test cases

You know that Maven is based on the Convention over Configuration pardigm? so you shouldn't configure things which are the defaults.

All that stuff represents the default in Maven. So best practice is don't define it it's already done.

    <directory>target</directory>
    <outputDirectory>target/classes</outputDirectory>
    <testOutputDirectory>target/test-classes</testOutputDirectory>
    <sourceDirectory>src/main/java</sourceDirectory>
    <testSourceDirectory>src/test/java</testSourceDirectory>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
        </resource>
    </resources>
    <testResources>
        <testResource>
            <directory>src/test/resources</directory>
        </testResource>
    </testResources>

How to detect pressing Enter on keyboard using jQuery?

$(document).keydown(function (event) {
      //proper indentiation of keycode and which to be equal to 13.
    if ( (event.keyCode || event.which) === 13) {
        // Cancel the default action, if needed
        event.preventDefault();
        //call function, trigger events and everything tou want to dd . ex : Trigger the button element with a click
        $("#btnsearch").trigger('click');
    }
});

SQL: how to select a single id ("row") that meets multiple criteria from a single column

Users who have one of the 3 countries

SELECT DISTINCT user_id
FROM table
WHERE ancestry IN('England','France','Germany')

Users who have all 3 countries

SELECT DISTINCT A.userID
FROM table A
   INNER JOIN table B on A.user_id = B.user_id
   INNER JOIN table C on A.user_id = C.user_id
WHERE A.ancestry = 'England'
   AND B.ancestry = 'Germany'
   AND C.ancestry = 'France'

Memcache Vs. Memcached

They are not identical. Memcache is older but it has some limitations. I was using just fine in my application until I realized you can't store literal FALSE in cache. Value FALSE returned from the cache is the same as FALSE returned when a value is not found in the cache. There is no way to check which is which. Memcached has additional method (among others) Memcached::getResultCode that will tell you whether key was found.

Because of this limitation I switched to storing empty arrays instead of FALSE in cache. I am still using Memcache, but I just wanted to put this info out there for people who are deciding.

Background position, margin-top?

 background-image: url(/images/poster.png);
 background-position: center;
 background-position-y: 50px;
 background-repeat: no-repeat;

Create a OpenSSL certificate on Windows

To create a self signed certificate on Windows 7 with IIS 6...

  1. Open IIS

  2. Select your server (top level item or your computer's name)

  3. Under the IIS section, open "Server Certificates"

  4. Click "Create Self-Signed Certificate"

  5. Name it "localhost" (or something like that that is not specific)

  6. Click "OK"

You can then bind that certificate to your website...

  1. Right click on your website and choose "Edit bindings..."

  2. Click "Add"

    • Type: https
    • IP address: "All Unassigned"
    • Port: 443
    • SSL certificate: "localhost"
  3. Click "OK"

  4. Click "Close"

How can I see all the "special" characters permissible in a varchar or char field in SQL Server?

You probably just need to see the ASCII and EXTENDED ASCII character sets. As far as I know any of these are allowed in a char/varchar field.

If you use nchar/nvarchar then it's pretty much any character in any unicode set in the world.

enter image description here

enter image description here

Determining the path that a yum package installed to

yum uses RPM, so the following command will list the contents of the installed package:

$ rpm -ql package-name

Removing a non empty directory programmatically in C or C++

//======================================================
// Recursely Delete files using:
//   Gnome-Glib & C++11
//======================================================

#include <iostream>
#include <string>
#include <glib.h>
#include <glib/gstdio.h>

using namespace std;

int DirDelete(const string& path)
{
   const gchar*    p;
   GError*   gerr;
   GDir*     d;
   int       r;
   string    ps;
   string    path_i;
   cout << "open:" << path << "\n";
   d        = g_dir_open(path.c_str(), 0, &gerr);
   r        = -1;

   if (d) {
      r = 0;

      while (!r && (p=g_dir_read_name(d))) {
          ps = string{p};
          if (ps == "." || ps == "..") {
            continue;
          }

          path_i = path + string{"/"} + p;


          if (g_file_test(path_i.c_str(), G_FILE_TEST_IS_DIR) != 0) {
            cout << "recurse:" << path_i << "\n";
            r = DirDelete(path_i);
          }
          else {
            cout << "unlink:" << path_i << "\n";
            r = g_unlink(path_i.c_str());
          }
      }

      g_dir_close(d);
   }

   if (r == 0) {
      r = g_rmdir(path.c_str());
     cout << "rmdir:" << path << "\n";

   }

   return r;
}

Script Tag - async & defer

I think Jake Archibald presented us some insights back in 2013 that might add even more positiveness to the topic:

https://www.html5rocks.com/en/tutorials/speed/script-loading/

The holy grail is having a set of scripts download immediately without blocking rendering and execute as soon as possible in the order they were added. Unfortunately HTML hates you and won’t let you do that.

(...)

The answer is actually in the HTML5 spec, although it’s hidden away at the bottom of the script-loading section. "The async IDL attribute controls whether the element will execute asynchronously or not. If the element's "force-async" flag is set, then, on getting, the async IDL attribute must return true, and on setting, the "force-async" flag must first be unset…".

(...)

Scripts that are dynamically created and added to the document are async by default, they don’t block rendering and execute as soon as they download, meaning they could come out in the wrong order. However, we can explicitly mark them as not async:

[
    '//other-domain.com/1.js',
    '2.js'
].forEach(function(src) {
    var script = document.createElement('script');
    script.src = src;
    script.async = false;
    document.head.appendChild(script);
});

This gives our scripts a mix of behaviour that can’t be achieved with plain HTML. By being explicitly not async, scripts are added to an execution queue, the same queue they’re added to in our first plain-HTML example. However, by being dynamically created, they’re executed outside of document parsing, so rendering isn’t blocked while they’re downloaded (don’t confuse not-async script loading with sync XHR, which is never a good thing).

The script above should be included inline in the head of pages, queueing script downloads as soon as possible without disrupting progressive rendering, and executes as soon as possible in the order you specified. “2.js” is free to download before “1.js”, but it won’t be executed until “1.js” has either successfully downloaded and executed, or fails to do either. Hurrah! async-download but ordered-execution!

Still, this might not be the fastest way to load scripts:

(...) With the example above the browser has to parse and execute script to discover which scripts to download. This hides your scripts from preload scanners. Browsers use these scanners to discover resources on pages you’re likely to visit next, or discover page resources while the parser is blocked by another resource.

We can add discoverability back in by putting this in the head of the document:

<link rel="subresource" href="//other-domain.com/1.js">
<link rel="subresource" href="2.js">

This tells the browser the page needs 1.js and 2.js. link[rel=subresource] is similar to link[rel=prefetch], but with different semantics. Unfortunately it’s currently only supported in Chrome, and you have to declare which scripts to load twice, once via link elements, and again in your script.

Correction: I originally stated these were picked up by the preload scanner, they're not, they're picked up by the regular parser. However, preload scanner could pick these up, it just doesn't yet, whereas scripts included by executable code can never be preloaded. Thanks to Yoav Weiss who corrected me in the comments.

How to check for palindrome using Python logic

I tried using this:

def palindrome_numer(num):
num_str = str(num)
str_list = list(num_str)
if str_list[0] == str_list[-1]:
    return True
return False

and it worked for a number but I don't know if a string

Python - TypeError: 'int' object is not iterable

Your problem is with this line:

number4 = list(cow[n])

It tries to take cow[n], which returns an integer, and make it a list. This doesn't work, as demonstrated below:

>>> a = 1
>>> list(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>>

Perhaps you meant to put cow[n] inside a list:

number4 = [cow[n]]

See a demonstration below:

>>> a = 1
>>> [a]
[1]
>>>

Also, I wanted to address two things:

  1. Your while-statement is missing a : at the end.
  2. It is considered very dangerous to use input like that, since it evaluates its input as real Python code. It would be better here to use raw_input and then convert the input to an integer with int.

To split up the digits and then add them like you want, I would first make the number a string. Then, since strings are iterable, you can use sum:

>>> a = 137
>>> a = str(a)
>>> # This way is more common and preferred
>>> sum(int(x) for x in a)
11
>>> # But this also works
>>> sum(map(int, a))
11
>>>

Error importing Seaborn module in Python

it's a problem with the scipy package, just pip uninstall scipy and reinstall it

Missing artifact com.oracle:ojdbc6:jar:11.2.0 in pom.xml

oracle driver. `

<dependency>
    <groupId>com.hynnet</groupId>
    <artifactId>jdbc-fo</artifactId>
    <version>12.1.0.2</version>
</dependency>

`

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

If you are using a WAMP server then try this:

  • Single click on the WAMP server icon at the taskbar

  • Select the option put online

  • Your server will restart automatically

  • Then try to access your localwebsite

How to change legend size with matplotlib.pyplot

There are also a few named fontsizes, apart from the size in points:

xx-small
x-small
small
medium
large
x-large
xx-large

Usage:

pyplot.legend(loc=2, fontsize = 'x-small')

How to store a command in a variable in a shell script?

Use eval:

x="ls | wc"
eval "$x"
y=$(eval "$x")
echo "$y"

Comparing two strings, ignoring case in C#

The first one is the correct one, and IMHO the more efficient one, since the second 'solution' instantiates a new string instance.

How do I calculate square root in Python?

/ performs an integer division in Python 2:

>>> 1/2
0

If one of the numbers is a float, it works as expected:

>>> 1.0/2
0.5
>>> 16**(1.0/2)
4.0

Select all where [first letter starts with B]

SELECT author FROM lyrics WHERE author LIKE 'B%';

Make sure you have an index on author, though!

Alternative to file_get_contents?

You should try something like this, I am doing this for my project, its a fallback system

//function to get the remote data
function url_get_contents ($url) {
    if (function_exists('curl_exec')){ 
        $conn = curl_init($url);
        curl_setopt($conn, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($conn, CURLOPT_FRESH_CONNECT,  true);
        curl_setopt($conn, CURLOPT_RETURNTRANSFER, 1);
        $url_get_contents_data = (curl_exec($conn));
        curl_close($conn);
    }elseif(function_exists('file_get_contents')){
        $url_get_contents_data = file_get_contents($url);
    }elseif(function_exists('fopen') && function_exists('stream_get_contents')){
        $handle = fopen ($url, "r");
        $url_get_contents_data = stream_get_contents($handle);
    }else{
        $url_get_contents_data = false;
    }
return $url_get_contents_data;
} 

then later you can do like this

$data = url_get_contents("http://www.google.com");
if($data){
//Do Something....
}

How to edit an Android app?

Generally speaking, a software product isn't your "property already", as you said in the comment. Most of the times (I won't be irresponsible to say anything in open), it's licensed to you. A license to use some thing is not the same thing as owning (property rights) that very same thing.

That's because there are authorship, copyright, intellectual property rights applicable to it. I don't know how things work in United States (or in your country), but it's generally accepted that the work of a mind, a creative work, must not be changed in its nature as such to make the expression of art to be different than that expression that the author intended. That applies for example, in some cases, to architectural work (in most countries, you can't change the appearance of a building to "desfigure" the work of art of the architect, without his prior consent). Exceptions are made, obviously, when the author expressly authorizes such changes (e.g., Creative Commons licenses, open source licenses etc.).

Anyway, that's why you see in most EULAs the typical sentence: "this software is licensed, not sold". That's the purpose and reason why.

Now that you understand the reasons why you can't wander around changing other people's art, let me be technical.

There are possible ways to decompile Java programs. You can use dex2jar, it provides a somewhat good start for you to start looking for things and changes. And perhaps rebuild the code by mounting back the pieces together. Good luck, as most people obfuscate their codes to make that harder.

However, let me say that it's still forbidden to change programs, as I said above. And it's extremely unethical. It makes me sad that people do that with no scruples (not saying it's your case, just warning you). It shouldn't need people to be at the other side to understand that. Or maybe that's just me, who lives in a country where piracy is rampant.

The tools are always out there. But the conscience, unfortunately, not always.

edit: in case it isn't clear enough already, I do NOT approve the use of these programs. I use them myself to check how hard my own applications are to be reverse engineered. But I also think that explaning is always better than denial (better be here).

Convert hex string to int in Python

If you are using the python interpreter, you can just type 0x(your hex value) and the interpreter will convert it automatically for you.

>>> 0xffff

65535

MySql: Tinyint (2) vs tinyint(1) - what is the difference?

About the INT, TINYINT... These are different data types, INT is 4-byte number, TINYINT is 1-byte number. More information here - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT.

The syntax of TINYINT data type is TINYINT(M), where M indicates the maximum display width (used only if your MySQL client supports it).

Numeric Type Attributes.

Getting the ID of the element that fired an event

You can use (this) to reference the object that fired the function.

'this' is a DOM element when you are inside of a callback function (in the context of jQuery), for example, being called by the click, each, bind, etc. methods.

Here is where you can learn more: http://remysharp.com/2007/04/12/jquerys-this-demystified/

What is initial scale, user-scalable, minimum-scale, maximum-scale attribute in meta tag?

user-scalable:

user-scalable=yes (default) to allow the user to zoom in or out on the web page;

user-scalable=no to prevent the user from zooming in or out.

You can get more detailed information by reading the following articles.

Demo Code (recommended)

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="UTF-8">_x000D_
    <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=0.5, maximum-scale=3.0">_x000D_
</head>_x000D_
<body>_x000D_
    <header>_x000D_
    </header>_x000D_
    <main>_x000D_
        <section>_x000D_
            <h1>do not using <mark>user-scalable=no</mark></h1>_x000D_
        </section>_x000D_
    </main>_x000D_
    <footer>_x000D_
    </footer>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Format numbers in thousands (K) in Excel

I've found the following combination that works fine for positive and negative numbers (43787200020 is transformed to 43.787.200,02 K)

[>=1000] #.##0,#0. "K";#.##0,#0. "K"

Purpose of returning by const value?

It makes sure that the returned object (which is an RValue at that point) can't be modified. This makes sure the user can't do thinks like this:

myFunc() = Object(...);

That would work nicely if myFunc returned by reference, but is almost certainly a bug when returned by value (and probably won't be caught by the compiler). Of course in C++11 with its rvalues this convention doesn't make as much sense as it did earlier, since a const object can't be moved from, so this can have pretty heavy effects on performance.

Capture the Screen into a Bitmap

Try this code

Bitmap bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics gr = Graphics.FromImage(bmp);
gr.CopyFromScreen(0, 0, 0, 0, bmp.Size);
pictureBox1.Image = bmp;
bmp.Save("img.png",System.Drawing.Imaging.ImageFormat.Png);

How to Detect Browser Window /Tab Close Event?

You can also do like below.

put below script code in header tag

<script type="text/javascript" language="text/javascript"> 
function handleBrowserCloseButton(event) { 
   if (($(window).width() - window.event.clientX) < 35 && window.event.clientY < 0) 
    {
      //Call method by Ajax call
      alert('Browser close button clicked');    
    } 
} 
</script>

call above function from body tag like below

<body onbeforeunload="handleBrowserCloseButton(event);">

Thank you