Programs & Examples On #Jce

Java Cryptographic Extension : a pluggable cryptography framework where various providers can bring the desired functionality

Hash String via SHA-256 in Java

To hash a string, use the built-in MessageDigest class:

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.nio.charset.StandardCharsets;
import java.math.BigInteger;

public class CryptoHash {
  public static void main(String[] args) throws NoSuchAlgorithmException {
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    String text = "Text to hash, cryptographically.";

    // Change this to UTF-16 if needed
    md.update(text.getBytes(StandardCharsets.UTF_8));
    byte[] digest = md.digest();

    String hex = String.format("%064x", new BigInteger(1, digest));
    System.out.println(hex);
  }
}

In the snippet above, digest contains the hashed string and hex contains a hexadecimal ASCII string with left zero padding.

Trust Store vs Key Store - creating with keytool

The terminology is a bit confusing indeed, but both javax.net.ssl.keyStore and javax.net.ssl.trustStore are used to specify which keystores to use, for two different purposes. Keystores come in various formats and are not even necessarily files (see this question), and keytool is just a tool to perform various operations on them (import/export/list/...).

The javax.net.ssl.keyStore and javax.net.ssl.trustStore parameters are the default parameters used to build KeyManagers and TrustManagers (respectively), then used to build an SSLContext which essentially contains the SSL/TLS settings to use when making an SSL/TLS connection via an SSLSocketFactory or an SSLEngine. These system properties are just where the default values come from, which is then used by SSLContext.getDefault(), itself used by SSLSocketFactory.getDefault() for example. (All of this can be customized via the API in a number of places, if you don't want to use the default values and that specific SSLContexts for a given purpose.)

The difference between the KeyManager and TrustManager (and thus between javax.net.ssl.keyStore and javax.net.ssl.trustStore) is as follows (quoted from the JSSE ref guide):

TrustManager: Determines whether the remote authentication credentials (and thus the connection) should be trusted.

KeyManager: Determines which authentication credentials to send to the remote host.

(Other parameters are available and their default values are described in the JSSE ref guide. Note that while there is a default value for the trust store, there isn't one for the key store.)

Essentially, the keystore in javax.net.ssl.keyStore is meant to contain your private keys and certificates, whereas the javax.net.ssl.trustStore is meant to contain the CA certificates you're willing to trust when a remote party presents its certificate. In some cases, they can be one and the same store, although it's often better practice to use distinct stores (especially when they're file-based).

How to avoid installing "Unlimited Strength" JCE policy files when deploying an application?

During installation of your program, just prompt the user and have a DOS Batch script or a Bash shell script download and copy the JCE into the proper system location.

I used to have to do this for a server webservice and instead of a formal installer, I just provided scripts to setup the app before the user could run it. You can make the app un-runnable until they run the setup script. You could also make the app complain that the JCE is missing and then ask to download and restart the app?

How to create a secure random AES key in Java?

Lots of good advince in the other posts. This is what I use:

Key key;
SecureRandom rand = new SecureRandom();
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(256, rand);
key = generator.generateKey();

If you need another randomness provider, which I sometime do for testing purposes, just replace rand with

MySecureRandom rand = new MySecureRandom();

Why java.security.NoSuchProviderException No such provider: BC?

Im not very familiar with the Android sdk, but it seems that the android-sdk comes with the BouncyCastle provider already added to the security.

What you will have to do in the PC environment is just add it manually,

Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

if you have access to the policy file, just add an entry like:

security.provider.5=org.bouncycastle.jce.provider.BouncyCastleProvider 

Notice the .5 it is equal to a sequential number of the already added providers.

How to use BufferedReader in Java

As far as i understand fr is the object of your FileReadExample class. So it is obvious it will not have any method like fr.readLine() if you dont create one yourself.

secondly, i think a correct constructor of the BufferedReader class will help you do your task.

String str;
BufferedReader buffread = new BufferedReader(new FileReader(new File("file.dat")));
str = buffread.readLine();
.
.
buffread.close();

this should help you.

Get the Highlighted/Selected text

Use window.getSelection().toString().

You can read more on developer.mozilla.org

How do I get the RootViewController from a pushed controller?

A slightly less ugly version of the same thing mentioned in pretty much all these answers:

UIViewController *rootViewController = [[self.navigationController viewControllers] firstObject];

in your case, I'd probably do something like:

inside your UINavigationController subclass:

- (UIViewController *)rootViewController
{
    return [[self viewControllers] firstObject];
}

then you can use:

UIViewController *rootViewController = [self.navigationController rootViewController];

edit

OP asked for a property in the comments.

if you like, you can access this via something like self.navigationController.rootViewController by just adding a readonly property to your header:

@property (nonatomic, readonly, weak) UIViewController *rootViewController;

How do I add a placeholder on a CharField in Django?

The other methods are all good. However, if you prefer to not specify the field (e.g. for some dynamic method), you can use this:

def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    self.fields['email'].widget.attrs['placeholder'] = self.fields['email'].label or '[email protected]'

It also allows the placeholder to depend on the instance for ModelForms with instance specified.

Disposing WPF User Controls

You have to be careful using the destructor. This will get called on the GC Finalizer thread. In some cases the resources that your freeing may not like being released on a different thread from the one they were created on.

Print multiple arguments in Python

In Python 3.6, f-string is much cleaner.

In earlier version:

print("Total score for %s is %s. " % (name, score))

In Python 3.6:

print(f'Total score for {name} is {score}.')

will do.

It is more efficient and elegant.

Fatal error: Call to a member function query() on null

First, you declared $db outside the function. If you want to use it inside the function, you should put this at the begining of your function code:

global $db;

And I guess, when you wrote:

if($result->num_rows){
        return (mysqli_result($query, 0) == 1) ? true : false;

what you really wanted was:

if ($result->num_rows==1) { return true; } else { return false; }

Uncaught TypeError: Cannot set property 'onclick' of null

Does document.getElementById("blue") exist? if it doesn't then blue_box will be equal to null. you can't set a onclick on something that's null

adding child nodes in treeview

You can improve that code

 private void Form1_Load(object sender, EventArgs e)
    {
        /*
         D:\root\Project1\A\A.pdf
         D:\root\Project1\B\t.pdf
         D:\root\Project2\c.pdf
         */
        List<string> n = new List<string>();
        List<string> kn = new List<string>();
        n = Directory.GetFiles(@"D:\root\", "*.*", SearchOption.AllDirectories).ToList();
        kn = Directory.GetDirectories(@"D:\root\", "*.*", SearchOption.AllDirectories).ToList();
        foreach (var item in kn)
        {
            treeView1.Nodes.Add(item.ToString());
        }
        for (int i = 0; i < treeView1.Nodes.Count; i++)
        {
            n = Directory.GetFiles(treeView1.Nodes[i].Text, "*.*", SearchOption.AllDirectories).ToList();
            for (int zik = 0; zik < n.Count; zik++)
            {
                treeView1.Nodes[i].Nodes.Add(n[zik].ToString());
            }
        }        
    }

Disabling buttons on react native

You can build an CustButton with TouchableWithoutFeedback, and set the effect and logic you want with onPressIn, onPressout or other props.

Updating records codeigniter

In your_controller write this...

public function update_title() 
{   
    $data = array
      (
        'table_id' => $this->input->post('table_id'),
        'table_title' => $this->input->post('table_title')
      );

    $this->load->model('your_model'); // First load the model
    if($this->your_model->update_title($data)) // call the method from the controller
    {
        // update successful...
    }
    else
    {
        // update not successful...
    }

}

While in your_model...

public function update_title($data)
{
   $this->db->set('table_title',$data['title'])
         ->where('table_id',$data['table_id'])
        ->update('your_table');
}

This will works fine...

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i input.mov -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i input.mov -q:v 0 output.mp4

How to comment and uncomment blocks of code in the Office VBA Editor

Have you checked MZTools?? It does a lot of cool stuff...

If I'm not wrong, one of the functionalities it offers is to set your own shortcuts.

Display a float with two decimal places in Python

Using python string formatting.

>>> "%0.2f" % 3
'3.00'

When to use single quotes, double quotes, and backticks in MySQL

In combination of PHP and MySQL, double quotes and single quotes make your query-writing time so much easier.

$query = "INSERT INTO `table` (`id`, `col1`, `col2`) VALUES (NULL, '$val1', '$val2')";

Now, suppose you are using a direct post variable into the MySQL query then, use it this way:

$query = "INSERT INTO `table` (`id`, `name`, `email`) VALUES (' ".$_POST['id']." ', ' ".$_POST['name']." ', ' ".$_POST['email']." ')";

This is the best practice for using PHP variables into MySQL.

Jquery, Clear / Empty all contents of tbody element?

You probably have found this out already, but for someone stuck with this problem:

$("#tableId > tbody").html("");

Difference Between Schema / Database in MySQL

Depends on the database server. MySQL doesn't care, its basically the same thing.

Oracle, DB2, and other enterprise level database solutions make a distinction. Usually a schema is a collection of tables and a Database is a collection of schemas.

Inserting Image Into BLOB Oracle 10g

You should do something like this:

1) create directory object what would point to server-side accessible folder

CREATE DIRECTORY image_files AS '/data/images'
/

2) Place your file into OS folder directory object points to

3) Give required access privileges to Oracle schema what will load data from file into table:

GRANT READ ON DIRECTORY image_files TO scott
/

4) Use BFILENAME, EMPTY_BLOB functions and DBMS_LOB package (example NOT tested - be care) like in below:

DECLARE
  l_blob BLOB; 
  v_src_loc  BFILE := BFILENAME('IMAGE_FILES', 'myimage.png');
  v_amount   INTEGER;
BEGIN
  INSERT INTO esignatures  
  VALUES (100, 'BOB', empty_blob()) RETURN iblob INTO l_blob; 
  DBMS_LOB.OPEN(v_src_loc, DBMS_LOB.LOB_READONLY);
  v_amount := DBMS_LOB.GETLENGTH(v_src_loc);
  DBMS_LOB.LOADFROMFILE(l_blob, v_src_loc, v_amount);
  DBMS_LOB.CLOSE(v_src_loc);
  COMMIT;
END;
/

After this you get the content of your file in BLOB column and can get it back using Java for example.

edit: One letter left missing: it should be LOADFROMFILE.

Use .htaccess to redirect HTTP to HTTPs

For your information, it really depends on your hosting provider.

In my case (Infomaniak), nothing above actually worked and I got infinite redirect loop.

The right way to do this is actually explained in their support site:

RewriteEngine on
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://your-domain.com/$1 [R=301,L]

So, always check with your hosting provider. Hopefully they have an article explaining how to do this. Otherwise, just ask the support.

Construct pandas DataFrame from items in nested dictionary

pd.concat accepts a dictionary. With this in mind, it is possible to improve upon the currently accepted answer in terms of simplicity and performance by use a dictionary comprehension to build a dictionary mapping keys to sub-frames.

pd.concat({k: pd.DataFrame(v).T for k, v in user_dict.items()}, axis=0)

Or,

pd.concat({
        k: pd.DataFrame.from_dict(v, 'index') for k, v in user_dict.items()
    }, 
    axis=0)

              att_1     att_2
12 Category 1     1  whatever
   Category 2    23   another
15 Category 1    10       foo
   Category 2    30       bar

How to upgrade all Python packages with pip

I've been using pur lately. It's simple and to the point. It updates your requirements.txt file to reflect the upgrades and you can then upgrade with your requirements.txt file as usual.

$ pip install pur
...
Successfully installed pur-4.0.1

$ pur
Updated boto3: 1.4.2 -> 1.4.4
Updated Django: 1.10.4 -> 1.10.5
Updated django-bootstrap3: 7.1.0 -> 8.1.0
All requirements up-to-date.

$ pip install --upgrade -r requirements.txt
Successfully installed Django-1.10.5 ...

How to display image from URL on Android

You can try with Picasso, it's really nice and easy. Don't forget to add the permissions in the manifest.

Picasso.with(context)
                     .load("http://ImageURL")
                     .resize(width,height)
                     .into(imageView );

You can also take a look at a tutorial here : Youtube / Github

Should a function have only one return statement?

You know the adage - beauty is in the eyes of the beholder.

Some people swear by NetBeans and some by IntelliJ IDEA, some by Python and some by PHP.

In some shops you could lose your job if you insist on doing this:

public void hello()
{
   if (....)
   {
      ....
   }
}

The question is all about visibility and maintainability.

I am addicted to using boolean algebra to reduce and simplify logic and use of state machines. However, there were past colleagues who believed my employ of "mathematical techniques" in coding is unsuitable, because it would not be visible and maintainable. And that would be a bad practice. Sorry people, the techniques I employ is very visible and maintainable to me - because when I return to the code six months later, I would understand the code clearly rather seeing a mess of proverbial spaghetti.

Hey buddy (like a former client used to say) do what you want as long as you know how to fix it when I need you to fix it.

I remember 20 years ago, a colleague of mine was fired for employing what today would be called agile development strategy. He had a meticulous incremental plan. But his manager was yelling at him "You can't incrementally release features to users! You must stick with the waterfall." His response to the manager was that incremental development would be more precise to customer's needs. He believed in developing for the customers needs, but the manager believed in coding to "customer's requirement".

We are frequently guilty for breaking data normalization, MVP and MVC boundaries. We inline instead of constructing a function. We take shortcuts.

Personally, I believe that PHP is bad practice, but what do I know. All the theoretical arguments boils down to trying fulfill one set of rules

quality = precision, maintainability and profitability.

All other rules fade into the background. And of course this rule never fades:

Laziness is the virtue of a good programmer.

HTTP Error 404 when running Tomcat from Eclipse

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

Fatal error: Call to undefined function mysql_connect() in C:\Apache\htdocs\test.php on line 2

I had the similar issue. I solved it the following way after a number of attempts to follow the pieces of advice in the forums. I am reposting the solution because it could be helpful for others.

I am running Windows 7 (Apache 2.2 & PHP 5.2.17 & MySQL 5.0.51a), the syntax in the file "httpd.conf" (C:\Program Files (x86)\Apache Software Foundation\Apache2.2\conf\httpd.conf) was sensitive to slashes. You can check if "php.ini" is read from the right directory. Just type in your browser "localhost/index.php". The code of index.php is the following:

<?php echo phpinfo(); ?>

There is the row (not far from the top) called "Loaded Configuration File". So, if there is nothing added, then the problem could be that your "php.ini" is not read, even you uncommented (extension=php_mysql.dll and extension=php_mysqli.dll). So, in order to make it work I did the following step. I needed to change from

PHPIniDir 'c:\PHP\'

to

PHPIniDir 'c:\PHP'

Pay the attention that the last slash disturbed everything!

Now the row "Loaded Configuration File" gets "C:\PHP\php.ini" after refreshing "localhost/index.php" (before I restarted Apache2.2) as well as mysql block is there. MySQL and PHP are working together!

Declare and assign multiple string variables at the same time

You can to do it this way:

string Camnr = "", Klantnr = "", ... // or String.Empty

Or you could declare them all first and then in the next line use your way.

How to comment multiple lines with space or indent

  • You can customize every short cut operation according to your habbit.

Just go to Tools > Options > Environment > Keyboard > Find the action you want to set key board short-cut and change according to keyboard habbit.

can we use xpath with BeautifulSoup?

As others have said, BeautifulSoup doesn't have xpath support. There are probably a number of ways to get something from an xpath, including using Selenium. However, here's a solution that works in either Python 2 or 3:

from lxml import html
import requests

page = requests.get('http://econpy.pythonanywhere.com/ex/001.html')
tree = html.fromstring(page.content)
#This will create a list of buyers:
buyers = tree.xpath('//div[@title="buyer-name"]/text()')
#This will create a list of prices
prices = tree.xpath('//span[@class="item-price"]/text()')

print('Buyers: ', buyers)
print('Prices: ', prices)

I used this as a reference.

Deserialize JSON string to c# object

I think the JavaScriptSerializer does not create a dynamic object.

So you should define the class first:

class MyObj {
    public int arg1 {get;set;}
    public int arg2 {get;set;}
}

And deserialize that instead of object:

serializer.Deserialize<MyObj>(str);

Not testet, please try.

How can I verify if an AD account is locked?

The LockedOut property is what you are looking for among all the properties you returned. You are only seeing incomplete output in TechNet. The information is still there. You can isolate that one property using Select-Object

Get-ADUser matt -Properties * | Select-Object LockedOut

LockedOut
---------
False

The link you referenced doesn't contain this information which is obviously misleading. Test the command with your own account and you will see much more information.

Note: Try to avoid -Properties *. While it is great for simple testing it can make queries, especially ones with multiple accounts, unnecessarily slow. So, in this case, since you only need lockedout:

Get-ADUser matt -Properties LockedOut | Select-Object LockedOut

Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id}

The possible reason can also be that you have not inherited Controller from ApiController. Happened with me took a while to understand the same.

OpenVPN failed connection / All TAP-Win32 adapters on this system are currently in use

I found a solution to this. It's bloody witchcraft, but it works.

When you install the client, open Control Panel > Network Connections.

You'll see a disabled network connection that was added by the TAP installer (Local Area Connection 3 or some such).

Right Click it, click Enable.

The device will not reset itself to enabled, but that's ok; try connecting w/ the client again. It'll work.

Initialise a list to a specific length in Python

In a talk about core containers internals in Python at PyCon 2012, Raymond Hettinger is suggesting to use [None] * n to pre-allocate the length you want.

Slides available as PPT or via Google

The whole slide deck is quite interesting. The presentation is available on YouTube, but it doesn't add much to the slides.

OCI runtime exec failed: exec failed: (...) executable file not found in $PATH": unknown

If @papigee does solution doesn't work, maybe you don't have the permissions.

I tried @papigee solution but does't work without sudo.

I did :

sudo docker exec -it <container id or name> /bin/sh

How to print Two-Dimensional Array like table

You need to print a new line after each row... System.out.print("\n"), or use println, etc. As it stands you are just printing nothing - System.out.print(""), replace print with println or "" with "\n".

Display an array in a readable/hierarchical format

I think that var_export(), the forgotten brother of var_dump() has the best output - it's more compact:

echo "<pre>";
var_export($menue);
echo "</pre>";

By the way: it's not allway necessary to use <pre>. var_dump() and var_export() are already formatted when you take a look in the source code of your webpage.

Match line break with regular expression

By default . (any character) does not match newline characters.

This means you can simply match zero or more of any character then append the end tag.

Find: <li><a href="#">.* Replace: $0</a>

How to replace (null) values with 0 output in PIVOT

You cannot place the IsNull() until after the data is selected so you will place the IsNull() around the final value in the SELECT:

SELECT CLASS,
  IsNull([AZ], 0) as [AZ],
  IsNull([CA], 0) as [CA],
  IsNull([TX], 0) as [TX]
FROM #TEMP
PIVOT 
(
  SUM(DATA)
  FOR STATE IN ([AZ], [CA], [TX])
) AS PVT
ORDER BY CLASS

Django REST Framework: adding additional field to ModelSerializer

You can change your model method to property and use it in serializer with this approach.

class Foo(models.Model):
    . . .
    @property
    def my_field(self):
        return stuff
    . . .

class FooSerializer(ModelSerializer):
    my_field = serializers.ReadOnlyField(source='my_field')

    class Meta:
        model = Foo
        fields = ('my_field',)

Edit: With recent versions of rest framework (I tried 3.3.3), you don't need to change to property. Model method will just work fine.

More elegant "ps aux | grep -v grep"

You could use preg_split instead of explode and split on [ ]+ (one or more spaces). But I think in this case you could go with preg_match_all and capturing:

preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];

The pattern matches a space, php, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php as part of a user name but really only as a command.

An alternative to capturing is the "keep" feature of PCRE. If you use \K in the pattern, everything before it is discarded in the match:

preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];

I would use preg_match(). I do something similar for many of my system management scripts. Here is an example:

$test = "user     12052  0.2  0.1 137184 13056 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user     12054  0.2  0.1 137184 13064 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user     12055  0.6  0.1 137844 14220 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user     12057  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user     12058  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user     12059  0.3  0.1 135112 13000 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root     12068  0.0  0.0 106088  1164 pts/1    S+   10:00   0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root     12070  0.0  0.0 103240   828 pts/1    R+   10:00   0:00 grep utilities";

$lines = explode("\n", $test);

foreach($lines as $line){
        if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
                print_r($matches);
        }

}

The above prints:

Array
(
    [0] => .php cust1 cron
    [1] => cust1
)
Array
(
    [0] => .php cust3 cron
    [1] => cust3
)
Array
(
    [0] => .php cust4 cron
    [1] => cust4
)
Array
(
    [0] => .php cust89 cron
    [1] => cust89
)
Array
(
    [0] => .php cust435 cron
    [1] => cust435
)
Array
(
    [0] => .php cust16 cron
    [1] => cust16
)

You can set $test to equal the output from exec. the values you are looking for would be in the if statement under the foreach. $matches[1] will have the custx value.

How to save S3 object to a file using boto3

For those of you who would like to simulate the set_contents_from_string like boto2 methods, you can try

import boto3
from cStringIO import StringIO

s3c = boto3.client('s3')
contents = 'My string to save to S3 object'
target_bucket = 'hello-world.by.vor'
target_file = 'data/hello.txt'
fake_handle = StringIO(contents)

# notice if you do fake_handle.read() it reads like a file handle
s3c.put_object(Bucket=target_bucket, Key=target_file, Body=fake_handle.read())

For Python3:

In python3 both StringIO and cStringIO are gone. Use the StringIO import like:

from io import StringIO

To support both version:

try:
   from StringIO import StringIO
except ImportError:
   from io import StringIO

Is there possibility of sum of ArrayList without looping

If you know about the map function, then you know that a map is also can be recursive loop or recursive loop. But obviously you have to reach each element for that. so, I could not work out the Java 8, because some syntax mismatch but wanted a very short so this is what I got.

int sum = 0
for (Integer e : myList) sum += e;

Operand type clash: int is incompatible with date + The INSERT statement conflicted with the FOREIGN KEY constraint

I had the same problem. I tried 'yyyy-mm-dd' format i.e. '2013-26-11' and got rid of this problem...

how to rotate a bitmap 90 degrees

Short extension for Kotlin

fun Bitmap.rotate(degrees: Float): Bitmap {
    val matrix = Matrix().apply { postRotate(degrees) }
    return Bitmap.createBitmap(this, 0, 0, width, height, matrix, true)
}

And usage:

val rotatedBitmap = bitmap.rotate(90f)

Using CMake to generate Visual Studio C++ project files

Not sure if it's directly related to the question, but I was looking for an answer for how to generate *.sln from cmake projects I've discovered that one can use something like this:

cmake -G "Visual Studio 10"

The example generates needed VS 2010 files from an input CMakeLists.txt file

How to update-alternatives to Python 3 without breaking apt?

Somehow python 3 came back (after some updates?) and is causing big issues with apt updates, so I've decided to remove python 3 completely from the alternatives:

root:~# python -V
Python 3.5.2

root:~# update-alternatives --config python
There are 2 choices for the alternative python (providing /usr/bin/python).

  Selection    Path                Priority   Status
------------------------------------------------------------
* 0            /usr/bin/python3.5   3         auto mode
  1            /usr/bin/python2.7   2         manual mode
  2            /usr/bin/python3.5   3         manual mode


root:~# update-alternatives --remove python /usr/bin/python3.5

root:~# update-alternatives --config python
There is 1 choice for the alternative python (providing /usr/bin/python).

    Selection    Path                Priority   Status
------------------------------------------------------------
  0            /usr/bin/python2.7   2         auto mode
* 1            /usr/bin/python2.7   2         manual mode

Press <enter> to keep the current choice[*], or type selection number: 0


root:~# python -V
Python 2.7.12

root:~# update-alternatives --config python
There is only one alternative in link group python (providing /usr/bin/python): /usr/bin/python2.7
Nothing to configure.

When & why to use delegates?

I agree with everything that is said already, just trying to put some other words on it.

A delegate can be seen as a placeholder for a/some method(s).

By defining a delegate, you are saying to the user of your class, "Please feel free to assign, any method that matches this signature, to the delegate and it will be called each time my delegate is called".

Typical use is of course events. All the OnEventX delegate to the methods the user defines.

Delegates are useful to offer to the user of your objects some ability to customize their behavior. Most of the time, you can use other ways to achieve the same purpose and I do not believe you can ever be forced to create delegates. It is just the easiest way in some situations to get the thing done.

Replace given value in vector

A simple way to do this is using ifelse, which is vectorized. If the condition is satisfied, we use a replacement value, otherwise we use the original value.

v <- c(3, 2, 1, 0, 4, 0)
ifelse(v == 0, 1, v)

We can avoid a named variable by using a pipe.

c(3, 2, 1, 0, 4, 0) %>% ifelse(. == 0, 1, .)

A common task is to do multiple replacements. Instead of nested ifelse statements, we can use case_when from dplyr:

case_when(v == 0 ~ 1,
          v == 1 ~ 2,
          TRUE ~ v)

Old answer:

For factor or character vectors, we can use revalue from plyr:

> revalue(c("a", "b", "c"), c("b" = "B"))
[1] "a" "B" "c"

This has the advantage of only specifying the input vector once, so we can use a pipe like

x %>% revalue(c("b" = "B"))

RestClientException: Could not extract response. no suitable HttpMessageConverter found

Other possible solution : I tried to map the result of a restTemplate.getForObject with a private class instance (defined inside of my working class). It did not work, but if I define the object to public, inside its own file, it worked correctly.

How to test for $null array in PowerShell

You can reorder the operands:

$null -eq $foo

Note that -eq in PowerShell is not an equivalence relation.

Send response to all clients except sender

Other cases

io.of('/chat').on('connection', function (socket) {
    //sending to all clients in 'room' and you
    io.of('/chat').in('room').emit('message', "data");
};

How to determine if string contains specific substring within the first X characters

shorter version:

found = Value1.StartsWith("abc");

sorry, but I am a stickler for 'less' code.


Given the edit of the questioner I would actually go with something that accepted an offset, this may in fact be a Great place to an Extension method that overloads StartsWith

public static class StackOverflowExtensions
{
    public static bool StartsWith(this String val, string findString, int count)
    {
        return val.Substring(0, count).Contains(findString);
    }
}

How to make a programme continue to run after log out from ssh?

Start in the background:

./long_running_process options &

And disown the job before you log out:

disown

Replace \n with actual new line in Sublime Text

In Sublime Text (with shortcuts on Mac):

  1. Highlight the text that you want to search to apply Find & Replace

  2. Go to Menu > Find > Replace... (Keyboard Shortcut: Alt + Command + F)

  3. In the Find & Replace tool, enable Regular Expression by clicking on the button which looks like [.*] (Keyboard Shortcut: Alt + Command + R)

  4. In Find What, type: \\n

    Note: The additional \ escapes the Regular Expression syntax when searched.

  5. In Replace With, type: \n

  6. Click on the 'Replace All' button (Keyboard Shortcut: CTRL + Alt + Enter)

Your literal text \n will then turn into an actual line break.

Convert HTML string to image

Try the following:

using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

class Program
{
    static void Main(string[] args)
    {
        var source =  @"
        <!DOCTYPE html>
        <html>
            <body>
                <p>An image from W3Schools:</p>
                <img 
                    src=""http://www.w3schools.com/images/w3schools_green.jpg"" 
                    alt=""W3Schools.com"" 
                    width=""104"" 
                    height=""142"">
            </body>
        </html>";
        StartBrowser(source);
        Console.ReadLine();
    }

    private static void StartBrowser(string source)
    {
        var th = new Thread(() =>
        {
            var webBrowser = new WebBrowser();
            webBrowser.ScrollBarsEnabled = false;
            webBrowser.DocumentCompleted +=
                webBrowser_DocumentCompleted;
            webBrowser.DocumentText = source;
            Application.Run();
        });
        th.SetApartmentState(ApartmentState.STA);
        th.Start();
    }

    static void 
        webBrowser_DocumentCompleted(
        object sender, 
        WebBrowserDocumentCompletedEventArgs e)
    {
        var webBrowser = (WebBrowser)sender;
        using (Bitmap bitmap = 
            new Bitmap(
                webBrowser.Width, 
                webBrowser.Height))
        {
            webBrowser
                .DrawToBitmap(
                bitmap, 
                new System.Drawing
                    .Rectangle(0, 0, bitmap.Width, bitmap.Height));
            bitmap.Save(@"filename.jpg", 
                System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
}

Note: Credits should go to Hans Passant for his excellent answer on the question WebBrowser Control in a new thread which inspired this solution.

Adding delay between execution of two following lines

You can use the NSThread method:

[NSThread sleepForTimeInterval: delay];

However, if you do this on the main thread you'll block the app, so only do this on a background thread.


or in Swift

NSThread.sleepForTimeInterval(delay)

in Swift 3

Thread.sleep(forTimeInterval: delay)

Fragments onResume from back stack

In my activity onCreate()

getSupportFragmentManager().addOnBackStackChangedListener(getListener());

Use this method to catch specific Fragment and call onResume()

private FragmentManager.OnBackStackChangedListener getListener()
    {
        FragmentManager.OnBackStackChangedListener result = new FragmentManager.OnBackStackChangedListener()
        {
            public void onBackStackChanged()
            {
                Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
                if (currentFragment instanceof YOURFRAGMENT) {
                    currentFragment.onResume();
                }
            }
        };

        return result;
    }

How do I position an image at the bottom of div?

Add relative positioning to the wrapping div tag, then absolutely position the image within it like this:

CSS:

.div-wrapper {
    position: relative;
    height: 300px;
    width: 300px;
}

.div-wrapper img {
    position: absolute;
    left: 0;
    bottom: 0;
}

HTML:

<div class="div-wrapper">
    <img src="blah.png"/>
</div>

Now the image sits at the bottom of the div.

Differences between key, superkey, minimal superkey, candidate key and primary key

Superkey - An attribute or set of attributes that uniquely defines a tuple within a relation. However, a superkey may contain additional attributes that are not necessary for unique identification.

Candidate key - A superkey such that no proper subset is a superkey within the relation. So, basically has two properties: Each candidate key uniquely identifies tuple in the relation ; & no proper subset of the composite key has the uniqueness property.

Composite key - When a candidate key consists of more than one attribute.

Primary key - The candidate key chosen to identify tuples uniquely within the relation.

Alternate key - Candidate key that is not a primary key.

Foreign key - An attribute or set of attributes within a relation that matches the candidate key of some relation.

PHP - Extracting a property from an array of objects

If you have PHP 5.5 or later, the best way is to use the built in function array_column():

$idCats = array_column($cats, 'id');

But the son has to be an array or converted to an array

Interfaces vs. abstract classes

Another thing to consider is that, since there is no multiple inheritance, if you want a class to be able to implement/inherit from your interface/abstract class, but inherit from another base class, use an interface.

Correct way to synchronize ArrayList in java

Let's take a normal list (implemented by the ArrayList class) and make it synchronized. This is shown in the SynchronizedListExample class. We pass the Collections.synchronizedList method a new ArrayList of Strings. The method returns a synchronized List of Strings. //Here is SynchronizedArrayList class

package com.mnas.technology.automation.utility;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
/**
* 
* @author manoj.kumar
* @email [email protected]
* 
*/
public class SynchronizedArrayList {
    static Logger log = Logger.getLogger(SynchronizedArrayList.class.getName());
    public static void main(String[] args) {    
        List<String> synchronizedList = Collections.synchronizedList(new ArrayList<String>());
        synchronizedList.add("Aditya");
        synchronizedList.add("Siddharth");
        synchronizedList.add("Manoj");
        // when iterating over a synchronized list, we need to synchronize access to the synchronized list
        synchronized (synchronizedList) {
            Iterator<String> iterator = synchronizedList.iterator();
            while (iterator.hasNext()) {
                log.info("Synchronized Array List Items: " + iterator.next());
            }
        }    
    }
}

Notice that when iterating over the list, this access is still done using a synchronized block that locks on the synchronizedList object. In general, iterating over a synchronized collection should be done in a synchronized block

How to wrap text of HTML button with fixed width?

You can force it (browser permitting, I imagine) by inserting line breaks in the HTML source, like this:

<INPUT value="Line 1
Line 2">

Of course working out where to place the line breaks is not necessarily trivial...

If you can use an HTML <BUTTON> instead of an <INPUT>, such that the button label is the element's content rather than its value attribute, placing that content inside a <SPAN> with a width attribute that is a few pixels narrower than that of the button seems to do the trick (even in IE6 :-).

Set time to 00:00:00

We can set java.util.Date time part to 00:00:00 By using LocalDate class of Java 8/Joda-datetime api:

Date datewithTime = new Date() ; // ex: Sat Apr 21 01:30:44 IST 2018
LocalDate localDate = LocalDate.fromDateFields(datewithTime);
Date datewithoutTime = localDate.toDate(); // Sat Apr 21 00:00:00 IST 2018

Django - Did you forget to register or load this tag?

did you try this

{% load games_tags %} 

at the top instead of pygmentize?

Get selected value from combo box in C# WPF

Solving this problem is simple. All I did was to add "SelectedValuePath" to my XAML code and bind it to my model property that I want to return with the combobox.

<ComboBox SelectedValuePath="_Department"
          DisplayMemberPath="_Department"
          Height="23"
          HorizontalAlignment="Left"
          ItemsSource="{Binding}"
          Margin="-58,1,0,5"
          Name="_DepartmentComboBox"
          VerticalAlignment="Center"
          Width="268"/>

How to use the "required" attribute with a "radio" input field

Here is a very basic but modern implementation of required radio buttons with native HTML5 validation:

_x000D_
_x000D_
fieldset { 
  display: block;
  margin-left: 0;
  margin-right: 0;
  padding-top: 0;
  padding-bottom: 0;
  padding-left: 0;
  padding-right: 0;
  border: none;
}
body {font-size: 15px; font-family: serif;}
input {
  background: transparent;
  border-radius: 0px;
  border: 1px solid black;
  padding: 5px;
  box-shadow: none!important;
  font-size: 15px; font-family: serif;
}
input[type="submit"] {padding: 5px 10px; margin-top: 5px;}
label {display: block; padding: 0 0 5px 0;}
form > div {margin-bottom: 1em; overflow: auto;}
.hidden {
  opacity: 0; 
  position: absolute; 
  pointer-events: none;
}
.checkboxes label {display: block; float: left;}
input[type="radio"] + span {
  display: block;
  border: 1px solid black;
  border-left: 0;
  padding: 5px 10px;
}
label:first-child input[type="radio"] + span {border-left: 1px solid black;}
input[type="radio"]:checked + span {background: silver;}
_x000D_
<form>
  <div>
    <label for="name">Name (optional)</label>
    <input id="name" type="text" name="name">
  </div>
  <fieldset>
  <legend>Gender</legend>
  <div class="checkboxes">
    <label for="male"><input id="male" type="radio" name="gender" value="male" class="hidden" required="required"><span>Male</span></label>
    <label for="female"><input id="female" type="radio" name="gender" value="female" class="hidden" required="required"><span>Female </span></label>
    <label for="other"><input id="other" type="radio" name="gender" value="other" class="hidden" required="required"><span>Other</span></label>
  </div>
  </fieldset>
  <input type="submit" value="Send" />
</form>
_x000D_
_x000D_
_x000D_

Although I am a big fan of the minimalistic approach of using native HTML5 validation, you might want to replace it with Javascript validation on the long run. Javascript validation gives you far more control over the validation process and it allows you to set real classes (instead of pseudo classes) to improve the styling of the (in)valid fields. This native HTML5 validation can be your fall-back in case of broken (or lack of) Javascript. You can find an example of that here, along with some other suggestions on how to make Better forms, inspired by Andrew Cole.

Practical uses for the "internal" keyword in C#

Internal classes enable you to limit the API of your assembly. This has benefits, like making your API simpler to understand.

Also, if a bug exists in your assembly, there is less of a chance of the fix introducing a breaking change. Without internal classes, you would have to assume that changing any class's public members would be a breaking change. With internal classes, you can assume that modifying their public members only breaks the internal API of the assembly (and any assemblies referenced in the InternalsVisibleTo attribute).

I like having encapsulation at the class level and at the assembly level. There are some who disagree with this, but it's nice to know that the functionality is available.

How to find out if you're using HTTPS without $_SERVER['HTTPS']

The only reliable method is the one described by Igor M.

$pv_URIprotocol = isset($_SERVER["HTTPS"]) ? (($_SERVER["HTTPS"]==="on" || $_SERVER["HTTPS"]===1 || $_SERVER["SERVER_PORT"]===$pv_sslport) ? "https://" : "http://") :  (($_SERVER["SERVER_PORT"]===$pv_sslport) ? "https://" : "http://");

Consider following: You are using nginx with fastcgi, by default(debian, ubuntu) fastgi_params contain directive:

fastcgi_param HTTPS $https;

if you are NOT using SSL, it gets translated as empty value, not 'off', not 0 and you are doomed.

http://unpec.blogspot.cz/2013/01/nette-nginx-php-fpm-redirect.html

How to find a parent with a known class in jQuery?

<div id="412412412" class="input-group date">
     <div class="input-group-prepend">
          <button class="btn btn-danger" type="button">Button Click</button>
          <input type="text" class="form-control" value="">
      </div>
</div>

In my situation, i use this code:

$(this).parent().closest('.date').attr('id')

Hope this help someone.

How to use querySelectorAll only for elements that have a specific attribute set?

With your example:

<input type="checkbox" id="c2" name="c2" value="DE039230952"/>

Replace $$ with document.querySelectorAll in the examples:

$$('input') //Every input
$$('[id]') //Every element with id
$$('[id="c2"]') //Every element with id="c2"
$$('input,[id]') //Every input + every element with id
$$('input[id]') //Every input including id
$$('input[id="c2"]') //Every input including id="c2"
$$('input#c2') //Every input including id="c2" (same as above)
$$('input#c2[value="DE039230952"]') //Every input including id="c2" and value="DE039230952"
$$('input#c2[value^="DE039"]') //Every input including id="c2" and value has content starting with DE039
$$('input#c2[value$="0952"]') //Every input including id="c2" and value has content ending with 0952
$$('input#c2[value*="39230"]') //Every input including id="c2" and value has content including 39230

Use the examples directly with:

const $$ = document.querySelectorAll.bind(document);

Some additions:

$$(.) //The same as $([class])
$$(div > input) //div is parent tag to input
document.querySelector() //equals to $$()[0] or $()

How to pass parameters or arguments into a gradle task

task mathOnProperties << {
    println Integer.parseInt(a)+Integer.parseInt(b)
    println new Integer(a) * new Integer(b)
}

$ gradle -Pa=3 -Pb=4 mathOnProperties
:mathOnProperties
7
12

BUILD SUCCESSFUL

Submit HTML form, perform javascript function (alert then redirect)

<form action="javascript:completeAndRedirect();">
    <input type="text" id="Edit1" 
    style="width:280; height:50; font-family:'Lucida Sans Unicode', 'Lucida Grande', sans-serif; font-size:22px">
</form>

Changing action to point at your function would solve the problem, in a different way.

Insert Update trigger how to determine if insert or update

DECLARE @INSERTEDCOUNT INT,
        @DELETEDCOUNT INT

SELECT @INSERTEDCOUNT = COUNT([YourColumnName]) FROM inserted

SELECT @DELETEDCOUNT = COUNT([YourColumnName]) FROM deleted

IF its updation

 @INSERTEDCOUNT = 1
 @DELETEDCOUNT = 1

if its insertion

 @INSERTEDCOUNT = 1
 @DELETEDCOUNT = 0

How to align 3 divs (left/center/right) inside another div?

I like my bars tight and dynamic. This is for CSS 3 & HTML 5

  1. First, setting the Width to 100px is limiting. Don't do it.

  2. Second, setting the container's width to 100% will work ok, until were talking about it being a header/footer bar for the whole app, like a navigation or credits/copyright bar. Use right: 0; instead for that scenario.

  3. You are using id's (hash #container, #left, etc) instead of classes (.container, .left, etc), which is fine, unless you want to repeat your style pattern elsewhere in your code. I'd consider using classes instead.

  4. For HTML, no need to swap order for: left, center, & right. display: inline-block; fixes this, returning your code to something cleaner and logically in order again.

  5. Lastly, you need to clear the floats all up so that it doesn't mess with future <div>. You do this with the clear: both;

To summarize:

HTML:

<div class="container">
  <div class="left"></div>
  <div class="center"></div>
  <div class="right"></div>
  <div class="clear"></div>
</div>

CSS:

.container {right: 0; text-align: center;}

.container .left, .container .center, .container .right { display: inline-block; }

.container .left { float: left; }
.container .center { margin: 0 auto; }
.container .right { float: right; }
.clear { clear: both; }

Bonus point if using HAML and SASS ;)

HAML:

.container
  .left
  .center
  .right
  .clear

SASS:

.container {
  right: 0;
  text-align: center;

  .left, .center, .right { display: inline-block; }

  .left { float: left; }
  .center { margin: 0 auto; }
  .right { float: right; }
  .clear { clear: both; }
}

Box shadow in IE7 and IE8

in ie8 you can try

-ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=5, Direction=135, Color='#c0c0c0')";
 filter: progid:DXImageTransform.Microsoft.Shadow(Strength=5, Direction=135, Color='#c0c0c0');

caveat: in ie8 you loose smooth fonts for some reason, they will look ragged

How to Set user name and Password of phpmyadmin

You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.

Count how many rows have the same value

SELECT sum(num) WHERE num = 1;

Understanding CUDA grid dimensions, block dimensions and threads organization (simple explanation)

Suppose a 9800GT GPU:

  • it has 14 multiprocessors (SM)
  • each SM has 8 thread-processors (AKA stream-processors, SP or cores)
  • allows up to 512 threads per block
  • warpsize is 32 (which means each of the 14x8=112 thread-processors can schedule up to 32 threads)

https://www.tutorialspoint.com/cuda/cuda_threads.htm

A block cannot have more active threads than 512 therefore __syncthreads can only synchronize limited number of threads. i.e. If you execute the following with 600 threads:

func1();
__syncthreads();
func2();
__syncthreads();

then the kernel must run twice and the order of execution will be:

  1. func1 is executed for the first 512 threads
  2. func2 is executed for the first 512 threads
  3. func1 is executed for the remaining threads
  4. func2 is executed for the remaining threads

Note:

The main point is __syncthreads is a block-wide operation and it does not synchronize all threads.


I'm not sure about the exact number of threads that __syncthreads can synchronize, since you can create a block with more than 512 threads and let the warp handle the scheduling. To my understanding it's more accurate to say: func1 is executed at least for the first 512 threads.

Before I edited this answer (back in 2010) I measured 14x8x32 threads were synchronized using __syncthreads.

I would greatly appreciate if someone test this again for a more accurate piece of information.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

Paste this code to your pom.xml file. It works for me.

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.6.1</version>
    <scope>test</scope>
</dependency>

Apache Tomcat Not Showing in Eclipse Server Runtime Environments

Help -> check for updates upon Eclipse update solved the issue

Android: Center an image

change layout weight according you will get....

Enter this:

 <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_weight="0.03">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:scaleType="centerInside"
        android:layout_gravity="center"
        android:src="@drawable/logo" />

</LinearLayout>

How do you add UI inside cells in a google spreadsheet using app script?

Status 2018:

There seems to be no way to place buttons (drawings, images) within cells in a way that would allow them to be linked to Apps Script functions.


This being said, there are some things that you can indeed do:

You can...

You can place images within cells using IMAGE(URL), but they cannot be linked to Apps Script functions.

You can place images within cells and link them to URLs using:
=HYPERLINK("http://example.com"; IMAGE("http://example.com/myimage.png"; 1))

You can create drawings as described in the answer of @Eduardo and they can be linked to Apps Script functions, but they will be stand-alone items that float freely "above" the spreadsheet and cannot be positioned in cells. They cannot be copied from cell to cell and they do not have a row or col position that the script function could read.

HTTP 415 unsupported media type error when calling Web API 2 endpoint

SOLVED
After banging my head on the wall for a couple days with this issue, it was looking like the problem had something to do with the content type negotiation between the client and server. I dug deeper into that using Fiddler to check the request details coming from the client app, here's a screenshot of the raw request as captured by fiddler:

Fiddler capture of http request from client app

What's obviously missing there is the Content-Type header, even though I was setting it as seen in the code sample in my original post. I thought it was strange that the Content-Type never came through even though I was setting it, so I had another look at my other (working) code calling a different Web API service, the only difference was that I happened to be setting the req.ContentType property prior to writing to the request body in that case. I made that change to this new code and that did it, the Content-Type was now showing up and I got the expected success response from the web service. The new code from my .NET client now looks like this:

req.Method = "POST"
req.ContentType = "application/json"
lstrPagingJSON = JsonSerializer(Of Paging)(lPaging)
bytData = Encoding.UTF8.GetBytes(lstrPagingJSON)
req.ContentLength = bytData.Length
reqStream = req.GetRequestStream()
reqStream.Write(bytData, 0, bytData.Length)
reqStream.Close()
'// Content-Type was being set here, causing the problem
'req.ContentType = "application/json"

That's all it was, the ContentType property just needed to be set prior to writing to the request body

I believe this behavior is because once content is written to the body it is streamed to the service endpoint being called, any other attributes pertaining to the request need to be set prior to that. Please correct me if I'm wrong or if this needs more detail.

MySQL - Make an existing Field Unique

ALTER IGNORE TABLE mytbl ADD UNIQUE (columnName);

For MySQL 5.7.4 or later:

ALTER TABLE mytbl ADD UNIQUE (columnName);

As of MySQL 5.7.4, the IGNORE clause for ALTER TABLE is removed and its use produces an error.

So, make sure to remove duplicate entries first as IGNORE keyword is no longer supported.

Reference

Cross-reference (named anchor) in markdown

Take me to [pookie](#pookie)

should be the correct markdown syntax to jump to the anchor point named pookie.

To insert an anchor point of that name use HTML:

<a name="pookie"></a>

Markdown doesn't seem to mind where you put the anchor point. A useful place to put it is in a header. For example:

### <a name="tith"></a>This is the Heading

works very well. (I'd demonstrate here but SO's renderer strips out the anchor.)

Note on self-closing tags and id= versus name=

An earlier version of this post suggested using <a id='tith' />, using the self-closing syntax for XHTML, and using the id attribute instead of name.

XHTML allows for any tag to be 'empty' and 'self-closed'. That is, <tag /> is short-hand for <tag></tag>, a matched pair of tags with an empty body. Most browsers will accept XHTML, but some do not. To avoid cross-browser problems, close the tag explicitly using <tag></tag>, as recommended above.

Finally, the attribute name= was deprecated in XHTML, so I originally used id=, which everyone recognises. However, HTML5 now creates a global variable in JavaScript when using id=, and this may not necessarily be what you want. So, using name= is now likely to be more friendly.

(Thanks to Slipp Douglas for explaining XHTML to me, and nailer for pointing out the HTML5 side-effect — see the comments and nailer's answer for more detail. name= appears to work everywhere, though it is deprecated in XHTML.)

Best way to encode text data for XML in Java?

To escape XML characters, the easiest way is to use the Apache Commons Lang project, JAR downloadable from: http://commons.apache.org/lang/

The class is this: org.apache.commons.lang3.StringEscapeUtils;

It has a method named "escapeXml", that will return an appropriately escaped String.

X-Frame-Options: ALLOW-FROM in firefox and chrome

I posted this question and never saw the feedback (which came in several months after, it seems :).

As Kinlan mentioned, ALLOW-FROM is not supported in all browsers as an X-Frame-Options value.

The solution was to branch based on browser type. For IE, ship X-Frame-Options. For everyone else, ship X-Content-Security-Policy.

Hope this helps, and sorry for taking so long to close the loop!

Switching the order of block elements with CSS

Update: Two lightweight CSS solutions:

Using flex, flex-flow and order:

Example1: Demo Fiddle

    body{
        display:flex;
        flex-flow: column;
    }
    #blockA{
        order:4;
    }
    #blockB{
        order:3;
    }
    #blockC{
        order:2;
    }

Alternatively, reverse the Y scale:

Example2: Demo Fiddle

body{
    -webkit-transform: scaleY(-1);
    transform: scaleY(-1);
}
div{
    -webkit-transform: scaleY(-1);
    transform: scaleY(-1);
}

Java - What does "\n" mean?

\n 

This means insert a newline in the text at this point.

Just example

System.out.println("hello\nworld");

Output:

hello
world

error C2065: 'cout' : undeclared identifier

Include the std library by inserting the following line at the top of your code:

using namespace std;

Iterate through object properties

To add ES2015's usage of Reflect.ownKeys(obj) and also iterating over the properties via an iterator.

For example:

let obj = { a: 'Carrot', b: 'Potato', Car: { doors: 4 } };

can be iterated over by

// logs each key
Reflect.ownKeys(obj).forEach(key => console.log(key));

If you would like to iterate directly over the values of the keys of an object, you can define an iterator, just like JavaScipts's default iterators for strings, arrays, typed arrays, Map and Set.

JS will attempt to iterate via the default iterator property, which must be defined as Symbol.iterator.

If you want to be able to iterate over all objects you can add it as a prototype of Object:

Object.prototype[Symbol.iterator] = function*() { 
    for(p of Reflect.ownKeys(this)){ yield this[p]; }
}

This would enable you to iterate over the values of an object with a for...of loop, for example:

for(val of obj) { console.log('Value is:' + val ) }

Caution: As of writing this answer (June 2018) all other browsers, but IE, support generators and for...of iteration via Symbol.iterator

Iterating through a List Object in JSP

Before teaching yourself Spring and Struts, you should probably learn Java. Output like this

org.classes.database.Employee@d9b02

is the result of the Object#toString() method which all objects inherit from the Object class, the superclass of all classes in Java.

The List sub classes implement this by iterating over all the elements and calling toString() on those. It seems, however, that you haven't implemented (overriden) the method in your Employee class.

Your JSTL here

<c:forEach items="${eList}" var="employee">
    <tr>
        <td>Employee ID: <c:out value="${employee.eid}"/></td>
        <td>Employee Pass: <c:out value="${employee.ename}"/></td>  
    </tr>
</c:forEach>

is fine except for the fact that you don't have a page, request, session, or application scoped attribute named eList.

You need to add it

<% List eList = (List)session.getAttribute("empList");
   request.setAttribute("eList", eList);
%>

Or use the attribute empList in the forEach.

<c:forEach items="${empList}" var="employee">
    <tr>
        <td>Employee ID: <c:out value="${employee.eid}"/></td>
        <td>Employee Pass: <c:out value="${employee.ename}"/></td>  
    </tr>
</c:forEach>

How to get label of select option with jQuery?

<SELECT id="sel" onmouseover="alert(this.options[1].text);"
<option value=1>my love</option>
<option value=2>for u</option>
</SELECT>

How to specify line breaks in a multi-line flexbox layout?

I think the traditional way is flexible and fairly easy to understand:

Markup

<div class="flex-grid">
    <div class="col-4">.col-4</div>
    <div class="col-4">.col-4</div>
    <div class="col-4">.col-4</div>

    <div class="col-4">.col-4</div>
    <div class="col-4">.col-4</div>
    <div class="col-4">.col-4</div>

    <div class="col-3">.col-3</div>
    <div class="col-9">.col-9</div>

    <div class="col-6">.col-6</div>
    <div class="col-6">.col-6</div>
</div>

Create grid.css file:

.flex-grid {
  display: flex;
  flex-flow: wrap;
}

.col-1 {flex: 0 0 8.3333%}
.col-2 {flex: 0 0 16.6666%}
.col-3 {flex: 0 0 25%}
.col-4 {flex: 0 0 33.3333%}
.col-5 {flex: 0 0 41.6666%}
.col-6 {flex: 0 0 50%}
.col-7 {flex: 0 0 58.3333%}
.col-8 {flex: 0 0 66.6666%}
.col-9 {flex: 0 0 75%}
.col-10 {flex: 0 0 83.3333%}
.col-11 {flex: 0 0 91.6666%}
.col-12 {flex: 0 0 100%}

[class*="col-"] {
  margin: 0 0 10px 0;

  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

@media (max-width: 400px) {
  .flex-grid {
    display: block;
  }
}

I've created an example (jsfiddle)

Try to resize the window under 400px, it's responsive!!

An error occurred while updating the entries. See the inner exception for details

Click "View Detail..." a window will open where you can expand the "Inner Exception" my guess is that when you try to delete the record there is a reference constraint violation. The inner exception will give you more information on that so you can modify your code to remove any references prior to deleting the record.

enter image description here

Ruby function to remove all white spaces?

"asd sda sda sd".gsub(' ', '')
=> "asdsdasdasd"

Change color of Back button in navigation bar

Very easy to set up in the storyboard:

enter image description here

enter image description here

SSRS the definition of the report is invalid

The report definition is not valid or supported by this version of Reporting Services. This could be the result of publishing a report definition of a later version of Reporting Services, or that the report definition contains XML that is not well-formed or the XML is not valid based on the Report Definition schema.

I got this error when I used ReportSync to upload some .rdl files to SQL Server Report Services. In my case, the issue was that these .rdl files had some Text Box containing characters like ©, (Em dash), (En dash) characters, etc. When uploading .rdl files using ReportSync, I had to encode these characters (&copy;, &mdash;, &ndash;, etc.) and use Placeholder Properties to set the Markup type to HTML in order to get rid of this error.

I wouldn't get this error If I manually uploaded each of the .rdl files one-by-one using SQL Server Reporting Services. But I have a lot of .rdl files and uploading each one individually would be time-consuming, which is why I use ReportSync to mass upload all .rdl files.

Sorry, if my answer doesn't seem relevant, but I hope this helps anyone else getting this error message when dealing with SSRS .rdl files.

C# 30 Days From Todays Date

A bit late to this question, but I created a class with all the handy methods needed to create a fully functional time trial in C#. Rather than your application config, I write the expiry time to the Windows Application Data path, and that will also remain persistent even after the program has closed (it's also tricky to find the path for the average user).

Fully documented and simple to use, I hope someone finds it useful!

public class TimeTrialManager
{
    private long expiryTime=0;
    private string softwareName = "";
    private string userPath="";
    private bool useSeconds = false;

    public TimeTrialManager(string softwareName) {
        this.softwareName = softwareName;
        // Create folder in Windows Application Data folder for persistence:
        userPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString() + "\\" + softwareName + "_prefs\\";
        if (!Directory.Exists(userPath)) Directory.CreateDirectory(Path.GetDirectoryName(userPath));
        userPath += "expiryinfo.txt";
    }

    // Use this method to check if the expiry has already been created. If
    // it has, you don't need to call the setExpiryDate() method ever again.
    public bool expiryHasBeenStored(){
        return File.Exists(userPath);
    }

    // Use this to set expiry as the number of days from the current time.
    // This should be called just once in the program's lifetime for that user.
    public void setExpiryDate(double days)  {
        DateTime time = DateTime.Now.AddDays(days);
        expiryTime = time.ToFileTimeUtc();
        storeExpiry(expiryTime.ToString() );
        useSeconds = false;
    }

    // Like above, but set the number of seconds. This should be just used for testing
    // as no sensible time trial would allow the user seconds to test the trial out:
    public void setExpiryTime(double seconds)   {
        DateTime time = DateTime.Now.AddSeconds(seconds);
        expiryTime = time.ToFileTimeUtc();
        storeExpiry(expiryTime.ToString());
        useSeconds = true;
    }

    // Check for this in a background timer or whenever else you wish to check if the time has run out
    public bool trialHasExpired()   {
        if(!File.Exists(userPath)) return false;
        if (expiryTime == 0)    expiryTime = Convert.ToInt64(File.ReadAllText(userPath));
        if (DateTime.Now.ToFileTimeUtc() >= expiryTime) return true; else return false;
    }

    // This method is optional and isn't required to use the core functionality of the class
    // Perhaps use it to tell the user how long he has left to trial the software
    public string expiryAsHumanReadableString(bool remaining=false) {
        DateTime dt = new DateTime();
        dt = DateTime.FromFileTimeUtc(expiryTime);
        if (remaining == false) return dt.ToShortDateString() + " " + dt.ToLongTimeString();
        else {
            if (useSeconds) return dt.Subtract(DateTime.Now).TotalSeconds.ToString();
            else return (dt.Subtract(DateTime.Now).TotalDays ).ToString();
        }
    }

    // This method is private to the class, so no need to worry about it
    private void storeExpiry(string value)  {
        try { File.WriteAllText(userPath, value); }
        catch (Exception ex) { MessageBox.Show(ex.Message); }
    }

}

Here is a typical usage of the above class. Couldn't be simpler!

TimeTrialManager ttm;
private void Form1_Load(object sender, EventArgs e)
{
    ttm = new TimeTrialManager("TestTime");
    if (!ttm.expiryHasBeenStored()) ttm.setExpiryDate(30); // Expires in 30 days time
}

private void timer1_Tick(object sender, EventArgs e)
{
    if (ttm.trialHasExpired()) { MessageBox.Show("Trial over! :("); Environment.Exit(0); }
}

How to get all count of mongoose model?

The highest voted answers here are perfectly fine I just want to add up the use of await so that the functionality asked for can be archived:

const documentCount = await userModel.count({});
console.log( "Number of users:", documentCount );

It's recommended to use countDocuments() over 'count()' as it will be deprecated going on. So, for now, the perfect code would be:

const documentCount = await userModel.countDocuments({});
console.log( "Number of users:", documentCount );

How do I get bootstrap-datepicker to work with Bootstrap 3?

For anyone else who runs into this...

Version 1.2.0 of this plugin (current as of this post) doesn't quite work in all cases as documented with Bootstrap 3.0, but it does with a minor workaround.

Specifically, if using an input with icon, the HTML markup is of course slightly different as class names have changed:

<div class="input-group" data-datepicker="true">
    <input name="date" type="text" class="form-control" />
    <span class="input-group-addon"><i class="icon-calendar"></i></span>
</div>

It seems because of this, you need to use a selector that points directly to the input element itself NOT the parent container (which is what the auto generated HTML on the demo page suggests).

$('*[data-datepicker="true"] input[type="text"]').datepicker({
    todayBtn: true,
    orientation: "top left",
    autoclose: true,
    todayHighlight: true
});

Having done this you will probably also want to add a listener for clicking/tapping on the icon so it sets focus on the text input when clicked (which is the behaviour when using this plugin with TB 2.x by default).

$(document).on('touch click', '*[data-datepicker="true"] .input-group-addon', function(e){
    $('input[type="text"]', $(this).parent()).focus();
});

NB: I just use a data-datepicker boolean attribute because the class name 'datepicker' is reserved by the plugin and I already use 'date' for styling elements.

Check the current number of connections to MongoDb

Also some more details on the connections with: db.currentOp(true)

Taken from: https://jira.mongodb.org/browse/SERVER-5085

gpg: no valid OpenPGP data found

In my case, the problem turned out to be that the keyfile was behind a 301 Moved Permanently redirect, which the curl command failed to follow. I fixed it by using wget instead:

wget URL
sudo apt-key add FILENAME

...where FILENAME is the file name that wget outputs after it downloads the file.

Update: Alternatively, you can use curl -L to make curl follow redirects.

String contains another two strings

public static class StringExtensions
{
    public static bool Contains(this string s, params string[] predicates)
    {
        return predicates.All(s.Contains);
    }
}

string d = "You hit someone for 50 damage";
string a = "damage";
string b = "someone";
string c = "you";

if (d.Contains(a, b))
{
    Console.WriteLine("d contains a and b");
}

Read and write a String from text file

For reading and writing you should use a location that is writeable, for example documents directory. The following code shows how to read and write a simple string. You can test it on a playground.

Swift 3.x - 5.x

let file = "file.txt" //this is the file. we will write to and read from it

let text = "some text" //just a text

if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {

    let fileURL = dir.appendingPathComponent(file)

    //writing
    do {
        try text.write(to: fileURL, atomically: false, encoding: .utf8)
    }
    catch {/* error handling here */}

    //reading
    do {
        let text2 = try String(contentsOf: fileURL, encoding: .utf8)
    }
    catch {/* error handling here */}
}

Swift 2.2

let file = "file.txt" //this is the file. we will write to and read from it

let text = "some text" //just a text

if let dir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
    let path = NSURL(fileURLWithPath: dir).URLByAppendingPathComponent(file)

    //writing
    do {
        try text.writeToURL(path, atomically: false, encoding: NSUTF8StringEncoding)
    }
    catch {/* error handling here */}

    //reading
    do {
        let text2 = try NSString(contentsOfURL: path, encoding: NSUTF8StringEncoding)
    }
    catch {/* error handling here */}
}

Swift 1.x

let file = "file.txt"

if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] {
    let dir = dirs[0] //documents directory
    let path = dir.stringByAppendingPathComponent(file);
    let text = "some text"

    //writing
    text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil);

    //reading
    let text2 = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)
}

How to import image (.svg, .png ) in a React Component

You can also try:

...
var imageName = require('relative_path_of_image_from_component_file');
...
...

class XYZ extends Component {
    render(){
        return(
            ...
            <img src={imageName.default} alt="something"/>
            ...
        )
    }
}
...

Note: Make sure Image is not outside the project root folder.

multiple conditions for filter in spark data frames

You need to use filter

package dataframe

import org.apache.spark.sql.SparkSession
/**
 * @author [email protected]
 */
//

object DataFrameExample{
  //
  case class Employee(id: Integer, name: String, address: String, salary: Double, state: String,zip:Integer)
  //
  def main(args: Array[String]) {
    val spark =
      SparkSession.builder()
        .appName("DataFrame-Basic")
        .master("local[4]")
        .getOrCreate()

    import spark.implicits._

    // create a sequence of case class objects 

    // (we defined the case class above)

    val emp = Seq( 
    Employee(1, "vaquar khan", "111 algoinquin road chicago", 120000.00, "AZ",60173),
    Employee(2, "Firdos Pasha", "1300 algoinquin road chicago", 2500000.00, "IL",50112),
    Employee(3, "Zidan khan", "112 apt abcd timesqure NY", 50000.00, "NY",55490),
    Employee(4, "Anwars khan", "washington dc", 120000.00, "VA",33245),
    Employee(5, "Deepak sharma ", "rolling edows schumburg", 990090.00, "IL",60172),
    Employee(6, "afaq khan", "saeed colony Bhopal", 1000000.00, "AZ",60173)
    )

    val employee=spark.sparkContext.parallelize(emp, 4).toDF()

     employee.printSchema()

    employee.show()


    employee.select("state", "zip").show()

    println("*** use filter() to choose rows")

    employee.filter($"state".equalTo("IL")).show()

    println("*** multi contidtion in filer || ")

    employee.filter($"state".equalTo("IL") || $"state".equalTo("AZ")).show()

    println("*** multi contidtion in filer &&  ")

    employee.filter($"state".equalTo("AZ") && $"zip".equalTo("60173")).show()

  }
}

How to clear all input fields in bootstrap modal when clicking data-dismiss button?

If you are using a form in the modal then you can use

$("#form_id").trigger("reset");

How to add a class with React.js?

Taken from their site.

render() {
  let className = 'menu';
  if (this.props.isActive) {
    className += ' menu-active';
  }
  return <span className={className}>Menu</span>
}

https://reactjs.org/docs/faq-styling.html

Can you run GUI applications in a Docker container?

The other solutions should work, but here is a solution for docker-compose.

To fix that error, you need to pass $DISPLAY and .X11-unix to docker, as well as grant the user who started docker access to xhost.

Within docker-compose.yml file:

version: '2'
services:
    node:
        build: .
        container_name: node
        environment:
            - DISPLAY
        volumes:
            - /tmp/.X11-unix:/tmp/.X11-unix

In terminal or script:

  • xhost +si:localuser:$USER
  • xhost +local:docker
  • export DISPLAY=$DISPLAY
  • docker-compose up

MySQL Removing Some Foreign keys

The foreign keys are there to ensure data integrity, so you can't drop a column as long as it's part of a foreign key. You need to drop the key first.

I would think the following query would do it:

ALTER TABLE assignmentStuff DROP FOREIGN KEY assignmentIDX;

Installing tensorflow with anaconda in windows

I use windows 10, Anaconda and python 2. A combination of mentioned solutions worked for me:

Once you installed tensorflow using:

C:\Users\Laleh>conda create -n tensorflow python=3.5 # use your python version

C:\Users\Laleh>activate tensorflow

(tensorflow) C:\Users\Laleh>conda install -c conda-forge tensorflow

Then I realized tensorflow can not be imported in jupyter notebook, although it can work in commad windows. To solve this issue first I checked:

jupyter kernelspec list

I removeed the Jupyter kernelspec, useing:

jupyter kernelspec remove python2

Now, the jupyter kernelspec list is pointing to the correct kernel. Again, I activate tensorflow and installed notebook in its environment:

C:\Users\Laleh>activate tensorflow

(tensorflow)C:> conda install notebook

Also if you want to use other libraries such as matplotlib, they should be installed separately in tensorflow environment

(tensorflow)C:> conda install -c conda-forge matplotlib

Now everything works fine for me.

PostgreSQL: days/months/years between two dates

SELECT
  AGE('2012-03-05', '2010-04-01'),
  DATE_PART('year', AGE('2012-03-05', '2010-04-01')) AS years,
  DATE_PART('month', AGE('2012-03-05', '2010-04-01')) AS months,
  DATE_PART('day', AGE('2012-03-05', '2010-04-01')) AS days;

This will give you full years, month, days ... between two dates:

          age          | years | months | days
-----------------------+-------+--------+------
 1 year 11 mons 4 days |     1 |     11 |    4

More detailed datediff information.

Creating watermark using html and css

#watermark
{
 position:fixed;
 bottom:5px;
 right:5px;
 opacity:0.5;
 z-index:99;
 color:white;
}

jSFiddle

Do you recommend using semicolons after every statement in JavaScript?

Yes, you should always use semicolons. Why? Because if you end up using a JavaScript compressor, all your code will be on one line, which will break your code.

Try http://www.jslint.com/; it will hurt your feelings, but show you many ways to write better JavaScript (and one of the ways is to always use semicolons).

How does a Breadth-First Search work when looking for Shortest Path?

I have wasted 3 days
ultimately solved a graph question
used for
finding shortest distance
using BFS

Want to share the experience.

When the (undirected for me) graph has
fixed distance (1, 6, etc.) for edges

#1
We can use BFS to find shortest path simply by traversing it
then, if required, multiply with fixed distance (1, 6, etc.)

#2
As noted above
with BFS
the very 1st time an adjacent node is reached, it is shortest path

#3
It does not matter what queue you use
   deque/queue(c++) or
   your own queue implementation (in c language)
   A circular queue is unnecessary

#4
Number of elements required for queue is N+1 at most, which I used
(dint check if N works)
here, N is V, number of vertices.

#5
Wikipedia BFS will work, and is sufficient.
    https://en.wikipedia.org/wiki/Breadth-first_search#Pseudocode

I have lost 3 days trying all above alternatives, verifying & re-verifying again and again above
they are not the issue.
(Try to spend time looking for other issues, if you dint find any issues with above 5).


More explanation from the comment below:

      A
     /  \
  B       C
 /\       /\
D  E     F  G

Assume above is your graph
graph goes downwards
For A, the adjacents are B & C
For B, the adjacents are D & E
For C, the adjacents are F & G

say, start node is A

  1. when you reach A, to, B & C the shortest distance to B & C from A is 1

  2. when you reach D or E, thru B, the shortest distance to A & D is 2 (A->B->D)

similarly, A->E is 2 (A->B->E)

also, A->F & A->G is 2

So, now instead of 1 distance between nodes, if it is 6, then just multiply the answer by 6
example,
if distance between each is 1, then A->E is 2 (A->B->E = 1+1)
if distance between each is 6, then A->E is 12 (A->B->E = 6+6)

yes, bfs may take any path
but we are calculating for all paths

if you have to go from A to Z, then we travel all paths from A to an intermediate I, and since there will be many paths we discard all but shortest path till I, then continue with shortest path ahead to next node J
again if there are multiple paths from I to J, we only take shortest one
example,
assume,
A -> I we have distance 5
(STEP) assume, I -> J we have multiple paths, of distances 7 & 8, since 7 is shortest
we take A -> J as 5 (A->I shortest) + 8 (shortest now) = 13
so A->J is now 13
we repeat now above (STEP) for J -> K and so on, till we get to Z

Read this part, 2 or 3 times, and draw on paper, you will surely get what i am saying, best of luck


JavaScript replace/regex

Your regex pattern should have the g modifier:

var pattern = /[somepattern]+/g;

notice the g at the end. it tells the replacer to do a global replace.

Also you dont need to use the RegExp object you can construct your pattern as above. Example pattern:

var pattern = /[0-9a-zA-Z]+/g;

a pattern is always surrounded by / on either side - with modifiers after the final /, the g modifier being the global.

EDIT: Why does it matter if pattern is a variable? In your case it would function like this (notice that pattern is still a variable):

var pattern = /[0-9a-zA-Z]+/g;
repeater.replace(pattern, "1234abc");

But you would need to change your replace function to this:

this.markup = this.markup.replace(pattern, value);

Difference between "char" and "String" in Java

A character is anything that you can type such as letters,digits,punctuations and spaces. Strings appears in variables.i.e they are text items in perls. A character consist of 16bits. While the lenght of a string is unlimited.

How to get the file-path of the currently executing javascript code

Regardless of whether its a script, a html file (for a frame, for example), css file, image, whatever, if you dont specify a server/domain the path of the html doc will be the default, so you could do, for example,

<script type=text/javascript src='/dir/jsfile.js'></script>

or

<script type=text/javascript src='../../scripts/jsfile.js'></script>

If you don't provide the server/domain, the path will be relative to either the path of the page or script of the main document's path

Using relative URL in CSS file, what location is it relative to?

In order to create modular style sheets that are not dependent on the absolute location of a resource, authors may use relative URIs. Relative URIs (as defined in [RFC3986]) are resolved to full URIs using a base URI. RFC 3986, section 5, defines the normative algorithm for this process. For CSS style sheets, the base URI is that of the style sheet, not that of the source document.

For example, suppose the following rule:

body { background: url("yellow") }

is located in a style sheet designated by the URI:

http://www.example.org/style/basic.css

The background of the source document's BODY will be tiled with whatever image is described by the resource designated by the URI

http://www.example.org/style/yellow

User agents may vary in how they handle invalid URIs or URIs that designate unavailable or inapplicable resources.

Taken from the CSS 2.1 spec.

How can I suppress the newline after a print statement?

There's some information on printing without newline here.

In Python 3.x we can use ‘end=’ in the print function. This tells it to end the string with a character of our choosing rather than ending with a newline. For example:

print("My 1st String", end=","); print ("My 2nd String.")

This results in:

My 1st String, My 2nd String.

HTML checkbox - allow to check only one checkbox

The unique name identifier applies to radio buttons:

<input type="radio" />

change your checkboxes to radio and everything should be working

Create request with POST, which response codes 200 or 201 and content

Check out HTTP: Method Definitions: POST.

The action performed by the POST method might not result in a resource that can be identified by a URI. In this case, either 200 (OK) or 204 (No Content) is the appropriate response status, depending on whether or not the response includes an entity that describes the result.

If a resource has been created on the origin server, the response SHOULD be 201 (Created) and contain an entity which describes the status of the request and refers to the new resource, and a Location header (see section 14.30).

jQuery attr() change img src

  1. Function imageMorph will create a new img element therefore the id is removed. Changed to

    $("#wrapper > img")

  2. You should use live() function for click event if you want you rocket lanch again.

Updated demo: http://jsfiddle.net/ynhat/QQRsW/4/

Get host domain from URL?

WWW is an alias, so you don't need it if you want a domain. Here is my litllte function to get the real domain from a string

private string GetDomain(string url)
    {
        string[] split = url.Split('.');
        if (split.Length > 2)
            return split[split.Length - 2] + "." + split[split.Length - 1];
        else
            return url;

    }

How to highlight text using javascript

Here's my regexp pure JavaScript solution:

function highlight(text) {
    document.body.innerHTML = document.body.innerHTML.replace(
        new RegExp(text + '(?!([^<]+)?<)', 'gi'),
        '<b style="background-color:#ff0;font-size:100%">$&</b>'
    );
}

Using Transactions or SaveChanges(false) and AcceptAllChanges()?

Because some database can throw an exception at dbContextTransaction.Commit() so better this:

using (var context = new BloggingContext()) 
{ 
  using (var dbContextTransaction = context.Database.BeginTransaction()) 
  { 
    try 
    { 
      context.Database.ExecuteSqlCommand( 
          @"UPDATE Blogs SET Rating = 5" + 
              " WHERE Name LIKE '%Entity Framework%'" 
          ); 

      var query = context.Posts.Where(p => p.Blog.Rating >= 5); 
      foreach (var post in query) 
      { 
          post.Title += "[Cool Blog]"; 
      } 

      context.SaveChanges(false); 

      dbContextTransaction.Commit(); 

      context.AcceptAllChanges();
    } 
    catch (Exception) 
    { 
      dbContextTransaction.Rollback(); 
    } 
  } 
} 

How to get the PID of a process by giving the process name in Mac OS X ?

You can install pidof with Homebrew:

brew install pidof
pidof <process_name>

What is the Maximum Size that an Array can hold?

System.Int32.MaxValue

Assuming you mean System.Array, ie. any normally defined array (int[], etc). This is the maximum number of values the array can hold. The size of each value is only limited by the amount of memory or virtual memory available to hold them.

This limit is enforced because System.Array uses an Int32 as it's indexer, hence only valid values for an Int32 can be used. On top of this, only positive values (ie, >= 0) may be used. This means the absolute maximum upper bound on the size of an array is the absolute maximum upper bound on values for an Int32, which is available in Int32.MaxValue and is equivalent to 2^31, or roughly 2 billion.

On a completely different note, if you're worrying about this, it's likely you're using alot of data, either correctly or incorrectly. In this case, I'd look into using a List<T> instead of an array, so that you are only using as much memory as needed. Infact, I'd recommend using a List<T> or another of the generic collection types all the time. This means that only as much memory as you are actually using will be allocated, but you can use it like you would a normal array.

The other collection of note is Dictionary<int, T> which you can use like a normal array too, but will only be populated sparsely. For instance, in the following code, only one element will be created, instead of the 1000 that an array would create:

Dictionary<int, string> foo = new Dictionary<int, string>();
foo[1000] = "Hello world!";
Console.WriteLine(foo[1000]);

Using Dictionary also lets you control the type of the indexer, and allows you to use negative values. For the absolute maximal sized sparse array you could use a Dictionary<ulong, T>, which will provide more potential elements than you could possible think about.

What is the Java equivalent of PHP var_dump?

I think that the best way to do It, is using google-gson (A Java library to convert JSON to Java objects and vice-versa)

Download It, add "jar" file to your project

HashMap<String, String> map = new HashMap<String, String>();

map.put("key_1", "Baku");
map.put("key_2", "Azerbaijan");
map.put("key_3", "Ali Mamedov");

Gson gson = new Gson();

System.out.println(gson.toJson(map));

Output:

{"key_3":"Ali Mamedov","key_2":"Azerbaijan","key_1":"Baku"}

You can convert any object (arrays, lists and etc) to JSON. I think, that It is the best analog of PHP's var_dump()

How to open an Excel file in C#?

For editing Excel files from within a C# application, I recently started using NPOI. I'm very satisfied with it.

error: expected primary-expression before ')' token (C)

You should create a variable of the type SelectionneNonSelectionne.

struct SelectionneNonSelectionne var;

After that pass that variable to the function like

characterSelection(screen, var);

The error is caused since you are passing the type name SelectionneNonSelectionne

Clearing NSUserDefaults

It's a bug or whatever but the removePersistentDomainForName is not working while clearing all the NSUserDefaults values.

So, better option is that to reset the PersistentDomain and that you can do via following way:

NSUserDefaults.standardUserDefaults().setPersistentDomain(["":""], forName: NSBundle.mainBundle().bundleIdentifier!)

How to put an image in div with CSS?

Take this as a sample code. Replace imageheight and image width with your image dimensions.

<div style="background:yourimage.jpg no-repeat;height:imageheight px;width:imagewidth px">
</div>

How do I compare version numbers in Python?

Posting my full function based on Kindall's solution. I was able to support any alphanumeric characters mixed in with the numbers by padding each version section with leading zeros.

While certainly not as pretty as his one-liner function, it seems to work well with alpha-numeric version numbers. (Just be sure to set the zfill(#) value appropriately if you have long strings in your versioning system.)

def versiontuple(v):
   filled = []
   for point in v.split("."):
      filled.append(point.zfill(8))
   return tuple(filled)

.

>>> versiontuple("10a.4.5.23-alpha") > versiontuple("2a.4.5.23-alpha")
True


>>> "10a.4.5.23-alpha" > "2a.4.5.23-alpha"
False

How to subtract 30 days from the current datetime in mysql?

Let's not use NOW() as you're losing any query caching or optimization because the query is different every time. See the list of functions you should not use in the MySQL documentation.

In the code below, let's assume this table is growing with time. New stuff is added and you want to show just the stuff in the last 30 days. This is the most common case.

Note that the date has been added as a string. It is better to add the date in this way, from your calling code, than to use the NOW() function as it kills your caching.

SELECT * FROM table WHERE exec_datetime >= DATE_SUB('2012-06-12', INTERVAL 30 DAY);

You can use BETWEEN if you really just want stuff from this very second to 30 days before this very second, but that's not a common use case in my experience, so I hope the simplified query can serve you well.

How to select first parent DIV using jQuery?

Use .closest(), which gets the first ancestor element that matches the given selector 'div':

var classes = $(this).closest('div').attr('class').split(' ');

EDIT:

As @Shef noted, .closest() will return the current element if it happens to be a DIV also. To take that into account, use .parent() first:

var classes = $(this).parent().closest('div').attr('class').split(' ');

Difference in boto3 between resource, client, and session?

I'll try and explain it as simple as possible. So there is no guarantee of the accuracy of the actual terms.

Session is where to initiate the connectivity to AWS services. E.g. following is default session that uses the default credential profile(e.g. ~/.aws/credentials, or assume your EC2 using IAM instance profile )

sqs = boto3.client('sqs')
s3 = boto3.resource('s3')

Because default session is limit to the profile or instance profile used, sometimes you need to use the custom session to override the default session configuration (e.g. region_name, endpoint_url, etc. ) e.g.

# custom resource session must use boto3.Session to do the override
my_west_session = boto3.Session(region_name = 'us-west-2')
my_east_session = boto3.Session(region_name = 'us-east-1')
backup_s3 = my_west_session.resource('s3')
video_s3 = my_east_session.resource('s3')

# you have two choices of create custom client session. 
backup_s3c = my_west_session.client('s3')
video_s3c = boto3.client("s3", region_name = 'us-east-1')

Resource : This is the high-level service class recommended to be used. This allows you to tied particular AWS resources and passes it along, so you just use this abstraction than worry which target services are pointed to. As you notice from the session part, if you have a custom session, you just pass this abstract object than worrying about all custom regions,etc to pass along. Following is a complicated example E.g.

import boto3 
my_west_session = boto3.Session(region_name = 'us-west-2')
my_east_session = boto3.Session(region_name = 'us-east-1')
backup_s3 = my_west_session.resource("s3")
video_s3 = my_east_session.resource("s3")
backup_bucket = backup_s3.Bucket('backupbucket') 
video_bucket = video_s3.Bucket('videobucket')

# just pass the instantiated bucket object
def list_bucket_contents(bucket):
   for object in bucket.objects.all():
      print(object.key)

list_bucket_contents(backup_bucket)
list_bucket_contents(video_bucket)

Client is a low level class object. For each client call, you need to explicitly specify the targeting resources, the designated service target name must be pass long. You will lose the abstraction ability.

For example, if you only deal with the default session, this looks similar to boto3.resource.

import boto3 
s3 = boto3.client('s3')

def list_bucket_contents(bucket_name):
   for object in s3.list_objects_v2(Bucket=bucket_name) :
      print(object.key)

list_bucket_contents('Mybucket') 

However, if you want to list objects from a bucket in different regions, you need to specify the explicit bucket parameter required for the client.

import boto3 
backup_s3 = my_west_session.client('s3',region_name = 'us-west-2')
video_s3 = my_east_session.client('s3',region_name = 'us-east-1')

# you must pass boto3.Session.client and the bucket name 
def list_bucket_contents(s3session, bucket_name):
   response = s3session.list_objects_v2(Bucket=bucket_name)
   if 'Contents' in response:
     for obj in response['Contents']:
        print(obj['key'])

list_bucket_contents(backup_s3, 'backupbucket')
list_bucket_contents(video_s3 , 'videobucket') 

Maven Modules + Building a Single Specific Module

If you have previously run mvn install on project B it will have been installed to your local repository, so when you build package A Maven can resolve the dependency. So as long as you install project B each time you change it your builds for project A will be up to date.

You can define a multi-module project with an aggregator pom to build a set of projects.

It's also worthwhile mentioning m2eclipse, it integrates Maven into Eclipse and allows you to (optionally) resolve dependencies from the workspace. So if you are hacking away on multiple projects, the workspace content will be used for compilation. Once you are happy with your changes, run mvn install (on each project in turn, or using an aggregator) to put them in your local repository.

UINavigationBar custom back button without title

Just use an image!

OBJ-C:

- (void)viewDidLoad {
     [super viewDidLoad];
     UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Icon-Back"]
                                                                                        style:UIBarButtonItemStylePlain
                                                                                       target:self.navigationController
                                                                                       action:@selector(popViewControllerAnimated:)];
     self.navigationItem.leftBarButtonItem = backButton;
}

SWIFT 4:

let backBTN = UIBarButtonItem(image: UIImage(named: "Back"), 
                              style: .plain, 
                              target: navigationController, 
                              action: #selector(UINavigationController.popViewController(animated:)))
navigationItem.leftBarButtonItem = backBTN
navigationController?.interactivePopGestureRecognizer?.delegate = self

Icon-Back.png

Icon-Back

[email protected]

Icon-Back@2x

[email protected]

Icon-Back@23x

Access Denied for User 'root'@'localhost' (using password: YES) - No Privileges?

Use the instructions for resetting the root password - but instead of resetting the root password, we'll going to forcefully INSERT a record into the mysql.user table

In the init file, use this instead

INSERT INTO mysql.user (Host, User, Password) VALUES ('%', 'root', password('YOURPASSWORD'));
GRANT ALL ON *.* TO 'root'@'%' WITH GRANT OPTION;

Data binding for TextBox

I Recommend you implement INotifyPropertyChanged and change your databinding code to this:

this.textBox.DataBindings.Add("Text",
                                this.Food,
                                "Name",
                                false,
                                DataSourceUpdateMode.OnPropertyChanged);

That'll fix it.

Note that the default DataSourceUpdateMode is OnValidation, so if you don't specify OnPropertyChanged, the model object won't be updated until after your validations have occurred.

Undo git update-index --assume-unchanged <file>

To get undo/show dir's/files that are set to assume-unchanged run this:

git update-index --no-assume-unchanged <file>

To get a list of dir's/files that are assume-unchanged run this:

git ls-files -v|grep '^h'

Improve INSERT-per-second performance of SQLite

If you care only about reading, somewhat faster (but might read stale data) version is to read from multiple connections from multiple threads (connection per-thread).

First find the items, in the table:

SELECT COUNT(*) FROM table

then read in pages (LIMIT/OFFSET):

SELECT * FROM table ORDER BY _ROWID_ LIMIT <limit> OFFSET <offset>

where and are calculated per-thread, like this:

int limit = (count + n_threads - 1)/n_threads;

for each thread:

int offset = thread_index * limit

For our small (200mb) db this made 50-75% speed-up (3.8.0.2 64-bit on Windows 7). Our tables are heavily non-normalized (1000-1500 columns, roughly 100,000 or more rows).

Too many or too little threads won't do it, you need to benchmark and profile yourself.

Also for us, SHAREDCACHE made the performance slower, so I manually put PRIVATECACHE (cause it was enabled globally for us)

PHP prepend leading zero before single digit number, on-the-fly

You can use sprintf: http://php.net/manual/en/function.sprintf.php

<?php
$num = 4;
$num_padded = sprintf("%02d", $num);
echo $num_padded; // returns 04
?>

It will only add the zero if it's less than the required number of characters.

Edit: As pointed out by @FelipeAls:

When working with numbers, you should use %d (rather than %s), especially when there is the potential for negative numbers. If you're only using positive numbers, either option works fine.

For example:

sprintf("%04s", 10); returns 0010
sprintf("%04s", -10); returns 0-10

Where as:

sprintf("%04d", 10); returns 0010
sprintf("%04d", -10); returns -010

Optional query string parameters in ASP.NET Web API

Use initial default values for all parameters like below

public string GetFindBooks(string author="", string title="", string isbn="", string  somethingelse="", DateTime? date= null) 
{
    // ...
}

What is JNDI? What is its basic use? When is it used?

What is JNDI ?

It stands for Java Naming and Directory Interface.

What is its basic use?

JNDI allows distributed applications to look up services in an abstract, resource-independent way.

When it is used?

The most common use case is to set up a database connection pool on a Java EE application server. Any application that's deployed on that server can gain access to the connections they need using the JNDI name java:comp/env/FooBarPool without having to know the details about the connection.

This has several advantages:

  1. If you have a deployment sequence where apps move from devl->int->test->prod environments, you can use the same JNDI name in each environment and hide the actual database being used. Applications don't have to change as they migrate between environments.
  2. You can minimize the number of folks who need to know the credentials for accessing a production database. Only the Java EE app server needs to know if you use JNDI.

Create PDF from a list of images

**** Convert images files to pdf file.****
from os import listdir
from fpdf import FPDF

path = "/home/bunny/images/" # get the path of images

imagelist = listdir(path) # get list of all images

pdf = FPDF('P','mm','A4') # create an A4-size pdf document 

x,y,w,h = 0,0,200,250

for image in imagelist:

    pdf.add_page()
    pdf.image(path+image,x,y,w,h)

pdf.output("images.pdf","F")

How to implement onBackPressed() in Fragments?

Just add addToBackStack while you are transitioning between your fragments like below:

fragmentManager.beginTransaction().replace(R.id.content_frame,fragment).addToBackStack("tag").commit();

if you write addToBackStack(null) , it will handle it by itself but if you give a tag , you should handle it manually.

Returning multiple values from a C++ function

Personally, I generally dislike return parameters for a number of reasons:

  • it is not always obvious in the invocation which parameters are ins and which are outs
  • you generally have to create a local variable to catch the result, while return values can be used inline (which may or may not be a good idea, but at least you have the option)
  • it seems cleaner to me to have an "in door" and an "out door" to a function -- all the inputs go in here, all the outputs come out there
  • I like to keep my argument lists as short as possible

I also have some reservations about the pair/tuple technique. Mainly, there is often no natural order to the return values. How is the reader of the code to know whether result.first is the quotient or the remainder? And the implementer could change the order, which would break existing code. This is especially insidious if the values are the same type so that no compiler error or warning would be generated. Actually, these arguments apply to return parameters as well.

Here's another code example, this one a bit less trivial:

pair<double,double> calculateResultingVelocity(double windSpeed, double windAzimuth,
                                               double planeAirspeed, double planeCourse);

pair<double,double> result = calculateResultingVelocity(25, 320, 280, 90);
cout << result.first << endl;
cout << result.second << endl;

Does this print groundspeed and course, or course and groundspeed? It's not obvious.

Compare to this:

struct Velocity {
    double speed;
    double azimuth;
};
Velocity calculateResultingVelocity(double windSpeed, double windAzimuth,
                                    double planeAirspeed, double planeCourse);

Velocity result = calculateResultingVelocity(25, 320, 280, 90);
cout << result.speed << endl;
cout << result.azimuth << endl;

I think this is clearer.

So I think my first choice in general is the struct technique. The pair/tuple idea is likely a great solution in certain cases. I'd like to avoid the return parameters when possible.

Evaluate if list is empty JSTL

empty is an operator:

The empty operator is a prefix operation that can be used to determine whether a value is null or empty.

<c:if test="${empty myObject.featuresList}">

Spring Boot access static resources missing scr/main/resources

I use spring boot, so i can simple use:

File file = ResourceUtils.getFile("classpath:myfile.xml");

Is there a better way to refresh WebView?

Yes for some reason WebView.reload() causes a crash if it failed to load before (something to do with the way it handles history). This is the code I use to refresh my webview. I store the current url in self.url

# 1: Pause timeout and page loading

self.timeout.pause()
sleep(1)

# 2: Check for internet connection (Really lazy way)

while self.page().networkAccessManager().networkAccessible() == QNetworkAccessManager.NotAccessible: sleep(2)

# 3:Try again

if self.url == self.page().mainFrame().url():
    self.page().action(QWebPage.Reload)
    self.timeout.resume(60)

else:
    self.page().action(QWebPage.Stop)
    self.page().mainFrame().load(self.url)
    self.timeout.resume(30)

return False

How to update multiple columns in single update statement in DB2

update table_name set (col1,col2,col3) values(col1,col2,col);

Is not standard SQL and not working you got to use this as Gordon Linoff said:

update table
    set col1 = expr1,
        col2 = expr2,
        . . .
        coln = exprn
    where some condition

How is Java platform-independent when it needs a JVM to run?

It means the Java programmer does not (in theory) need to know machine or OS details. These details do exist and the JVM and class libraries handle them. Further, in sharp contrast to C, Java binaries (bytecode) can often be moved to entirely different systems without modifying or recompiling.

How do I set the eclipse.ini -vm option?

Anything after the "vmargs" is taken to be vm arguments. Just make sure it's before that, which is the last piece in eclipse.ini.

Can't connect to Postgresql on port 5432

I had this same issue. I originally installed version 10 because that was the default install with Ubuntu 18.04. I later upgraded to 13.2 because I wanted the latest version. I made all the config modifications, but it was still just binging to 1207.0.0.1 and then I thought - maybe it is looking at the config files for version 10. I modified those and restarted the postgres service. Bingo! It was binding to 0.0.0.0

I will need to completely remove 10 and ensure that I am forcing the service to run under version 13.2, so if you upgraded from another version, try updating the other config files in that older directory.

Convert int to char in java

It seems like you are looking for the Character.forDigit method:

final int RADIX = 10;
int i = 4;
char ch = Character.forDigit(i, RADIX);
System.out.println(ch); // Prints '4'

There is also a method that can convert from a char back to an int:

int i2 = Character.digit(ch, RADIX);
System.out.println(i2); // Prints '4'

Note that by changing the RADIX you can also support hexadecimal (radix 16) and any radix up to 36 (or Character.MAX_RADIX as it is also known as).

How to read the RGB value of a given pixel in Python?

If you are looking to have three digits in the form of an RGB colour code, the following code should do just that.

i = Image.open(path)
pixels = i.load() # this is not a list, nor is it list()'able
width, height = i.size

all_pixels = []
for x in range(width):
    for y in range(height):
        cpixel = pixels[x, y]
        all_pixels.append(cpixel)

This may work for you.

get user timezone

Just as Oded has answered. You need to have this sort of detection functionality in javascript.

I've struggled with this myself and realized that the offset is not enough. It does not give you any information about daylight saving for example. I ended up writing some code to map to zoneinfo database keys.

By checking several dates around a year you can more accurately determine a timezone.

Try the script here: http://jsfiddle.net/pellepim/CsNcf/

Simply change your system timezone and click run to test it. If you are running chrome you need to do each test in a new tab though (and safar needs to be restarted to pick up timezone changes).

If you want more details of the code check out: https://bitbucket.org/pellepim/jstimezonedetect/

pip installation /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory

Only solution in OSX and its variant.

ln -s /usr/local/bin/python /usr/local/opt/python/bin/python2.7

In PHP, how do you change the key of an array element?

One which preservers ordering that's simple to understand:

function rename_array_key(array $array, $old_key, $new_key) {
  if (!array_key_exists($old_key, $array)) {
      return $array;
  }
  $new_array = [];
  foreach ($array as $key => $value) {
    $new_key = $old_key === $key
      ? $new_key
      : $key;
    $new_array[$new_key] = $value;
  }
  return $new_array;
}

Remove pandas rows with duplicate indices

I would suggest using the duplicated method on the Pandas Index itself:

df3 = df3[~df3.index.duplicated(keep='first')]

While all the other methods work, the currently accepted answer is by far the least performant for the provided example. Furthermore, while the groupby method is only slightly less performant, I find the duplicated method to be more readable.

Using the sample data provided:

>>> %timeit df3.reset_index().drop_duplicates(subset='index', keep='first').set_index('index')
1000 loops, best of 3: 1.54 ms per loop

>>> %timeit df3.groupby(df3.index).first()
1000 loops, best of 3: 580 µs per loop

>>> %timeit df3[~df3.index.duplicated(keep='first')]
1000 loops, best of 3: 307 µs per loop

Note that you can keep the last element by changing the keep argument to 'last'.

It should also be noted that this method works with MultiIndex as well (using df1 as specified in Paul's example):

>>> %timeit df1.groupby(level=df1.index.names).last()
1000 loops, best of 3: 771 µs per loop

>>> %timeit df1[~df1.index.duplicated(keep='last')]
1000 loops, best of 3: 365 µs per loop

what is Promotional and Feature graphic in Android Market/Play Store?

It's here http://www.android.com/market/featured.html Weirdly, you don't get to that page if you start from the android market and hit "featured". Mary

Launching an application (.EXE) from C#?

Use System.Diagnostics.Process.Start() method.

Check out this article on how to use it.

Process.Start("notepad", "readme.txt");

string winpath = Environment.GetEnvironmentVariable("windir");
string path = System.IO.Path.GetDirectoryName(
              System.Windows.Forms.Application.ExecutablePath);

Process.Start(winpath + @"\Microsoft.NET\Framework\v1.0.3705\Installutil.exe",
path + "\\MyService.exe");

How do I uniquely identify computers visiting my web site?

Cookies won't be useful for determining unique visitors. A user could clear cookies and refresh the site - he then is classed as a new user again.

I think that the best way to go about doing this is to implement a server side solution (as you will need somewhere to store your data). Depending on the complexity of your needs for such data, you will need to determine what is classed as a unique visit. A sensible method would be to allow an IP address to return the following day and be given a unique visit. Several visits from one IP address in one day shouldn't be counted as uniques.

Using PHP, for example, it is trivial to get the IP address of a visitor, and store it in a text file (or a sql database).

A server side solution will work on all machines, because you are going to track the user when he first loads up your site. Don't use javascript, as that is meant for client side scripting, plus the user may have disabled it in any case.

Hope that helps.

SQL Row_Number() function in Where Clause

In response to comments on rexem's answer, with respect to whether a an inline view or CTE would be faster I recast the queries to use a table I, and everyone, had available: sys.objects.

WITH object_rows AS (
    SELECT object_id, 
        ROW_NUMBER() OVER ( ORDER BY object_id) RN
    FROM sys.objects)
SELECT object_id
FROM object_rows
WHERE RN > 1

SELECT object_id
FROM (SELECT object_id, 
        ROW_NUMBER() OVER ( ORDER BY object_id) RN
    FROM sys.objects) T
WHERE RN > 1

The query plans produced were exactly the same. I would expect in all cases, the query optimizer would come up with the same plan, at least in simple replacement of CTE with inline view or vice versa.

Of course, try your own queries on your own system to see if there is a difference.

Also, row_number() in the where clause is a common error in answers given on Stack Overflow. Logicaly row_number() is not available until the select clause is processed. People forget that and when they answer without testing the answer, the answer is sometimes wrong. (A charge I have myself been guilty of.)

How to filter array in subdocument with MongoDB

Using aggregate is the right approach, but you need to $unwind the list array before applying the $match so that you can filter individual elements and then use $group to put it back together:

db.test.aggregate([
    { $match: {_id: ObjectId("512e28984815cbfcb21646a7")}},
    { $unwind: '$list'},
    { $match: {'list.a': {$gt: 3}}},
    { $group: {_id: '$_id', list: {$push: '$list.a'}}}
])

outputs:

{
  "result": [
    {
      "_id": ObjectId("512e28984815cbfcb21646a7"),
      "list": [
        4,
        5
      ]
    }
  ],
  "ok": 1
}

MongoDB 3.2 Update

Starting with the 3.2 release, you can use the new $filter aggregation operator to do this more efficiently by only including the list elements you want during a $project:

db.test.aggregate([
    { $match: {_id: ObjectId("512e28984815cbfcb21646a7")}},
    { $project: {
        list: {$filter: {
            input: '$list',
            as: 'item',
            cond: {$gt: ['$$item.a', 3]}
        }}
    }}
])

Java switch statement: Constant expression required, but it IS constant

You get Constant expression required because you left the values off your constants. Try:

public abstract class Foo {
    ...
    public static final int BAR=0;
    public static final int BAZ=1;
    public static final int BAM=2;
    ...
}

MVC 3: How to render a view without its layout page when loaded via ajax?

For a Ruby on Rails application, I was able to prevent a layout from loading by specifying render layout: false in the controller action that I wanted to respond with ajax html.

What is the difference between Sessions and Cookies in PHP?

Cookies are stored in browser as a text file format.It stores limited amount of data, up to 4kb[4096bytes].A single Cookie can not hold multiple values but yes we can have more than one cookie.

Cookies are easily accessible so they are less secure. The setcookie() function must appear BEFORE the tag.

Sessions are stored in server side.There is no such storage limit on session .Sessions can hold multiple variables.Since they are not easily accessible hence are more secure than cookies.

pip install mysql-python fails with EnvironmentError: mysql_config not found

You should install the mysql first:

yum install python-devel mysql-community-devel -y

Then you can install mysqlclient:

pip install  mysqlclient

Getting String Value from Json Object Android

This might help you.

Java:

JSONArray arr = new JSONArray(result);
JSONObject jObj = arr.getJSONObject(0);
String date = jObj.getString("NeededString");

Kotlin:

val jsonArray = JSONArray(result)
val jsonObject: JSONObject = jsonArray.getJSONObject(0)
val date= jsonObject.get("NeededString")
  • getJSONObject(index). In above example 0 represents index.

How to use Servlets and Ajax?

Ajax (also AJAX) an acronym for Asynchronous JavaScript and XML) is a group of interrelated web development techniques used on the client-side to create asynchronous web applications. With Ajax, web applications can send data to, and retrieve data from, a server asynchronously Below is example code:

Jsp page java script function to submit data to servlet with two variable firstName and lastName:

function onChangeSubmitCallWebServiceAJAX()
    {
      createXmlHttpRequest();
      var firstName=document.getElementById("firstName").value;
      var lastName=document.getElementById("lastName").value;
      xmlHttp.open("GET","/AJAXServletCallSample/AjaxServlet?firstName="
      +firstName+"&lastName="+lastName,true)
      xmlHttp.onreadystatechange=handleStateChange;
      xmlHttp.send(null);

    }

Servlet to read data send back to jsp in xml format ( You could use text as well. Just you need to change response content to text and render data on javascript function.)

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String firstName = request.getParameter("firstName");
    String lastName = request.getParameter("lastName");

    response.setContentType("text/xml");
    response.setHeader("Cache-Control", "no-cache");
    response.getWriter().write("<details>");
    response.getWriter().write("<firstName>"+firstName+"</firstName>");
    response.getWriter().write("<lastName>"+lastName+"</lastName>");
    response.getWriter().write("</details>");
}

PHP MySQL Query Where x = $variable

$result = mysqli_query($con,"SELECT `note` FROM `glogin_users` WHERE email = '".$email."'");
while($row = mysqli_fetch_array($result))
echo $row['note'];

.htaccess 301 redirect of single page

RedirectMatch uses a regular expression that is matched against the URL path. And your regular expression /contact.php just means any URL path that contains /contact.php but not just any URL path that is exactly /contact.php. So use the anchors for the start and end of the string (^ and $):

RedirectMatch 301 ^/contact\.php$ /contact-us.php

jquery find class and get the value

var myVar = $("#start").find('myClass').val();

needs to be

var myVar = $("#start").find('.myClass').val();

Remember the CSS selector rules require "." if selecting by class name. The absence of "." is interpreted to mean searching for <myclass></myclass>.

How to integrate sourcetree for gitlab

Using the SSH URL from GitLab:

Step 1: Generate an SSH Key with default values from GitLab.

GitLab provides the commands to generate it. Just copy them, edit the email, and paste it in the terminal. Using the default values is important. Else SourceTree will not be able to access the SSH key without additional configuration.

STEP 2: Add the SSH key to your keychain using the command ssh-add -K.

Open the terminal and paste the above command in it. This will add the key to your keychain.

STEP 3: Restart SourceTree and clone remote repo using URL.

Restarting SourceTree is needed so that SourceTree picks the new key.

enter image description here

STEP 4: Copy the SSH URL provided by GitLab.

enter image description here

STEP 5: Paste the SSH URL into the Source URL field of SourceTree.

enter image description here

These steps were successfully performed on Mac OS 10.13.2 using SourceTree 2.7.1.

enter image description hereenter image description here

How to check if an array element exists?

You can also use array_keys for number of occurrences

<?php
$array=array('1','2','6','6','6','5');
$i=count(array_keys($array, 6));
if($i>0)
 echo "Element exists in Array";
?>

Absolute and Flexbox in React Native

The first step would be to add

position: 'absolute',

then if you want the element full width, add

left: 0,
right: 0,

then, if you want to put the element in the bottom, add

bottom: 0,
// don't need set top: 0

if you want to position the element at the top, replace bottom: 0 by top: 0

Call jQuery Ajax Request Each X Minutes

I found a very good jquery plugin that can ease your life with this type of operation. You can checkout https://github.com/ocombe/jQuery-keepAlive.

$.fn.keepAlive({url: 'your-route/filename', timer: 'time'},       function(response) {
        console.log(response);
      });//

How to restore the dump into your running mongodb

Follow this path.

C:\Program Files\MongoDB\Server\4.2\bin

Run the cmd in bin folder and paste the below command

mongorestore --db <name-your-database-want-to-restore-as> <path-of-dumped-database>

For Example:

mongorestore --db testDb D:\Documents\Dump\myDb

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

I was struggling with Outlook and Office365. Surprisingly the thing that seemed to work was:

<table align='center' style='text-align:center'>
  <tr>
    <td align='center' style='text-align:center'>
      <!-- AMAZING CONTENT! -->
    </td>
  </tr>
</table>

I only listed some of the key things that resolved my Microsoft email issues.

Might I add that building an email that looks nice on all emails is a pain. This website was super nice for testing: https://putsmail.com/

It allows you to list all the emails you'd like to send your test email to. You can paste your code right into the window, edit, send, and resend. It helped me a ton.

How do I get the directory from a file's full path?

Use below mentioned code to get the folder path

Path.GetDirectoryName(filename);

This will return "C:\MyDirectory" in your case

How do I kill a VMware virtual machine that won't die?

Similar, but using WMIC command line to obtain the process ID and path:

WMIC /OUTPUT:C:\ProcessList.txt PROCESS get Caption,Commandline,Processid

This will create a text file with each process and its parameters. You can search in the file for your VM File Path, and get the correct Process ID to end task with.

Thanks to http://windowsxp.mvps.org/listproc.htm for the correct command line parameters.

Insert images to XML file

I always convert the byte data to a Base64 encoding and then insert the image.

This is also the way that Word does it, for it's XML files (not that Word is a good example on how to work with XML :P).

Change Orientation of Bluestack : portrait/landscape mode

I install go launcher on mine, (Windows 8)=> preferences => Screens => Screen orientation => vertical (disable QWE keyboard)

Error: Generic Array Creation

The following will give you an array of the type you want while preserving type safety.

PCB[] getAll(Class<PCB[]> arrayType) {  
    PCB[] res = arrayType.cast(java.lang.reflect.Array.newInstance(arrayType.getComponentType(), list.size()));  
    for (int i = 0; i < res.length; i++)  {  
        res[i] = list.get(i);  
    }  
    list.clear();  
    return res;  
}

How this works is explained in depth in my answer to the question that Kirk Woll linked as a duplicate.

Trim a string based on the string length

Here is the Kotlin solution

One line,

if (yourString?.length!! >= 10) yourString?.take(90).plus("...") else yourString

Traditional,

if (yourString?.length!! >= 10) {
  yourString?.take(10).plus("...")
 } else {
  yourString
 }

React - Preventing Form Submission

Make sure you put the onSubmit attribute on the form not the button in case you have a from.

<form onSubmit={e => e.preventDefault()}>
    <button onClick={this.handleClick}>Click Me</button>
</form>

Make sure to change the button onClick attribute to your custom function.

Go to particular revision

To get to a specific committed code, you need the hash code of that commit. You can get that hash code in two ways:

  1. Get it from your github/gitlab/bitbucket account. (It's on your commit url, i.e: github.com/user/my_project/commit/commit_hash_code), or you can
  2. git log and check your recent commits on that branch. It will show you the hash code of your commit and the message you leaved while you were committing your code. Just copy and then do git checkout commit_hash_code

After moving to that code, if you want to work on it and make changes, you should make another branch with git checkout -b <new-branch-name>, otherwise, the changes will not be retained.

Cut Corners using CSS

We had the problem of different background colors for our cutted elements. And we only wanted upper right und bottom left corner.

enter image description here

_x000D_
_x000D_
body {_x000D_
 background-color: rgba(0,0,0,0.3)_x000D_
 _x000D_
}_x000D_
_x000D_
.box {_x000D_
 position: relative;_x000D_
 display: block;_x000D_
 background: blue;_x000D_
 text-align: center;_x000D_
 color: white;_x000D_
 padding: 15px;_x000D_
 margin: 50px;_x000D_
}_x000D_
_x000D_
.box:before,_x000D_
.box:after {_x000D_
 content: "";_x000D_
 position: absolute;_x000D_
 left: 0; _x000D_
 right: 0;_x000D_
 bottom: 100%;_x000D_
 border-bottom: 15px solid blue;_x000D_
 border-left: 15px solid transparent;_x000D_
 border-right: 15px solid transparent;_x000D_
}_x000D_
_x000D_
.box:before{_x000D_
 border-left: 15px solid blue;_x000D_
}_x000D_
_x000D_
.box:after{_x000D_
 border-right: 15px solid blue;_x000D_
}_x000D_
_x000D_
.box:after {_x000D_
 bottom: auto;_x000D_
 top: 100%;_x000D_
 border-bottom: none;_x000D_
 border-top: 15px solid blue;_x000D_
}_x000D_
_x000D_
_x000D_
/* Active box */_x000D_
.box.active{_x000D_
 background: white;_x000D_
 color: black;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
.active:before,_x000D_
.active:after {_x000D_
 border-bottom: 15px solid white;_x000D_
}_x000D_
_x000D_
.active:before{_x000D_
 border-left: 15px solid white;_x000D_
}_x000D_
_x000D_
.active:after{_x000D_
 border-right: 15px solid white;_x000D_
}_x000D_
_x000D_
.active:after {_x000D_
 border-bottom: none;_x000D_
 border-top: 15px solid white;_x000D_
}
_x000D_
<div class="box">_x000D_
 Some text goes here. Some text goes here. Some text goes here. Some text goes here.<br/>Some text goes here.<br/>Some text goes here.<br/>Some text goes here.<br/>Some text goes here.<br/>Some text goes here.<br/>_x000D_
</div>_x000D_
<div class="box">_x000D_
 Some text goes here._x000D_
</div>_x000D_
<div class="box active">_x000D_
 Some text goes here._x000D_
 <span class="border-bottom"></span>_x000D_
</div>_x000D_
<div class="box">_x000D_
 Some text goes here._x000D_
</div>
_x000D_
_x000D_
_x000D_

Align contents inside a div

All the answers talk about horizontal align.

For vertical aligning multiple content elements, take a look at this approach:

_x000D_
_x000D_
<div style="display: flex; align-items: center; width: 200px; height: 140px; padding: 10px 40px; border: solid 1px black;">_x000D_
    <div>_x000D_
        <p>Paragraph #1</p>_x000D_
        <p>Paragraph #2</p>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Conditional Formatting (IF not empty)

You can use Conditional formatting with the option "Formula Is". One possible formula is

=NOT(ISBLANK($B1))

enter image description here

Another possible formula is

=$B1<>""

enter image description here