Programs & Examples On #Solid principles

The SOLID principles are the five principles of object-oriented design introduced or documented by Robert C. Martin.

What is an example of the Liskov Substitution Principle?

Would implementing ThreeDBoard in terms of an array of Board be that useful?

Perhaps you may want to treat slices of ThreeDBoard in various planes as a Board. In that case you may want to abstract out an interface (or abstract class) for Board to allow for multiple implementations.

In terms of external interface, you might want to factor out a Board interface for both TwoDBoard and ThreeDBoard (although none of the above methods fit).

Is an entity body allowed for an HTTP DELETE request?

Some versions of Tomcat and Jetty seem to ignore a entity body if it is present. Which can be a nuisance if you intended to receive it.

React - Component Full Screen (with height 100%)

For a project using CRNA i use this in index.css

html, body, #root {
  height: 100%;
}

and then in my App.css i use this

.App {
  height: 100%;
}

and also set height to 100% for a div within App if there is one eg-

.MainGridContainer {
  display: grid;
  width: 100%;
  height:100%;
  grid-template-columns: 1fr 3fr;
  grid-template-rows: 50px auto;
}

How to align this span to the right of the div?

The solution using flexbox without justify-content: space-between.

<div class="title">
  <span>Cumulative performance</span>
  <span>20/02/2011</span>
</div>

.title {
  display: flex;
}

span:first-of-type {
  flex: 1;
}

When we use flex:1 on the first <span>, it takes up the entire remaining space and moves the second <span> to the right. The Fiddle with this solution: https://jsfiddle.net/2k1vryn7/

Here https://jsfiddle.net/7wvx2uLp/3/ you can see the difference between two flexbox approaches: flexbox with justify-content: space-between and flexbox with flex:1 on the first <span>.

How to clear all input fields in a specific div with jQuery?

Just had to delete all inputs within a div & using the colon in front of the input when targeting gets most everything.

$('#divId').find(':input').val('');

How can I divide two integers stored in variables in Python?

x / y

quotient of x and y

x // y 

(floored) quotient of x and y

How to properly upgrade node using nvm

Node.JS to install a new version.

Step 1 : NVM Install

npm i -g nvm

Step 2 : NODE Newest version install

nvm install *.*.*(NodeVersion)

Step 3 : Selected Node Version

nvm use *.*.*(NodeVersion)

Finish

NSURLErrorDomain error codes description

I received the error Domain=NSURLErrorDomain Code=-1011 when using Parse, and providing the wrong clientKey. As soon as I corrected that, it began working.

Selenium WebDriver: I want to overwrite value in field instead of appending to it with sendKeys using Java

The original question says clear() cannot be used. This does not apply to that situation. I'm adding my working example here as this SO post was one of the first Google results for clearing an input before entering a value.

For input where here is no additional restriction I'm including a browser agnostic method for Selenium using NodeJS. This snippet is part of a common library I import with var test = require( 'common' ); in my test scripts. It is for a standard node module.exports definition.

when_id_exists_type : function( id, value ) {
driver.wait( webdriver.until.elementLocated( webdriver.By.id( id ) ) , 3000 )
    .then( function() {
        var el = driver.findElement( webdriver.By.id( id ) );
        el.click();
        el.clear();
        el.sendKeys( value );
    });
},

Find the element, click it, clear it, then send the keys.

This page has a complete code sample and article that may help.

font size in html code

<html>        
    <table>
        <tr>
            <td style="padding-left: 5px;padding-bottom:3px; font-size:35px;"> <b>Datum:</b><br/>
            November 2010 </td>
    </table>
</html>

How to add a href link in PHP?

you have problems with " :

 <a href=<?php echo "'www.someotherwebsite.com'><img src='". url::file_loc('img'). "media/img/twitter.png' style='vertical-align: middle' border='0'></a>"; ?>

What is CDATA in HTML?

From http://en.wikipedia.org/wiki/CDATA:

Since it is useful to be able to use less-than signs (<) and ampersands (&) in web page scripts, and to a lesser extent styles, without having to remember to escape them, it is common to use CDATA markers around the text of inline and elements in XHTML documents. But so that the document can also be parsed by HTML parsers, which do not recognise the CDATA markers, the CDATA markers are usually commented-out, as in this JavaScript example:

<script type="text/javascript">
//<![CDATA[
document.write("<");
//]]>
</script>

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

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

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

import types

class ComparesNicely(object):

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

            if key not in other.__dict__:
                return False

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

         return True

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

How to get response using cURL in PHP

The crux of the solution is setting

CURLOPT_RETURNTRANSFER => true

then

$response = curl_exec($ch);

CURLOPT_RETURNTRANSFER tells PHP to store the response in a variable instead of printing it to the page, so $response will contain your response. Here's your most basic working code (I think, didn't test it):

// init curl object        
$ch = curl_init();

// define options
$optArray = array(
    CURLOPT_URL => 'http://www.google.com',
    CURLOPT_RETURNTRANSFER => true
);

// apply those options
curl_setopt_array($ch, $optArray);

// execute request and get response
$result = curl_exec($ch);

Change Background color (css property) using Jquery

Try below jQuery snippet, you can change color :

<script type="text/javascript">
    $(document).ready(function(){
        $("#co").click(function() {
            $("body").css("background-color", "yellow");
        });
    });
</script>

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    $("#co").click(function() {_x000D_
        $("body").css("background-color", "yellow");_x000D_
    });_x000D_
});
_x000D_
body {_x000D_
    background-color:red;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="co" click="change()">hello</div>
_x000D_
_x000D_
_x000D_

How can I specify the schema to run an sql file against in the Postgresql command line

I was facing similar problems trying to do some dat import on an intermediate schema (that later we move on to the final one). As we rely on things like extensions (for example PostGIS), the "run_insert" sql file did not fully solved the problem.

After a while, we've found that at least with Postgres 9.3 the solution is far easier... just create your SQL script always specifying the schema when refering to the table:

CREATE TABLE "my_schema"."my_table" (...); COPY "my_schema"."my_table" (...) FROM stdin;

This way using psql -f xxxxx works perfectly, and you don't need to change search_paths nor use intermediate files (and won't hit extension schema problems).

List of remotes for a Git repository?

None of those methods work the way the questioner is asking for and which I've often had a need for as well. eg:

$ git remote
fatal: Not a git repository (or any of the parent directories): .git
$ git remote user@bserver
fatal: Not a git repository (or any of the parent directories): .git
$ git remote user@server:/home/user
fatal: Not a git repository (or any of the parent directories): .git
$ git ls-remote
fatal: No remote configured to list refs from.
$ git ls-remote user@server:/home/user
fatal: '/home/user' does not appear to be a git repository
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

The whole point of doing this is that you do not have any information except the remote user and server and want to find out what you have access to.

The majority of the answers assume you are querying from within a git working set. The questioner is assuming you are not.

As a practical example, assume there was a repository foo.git on the server. Someone in their wisdom decides they need to change it to foo2.git. It would really be nice to do a list of a git directory on the server. And yes, I see the problems for git. It would still be nice to have though.

QtCreator: No valid kits found

In my case the issue was that my default kit's Qt version was None.

Go to Tools -> Options... -> Build & Run -> Kits tab, click on the kit you want to make as default and you'll see a list of fields beneath, one of which is Qt version. If it's None, change it to one of the versions available to you in the Qt versions tab which is just next to the Kits tab.

Replace given value in vector

If you want to replace lot of values in single go, you can use 'library(car)'.

Example

library(car)

x <- rep(1:5,3)

xr <- recode(x, '3=1; 4=2')

x
## [1] 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
xr
## [1] 1 2 1 2 5 1 2 1 2 5 1 2 1 2 5

Call to undefined function curl_init().?

The CURL extension ext/curl is not installed or enabled in your PHP installation. Check the manual for information on how to install or enable CURL on your system.

Check image width and height before upload with Javascript

function uploadfile(ctrl) {
    var validate = validateimg(ctrl);

    if (validate) {
        if (window.FormData !== undefined) {
            ShowLoading();
            var fileUpload = $(ctrl).get(0);
            var files = fileUpload.files;


            var fileData = new FormData();


            for (var i = 0; i < files.length; i++) {
                fileData.append(files[i].name, files[i]);
            }


            fileData.append('username', 'Wishes');

            $.ajax({
                url: 'UploadWishesFiles',
                type: "POST",
                contentType: false,
                processData: false,
                data: fileData,
                success: function(result) {
                    var id = $(ctrl).attr('id');
                    $('#' + id.replace('txt', 'hdn')).val(result);

                    $('#imgPictureEn').attr('src', '../Data/Wishes/' + result).show();

                    HideLoading();
                },
                error: function(err) {
                    alert(err.statusText);
                    HideLoading();
                }
            });
        } else {
            alert("FormData is not supported.");
        }

    }

How to find row number of a value in R code

As of R 3.3.0, one may use startsWith() as a faster alternative to grepl():

which(startsWith(mydata_2$height_seca1, 1578))

Add and Remove Views in Android Dynamically?

Just use myView.setVisibility(View.GONE); to remove it completely. But if you want to reserve the occupied space inside its parent use myView.setVisibility(View.INVISIBLE);

Is this the proper way to do boolean test in SQL?

I personally prefer using char(1) with values 'Y' and 'N' for databases that don't have a native type for boolean. Letters are more user frendly than numbers which assume that those reading it will now that 1 corresponds to true and 0 corresponds to false.

'Y' and 'N' also maps nicely when using (N)Hibernate.

How do I insert values into a Map<K, V>?

There are two issues here.

Firstly, you can't use the [] syntax like you may be able to in other languages. Square brackets only apply to arrays in Java, and so can only be used with integer indexes.

data.put is correct but that is a statement and so must exist in a method block. Only field declarations can exist at the class level. Here is an example where everything is within the local scope of a method:

public class Data {
     public static void main(String[] args) {
         Map<String, String> data = new HashMap<String, String>();
         data.put("John", "Taxi Driver");
         data.put("Mark", "Professional Killer");
     }
 }

If you want to initialize a map as a static field of a class then you can use Map.of, since Java 9:

public class Data {
    private static final Map<String, String> DATA = Map.of("John", "Taxi Driver");
}

Before Java 9, you can use a static initializer block to accomplish the same thing:

public class Data {
    private static final Map<String, String> DATA = new HashMap<>();

    static {
        DATA.put("John", "Taxi Driver");
    }
}

Which Radio button in the group is checked?

You could use LINQ:

var checkedButton = container.Controls.OfType<RadioButton>()
                                      .FirstOrDefault(r => r.Checked);

Note that this requires that all of the radio buttons be directly in the same container (eg, Panel or Form), and that there is only one group in the container. If that is not the case, you could make List<RadioButton>s in your constructor for each group, then write list.FirstOrDefault(r => r.Checked).

What is the regular expression to allow uppercase/lowercase (alphabetical characters), periods, spaces and dashes only?

Check out the basics of regular expressions in a tutorial. All it requires is two anchors and a repeated character class:

^[a-zA-Z ._-]*$

If you use the case-insensitive modifier, you can shorten this to

^[a-z ._-]*$

Note that the space is significant (it is just a character like any other).

How to update values in a specific row in a Python Pandas DataFrame?

In SQL, I would have do it in one shot as

update table1 set col1 = new_value where col1 = old_value

but in Python Pandas, we could just do this:

data = [['ram', 10], ['sam', 15], ['tam', 15]] 
kids = pd.DataFrame(data, columns = ['Name', 'Age']) 
kids

which will generate the following output :

    Name    Age
0   ram     10
1   sam     15
2   tam     15

now we can run:

kids.loc[kids.Age == 15,'Age'] = 17
kids

which will show the following output

Name    Age
0   ram     10
1   sam     17
2   tam     17

which should be equivalent to the following SQL

update kids set age = 17 where age = 15

Array of char* should end at '\0' or "\0"?

Well, technically '\0' is a character while "\0" is a string, so if you're checking for the null termination character the former is correct. However, as Chris Lutz points out in his answer, your comparison won't work in it's current form.

Plot width settings in ipython notebook

If you're not in an ipython notebook (like the OP), you can also just declare the size when you declare the figure:

width = 12
height = 12
plt.figure(figsize=(width, height))

How can I discover the "path" of an embedded resource?

I use the following method to grab embedded resources:

    protected static Stream GetResourceStream(string resourcePath)
    {
        Assembly assembly = Assembly.GetExecutingAssembly();
        List<string> resourceNames = new List<string>(assembly.GetManifestResourceNames());

        resourcePath = resourcePath.Replace(@"/", ".");
        resourcePath = resourceNames.FirstOrDefault(r => r.Contains(resourcePath));

        if (resourcePath == null)
            throw new FileNotFoundException("Resource not found");

        return assembly.GetManifestResourceStream(resourcePath);
    }

I then call this with the path in the project:

GetResourceStream(@"DirectoryPathInLibrary/Filename")

How to solve "The directory is not empty" error when running rmdir command in a batch script?

As @gfullam stated in a comment to @BoffinbraiN's answer, the <dir> you are deleting itself might not be the one which contains files: there might be subdirectories in <dir> that get a "The directory is not empty" message and the only solution then would be to recursively iterate over the directories, manually deleting all their containing files... I ended up deciding to use a port of rm from UNIX. rm.exe comes with Git Bash, MinGW, Cygwin, GnuWin32 and others. You just need to have its parent directory in your PATH and then execute as you would in a UNIX system.

Batch script example:

set PATH=C:\cygwin64\bin;%PATH%
rm -rf "C:\<dir>"

Iterate through a C array

If the size of the array is known at compile time, you can use the structure size to determine the number of elements.

struct foo fooarr[10];

for(i = 0; i < sizeof(fooarr) / sizeof(struct foo); i++)
{
  do_something(fooarr[i].data);
}

If it is not known at compile time, you will need to store a size somewhere or create a special terminator value at the end of the array.

Broken references in Virtualenvs

If you using pipenv, just doing pipenv --rm solves the problem.

figure of imshow() is too small

Update 2020

as requested by @baxxx, here is an update because random.rand is deprecated meanwhile.

This works with matplotlip 3.2.1:

from matplotlib import pyplot as plt
import random
import numpy as np

random = np.random.random ([8,90])

plt.figure(figsize = (20,2))
plt.imshow(random, interpolation='nearest')

This plots:

enter image description here

To change the random number, you can experiment with np.random.normal(0,1,(8,90)) (here mean = 0, standard deviation = 1).

how to return a char array from a function in C

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *substring(int i,int j,char *ch)
{
    int n,k=0;
    char *ch1;
    ch1=(char*)malloc((j-i+1)*1);
    n=j-i+1;

    while(k<n)
    {
        ch1[k]=ch[i];
        i++;k++;
    }

    return (char *)ch1;
}

int main()
{
    int i=0,j=2;
    char s[]="String";
    char *test;

    test=substring(i,j,s);
    printf("%s",test);
    free(test); //free the test 
    return 0;
}

This will compile fine without any warning

  1. #include stdlib.h
  2. pass test=substring(i,j,s);
  3. remove m as it is unused
  4. either declare char substring(int i,int j,char *ch) or define it before main

Bold black cursor in Eclipse deletes code, and I don't know how to get rid of it

The problem is also identified in your status bar at the bottom:

overwrite label in status bar

You are in overwrite mode instead of insert mode.

The “Insert” key toggles between insert and overwrite modes.

How to get current user in asp.net core

This is old question but my case shows that my case wasn't discussed here.

I like the most the answer of Simon_Weaver (https://stackoverflow.com/a/54411397/2903893). He explains in details how to get user name using IPrincipal and IIdentity. This answer is absolutely correct and I recommend to use this approach. However, during debugging I encountered with the problem when ASP.NET can NOT populate service principle properly. (or in other words, IPrincipal.Identity.Name is null)

It's obvious that to get user name MVC framework should take it from somewhere. In the .NET world, ASP.NET or ASP.NET Core is using Open ID Connect middleware. In the simple scenario web apps authenticate a user in a web browser. In this scenario, the web application directs the user’s browser to sign them in to Azure AD. Azure AD returns a sign-in response through the user’s browser, which contains claims about the user in a security token. To make it work in the code for your application, you'll need to provide the authority to which you web app delegates sign-in. When you deploy your web app to Azure Service the common scenario to meet this requirements is to configure web app: "App Services" -> YourApp -> "Authentication / Authorization" blade -> "App Service Authenticatio" = "On" and so on (https://github.com/Huachao/azure-content/blob/master/articles/app-service-api/app-service-api-authentication.md). I beliebe (this is my educated guess) that under the hood of this process the wizard adjusts "parent" web config of this web app by adding the same settings that I show in following paragraphs. Basically, the issue why this approach does NOT work in ASP.NET Core is because "parent" machine config is ignored by webconfig. (this is not 100% sure, I just give the best explanation that I have). So, to meke it work you need to setup this manually in your app.

Here is an article that explains how to manyally setup your app to use Azure AD. https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/tree/aspnetcore2-2

Step 1: Register the sample with your Azure AD tenant. (it's obvious, don't want to spend my time of explanations).

Step 2: In the appsettings.json file: replace the ClientID value with the Application ID from the application you registered in Application Registration portal on Step 1. replace the TenantId value with common

Step 3: Open the Startup.cs file and in the ConfigureServices method, after the line containing .AddAzureAD insert the following code, which enables your application to sign in users with the Azure AD v2.0 endpoint, that is both Work and School and Microsoft Personal accounts.

services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
    options.Authority = options.Authority + "/v2.0/";
    options.TokenValidationParameters.ValidateIssuer = false;
});

Summary: I've showed one more possible issue that could leed to an error that topic starter is explained. The reason of this issue is missing configurations for Azure AD (Open ID middleware). In order to solve this issue I propose manually setup "Authentication / Authorization". The short overview of how to setup this is added.

How to play ringtone/alarm sound in Android

This works fine:

AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
MediaPlayer thePlayer = MediaPlayer.create(getApplicationContext(), RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

try {
    thePlayer.setVolume((float) (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) / 7.0)),
                        (float) (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) / 7.0)));
} catch (Exception e) {
    e.printStackTrace();
}

thePlayer.start();

Browser: Identifier X has already been declared

But I have declared that var in the top of the other files.

That's the problem. After all, this makes multiple declarations for the same name in the same (global) scope - which will throw an error with const.

Instead, use var, use only one declaration in your main file, or only assign to window.APP exclusively.
Or use ES6 modules right away, and let your module bundler/loader deal with exposing them as expected.

Find the server name for an Oracle database

The query below demonstrates use of the package and some of the information you can get.

select sys_context ( 'USERENV', 'DB_NAME' ) db_name,
sys_context ( 'USERENV', 'SESSION_USER' ) user_name,
sys_context ( 'USERENV', 'SERVER_HOST' ) db_host,
sys_context ( 'USERENV', 'HOST' ) user_host
from dual

NOTE: The parameter ‘SERVER_HOST’ is available in 10G only.

Any Oracle User that can connect to the database can run a query against “dual”. No special permissions are required and SYS_CONTEXT provides a greater range of application-specific information than “sys.v$instance”.

Disabling the button after once click

jQuery .one() should not be used with the click event but with the submit event as described below.

 $('input[type=submit]').one('submit', function() {
     $(this).attr('disabled','disabled');
 });

Is it not possible to stringify an Error using JSON.stringify?

Modifying Jonathan's great answer to avoid monkey patching:

var stringifyError = function(err, filter, space) {
  var plainObject = {};
  Object.getOwnPropertyNames(err).forEach(function(key) {
    plainObject[key] = err[key];
  });
  return JSON.stringify(plainObject, filter, space);
};

var error = new Error('testing');
error.detail = 'foo bar';

console.log(stringifyError(error, null, '\t'));

Group by with union mysql select query

This may be what your after:

SELECT Count(Owner_ID), Name
FROM (
    SELECT M.Owner_ID, O.Name, T.Type
    FROM Transport As T, Owner As O, Motorbike As M
    WHERE T.Type = 'Motorbike'
    AND O.Owner_ID = M.Owner_ID
    AND T.Type_ID = M.Motorbike_ID

    UNION ALL

    SELECT C.Owner_ID, O.Name, T.Type
    FROM Transport As T, Owner As O, Car As C
    WHERE T.Type = 'Car'
    AND O.Owner_ID = C.Owner_ID
    AND T.Type_ID = C.Car_ID
)
GROUP BY Owner_ID

Parse a URI String into Name-Value Collection

If you are using servlet doGet try this

request.getParameterMap()

Returns a java.util.Map of the parameters of this request.

Returns: an immutable java.util.Map containing parameter names as keys and parameter values as map values. The keys in the parameter map are of type String. The values in the parameter map are of type String array.

(Java doc)

A TypeScript GUID class?

There is an implementation in my TypeScript utilities based on JavaScript GUID generators.

Here is the code:

_x000D_
_x000D_
class Guid {_x000D_
  static newGuid() {_x000D_
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {_x000D_
      var r = Math.random() * 16 | 0,_x000D_
        v = c == 'x' ? r : (r & 0x3 | 0x8);_x000D_
      return v.toString(16);_x000D_
    });_x000D_
  }_x000D_
}_x000D_
_x000D_
// Example of a bunch of GUIDs_x000D_
for (var i = 0; i < 100; i++) {_x000D_
  var id = Guid.newGuid();_x000D_
  console.log(id);_x000D_
}
_x000D_
_x000D_
_x000D_

Please note the following:

C# GUIDs are guaranteed to be unique. This solution is very likely to be unique. There is a huge gap between "very likely" and "guaranteed" and you don't want to fall through this gap.

JavaScript-generated GUIDs are great to use as a temporary key that you use while waiting for a server to respond, but I wouldn't necessarily trust them as the primary key in a database. If you are going to rely on a JavaScript-generated GUID, I would be tempted to check a register each time a GUID is created to ensure you haven't got a duplicate (an issue that has come up in the Chrome browser in some cases).

In Python, how do I read the exif data for an image?

You can use the _getexif() protected method of a PIL Image.

import PIL.Image
img = PIL.Image.open('img.jpg')
exif_data = img._getexif()

This should give you a dictionary indexed by EXIF numeric tags. If you want the dictionary indexed by the actual EXIF tag name strings, try something like:

import PIL.ExifTags
exif = {
    PIL.ExifTags.TAGS[k]: v
    for k, v in img._getexif().items()
    if k in PIL.ExifTags.TAGS
}

anaconda update all possible packages?

TL;DR: dependency conflicts: Updating one requires (by it's requirements) to downgrade another

You are right:

conda update --all

is actually the way to go1. Conda always tries to upgrade the packages to the newest version in the series (say Python 2.x or 3.x).

Dependency conflicts

But it is possible that there are dependency conflicts (which prevent a further upgrade). Conda usually warns very explicitly if they occur.

e.g. X requires Y <5.0, so Y will never be >= 5.0

That's why you 'cannot' upgrade them all.

Resolving

To add: maybe it could work but a newer version of X working with Y > 5.0 is not available in conda. It is possible to install with pip, since more packages are available in pip. But be aware that pip also installs packages if dependency conflicts exist and that it usually breaks your conda environment in the sense that you cannot reliably install with conda anymore. If you do that, do it as a last resort and after all packages have been installed with conda. It's rather a hack.

A safe way you can try is to add conda-forge as a channel when upgrading (add -c conda-forge as a flag) or any other channel you find that contains your package if you really need this new version. This way conda does also search in this places for available packages.

Considering your update: You can upgrade them each separately, but doing so will not only include an upgrade but also a downgrade of another package as well. Say, to add to the example above:

X > 2.0 requires Y < 5.0, X < 2.0 requires Y > 5.0

So upgrading Y > 5.0 implies downgrading X to < 2.0 and vice versa.

(this is a pedagogical example, of course, but it's the same in reality, usually just with more complicated dependencies and sub-dependencies)

So you still cannot upgrade them all by doing the upgrades separately; the dependencies are just not satisfiable so earlier or later, an upgrade will downgrade an already upgraded package again. Or break the compatibility of the packages (which you usually don't want!), which is only possible by explicitly invoking an ignore-dependencies and force-command. But that is only to hack your way around issues, definitely not the normal-user case!


1 If you actually want to update the packages of your installation, which you usually don't. The command run in the base environment will update the packages in this, but usually you should work with virtual environments (conda create -n myenv and then conda activate myenv). Executing conda update --all inside such an environment will update the packages inside this environment. However, since the base environment is also an environment, the answer applies to both cases in the same way.

Failed to fetch URL https://dl-ssl.google.com/android/repository/addons_list-1.xml, reason: Connection to https://dl-ssl.google.com refused

After 7 long hours of searching I finally found the way!! None of the above solutions worked, only one of them pointed towards the issue!

If you are on Win7, then your Firewall blocks the SDK Manager from retrieving the addon list. You will have to add "android.bat" and "java.exe" to the trusted files and bingo! everything will start working!!

How do I run Selenium in Xvfb?

You can use PyVirtualDisplay (a Python wrapper for Xvfb) to run headless WebDriver tests.

#!/usr/bin/env python

from pyvirtualdisplay import Display
from selenium import webdriver

display = Display(visible=0, size=(800, 600))
display.start()

# now Firefox will run in a virtual display. 
# you will not see the browser.
browser = webdriver.Firefox()
browser.get('http://www.google.com')
print browser.title
browser.quit()

display.stop()

more info


You can also use xvfbwrapper, which is a similar module (but has no external dependencies):

from xvfbwrapper import Xvfb

vdisplay = Xvfb()
vdisplay.start()

# launch stuff inside virtual display here

vdisplay.stop()

or better yet, use it as a context manager:

from xvfbwrapper import Xvfb

with Xvfb() as xvfb:
    # launch stuff inside virtual display here.
    # It starts/stops in this code block.

Uncaught TypeError: Cannot set property 'onclick' of null

Make sure your javascript is being executed after your element(s) have loaded, perhaps try putting the js file call just before the tag or use the defer attribute in your script, like so: <script src="app.js" defer></script> this makes sure that your script will be executed after the dom has loaded.

Adjust plot title (main) position

Try this:

par(adj = 0)
plot(1, 1, main = "Title")

or equivalent:

plot(1, 1, main = "Title", adj = 0)

adj = 0 produces left-justified text, 0.5 (the default) centered text and 1 right-justified text. Any value in [0, 1] is allowed.

However, the issue is that this will also change the position of the label of the x-axis and y-axis.

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

Replace the dependency in the POM.xml file

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.2.3</version>
</dependency>

By the dependency

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.4</version>
    </dependency>

How to extract hours and minutes from a datetime.datetime object?

datetime has fields hour and minute. So to get the hours and minutes, you would use t1.hour and t1.minute.

However, when you subtract two datetimes, the result is a timedelta, which only has the days and seconds fields. So you'll need to divide and multiply as necessary to get the numbers you need.

Swift - How to convert String to Double

we can use CDouble value which will be obtained by myString.doubleValue

Eloquent Collection: Counting and Detect Empty

According to Laravel Documentation states you can use this way:

$result->isEmpty();

The isEmpty method returns true if the collection is empty; otherwise, false is returned.

What are the differences between 'call-template' and 'apply-templates' in XSL?

To add to the good answer by @Tomalak:

Here are some unmentioned and important differences:

  1. xsl:apply-templates is much richer and deeper than xsl:call-templates and even from xsl:for-each, simply because we don't know what code will be applied on the nodes of the selection -- in the general case this code will be different for different nodes of the node-list.

  2. The code that will be applied can be written way after the xsl:apply templates was written and by people that do not know the original author.

The FXSL library's implementation of higher-order functions (HOF) in XSLT wouldn't be possible if XSLT didn't have the <xsl:apply-templates> instruction.

Summary: Templates and the <xsl:apply-templates> instruction is how XSLT implements and deals with polymorphism.

Reference: See this whole thread: http://www.biglist.com/lists/lists.mulberrytech.com/xsl-list/archives/200411/msg00546.html

Finding all objects that have a given property inside a collection

Sounds a lot like something you would use LINQ for in .NET

While there's no "real" LINQ implementation for java yet, you might want to have a look at Quaere which could do what you describe easily enough.

How to pass data from child component to its parent in ReactJS?

You can even avoid the function at the parent updating the state directly

In Parent Component:

render(){
 return(<Child sendData={ v => this.setState({item: v}) } />);
}

In the Child Component:

demoMethod(){
   this.props.sendData(value);
}

How to check if a list is empty in Python?

I like Zarembisty's answer. Although, if you want to be more explicit, you can always do:

if len(my_list) == 0:
    print "my_list is empty"

Convert double to string

a = 0.000006;
b = 6;
c = a/b;

textbox.Text = c.ToString("0.000000");

As you requested:

textbox.Text = c.ToString("0.######");

This will only display out to the 6th decimal place if there are 6 decimals to display.

In Gradle, is there a better way to get Environment Variables?

I couldn't get the form suggested by @thoredge to work in Gradle 1.11, but this works for me:

home = System.getenv('HOME')

It helps to keep in mind that anything that works in pure Java will work in Gradle too.

Regex to extract substring, returning 2 results for some reason

match returns an array.

The default string representation of an array in JavaScript is the elements of the array separated by commas. In this case the desired result is in the second element of the array:

var tesst = "afskfsd33j"
var test = tesst.match(/a(.*)j/);
alert (test[1]);

How to use basic authorization in PHP curl

Can you try this,

 $ch = curl_init($url);
 ...
 curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);  
 ...

REF: http://php.net/manual/en/function.curl-setopt.php

How do I remove lines between ListViews on Android?

Set divider to null:

JAVA

  listview_id.setDivider(null);

XML

<ListView 
  android:id="@+id/listview"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:divider="@null"
  />

How do I find a particular value in an array and return its index?

the fancy answer. Use std::vector and search with std::find

the simple answer

use a for loop

How to convert a Collection to List?

What you request is quite a costy operation, make sure you don't need to do it often (e.g in a cycle).

If you need it to stay sorted and you update it frequently, you can create a custom collection. For example, I came up with one that has your TreeBidiMap and TreeMultiset under the hood. Implement only what you need and care about data integrity.

class MyCustomCollection implements Map<K, V> {
    TreeBidiMap<K, V> map;
    TreeMultiset<V> multiset;
    public V put(K key, V value) {
        removeValue(map.put(key, value));
        multiset.add(value);
    }
    public boolean remove(K key) {
        removeValue(map.remove(key));
    }
    /** removes value that was removed/replaced in map */
    private removeValue(V value) {
        if (value != null) {
            multiset.remove(value);
        }
    }
    public Set<K> keySet() {
        return Collections.unmodifiableSet(map.keySet());
    }
    public Collection<V> values() {
        return Collections.unmodifiableCollection(multiset);
    }
    // many more methods to be implemented, e.g. count, isEmpty etc.
    // but these are fairly simple
}

This way, you have a sorted Multiset returned from values(). However, if you need it to be a list (e.g. you need the array-like get(index) method), you'd need something more complex.

For brevity, I only return unmodifiable collections. What @Lino mentioned is correct, and modifying the keySet or values collection as it is would make it inconsistent. I don't know any consistent way to make the values mutable, but the keySet could support remove if it uses the remove method from the MyCustomCollection class above.

Unit testing click event in Angular

I had a similar problem (detailed explanation below), and I solved it (in jasmine-core: 2.52) by using the tick function with the same (or greater) amount of milliseconds as in original setTimeout call.

For example, if I had a setTimeout(() => {...}, 2500); (so it will trigger after 2500 ms), I would call tick(2500), and that would solve the problem.

What I had in my component, as a reaction on a Delete button click:

delete() {
    this.myService.delete(this.id)
      .subscribe(
        response => {
          this.message = 'Successfully deleted! Redirecting...';
          setTimeout(() => {
            this.router.navigate(['/home']);
          }, 2500); // I wait for 2.5 seconds before redirect
        });
  }

Her is my working test:

it('should delete the entity', fakeAsync(() => {
    component.id = 1; // preparations..
    component.getEntity(); // this one loads up the entity to my component
    tick(); // make sure that everything that is async is resolved/completed
    expect(myService.getMyThing).toHaveBeenCalledWith(1);
    // more expects here..
    fixture.detectChanges();
    tick();
    fixture.detectChanges();
    const deleteButton = fixture.debugElement.query(By.css('.btn-danger')).nativeElement;
    deleteButton.click(); // I've clicked the button, and now the delete function is called...

    tick(2501); // timeout for redirect is 2500 ms :)  <-- solution

    expect(myService.delete).toHaveBeenCalledWith(1);
    // more expects here..
  }));

P.S. Great explanation on fakeAsync and general asyncs in testing can be found here: a video on Testing strategies with Angular 2 - Julie Ralph, starting from 8:10, lasting 4 minutes :)

Search text in fields in every table of a MySQL database

If you are avoiding stored procedures like the plague, or are unable to do a mysql_dump due to permissions, or running into other various reasons.

I would suggest a three-step approach like this:

1) Where this query builds a bunch of queries as a result set.

# =================
# VAR/CHAR SEARCH
# =================
# BE ADVISED USE ANY OF THESE WITH CAUTION
# DON'T RUN ON YOUR PRODUCTION SERVER 
# ** USE AN ALTERNATE BACKUP **

SELECT 
    CONCAT('SELECT * FROM ', A.TABLE_SCHEMA, '.', A.TABLE_NAME, 
           ' WHERE ', A.COLUMN_NAME, ' LIKE \'%stuff%\';') 
FROM INFORMATION_SCHEMA.COLUMNS A
WHERE 
            A.TABLE_SCHEMA != 'mysql' 
AND     A.TABLE_SCHEMA != 'innodb' 
AND     A.TABLE_SCHEMA != 'performance_schema' 
AND     A.TABLE_SCHEMA != 'information_schema'
AND     
        (
            A.DATA_TYPE LIKE '%text%'
        OR  
            A.DATA_TYPE LIKE '%char%'
        )
;

.

# =================
# NUMBER SEARCH
# =================
# BE ADVISED USE WITH CAUTION

SELECT 
    CONCAT('SELECT * FROM ', A.TABLE_SCHEMA, '.', A.TABLE_NAME, 
           ' WHERE ', A.COLUMN_NAME, ' IN (\'%1234567890%\');') 
FROM INFORMATION_SCHEMA.COLUMNS A
WHERE 
            A.TABLE_SCHEMA != 'mysql' 
AND     A.TABLE_SCHEMA != 'innodb' 
AND     A.TABLE_SCHEMA != 'performance_schema' 
AND     A.TABLE_SCHEMA != 'information_schema'
AND     A.DATA_TYPE IN ('bigint','int','smallint','tinyint','decimal','double')
;

.

# =================
# BLOB SEARCH
# =================
# BE ADVISED THIS IS CAN END HORRIFICALLY IF YOU DONT KNOW WHAT YOU ARE DOING
# YOU SHOULD KNOW IF YOU HAVE FULL TEXT INDEX ON OR NOT
# MISUSE AND YOU COULD CRASH A LARGE SERVER
SELECT 
    CONCAT('SELECT CONVERT(',A.COLUMN_NAME, ' USING utf8) FROM ', A.TABLE_SCHEMA, '.', A.TABLE_NAME, 
           ' WHERE CONVERT(',A.COLUMN_NAME, ' USING utf8) IN (\'%someText%\');') 
FROM INFORMATION_SCHEMA.COLUMNS A
WHERE 
            A.TABLE_SCHEMA != 'mysql' 
AND     A.TABLE_SCHEMA != 'innodb' 
AND     A.TABLE_SCHEMA != 'performance_schema' 
AND     A.TABLE_SCHEMA != 'information_schema'
AND     A.DATA_TYPE LIKE '%blob%'
;

Results should look like this:

Copy these results into another query window

2) You can then just Right Click and use the Copy Row (tab-separated)

enter image description here

3) Paste results in a new query window and run to your heart's content.

Detail: I exclude system schema's that you may not usually see in your workbench unless you have the option Show Metadata and Internal Schemas checked.

I did this to provide a quick way to ANALYZE an entire HOST or DB if needed or to run OPTIMIZE statements to support performance improvements.

I'm sure there are different ways you may go about doing this but here’s what works for me:

-- ========================================== DYNAMICALLY FIND TABLES AND CREATE A LIST OF QUERIES IN THE RESULTS TO ANALYZE THEM
SELECT CONCAT('ANALYZE TABLE ', TABLE_SCHEMA, '.', TABLE_NAME, ';') FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbname';

-- ========================================== DYNAMICALLY FIND TABLES AND CREATE A LIST OF QUERIES IN THE RESULTS TO OPTIMIZE THEM
SELECT CONCAT('OPTIMIZE TABLE ', TABLE_SCHEMA, '.', TABLE_NAME, ';') FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbname';

Tested On MySQL Version: 5.6.23

WARNING: DO NOT RUN THIS IF:

  1. You are concerned with causing Table-locks (keep an eye on your client-connections)
  2. You are unsure about what you are doing.

  3. You are trying to anger you DBA. (you may have people at your desk with the quickness.)

Cheers, Jay ;-]

"RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38

I'm on macOS Catalina 10.15.3, and I had a similar error: ExecutableNotFound: failed to execute ['dot', '-Tsvg'], make sure the Graphviz executables are on your systems' PATH

Fixed it with:

pip3 install graphviz AND brew install graphviz

Note the pip3 install will only return the success message Successfully installed graphviz-0.13.2 so we still need to run brew install to get graphviz 2.42.3 (as of 10 Mar 2020, 6PM).

Should a retrieval method return 'null' or throw an exception when it can't produce the return value?

I prefer to just return a null, and rely on the caller to handle it appropriately. The (for lack of a better word) exception is if I am absolutely 'certain' this method will return an object. In that case a failure is an exceptional should and should throw.

UIScrollView Scrollable Content Size Ambiguity

You need to create an UIView as a subview of the UIScrollView as described below:

  • UIViewController
  • UIView 'Main View'
    • UIScrollView
      • UIView 'Container View'
        • [Your content]

The second step is to make the UIScrollView constraints. I did this with the top, bottom, leading and trailing constraints to its superView.

Next I added the constraints for the container of UIScrollView and here is where the problem begins. When you put the same constraints (top, bottom, leading and trailing) the Storyboard gives a warning message:

"Has ambiguous scrollable content width" and "Has ambiguous scrollable content height"

Continue with the same constraints above, and just add the constraints Equal Height and Equal Width to your Container View in relation to the Main View and not to your UIScrollView. In other words the Container View's constraints are tied to the UIScrollView's superview.

After that you will not have warnings in your Storyboard and you can continue adding the constraints for your subviews.

How to check empty DataTable

Normally when querying a database with SQL and then fill a data-table with its results, it will never be a null Data table. You have the column headers filled with column information even if you returned 0 records.When one tried to process a data table with 0 records but with column information it will throw exception.To check the datatable before processing one could check like this.

if (DetailTable != null && DetailTable.Rows.Count>0)

How do I append one string to another in Python?

Python 3.6 gives us f-strings, which are a delight:

var1 = "foo"
var2 = "bar"
var3 = f"{var1}{var2}"
print(var3)                       # prints foobar

You can do most anything inside the curly braces

print(f"1 + 1 == {1 + 1}")        # prints 1 + 1 == 2

spark submit add multiple jars in classpath

In Spark 2.3 you need to just set the --jars option. The file path should be prepended with the scheme though ie file:///<absolute path to the jars> Eg : file:////home/hadoop/spark/externaljsrs/* or file:////home/hadoop/spark/externaljars/abc.jar,file:////home/hadoop/spark/externaljars/def.jar

Android, How to create option Menu

Good Day I was checked And if You choose Empty Activity You Don't have build in Menu functions For Build in You must choose Basic Activity In this way You Activity will run onCreateOptionsMenu

Or if You work in Empty Activity from start Chenge in styles.xml the

How to return a part of an array in Ruby?

Yes, Ruby has very similar array-slicing syntax to Python. Here is the ri documentation for the array index method:

--------------------------------------------------------------- Array#[]
     array[index]                -> obj      or nil
     array[start, length]        -> an_array or nil
     array[range]                -> an_array or nil
     array.slice(index)          -> obj      or nil
     array.slice(start, length)  -> an_array or nil
     array.slice(range)          -> an_array or nil
------------------------------------------------------------------------
     Element Reference---Returns the element at index, or returns a 
     subarray starting at start and continuing for length elements, or 
     returns a subarray specified by range. Negative indices count 
     backward from the end of the array (-1 is the last element). 
     Returns nil if the index (or starting index) are out of range.

        a = [ "a", "b", "c", "d", "e" ]
        a[2] +  a[0] + a[1]    #=> "cab"
        a[6]                   #=> nil
        a[1, 2]                #=> [ "b", "c" ]
        a[1..3]                #=> [ "b", "c", "d" ]
        a[4..7]                #=> [ "e" ]
        a[6..10]               #=> nil
        a[-3, 3]               #=> [ "c", "d", "e" ]
        # special cases
        a[5]                   #=> nil
        a[6, 1]                #=> nil
        a[5, 1]                #=> []
        a[5..10]               #=> []

adding 1 day to a DATETIME format value

You can use

$now = new DateTime();
$date = $now->modify('+1 day')->format('Y-m-d H:i:s');

How to catch curl errors in PHP

you can generate curl error after its execution

$url = 'http://example.com';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if(curl_errno($ch)){
    echo 'Request Error:' . curl_error($ch);
}

and here are curl error code

if someone need more information about curl errors

<?php

    $error_codes=array(
    [1] => 'CURLE_UNSUPPORTED_PROTOCOL',
    [2] => 'CURLE_FAILED_INIT',
    [3] => 'CURLE_URL_MALFORMAT',
    [4] => 'CURLE_URL_MALFORMAT_USER',
    [5] => 'CURLE_COULDNT_RESOLVE_PROXY',
    [6] => 'CURLE_COULDNT_RESOLVE_HOST',
    [7] => 'CURLE_COULDNT_CONNECT',
    [8] => 'CURLE_FTP_WEIRD_SERVER_REPLY',
    [9] => 'CURLE_REMOTE_ACCESS_DENIED',
    [11] => 'CURLE_FTP_WEIRD_PASS_REPLY',
    [13] => 'CURLE_FTP_WEIRD_PASV_REPLY',
    [14]=>'CURLE_FTP_WEIRD_227_FORMAT',
    [15] => 'CURLE_FTP_CANT_GET_HOST',
    [17] => 'CURLE_FTP_COULDNT_SET_TYPE',
    [18] => 'CURLE_PARTIAL_FILE',
    [19] => 'CURLE_FTP_COULDNT_RETR_FILE',
    [21] => 'CURLE_QUOTE_ERROR',
    [22] => 'CURLE_HTTP_RETURNED_ERROR',
    [23] => 'CURLE_WRITE_ERROR',
    [25] => 'CURLE_UPLOAD_FAILED',
    [26] => 'CURLE_READ_ERROR',
    [27] => 'CURLE_OUT_OF_MEMORY',
    [28] => 'CURLE_OPERATION_TIMEDOUT',
    [30] => 'CURLE_FTP_PORT_FAILED',
    [31] => 'CURLE_FTP_COULDNT_USE_REST',
    [33] => 'CURLE_RANGE_ERROR',
    [34] => 'CURLE_HTTP_POST_ERROR',
    [35] => 'CURLE_SSL_CONNECT_ERROR',
    [36] => 'CURLE_BAD_DOWNLOAD_RESUME',
    [37] => 'CURLE_FILE_COULDNT_READ_FILE',
    [38] => 'CURLE_LDAP_CANNOT_BIND',
    [39] => 'CURLE_LDAP_SEARCH_FAILED',
    [41] => 'CURLE_FUNCTION_NOT_FOUND',
    [42] => 'CURLE_ABORTED_BY_CALLBACK',
    [43] => 'CURLE_BAD_FUNCTION_ARGUMENT',
    [45] => 'CURLE_INTERFACE_FAILED',
    [47] => 'CURLE_TOO_MANY_REDIRECTS',
    [48] => 'CURLE_UNKNOWN_TELNET_OPTION',
    [49] => 'CURLE_TELNET_OPTION_SYNTAX',
    [51] => 'CURLE_PEER_FAILED_VERIFICATION',
    [52] => 'CURLE_GOT_NOTHING',
    [53] => 'CURLE_SSL_ENGINE_NOTFOUND',
    [54] => 'CURLE_SSL_ENGINE_SETFAILED',
    [55] => 'CURLE_SEND_ERROR',
    [56] => 'CURLE_RECV_ERROR',
    [58] => 'CURLE_SSL_CERTPROBLEM',
    [59] => 'CURLE_SSL_CIPHER',
    [60] => 'CURLE_SSL_CACERT',
    [61] => 'CURLE_BAD_CONTENT_ENCODING',
    [62] => 'CURLE_LDAP_INVALID_URL',
    [63] => 'CURLE_FILESIZE_EXCEEDED',
    [64] => 'CURLE_USE_SSL_FAILED',
    [65] => 'CURLE_SEND_FAIL_REWIND',
    [66] => 'CURLE_SSL_ENGINE_INITFAILED',
    [67] => 'CURLE_LOGIN_DENIED',
    [68] => 'CURLE_TFTP_NOTFOUND',
    [69] => 'CURLE_TFTP_PERM',
    [70] => 'CURLE_REMOTE_DISK_FULL',
    [71] => 'CURLE_TFTP_ILLEGAL',
    [72] => 'CURLE_TFTP_UNKNOWNID',
    [73] => 'CURLE_REMOTE_FILE_EXISTS',
    [74] => 'CURLE_TFTP_NOSUCHUSER',
    [75] => 'CURLE_CONV_FAILED',
    [76] => 'CURLE_CONV_REQD',
    [77] => 'CURLE_SSL_CACERT_BADFILE',
    [78] => 'CURLE_REMOTE_FILE_NOT_FOUND',
    [79] => 'CURLE_SSH',
    [80] => 'CURLE_SSL_SHUTDOWN_FAILED',
    [81] => 'CURLE_AGAIN',
    [82] => 'CURLE_SSL_CRL_BADFILE',
    [83] => 'CURLE_SSL_ISSUER_ERROR',
    [84] => 'CURLE_FTP_PRET_FAILED',
    [84] => 'CURLE_FTP_PRET_FAILED',
    [85] => 'CURLE_RTSP_CSEQ_ERROR',
    [86] => 'CURLE_RTSP_SESSION_ERROR',
    [87] => 'CURLE_FTP_BAD_FILE_LIST',
    [88] => 'CURLE_CHUNK_FAILED');

    ?>

MySQL Multiple Where Clause

May be using this query you don't get any result or empty result. You need to use OR instead of AND in your query like below.

$query = mysql_query("SELECT image_id FROM list WHERE (style_id = 24 AND style_value = 'red') OR (style_id = 25 AND style_value = 'big') OR (style_id = 27 AND style_value = 'round');

Try out this query.

How to find and turn on USB debugging mode on Nexus 4

Step 1 : Go to Settings >> About Phone >> scroll to the bottom >> tap Build number seven times; this message will appear “You are now 3 steps away from being a developer.”

Step 2 : Now go to Settings >> Developer Options >> Check USB Debugging

this is great article will help you to enable this mode on your phone

Enable USB Debugging Mode on Android

What is lazy loading in Hibernate?

Lazy fetching decides whether to load child objects while loading the Parent Object. You need to do this setting respective hibernate mapping file of the parent class. Lazy = true (means not to load child) By default the lazy loading of the child objects is true.

This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent.In this case hibernate issues a fresh database call to load the child when getChild() is actully called on the Parent object.

But in some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database.

Example : If you have a TABLE ? EMPLOYEE mapped to Employee object and contains set of Address objects. Parent Class : Employee class, Child class : Address Class

public class Employee { 
private Set address = new HashSet(); // contains set of child Address objects 
public Set getAddress () { 
return address; 
} 
public void setAddresss(Set address) { 
this. address = address; 
} 
} 

In the Employee.hbm.xml file

<set name="address" inverse="true" cascade="delete" lazy="false"> 
<key column="a_id" /> 
<one-to-many class="beans Address"/> 
</set> 

In the above configuration. If lazy="false" : - when you load the Employee object that time child object Address is also loaded and set to setAddresss() method. If you call employee.getAdress() then loaded data returns.No fresh database call.

If lazy="true" :- This the default configuration. If you don?t mention then hibernate consider lazy=true. when you load the Employee object that time child object Adress is not loaded. You need extra call to data base to get address objects. If you call employee.getAdress() then that time database query fires and return results. Fresh database call.

TypeError: 'dict' object is not callable

The syntax for accessing a dict given a key is number_map[int(x)]. number_map(int(x)) would actually be a function call but since number_map is not a callable, an exception is raised.

Is there a constraint that restricts my generic method to numeric types?

The .NET numeric primitive types do not share any common interface that would allow them to be used for calculations. It would be possible to define your own interfaces (e.g. ISignedWholeNumber) which would perform such operations, define structures which contain a single Int16, Int32, etc. and implement those interfaces, and then have methods which accept generic types constrained to ISignedWholeNumber, but having to convert numeric values to your structure types would likely be a nuisance.

An alternative approach would be to define static class Int64Converter<T> with a static property bool Available {get;}; and static delegates for Int64 GetInt64(T value), T FromInt64(Int64 value), bool TryStoreInt64(Int64 value, ref T dest). The class constructor could use be hard-coded to load delegates for known types, and possibly use Reflection to test whether type T implements methods with the proper names and signatures (in case it's something like a struct which contains an Int64 and represents a number, but has a custom ToString() method). This approach would lose the advantages associated with compile-time type-checking, but would still manage to avoid boxing operations and each type would only have to be "checked" once. After that, operations associated with that type would be replaced with a delegate dispatch.

ng-change not working on a text input

One can also bind a function with ng-change event listener, if they need to run a bit more complex logic.

<div ng-app="myApp" ng-controller="myCtrl">      
        <input type='text' ng-model='name' ng-change='change()'>
        <br/> <span>changed {{counter}} times </span>
 </div>

...

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
      $scope.name = 'Australia';
      $scope.counter = 0;
      $scope.change = function() {
        $scope.counter++;
      };
});

https://jsfiddle.net/as0nyre3/1/

React - How to get parameter value from query string?

You could create simple hook for extracting search params from current location:

import React from 'react';
import { useLocation } from 'react-router-dom';

export function useSearchParams<ParamNames extends string[]>(...parameterNames: ParamNames): Record<ParamNames[number], string | null> {
    const { search } = useLocation();
    return React.useMemo(() => { // recalculate only when 'search' or arguments changed
        const searchParams = new URLSearchParams(search);
        return parameterNames.reduce((accumulator, parameterName: ParamNames[number]) => {
            accumulator[ parameterName ] = searchParams.get(parameterName);
            return accumulator;
        }, {} as Record<ParamNames[number], string | null>);
    }, [ search, parameterNames.join(',') ]); // join for sake of reducing array of strings to simple, comparable string
}

then you could use it inside your functional component like this:

// current url: http://localhost:8000/#/signin?_k=v9ifuf&__firebase_request_key=blablabla
const { __firebase_request_key } = useSearchParams('__firebase_request_key');
// current url: http://localhost:3000/home?b=value
const searchParams = useSearchParameters('a', 'b'); // {a: null, b: 'value'}

Ignore self-signed ssl cert using Jersey Client

For anyone on Jersey 2.x without lambdas, use this:

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;

public static Client getUnsecureClient() throws Exception 
{
    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[]{new X509TrustManager() 
    {
            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException{}
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException{}
            public X509Certificate[] getAcceptedIssuers()
            {
                return new X509Certificate[0];
            }

    }}, new java.security.SecureRandom());


    HostnameVerifier allowAll = new HostnameVerifier() 
    {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    return ClientBuilder.newBuilder().sslContext(sslcontext).hostnameVerifier(allowAll).build();
}

Tested with jersey-client 2.11 on JRE 1.7.

Uncaught TypeError: .indexOf is not a function

I ran across this error recently using a javascript library which changes the parameters of a function based on conditions.

You can test an object to see if it has the function. I would only do this in scenarios where you don't control what is getting passed to you.

if( param.indexOf != undefined ) {
   // we have a string or other object that 
   // happens to have a function named indexOf
}

You can test this in your browser console:

> (3).indexOf == undefined;
true

> "".indexOf == undefined;
false

jQuery $("#radioButton").change(...) not firing during de-selection

<input id='r1' type='radio' class='rg' name="asdf"/>
<input id='r2' type='radio' class='rg' name="asdf"/>
<input id='r3' type='radio' class='rg' name="asdf"/>
<input id='r4' type='radio' class='rg' name="asdf"/><br/>
<input type='text' id='r1edit'/>                  

jquery part

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

if ($("#r1").attr("checked")) {
            $('#r1edit:input').removeAttr('disabled');
        }
        else {
            $('#r1edit:input').attr('disabled', 'disabled');
        }
                    });

here is the DEMO

jQuery textbox change event doesn't fire until textbox loses focus?

Try this:

$("#textbox").bind('paste',function() {alert("Change detected!");});

See demo on JSFiddle.

setup.py examples?

You may find the HitchHiker's Guide to Packaging helpful, even though it is incomplete. I'd start with the Quick Start tutorial. Try also just browsing through Python packages on the Python Package Index. Just download the tarball, unpack it, and have a look at the setup.py file. Or even better, only bother looking through packages that list a public source code repository such as one hosted on GitHub or BitBucket. You're bound to run into one on the front page.

My final suggestion is to just go for it and try making one; don't be afraid to fail. I really didn't understand it until I started making them myself. It's trivial to create a new package on PyPI and just as easy to remove it. So, create a dummy package and play around.

How to delete object?

I would suggest , to use .Net's IDisposable interface if your are thinking of to release instance after its usage.

See a sample implementation below.

public class Car : IDisposable
{

   public void Dispose()
   {  
      Dispose(true);
       // any other managed resource cleanups you can do here
       Gc.SuppressFinalize(this);
   }
   ~Car()      // finalizer
   {
        Dispose(false);
   }

   protected virtual void Dispose(bool disposing)
   {
     if (!_disposed)
     {
      if (disposing)
      {
        if (_stream != null) _stream.Dispose(); // say you have to dispose a stream
      }

      _stream = null;
    _disposed = true;
    }

   }
}

Now in your code:

void main()
{
   using(var car = new Car())
   {
     // do something with car
   } // here dispose will automtically get called. 
}

Can angularjs routes have optional parameter values?

Like @g-eorge mention, you can make it like this:

module.config(['$routeProvider', function($routeProvider) {
$routeProvider.
  when('/users/:userId?', {templateUrl: 'template.tpl.html', controller: myCtrl})
}]);

You can also make as much as u need optional parameters.

How to add a Hint in spinner in XML

For Kotlin !!

Custom Array adapter to hide the last item of the spinner

 import android.content.Context
 import android.widget.ArrayAdapter
 import android.widget.Spinner

 class HintAdapter<T>(context: Context, resource: Int, objects: Array<T>) :
    ArrayAdapter<T>(context, resource, objects) {

    override fun getCount(): Int {
        val count = super.getCount()
        // The last item will be the hint.
        return if (count > 0) count - 1 else count
    }
}

Spinner Extension function to set hint on spinner

fun Spinner.addHintWithArray(context: Context, stringArrayResId: Int) {
    val hintAdapter =
        HintAdapter<String>(
            context,
            android.R.layout.simple_spinner_dropdown_item,
            context.resources.getStringArray(stringArrayResId)
        )
    hintAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
    adapter = hintAdapter
    setSelection(hintAdapter.count)
}

How to use: add the extension by passing context and array on Spinner

spinnerMonth.addHintWithArray(context, R.array.months)

Note: The hint should be the last item of your string array

<string-array name="months">
    <item>Jan</item>
    <item>Feb</item>
    <item>Mar</item>
    <item>Apr</item>
    <item>May</item>
    <item>Months</item>
</string-array>

Create a tag in a GitHub repository

CAREFUL: In the command in Lawakush Kurmi's answer (git tag -a v1.0) the -a flag is used. This flag tells Git to create an annotated flag. If you don't provide the flag (i.e. git tag v1.0) then it'll create what's called a lightweight tag.


Annotated tags are recommended, because they include a lot of extra information such as:

  • the person who made the tag
  • the date the tag was made
  • a message for the tag

Because of this, you should always use annotated tags.

mongodb group values by multiple fields

Using aggregate function like below :

[
{$group: {_id : {book : '$book',address:'$addr'}, total:{$sum :1}}},
{$project : {book : '$_id.book', address : '$_id.address', total : '$total', _id : 0}}
]

it will give you result like following :

        {
            "total" : 1,
            "book" : "book33",
            "address" : "address90"
        }, 
        {
            "total" : 1,
            "book" : "book5",
            "address" : "address1"
        }, 
        {
            "total" : 1,
            "book" : "book99",
            "address" : "address9"
        }, 
        {
            "total" : 1,
            "book" : "book1",
            "address" : "address5"
        }, 
        {
            "total" : 1,
            "book" : "book5",
            "address" : "address2"
        }, 
        {
            "total" : 1,
            "book" : "book3",
            "address" : "address4"
        }, 
        {
            "total" : 1,
            "book" : "book11",
            "address" : "address77"
        }, 
        {
            "total" : 1,
            "book" : "book9",
            "address" : "address3"
        }, 
        {
            "total" : 1,
            "book" : "book1",
            "address" : "address15"
        }, 
        {
            "total" : 2,
            "book" : "book1",
            "address" : "address2"
        }, 
        {
            "total" : 3,
            "book" : "book1",
            "address" : "address1"
        }

I didn't quite get your expected result format, so feel free to modify this to one you need.

How do I round a double to two decimal places in Java?

DecimalFormat df = new DecimalFormat("###.##");
double total = Double.valueOf(val);

ASP.net page without a code behind

By default Sharepoint does not allow server-side code to be executed in ASPX files. See this for how to resolve that.

However, I would raise that having a code-behind is not necessarily difficult to deploy in Sharepoint (we do it extensively) - just compile your code-behind classes into an assembly and deploy it using a solution.

If still no, you can include all the code you'd normally place in a codebehind like so:

<script language="c#" runat="server">
public void Page_Load(object sender, EventArgs e)
{
  //hello, world!
}
</script>

How to get the ASCII value of a character

From here:

The function ord() gets the int value of the char. And in case you want to convert back after playing with the number, function chr() does the trick.

>>> ord('a')
97
>>> chr(97)
'a'
>>> chr(ord('a') + 3)
'd'
>>>

In Python 2, there was also the unichr function, returning the Unicode character whose ordinal is the unichr argument:

>>> unichr(97)
u'a'
>>> unichr(1234)
u'\u04d2'

In Python 3 you can use chr instead of unichr.


ord() - Python 3.6.5rc1 documentation

ord() - Python 2.7.14 documentation

Declare a const array

You could take a different approach: define a constant string to represent your array and then split the string into an array when you need it, e.g.

const string DefaultDistances = "5,10,15,20,25,30,40,50";
public static readonly string[] distances = DefaultDistances.Split(',');

This approach gives you a constant which can be stored in configuration and converted to an array when needed.

How to parse XML to R data frame

Use xpath more directly for both performance and clarity.

time_path <- "//start-valid-time"
temp_path <- "//temperature[@type='hourly']/value"

df <- data.frame(
    latitude=data[["number(//point/@latitude)"]],
    longitude=data[["number(//point/@longitude)"]],
    start_valid_time=sapply(data[time_path], xmlValue),
    hourly_temperature=as.integer(sapply(data[temp_path], as, "integer"))

leading to

> head(df, 2)
  latitude longitude          start_valid_time hourly_temperature
1    29.81    -82.42 2014-02-14T18:00:00-05:00                 60
2    29.81    -82.42 2014-02-14T19:00:00-05:00                 55

WebDriver: check if an element exists?

This works for me every time:

    if(!driver.findElements(By.xpath("//*[@id='submit']")).isEmpty()){
        //THEN CLICK ON THE SUBMIT BUTTON
    }else{
        //DO SOMETHING ELSE AS SUBMIT BUTTON IS NOT THERE
    }

Open a file with Notepad in C#

this will open the file with the default windows program (notepad if you haven't changed it);

Process.Start(@"c:\myfile.txt")

Starting a node.js server

Run cmd and then run node server.js. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)

Bootstrap 4, How do I center-align a button?

Try this with bootstrap

CODE:

<div class="row justify-content-center">
  <button type="submit" class="btn btn-primary">btnText</button>
</div>

LINK:

https://getbootstrap.com/docs/4.1/layout/grid/#variable-width-content

Leave menu bar fixed on top when scrolled

In this example, you may show your menu centered.

HTML

<div id="main-menu-container">
    <div id="main-menu">
        //your menu
    </div>
</div>

CSS

.f-nav{  /* To fix main menu container */
    z-index: 9999;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
}
#main-menu-container {
    text-align: center; /* Assuming your main layout is centered */
}
#main-menu {
    display: inline-block;
    width: 1024px; /* Your menu's width */
}

JS

$("document").ready(function($){
    var nav = $('#main-menu-container');

    $(window).scroll(function () {
        if ($(this).scrollTop() > 125) {
            nav.addClass("f-nav");
        } else {
            nav.removeClass("f-nav");
        }
    });
});

Renaming columns in Pandas

As documented in Working with text data:

df.columns = df.columns.str.replace('$', '')

Which Android IDE is better - Android Studio or Eclipse?

Both are equally good. With Android Studio you have ADT tools integrated, and with eclipse you need to integrate them manually. With Android Studio, it feels like a tool designed from the outset with Android development in mind. Go ahead, they have same features.

How can I schedule a job to run a SQL query daily?

  1. Expand the SQL Server Agent node and right click the Jobs node in SQL Server Agent and select 'New Job'

  2. In the 'New Job' window enter the name of the job and a description on the 'General' tab.

  3. Select 'Steps' on the left hand side of the window and click 'New' at the bottom.

  4. In the 'Steps' window enter a step name and select the database you want the query to run against.

  5. Paste in the T-SQL command you want to run into the Command window and click 'OK'.

  6. Click on the 'Schedule' menu on the left of the New Job window and enter the schedule information (e.g. daily and a time).

  7. Click 'OK' - and that should be it.

(There are of course other options you can add - but I would say that is the bare minimum you need to get a job set up and scheduled)

Android emulator: could not get wglGetExtensionsStringARB error

just change your JDK I installed the JDK of SUN not Oracle and it works for me....

What is the best way to iterate over a dictionary?

Dictionary< TKey, TValue > It is a generic collection class in c# and it stores the data in the key value format.Key must be unique and it can not be null whereas value can be duplicate and null.As each item in the dictionary is treated as KeyValuePair< TKey, TValue > structure representing a key and its value. and hence we should take the element type KeyValuePair< TKey, TValue> during the iteration of element.Below is the example.

Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1,"One");
dict.Add(2,"Two");
dict.Add(3,"Three");

foreach (KeyValuePair<int, string> item in dict)
{
    Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value);
}

Is there a C++ decompiler?

I haven't seen any decompilers that generate C++ code. I've seen a few experimental ones that make a reasonable attempt at generating C code, but they tended to be dependent on matching the code-generation patterns of a particular compiler (that may have changed, it's been awhile since I last looked into this). Of course any symbolic information will be gone. Google for "decompiler".

document.getElementById("test").style.display="hidden" not working

Using jQuery:

   $('#test').hide();

Using Javascript:

document.getElementById("test").style.display="none";

Threw an error "Cannot set property 'display' of undefined"

So, fix for this would be:

document.getElementById("test").style="display:none";

where your html code will look like this:

<div style="display:inline-block" id="test"></div>

How To have Dynamic SQL in MySQL Stored Procedure

I don't believe MySQL supports dynamic sql. You can do "prepared" statements which is similar, but different.

Here is an example:

mysql> PREPARE stmt FROM 
    -> 'select count(*) 
    -> from information_schema.schemata 
    -> where schema_name = ? or schema_name = ?'
;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> EXECUTE stmt 
    -> USING @schema1,@schema2
+----------+
| count(*) |
+----------+
|        2 |
+----------+
1 row in set (0.00 sec)
mysql> DEALLOCATE PREPARE stmt;

The prepared statements are often used to see an execution plan for a given query. Since they are executed with the execute command and the sql can be assigned to a variable you can approximate the some of the same behavior as dynamic sql.

Here is a good link about this:

Don't forget to deallocate the stmt using the last line!

Good Luck!

Ansible Ignore errors in tasks and fail at end of the playbook if any tasks had errors

Fail module works great! Thanks.

I had to define my fact before checking it, otherwise I'd get an undefined variable error.

And I had issues when doing setting the fact with quotes and without spaces.

This worked:

set_fact: flag="failed"

This threw errors:

set_fact: flag = failed 

Strip first and last character from C string

To "remove" the 1st character point to the second character:

char mystr[] = "Nmy stringP";
char *p = mystr;
p++; /* 'N' is not in `p` */

To remove the last character replace it with a '\0'.

p[strlen(p)-1] = 0; /* 'P' is not in `p` (and it isn't in `mystr` either) */

MySQL Database won't start in XAMPP Manager-osx

All the answers stated above in relation to changing the port number are in this situation the best way to solve this problem since you need your voice recognition software to coexist with MAMP. However, you must remember that changing this port number is going to affect all you subsequent connections to MySQL (i.e, terminal,php code,phpmyadmin,etc). Hence It would be advisable to change the port on which the voice recognition software runs. Hope this was helpful.

:)

Invariant Violation: _registerComponent(...): Target container is not a DOM element

just a wild guess, how about adding to index.html the following:

type="javascript"

like this:

<script type="javascript" src="public/bundle.js"> </script>

For me it worked! :-)

Return number of rows affected by UPDATE statements

This is exactly what the OUTPUT clause in SQL Server 2005 onwards is excellent for.

EXAMPLE

CREATE TABLE [dbo].[test_table](
    [LockId] [int] IDENTITY(1,1) NOT NULL,
    [StartTime] [datetime] NULL,
    [EndTime] [datetime] NULL,
PRIMARY KEY CLUSTERED 
(
    [LockId] ASC
) ON [PRIMARY]
) ON [PRIMARY]

INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 07','2009 JUL 07')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 08','2009 JUL 08')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 09','2009 JUL 09')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 10','2009 JUL 10')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 11','2009 JUL 11')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 12','2009 JUL 12')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 13','2009 JUL 13')

UPDATE test_table
    SET StartTime = '2011 JUL 01'
    OUTPUT INSERTED.* -- INSERTED reflect the value after the UPDATE, INSERT, or MERGE statement is completed 
WHERE
    StartTime > '2009 JUL 09'

Results in the following being returned

    LockId StartTime                EndTime
-------------------------------------------------------
4      2011-07-01 00:00:00.000  2009-07-10 00:00:00.000
5      2011-07-01 00:00:00.000  2009-07-11 00:00:00.000
6      2011-07-01 00:00:00.000  2009-07-12 00:00:00.000
7      2011-07-01 00:00:00.000  2009-07-13 00:00:00.000

In your particular case, since you cannot use aggregate functions with OUTPUT, you need to capture the output of INSERTED.* in a table variable or temporary table and count the records. For example,

DECLARE @temp TABLE (
  [LockId] [int],
  [StartTime] [datetime] NULL,
  [EndTime] [datetime] NULL 
)

UPDATE test_table
    SET StartTime = '2011 JUL 01'
    OUTPUT INSERTED.* INTO @temp
WHERE
    StartTime > '2009 JUL 09'


-- now get the count of affected records
SELECT COUNT(*) FROM @temp

Hidden Columns in jqGrid

I just want to expand on queen3's suggestion, applying the following does the trick:

editoptions: { 
              dataInit: function(element) { 
                          $(element).attr("readonly", "readonly"); 
                        } 
             }

Scenario #1:

  • Field must be visible in the grid
  • Field must be visible in the form
  • Field must be read-only

Solution:

colModel:[
        {  name:'providerUserId',
               index:'providerUserId', 
               width:100,editable:true, 
               editrules:{required:true}, 
               editoptions:{ 
                            dataInit: function(element) { 
                                  jq(element).attr("readonly", "readonly"); 
                             } 
                           }
            },
],

The providerUserId is visible in the grid and visible when editing the form. But you cannot edit the contents.


Scenario #2:

  • Field must not be visible in the grid
  • Field must be visible in the form
  • Field must be read-only

Solution:

colModel:[
           {name:'providerUserId',
            index:'providerUserId', 
            width:100,editable:true, 
            editrules:{
                         required:true, 
                         edithidden:true
                      },
            hidden:true, 
            editoptions:{ 
                  dataInit: function(element) {                     
                             jq(element).attr("readonly", "readonly"); 
                          } 
                     }
         },
        ]

Notice in both instances I'm using jq to reference jquery, instead of the usual $. In my HTML I have the following script to modify the variable used by jQuery:

<script type="text/javascript">
    var jq = jQuery.noConflict();
</script>

How to add url parameter to the current url?

There is no way to write a relative URI that preserves the existing query string while adding additional parameters to it.

You have to:

topic.php?id=14&like=like

VT-x is disabled in the BIOS for both all CPU modes (VERR_VMX_MSR_ALL_VMX_DISABLED)

Simply check how many CPUs you are allocating. With one CPU you do not need to play with your bios.

How to add a "confirm delete" option in ASP.Net Gridview?

You can do using OnClientClick of button.

OnClientClick="return confirm('confirm delete')"

Failed to resolve: com.android.support:appcompat-v7:26.0.0

If you are using Android Studio 3.0, add the Google maven repository as shown below:

allprojects {
  repositories {
    jcenter()
    google()
 }
}

How do I print colored output to the terminal in Python?

You can try this with python 3:

from termcolor import colored
print(colored('Hello, World!', 'green', 'on_red'))

If you are using windows operating system, the above code may not work for you. Then you can try this code:

from colorama import init
from termcolor import colored

# use Colorama to make Termcolor work on Windows too
init()

# then use Termcolor for all colored text output
print(colored('Hello, World!', 'green', 'on_red'))

Hope that helps.

How to write std::string to file?

remove the ios::binary from your modes in your ofstream and use studentPassword.c_str() instead of (char *)&studentPassword in your write.write()

Fetch first element which matches criteria

This might be what you are looking for:

yourStream
    .filter(/* your criteria */)
    .findFirst()
    .get();

And better, if there's a possibility of matching no element, in which case get() will throw a NPE. So use:

yourStream
    .filter(/* your criteria */)
    .findFirst()
    .orElse(null); /* You could also create a default object here */


An example:
public static void main(String[] args) {
    class Stop {
        private final String stationName;
        private final int    passengerCount;

        Stop(final String stationName, final int passengerCount) {
            this.stationName    = stationName;
            this.passengerCount = passengerCount;
        }
    }

    List<Stop> stops = new LinkedList<>();

    stops.add(new Stop("Station1", 250));
    stops.add(new Stop("Station2", 275));
    stops.add(new Stop("Station3", 390));
    stops.add(new Stop("Station2", 210));
    stops.add(new Stop("Station1", 190));

    Stop firstStopAtStation1 = stops.stream()
            .filter(e -> e.stationName.equals("Station1"))
            .findFirst()
            .orElse(null);

    System.out.printf("At the first stop at Station1 there were %d passengers in the train.", firstStopAtStation1.passengerCount);
}

Output is:

At the first stop at Station1 there were 250 passengers in the train.

Can iterators be reset in Python?

This is perhaps orthogonal to the original question, but one could wrap the iterator in a function that returns the iterator.

def get_iter():
    return iterator

To reset the iterator just call the function again. This is of course trivial if the function when the said function takes no arguments.

In the case that the function requires some arguments, use functools.partial to create a closure that can be passed instead of the original iterator.

def get_iter(arg1, arg2):
   return iterator
from functools import partial
iter_clos = partial(get_iter, a1, a2)

This seems to avoid the caching that tee (n copies) or list (1 copy) would need to do

React Native fixed footer

import {Dimensions} from 'react-native'

const WIDTH = Dimensions.get('window').width;
const HEIGHT = Dimensions.get('window').height;

then on the write this styles

 position: 'absolute',
 top: HEIGHT-80,
 left: 0,
 right: 0,

worked like a charm

VBA Object doesn't support this property or method

Object doesn't support this property or method.

Think of it like if anything after the dot is called on an object. It's like a chain.

An object is a class instance. A class instance supports some properties defined in that class type definition. It exposes whatever intelli-sense in VBE tells you (there are some hidden members but it's not related to this). So after each dot . you get intelli-sense (that white dropdown) trying to help you pick the correct action.

(you can start either way - front to back or back to front, once you understand how this works you'll be able to identify where the problem occurs)

Type this much anywhere in your code area

Dim a As Worksheets
a.

you get help from VBE, it's a little dropdown called Intelli-sense

enter image description here

It lists all available actions that particular object exposes to any user. You can't see the .Selection member of the Worksheets() class. That's what the error tells you exactly.

Object doesn't support this property or method.

If you look at the example on MSDN

Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count

It activates the sheet first then calls the Selection... it's not connected together because Selection is not a member of Worksheets() class. Simply, you can't prefix the Selection

What about

Sub DisplayColumnCount()
    Dim iAreaCount As Integer
    Dim i As Integer

    Worksheets("GRA").Activate
    iAreaCount = Selection.Areas.Count

    If iAreaCount <= 1 Then
        MsgBox "The selection contains " & Selection.Columns.Count & " columns."
    Else
        For i = 1 To iAreaCount
        MsgBox "Area " & i & " of the selection contains " & _
        Selection.Areas(i).Columns.Count & " columns."
        Next i
    End If
End Sub

from HERE

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

str.split() without any arguments splits on runs of whitespace characters:

>>> s = 'I am having a very nice day.'
>>> 
>>> len(s.split())
7

From the linked documentation:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

Null or empty check for a string variable

Yes, that code does exactly that.

You can also use:

if (@value is null or @value = '')

Edit:

With the added information that @value is an int value, you need instead:

if (@value is null)

An int value can never contain the value ''.

Iterate through string array in Java

String current = elements[i];
if (i != elements.length - 1) {
   String next = elements[i+1];
}

This makes sure you don't get an ArrayIndexOutOfBoundsException for the last element (there is no 'next' there). The other option is to iterate to i < elements.length - 1. It depends on your requirements.

Serialize object to query string in JavaScript/jQuery

You want $.param(): http://api.jquery.com/jQuery.param/

Specifically, you want this:

var data = { one: 'first', two: 'second' };
var result = $.param(data);

When given something like this:

{a: 1, b : 23, c : "te!@#st"}

$.param will return this:

a=1&b=23&c=te!%40%23st

How to Sort Multi-dimensional Array by Value?

Try a usort, If you are still on PHP 5.2 or earlier, you'll have to define a sorting function first:

function sortByOrder($a, $b) {
    return $a['order'] - $b['order'];
}

usort($myArray, 'sortByOrder');

Starting in PHP 5.3, you can use an anonymous function:

usort($myArray, function($a, $b) {
    return $a['order'] - $b['order'];
});

And finally with PHP 7 you can use the spaceship operator:

usort($myArray, function($a, $b) {
    return $a['order'] <=> $b['order'];
});

To extend this to multi-dimensional sorting, reference the second/third sorting elements if the first is zero - best explained below. You can also use this for sorting on sub-elements.

usort($myArray, function($a, $b) {
    $retval = $a['order'] <=> $b['order'];
    if ($retval == 0) {
        $retval = $a['suborder'] <=> $b['suborder'];
        if ($retval == 0) {
            $retval = $a['details']['subsuborder'] <=> $b['details']['subsuborder'];
        }
    }
    return $retval;
});

If you need to retain key associations, use uasort() - see comparison of array sorting functions in the manual

lvalue required as left operand of assignment

You cannot assign an rvalue to an rvalue.

if (strcmp("hello", "hello") = 0)

is wrong. Suggestions:

if (strcmp("hello", "hello") == 0)
                              ^

= is the assign operator.
== is the equal to operator.
I know many new programmers are confused with this fact.

curl error 18 - transfer closed with outstanding read data remaining

I got this error when my server ran out of disk space and closed the connection midway during generating the response and simply closed the connection

ImportError: No module named pandas

It might be too late to answer this but I just had the problem and I kept installing and uninstalling, it turns out the the problem happens when you're installing pandas to a version of python and trying to run the program using another python version

So to start off, run:

which python
python --version
which pip

make sure both are aligned, most probably, python is 2.7 and pip is working on 3.x or pip is coming from anaconda's python version which is highly likely to be 3.x as well

Incase of python redirects to 2.7, and pip redirects to pip3, install pandas using pip install pandas and use python3 file_name.py to run the program.

How to get option text value using AngularJS?

Instead of ng-options="product as product.label for product in products"> in the select element, you can even use this:

<option ng-repeat="product in products" value="{{product.label}}">{{product.label}}

which works just fine as well.

How to insert an item at the beginning of an array in PHP?

For an associative array you can just use merge.

$arr = array('item2', 'item3', 'item4');
$arr = array_merge(array('item1'), $arr)

Visual Studio Code open tab in new window

This is a very highly upvoted issue request in Github for Floating Windows.

Until they support it, you can try the following workarounds:

1. Duplicate Workspace in New Window [1]

The Duplicate Workspace in new Window Command was added in v1.24 (May 2018) to sort of address this.

  1. Open up Keyboard Shortcuts Ctrl + K, Ctrl + S
  2. Map workbench.action.duplicateWorkspaceInNewWindow to Ctrl + Shift + N or whatever you'd like

Duplicate Workspace in New Window

2. Open Active File in New Window [2]

Rather than manually open a new window and dragging the file, you can do it all with a single command.

  1. Open Active File in New Window Ctrl + K, O

Open Active File in New Window

3. New Window with Same File [3]

As AllenBooTung also pointed out, you can open/drag any file in a separate blank instance.

  1. Open New Window Ctrl + Shift + N
  2. Drag tab into new window

4. Open Workspace and Folder Simultaneously [4]

VS Code will not allow you to open the same folder in two different instances, but you can use Workspaces to open the same directory of files in a side by side instance.

  1. Open Folder Ctrl + K,Ctrl + O
  2. Save Current Project As a Workspace
  3. Open Folder Ctrl + K,Ctrl + O

For any workaround, also consider setting setting up auto save so the documents are kept in sync by updating the files.autoSave setting to afterDelay, onFocusChange, or onWindowChange

AutoSave

How to close Android application?

Use "this.FinishAndRemoveTask();" - it closes application properly

How to tell if a file is git tracked (by shell exit code)?

EDIT

If you need to use git from bash there is --porcelain option to git status:

--porcelain

Give the output in a stable, easy-to-parse format for scripts. Currently this is identical to --short output, but is guaranteed not to change in the future, making it safe for scripts.

Output looks like this:

> git status --porcelain
 M starthudson.sh
?? bla

Or if you do only one file at a time:

> git status --porcelain bla
?? bla

ORIGINAL

do:

git status

You will see report stating which files were updated and which ones are untracked.

You can see bla.sh is tracked and modified and newbla is not tracked:

# On branch master
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#
#       modified:   bla.sh
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       newbla
no changes added to commit (use "git add" and/or "git commit -a")

Yes/No message box using QMessageBox

If you want to make it in python you need check this code in your workbench. also write like this. we created a popup box with python.

msgBox = QMessageBox()
msgBox.setText("The document has been modified.")
msgBox.setInformativeText("Do you want to save your changes?")
msgBox.setStandardButtons(QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)
msgBox.setDefaultButton(QMessageBox.Save)
ret = msgBox.exec_()

How to replace list item in best way

You are accessing your list twice to replace one element. I think simple for loop should be enough:

var key = valueFieldValue.ToString();
for (int i = 0; i < listofelements.Count; i++)
{
    if (listofelements[i] == key)
    {
        listofelements[i] = value.ToString();
        break;
    }
}

Google maps Marker Label with multiple characters

You can use MarkerWithLabel with SVG icons.

Update: The Google Maps Javascript API v3 now natively supports multiple characters in the MarkerLabel

proof of concept fiddle (you didn't provide your icon, so I made one up)

Note: there is an issue with labels on overlapping markers that is addressed by this fix, credit to robd who brought it up in the comments.

code snippet:

_x000D_
_x000D_
function initMap() {_x000D_
  var latLng = new google.maps.LatLng(49.47805, -123.84716);_x000D_
  var homeLatLng = new google.maps.LatLng(49.47805, -123.84716);_x000D_
_x000D_
  var map = new google.maps.Map(document.getElementById('map_canvas'), {_x000D_
    zoom: 12,_x000D_
    center: latLng,_x000D_
    mapTypeId: google.maps.MapTypeId.ROADMAP_x000D_
  });_x000D_
_x000D_
  var marker = new MarkerWithLabel({_x000D_
    position: homeLatLng,_x000D_
    map: map,_x000D_
    draggable: true,_x000D_
    raiseOnDrag: true,_x000D_
    labelContent: "ABCD",_x000D_
    labelAnchor: new google.maps.Point(15, 65),_x000D_
    labelClass: "labels", // the CSS class for the label_x000D_
    labelInBackground: false,_x000D_
    icon: pinSymbol('red')_x000D_
  });_x000D_
_x000D_
  var iw = new google.maps.InfoWindow({_x000D_
    content: "Home For Sale"_x000D_
  });_x000D_
  google.maps.event.addListener(marker, "click", function(e) {_x000D_
    iw.open(map, this);_x000D_
  });_x000D_
}_x000D_
_x000D_
function pinSymbol(color) {_x000D_
  return {_x000D_
    path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',_x000D_
    fillColor: color,_x000D_
    fillOpacity: 1,_x000D_
    strokeColor: '#000',_x000D_
    strokeWeight: 2,_x000D_
    scale: 2_x000D_
  };_x000D_
}_x000D_
google.maps.event.addDomListener(window, 'load', initMap);
_x000D_
html,_x000D_
body,_x000D_
#map_canvas {_x000D_
  height: 500px;_x000D_
  width: 500px;_x000D_
  margin: 0px;_x000D_
  padding: 0px_x000D_
}_x000D_
.labels {_x000D_
  color: white;_x000D_
  background-color: red;_x000D_
  font-family: "Lucida Grande", "Arial", sans-serif;_x000D_
  font-size: 10px;_x000D_
  text-align: center;_x000D_
  width: 30px;_x000D_
  white-space: nowrap;_x000D_
}
_x000D_
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry,places&ext=.js"></script>_x000D_
<script src="https://cdn.rawgit.com/googlemaps/v3-utility-library/master/markerwithlabel/src/markerwithlabel.js"></script>_x000D_
<div id="map_canvas" style="height: 400px; width: 100%;"></div>
_x000D_
_x000D_
_x000D_

Turning error reporting off php

Read up on the configuration settings (e.g., display_errors, display_startup_errors, log_errors) and update your php.ini or .htaccess or .user.ini file, whichever is appropriate.

It works.

@POST in RESTful web service

Please find example below, it might help you

package jersey.rest.test;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/hello")
public class SimpleService {
    @GET
    @Path("/{param}")
    public Response getMsg(@PathParam("param") String msg) {
        String output = "Get:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @POST
    @Path("/{param}")
    public Response postMsg(@PathParam("param") String msg) {
        String output = "POST:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @POST
    @Path("/post")
    //@Consumes(MediaType.TEXT_XML)
    public Response postStrMsg( String msg) {
        String output = "POST:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @PUT
    @Path("/{param}")
    public Response putMsg(@PathParam("param") String msg) {
        String output = "PUT: Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @DELETE
    @Path("/{param}")
    public Response deleteMsg(@PathParam("param") String msg) {
        String output = "DELETE:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @HEAD
    @Path("/{param}")
    public Response headMsg(@PathParam("param") String msg) {
        String output = "HEAD:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }
}

for testing you can use any tool like RestClient (http://code.google.com/p/rest-client/)

Create own colormap using matplotlib and plot color scale

There is an illustrative example of how to create custom colormaps here. The docstring is essential for understanding the meaning of cdict. Once you get that under your belt, you might use a cdict like this:

cdict = {'red':   ((0.0, 1.0, 1.0), 
                   (0.1, 1.0, 1.0),  # red 
                   (0.4, 1.0, 1.0),  # violet
                   (1.0, 0.0, 0.0)), # blue

         'green': ((0.0, 0.0, 0.0),
                   (1.0, 0.0, 0.0)),

         'blue':  ((0.0, 0.0, 0.0),
                   (0.1, 0.0, 0.0),  # red
                   (0.4, 1.0, 1.0),  # violet
                   (1.0, 1.0, 0.0))  # blue
          }

Although the cdict format gives you a lot of flexibility, I find for simple gradients its format is rather unintuitive. Here is a utility function to help generate simple LinearSegmentedColormaps:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors


def make_colormap(seq):
    """Return a LinearSegmentedColormap
    seq: a sequence of floats and RGB-tuples. The floats should be increasing
    and in the interval (0,1).
    """
    seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]
    cdict = {'red': [], 'green': [], 'blue': []}
    for i, item in enumerate(seq):
        if isinstance(item, float):
            r1, g1, b1 = seq[i - 1]
            r2, g2, b2 = seq[i + 1]
            cdict['red'].append([item, r1, r2])
            cdict['green'].append([item, g1, g2])
            cdict['blue'].append([item, b1, b2])
    return mcolors.LinearSegmentedColormap('CustomMap', cdict)


c = mcolors.ColorConverter().to_rgb
rvb = make_colormap(
    [c('red'), c('violet'), 0.33, c('violet'), c('blue'), 0.66, c('blue')])
N = 1000
array_dg = np.random.uniform(0, 10, size=(N, 2))
colors = np.random.uniform(-2, 2, size=(N,))
plt.scatter(array_dg[:, 0], array_dg[:, 1], c=colors, cmap=rvb)
plt.colorbar()
plt.show()

enter image description here


By the way, the for-loop

for i in range(0, len(array_dg)):
  plt.plot(array_dg[i], markers.next(),alpha=alpha[i], c=colors.next())

plots one point for every call to plt.plot. This will work for a small number of points, but will become extremely slow for many points. plt.plot can only draw in one color, but plt.scatter can assign a different color to each dot. Thus, plt.scatter is the way to go.

ReflectionException: Class ClassName does not exist - Laravel

I have the same problem with a class. I tried composer dump-autoload and php artisan config:clear but it did not solve my problem.

Then I decided to read my code to find the problem and I found the problem. The problem in my case was a missing comma in my class. See my Model code:

{
    protected
    $fillable = ['agente_id', 'matter_id', 'amendment_id', 'tipo_id'];

    public
    $rules = [
        'agente_id' => 'required', // <= See the comma
        'tipo_id' => 'required'
    ];

    public
    $niceNames = [
        'agente_id' => 'Membro', // <= This comma is missing on my code
        'tipo_id' => 'Membro'
    ];
}

PuTTY scripting to log onto host

I'm not sure why previous answers haven't suggested that the original poster set up a shell profile (bashrc, .tcshrc, etc.) that executed their commands automatically every time they log in on the server side.

The quest that brought me to this page for help was a bit different -- I wanted multiple PuTTY shortcuts for the same host that would execute different startup commands.

I came up with two solutions, both of which worked:

(background) I have a folder with a variety of PuTTY shortcuts, each with the "target" property in the shortcut tab looking something like:

"C:\Program Files (x86)\PuTTY\putty.exe" -load host01

with each load corresponding to a PuTTY profile I'd saved (with different hosts in the "Session" tab). (Mostly they only differ in color schemes -- I like to have each group of related tasks share a color scheme in the terminal window, with critical tasks, like logging in as root on a production system, performed only in distinctly colored windows.)

The folder's Windows properties are set to very clean and stripped down -- it functions as a small console with shortcut icons for each of my frequent remote PuTTY and RDP connections.

(solution 1) As mentioned in other answers the -m switch is used to configure a script on the Windows side to run, the -t switch is used to stay connected, but I found that it was order-sensitive if I wanted to get it to run without exiting

What I finally got to work after a lot of trial and error was:

(shortcut target field):

"C:\Program Files (x86)\PuTTY\putty.exe" -t -load "SSH Proxy" -m "C:\Users\[me]\Documents\hello-world-bash.txt"

where the file being executed looked like

echo "Hello, World!"
echo ""
export PUTTYVAR=PROXY
/usr/local/bin/bash

(no semicolons needed)

This runs the scripted command (in my case just printing "Hello, world" on the terminal) and sets a variable that my remote session can interact with.

Note for debugging: when you run PuTTY it loads the -m script, if you edit the script you need to re-launch PuTTY instead of just restarting the session.

(solution 2) This method feels a lot cleaner, as the brains are on the remote Unix side instead of the local Windows side:

From Putty master session (not "edit settings" from existing session) load a saved config and in the SSH tab set remote command to:

export PUTTYVAR=GREEN; bash -l

Then, in my .bashrc, I have a section that performs different actions based on that variable:

case ${PUTTYVAR} in
  "")
    echo "" 
    ;;
  "PROXY")
    # this is the session config with all the SSH tunnels defined in it
    echo "";
    echo "Special window just for holding tunnels open." ;
    echo "";
    PROMPT_COMMAND='echo -ne "\033]0;Proxy Session @master01\$\007"'
    alias temppass="ssh keyholder.example.com makeonetimepassword"
    alias | grep temppass
    ;;
  "GREEN")
    echo "";
    echo "It's not easy being green"
    ;;
  "GRAY")
    echo ""
    echo "The gray ghost"
    ;;
  *)
    echo "";
    echo "Unknown PUTTYVAR setting ${PUTTYVAR}"
    ;;
esac

(solution 3, untried)

It should also be possible to have bash skip my .bashrc and execute a different startup script, by putting this in the PuTTY SSH command field:

bash --rcfile .bashrc_variant -l 

Jquery .on('scroll') not firing the event while scrolling

$("body").on("custom-scroll", ".myDiv", function(){
    console.log("Scrolled :P");
})

$("#btn").on("click", function(){
    $("body").append('<div class="myDiv"><br><br><p>Content1<p><br><br><p>Content2<p><br><br></div>');
    listenForScrollEvent($(".myDiv"));
});


function listenForScrollEvent(el){
    el.on("scroll", function(){
        el.trigger("custom-scroll");
    })
}

see this post - Bind scroll Event To Dynamic DIV?

javax.net.ssl.SSLException: Received fatal alert: protocol_version

I was getting the same error. For Java version 7, following is working for me.

java.lang.System.setProperty("https.protocols", "TLSv1.2");

How to convert ZonedDateTime to Date?

I use this.

public class TimeTools {

    public static Date getTaipeiNowDate() {
        Instant now = Instant.now();
        ZoneId zoneId = ZoneId.of("Asia/Taipei");
        ZonedDateTime dateAndTimeInTai = ZonedDateTime.ofInstant(now, zoneId);
        try {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateAndTimeInTai.toString().substring(0, 19).replace("T", " "));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}

Because Date.from(java.time.ZonedDateTime.ofInstant(now, zoneId).toInstant()); It's not work!!! If u run your application in your computer, it's not problem. But if you run in any region of AWS or Docker or GCP, it will generate problem. Because computer is not your timezone on Cloud. You should set your correctly timezone in Code. For example, Asia/Taipei. Then it will correct in AWS or Docker or GCP.

public class App {
    public static void main(String[] args) {
        Instant now = Instant.now();
        ZoneId zoneId = ZoneId.of("Australia/Sydney");
        ZonedDateTime dateAndTimeInLA = ZonedDateTime.ofInstant(now, zoneId);
        try {
            Date ans = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateAndTimeInLA.toString().substring(0, 19).replace("T", " "));
            System.out.println("ans="+ans);
        } catch (ParseException e) {
        }
        Date wrongAns = Date.from(java.time.ZonedDateTime.ofInstant(now, zoneId).toInstant());
        System.out.println("wrongAns="+wrongAns);
    }
}

Difference between adjustResize and adjustPan in android?

You can use android:windowSoftInputMode="stateAlwaysHidden|adjustResize" in AndroidManifest.xml for your current activity, and use android:fitsSystemWindows="true" in styles or rootLayout.

Batch Extract path and filename from a variable

Late answer, I know, but for me the following script is quite useful - and it answers the question too, hitting two flys with one flag ;-)

The following script expands SendTo in the file explorer's context menu:

@echo off
cls
if "%~dp1"=="" goto Install

REM change drive, then cd to path given and run shell there
%~d1
cd "%~dp1"
cmd /k
goto End

:Install
rem No arguments: Copies itself into SendTo folder
copy "%0" "%appdata%\Microsoft\Windows\SendTo\A - Open in CMD shell.cmd"

:End

If you run this script without any parameters by double-clicking on it, it will copy itself to the SendTo folder and renaming it to "A - Open in CMD shell.cmd". Afterwards it is available in the "SentTo" context menu.

Then, right-click on any file or folder in Windows explorer and select "SendTo > A - Open in CMD shell.cmd"

The script will change drive and path to the path containing the file or folder you have selected and open a command shell with that path - useful for Visual Studio Code, because then you can just type "code ." to run it in the context of your project.

How does it work?

%0 - full path of the batch script
%~d1 - the drive contained in the first argument (e.g. "C:")
%~dp1 - the path contained in the first argument
cmd /k - opens a command shell which stays open

Not used here, but %~n1 is the file name of the first argument.

I hope this is helpful for someone.

Positioning the colorbar

The best way to get good control over the colorbar position is to give it its own axis. Like so:

# What I imagine your plotting looks like so far
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(your_data)

# Now adding the colorbar
cbaxes = fig.add_axes([0.8, 0.1, 0.03, 0.8]) 
cb = plt.colorbar(ax1, cax = cbaxes)  

The numbers in the square brackets of add_axes refer to [left, bottom, width, height], where the coordinates are just fractions that go from 0 to 1 of the plotting area.

What are the most widely used C++ vector/matrix math/linear algebra libraries, and their cost and benefit tradeoffs?

I'm new to this topic, so I can't say a whole lot, but BLAS is pretty much the standard in scientific computing. BLAS is actually an API standard, which has many implementations. I'm honestly not sure which implementations are most popular or why.

If you want to also be able to do common linear algebra operations (solving systems, least squares regression, decomposition, etc.) look into LAPACK.

How to show matplotlib plots in python

You must use plt.show() at the end in order to see the plot

How to Empty Caches and Clean All Targets Xcode 4 and later

I had some problems with Xcode 5.1 crashing on me, when I opened the doc window.

I am not sure of the cause of it, because I was also updating docsets, while I opened the window.

Well, in Xcode 5 the modules directory now resides within the derived data folder, which I for obvious reasons didn't delete. I deleted the contents of ~/Library/Developer/Xcode/DerivedData/ModuleCache and the ~/Library/Preferences/com.apple.Xcode.plist and everything then seems to work, after I restarted Xcode.

Using SQL LOADER in Oracle to import CSV file

I hade a csv file named FAR_T_SNSA.csv that i wanted to import in oracle database directly. For this i have done the following steps and it worked absolutely fine. Here are the steps that u vand follow out:

HOW TO IMPORT CSV FILE IN ORACLE DATABASE ?

  1. Get a .csv format file that is to be imported in oracle database. Here this is named “FAR_T_SNSA.csv”
  2. Create a table in sql with same column name as there were in .csv file. create table Billing ( iocl_id char(10), iocl_consumer_id char(10));

  3. Create a Control file that contains sql*loder script. In notepad type the script as below and save this with .ctl extension, in selecting file type as All Types(*). Here control file is named as Billing. And the Script is as Follows:

    LOAD DATA
    INFILE 'D:FAR_T_SNSA.csv'
    INSERT INTO TABLE Billing
    FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
    TRAILING NULLCOLS
    (
    iocl_id,
    iocl_consumer_id
    )
    
  4. Now in Command prompt run command:

    Sqlldr UserId/Password
    Control = “ControlFileName” 
    --------------------------------
    Here ControlFileName is Billing.
    

How can I clear an HTML file input with JavaScript?

There's 3 ways to clear file input with javascript:

  1. set value property to empty or null.

    Works for IE11+ and other modern browsers.

  2. Create an new file input element and replace the old one.

    The disadvantage is you will lose event listeners and expando properties.

  3. Reset the owner form via form.reset() method.

    To avoid affecting other input elements in the same owner form, we can create an new empty form and append the file input element to this new form and reset it. This way works for all browsers.

I wrote a javascript function. demo: http://jsbin.com/muhipoye/1/

function clearInputFile(f){
    if(f.value){
        try{
            f.value = ''; //for IE11, latest Chrome/Firefox/Opera...
        }catch(err){ }
        if(f.value){ //for IE5 ~ IE10
            var form = document.createElement('form'),
                parentNode = f.parentNode, ref = f.nextSibling;
            form.appendChild(f);
            form.reset();
            parentNode.insertBefore(f,ref);
        }
    }
}

Shell script - remove first and last quote (") from a variable

You can do it with only one call to sed:

$ echo "\"html\\test\\\"" | sed 's/^"\(.*\)"$/\1/'
html\test\

Create text file and fill it using bash

If you're wanting this as a script, the following Bash script should do what you want (plus tell you when the file already exists):

#!/bin/bash
if [ -e $1 ]; then
  echo "File $1 already exists!"
else
  echo >> $1
fi

If you don't want the "already exists" message, you can use:

#!/bin/bash
if [ ! -e $1 ]; then
  echo >> $1
fi

Edit about using:

Save whichever version with a name you like, let's say "create_file" (quotes mine, you don't want them in the file name). Then, to make the file executatble, at a command prompt do:

chmod u+x create_file

Put the file in a directory in your path, then use it with:

create_file NAME_OF_NEW_FILE

The $1 is a special shell variable which takes the first argument on the command line after the program name; i.e. $1 will pick up NAME_OF_NEW_FILE in the above usage example.

How can I check if the array of objects have duplicate property values?

if you are looking for a boolean, the quickest way would be

_x000D_
_x000D_
var values = [_x000D_
    { name: 'someName1' },_x000D_
    { name: 'someName2' },_x000D_
    { name: 'someName1' },_x000D_
    { name: 'someName1' }_x000D_
]_x000D_
_x000D_
// solution_x000D_
var hasDuplicate = false;_x000D_
values.map(v => v.name).sort().sort((a, b) => {_x000D_
  if (a === b) hasDuplicate = true_x000D_
})_x000D_
console.log('hasDuplicate', hasDuplicate)
_x000D_
_x000D_
_x000D_

Redirecting to another page in ASP.NET MVC using JavaScript/jQuery

<script type="text/javascript">
    function lnkLogout_Confirm()
    {
        var bResponse = confirm('Are you sure you want to exit?');

        if (bResponse === true) {
            ////console.log("lnkLogout_Confirm clciked.");
            var url = '@Url.Action("Login", "Login")';
            window.location.href = url;
        }
        return bResponse;
    }

</script>

Array length in angularjs returns undefined

var leg= $scope.name.length;
$log.info(leg);

Clip/Crop background-image with CSS

Another option is to use linear-gradient() to cover up the edges of your image. Note that this is a stupid solution, so I'm not going to put much effort into explaining it...

_x000D_
_x000D_
.flair {_x000D_
  min-width: 50px; /* width larger than sprite */_x000D_
  text-indent: 60px;_x000D_
  height: 25px;_x000D_
  display: inline-block;_x000D_
  background:_x000D_
    linear-gradient(#F00, #F00) 50px 0/999px 1px repeat-y,_x000D_
    url('https://championmains.github.io/dynamicflairs/riven/spritesheet.png') #F00;_x000D_
}_x000D_
_x000D_
.flair-classic {_x000D_
  background-position: 50px 0, 0 -25px;_x000D_
}_x000D_
_x000D_
.flair-r2 {_x000D_
  background-position: 50px 0, -50px -175px;_x000D_
}_x000D_
_x000D_
.flair-smite {_x000D_
  text-indent: 35px;_x000D_
  background-position: 25px 0, -50px -25px;_x000D_
}
_x000D_
<img src="https://championmains.github.io/dynamicflairs/riven/spritesheet.png" alt="spritesheet" /><br />_x000D_
<br />_x000D_
<span class="flair flair-classic">classic sprite</span><br /><br />_x000D_
<span class="flair flair-r2">r2 sprite</span><br /><br />_x000D_
<span class="flair flair-smite">smite sprite</span><br /><br />
_x000D_
_x000D_
_x000D_

I'm using this method on this page: https://championmains.github.io/dynamicflairs/riven/ and can't use ::before or ::after elements because I'm already using them for another hack.

jQuery delete all table rows except first

wrapped in a function:

function remove_rows(tablename) { 
    $(tablename).find("tr:gt(0)").remove();        
}

then call it:

remove_rows('#table1');
remove_rows('#table2');

library not found for -lPods

I was missing libPods.a in target, so the first thing to do is add it to linked frameworks and libraries.

Next, Product -> Build for -> Profiling (Or before adding libPods.a, if you completely missing it)

and finally check your Copy Pods resources script in Build phases (If its the same as your second target - it depends on Podfile and its targets sometimes). Then you should build successfully.

What are the sizes used for the iOS application splash screen?

Here I can add Resolutions and Display Specifications for iphone 6 & 6+ size:

iPhone 6+ - Asset Resolution (@3x) - Resolution (2208 x 1242)px

iPhone 6 - Asset Resolution (@2x) - Resolution (1334 x 750)px

iPad Air / Retina iPad (1st & 2nd Generation / 3rd & 4th) - Asset Resolution (@2x) - Resolution (2048 x 1536)px

iPad Mini (2nd & 3rd Generation) - Asset Resolution (@2x) - Resolution (2048 x 1536)px

iPhone (6, 5S, 5, 5C, 4S, 4) - App Icon (120x120 px) - AppStore Icon (1024x1024 px) - Spotlight (80x80 px) - Settings (58x58 px)

iPhone (6+) - App Icon (180x180 px) - AppStore Icon (1024x1024 px) - Spotlight (120x120 px) - Settings (87x87 px)

Write to UTF-8 file in Python

@S-Lott gives the right procedure, but expanding on the Unicode issues, the Python interpreter can provide more insights.

Jon Skeet is right (unusual) about the codecs module - it contains byte strings:

>>> import codecs
>>> codecs.BOM
'\xff\xfe'
>>> codecs.BOM_UTF8
'\xef\xbb\xbf'
>>> 

Picking another nit, the BOM has a standard Unicode name, and it can be entered as:

>>> bom= u"\N{ZERO WIDTH NO-BREAK SPACE}"
>>> bom
u'\ufeff'

It is also accessible via unicodedata:

>>> import unicodedata
>>> unicodedata.lookup('ZERO WIDTH NO-BREAK SPACE')
u'\ufeff'
>>> 

What's the difference between using "let" and "var"?

let is interesting, because it allows us to do something like this:

(() => {
    var count = 0;

    for (let i = 0; i < 2; ++i) {
        for (let i = 0; i < 2; ++i) {
            for (let i = 0; i < 2; ++i) {
                console.log(count++);
            }
        }
    }
})();

Which results in counting [0, 7].

Whereas

(() => {
    var count = 0;

    for (var i = 0; i < 2; ++i) {
        for (var i = 0; i < 2; ++i) {
            for (var i = 0; i < 2; ++i) {
                console.log(count++);
            }
        }
    }
})();

Only counts [0, 1].

Running an executable in Mac Terminal

To run an executable in mac

1). Move to the path of the file:

cd/PATH_OF_THE_FILE

2). Run the following command to set the file's executable bit using the chmod command:

chmod +x ./NAME_OF_THE_FILE

3). Run the following command to execute the file:

./NAME_OF_THE_FILE

Once you have run these commands, going ahead you just have to run command 3, while in the files path.

Real world use of JMS/message queues?

We are using JMS for communication with systems in a huge number of remote sites over unreliable networks. The loose coupling in combination with reliable messaging produces a stable system landscape: Each message will be sent as soon it is technically possible, bigger problems in network will not have influence on the whole system landscape...

What is the difference between JOIN and UNION?

UNION puts lines from queries after each other, while JOIN makes a cartesian product and subsets it -- completely different operations. Trivial example of UNION:

mysql> SELECT 23 AS bah
    -> UNION
    -> SELECT 45 AS bah;
+-----+
| bah |
+-----+
|  23 | 
|  45 | 
+-----+
2 rows in set (0.00 sec)

similary trivial example of JOIN:

mysql> SELECT * FROM 
    -> (SELECT 23 AS bah) AS foo 
    -> JOIN 
    -> (SELECT 45 AS bah) AS bar
    -> ON (33=33);
+-----+-----+
| foo | bar |
+-----+-----+
|  23 |  45 | 
+-----+-----+
1 row in set (0.01 sec)

Default Xmxsize in Java 8 (max heap size)

On my Ubuntu VM, with 1048 MB total RAM, java -XX:+PrintFlagsFinal -version | grep HeapSize printed : uintx MaxHeapSize := 266338304, which is approx 266MB and is 1/4th of my total RAM.

C convert floating point to int

Good guestion! -- where I have not yet found a satisfying answer for my case, the answer I provide here works for me, but may not be future proof...

If one uses gcc (clang?) and have -Werror and -Wbad-function-cast defined,

int val = (int)pow(10,9);

will result:

error: cast from function call of type 'double' to non-matching type 'int' [-Werror=bad-function-cast]

(for a good reason, overflow and where values are rounded needs to be thought out)

EDIT: 2020-08-30: So, my use case casting the value from function returning double to int, and chose pow() to represent that in place of a private function somewhere. Then I sidestepped thinking pow() more. (See comments more why pow() used below could be problematic...).

After properly thought out (that parameters to pow() are good), int val = pow(10,9); seems to work with gcc 9.2 x86-64 ...

but note:

printf("%d\n", pow(10,4));

may output e.g.

-1121380856

(did for me) where

int i = pow(10,4); printf("%d\n", i);

printed

10000

in one particular case I tried.

How to use RecyclerView inside NestedScrollView?

  1. You need to use support library 23.2.0 (or) above

  2. and RecyclerView height will be wrap_content.

  3. recyclerView.setNestedScrollingEnabled(false)

But by doing this the recycler pattern doesn't work. (i.e all the views will be loaded at once because wrap_content needs the height of complete RecyclerView so it will draw all child Views at once. No view will be recycled). Try not to use this pattern unless it is really required. Try to use viewType and add all other views that need to scroll to RecyclerView rather than using RecyclerView in Scrollview. The performance impact will be very high.

To make it simple "it just acts as LinearLayout with all the child views"

Differences between ConstraintLayout and RelativeLayout

In addition to @dhaval-jivani answer.

I've updated the project github project to latest version of constraint layout v.1.1.0-beta3

I've measured and compared the time of onCreate method and time between a start of onCreate and end of execution of last preformDraw method which visible in CPU monitor. All test were done on Samsung S5 mini with android 6.0.1 Here results:

Fresh start (first screen opening after application launch)

Relative Layout

OnCreate: 123ms

Last preformDraw time - OnCreate time: 311.3ms

Constraint Layout

OnCreate: 120.3ms

Last preformDraw time - OnCreate time: 310ms

Besides that, I've checked performance test from this article , here the code and found that on loop counts less than 100 constraint layout variant is faster during execution of inflating, measure, and layout then variants with Relative Layout. And on old Android devices, like Samsung S3 with Android 4.3, the difference is bigger.

As a conclusion I agree with comments from the article:

Does it worth to refactor old views switch on it from RelativeLayout or LinearLayout?

As always: It depends

I wouldn’t refactor anything unless you either have a performance problem with your current layout hierarchy or you want to make significant changes to the layout anyway. Though I haven’t measured it lately, I haven’t found any performance issues in the last releases. So I think you should be safe to use it. but – as I’v said – don’t just migrate for the sake of migrating. Only do so, if there’s a need for and benefit from it. For new layouts, though, I nearly always use ConstraintLayout. It’s so much better compare to what we had before.

How do you change library location in R?

I'm late to the party but I encountered the same thing when I tried to get fancy and move my library and then had files being saved to a folder that was outdated:

.libloc <<- "C:/Program Files/rest_of_your_Library_FileName"

One other point to mention is that for Windows Computers, if you copy the address from Windows Explorer, you have to manually change the '\' to a '/' for the directory to be recognized.

how to insert value into DataGridView Cell?

You can use this function if you want to add the data into database, with a button. I hope it will help.

// dgvBill is name of DataGridView

string StrQuery;
try
{
    using (SqlConnection conn = new SqlConnection(ConnectingString))
    {
        using (SqlCommand comm = new SqlCommand())
        {
            comm.Connection = conn;
            conn.Open();
            for (int i = 0; i < dgvBill.Rows.Count; i++) 
            {
                StrQuery = @"INSERT INTO tblBillDetails (IdBill, productID, quantity, price,  total) VALUES ('" + IdBillVar+ "','" + dgvBill.Rows[i].Cells[0].Value + "', '" + dgvBill.Rows[i].Cells[4].Value + "', '" + dgvBill.Rows[i].Cells[3].Value + "', '" + dgvBill.Rows[i].Cells[2].Value + "');";
                comm.CommandText = StrQuery;
                comm.ExecuteNonQuery();         
             }
         }
     }
 }
 catch (Exception err)
 {
     MessageBox.Show(err.Message  , "Error !");
 }

How do you count the elements of an array in java

Java doesn't have the concept of a "count" of the used elements in an array.

To get this, Java uses an ArrayList. The List is implemented on top of an array which gets resized whenever the JVM decides it's not big enough (or sometimes when it is too big).

To get the count, you use mylist.size() to ensure a capacity (the underlying array backing) you use mylist.ensureCapacity(20). To get rid of the extra capacity, you use mylist.trimToSize().

Changing Fonts Size in Matlab Plots

It's possible to change default fonts, both for the axes and for other text, by adding the following lines to the startup.m file.

% Change default axes fonts.
set(0,'DefaultAxesFontName', 'Times New Roman')
set(0,'DefaultAxesFontSize', 14)

% Change default text fonts.
set(0,'DefaultTextFontname', 'Times New Roman')
set(0,'DefaultTextFontSize', 14)

If you don't know if you have a startup.m file, run

which startup

to find its location. If Matlab says there isn't one, run

userpath

to know where it should be placed.

Switch to selected tab by name in Jquery-UI Tabs

You can get the index of the tab by name with the following script:

var index = $('#tabs ul').index($('#simple-tab-2'));
$('#tabs ul').tabs('select', index);

How to run cron job every 2 hours

To Enter into crontab :

crontab -e

write this into the file:

0 */2 * * * python/php/java yourfilepath

Example :0 */2 * * * python ec2-user/home/demo.py

and make sure you have keep one blank line after the last cron job in your crontab file

iOS 7 - Failing to instantiate default view controller

Using Interface Builder :

Check if 'Is initial view controller' is set. You can set it using below steps :

  1. Select your view controller (which is to be appeared as initial screen).
  2. Select Attribute inspector from Utilities window.
  3. Select 'Is Initial View Controller' from View Controller section (if not).

If you have done this step and still getting error then uncheck and do it again.

Steps to solve problem

Using programmatically :

Objective-C :

        self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];

        UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"HomeViewController"]; // <storyboard id>

        self.window.rootViewController = viewController;
        [self.window makeKeyAndVisible];

        return YES;

Swift :

        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
        let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

        var objMainViewController: MainViewController = mainStoryboard.instantiateViewControllerWithIdentifier("MainController") as! MainViewController

        self.window?.rootViewController = objMainViewController

        self.window?.makeKeyAndVisible()

        return true

How to print color in console using System.out.println?

I created a library called JColor that works on Linux, macOS, and Windows 10.

It uses the ANSI codes mentioned by WhiteFang, but abstracts them using words instead of codes which is more intuitive. Recently I added support for 8 and 24 bit colors

Choose your format, colorize it, and print it:

System.out.println(colorize("Green text on blue", GREEN_TEXT(), BLUE_BACK()));

You can also define a format once, and reuse it several times:

AnsiFormat fWarning = new AnsiFormat(RED_TEXT(), YELLOW_BACK(), BOLD());
System.out.println(colorize("Something bad happened!", fWarning));

Head over to JColor github repository for some examples.

Concatenating variables and strings in React

You're almost correct, just misplaced a few quotes. Wrapping the whole thing in regular quotes will literally give you the string #demo + {this.state.id} - you need to indicate which are variables and which are string literals. Since anything inside {} is an inline JSX expression, you can do:

href={"#demo" + this.state.id}

This will use the string literal #demo and concatenate it to the value of this.state.id. This can then be applied to all strings. Consider this:

var text = "world";

And this:

{"Hello " + text + " Andrew"}

This will yield:

Hello world Andrew 

You can also use ES6 string interpolation/template literals with ` (backticks) and ${expr} (interpolated expression), which is closer to what you seem to be trying to do:

href={`#demo${this.state.id}`}

This will basically substitute the value of this.state.id, concatenating it to #demo. It is equivalent to doing: "#demo" + this.state.id.

SQL SERVER, SELECT statement with auto generate row id

Is this perhaps what you are looking for?

select NEWID() * from TABLE

Difference between try-catch and throw in java

In my limited experience with the following details.throws is a declaration that declares multiple exceptions that may occur but do not necessarily occur, throw is an action that can throw only one exception, typically a non-runtime exception, try catch is a block that catches exceptions that can be handled when an exception occurs in a method,this exception can be thrown.An exception can be understood as a responsibility that should be taken care of by the behavior that caused the exception, rather than by its upper callers. I hope my answer will help you

Entity Framework - "An error occurred while updating the entries. See the inner exception for details"

View the Inner Exception of the exception to get a more specific error message.

One way to view the Inner Exception would be to catch the exception, and put a breakpoint on it. Then in the Locals window: select the Exception variable > InnerException > Message

And/Or just write to console:

    catch (Exception e)
    {
        Console.WriteLine(e.InnerException.Message);
    }

How to set Grid row and column positions programmatically

for (int i = 0; i < 6; i++)
{
    test.ColumnDefinitions.Add(new ColumnDefinition());

    Label t1 = new Label();
    t1.Content = "Test" + i;

    Grid.SetColumn(t1, i);
    Grid.SetRow(t1, 0);
    test.Children.Add(t1);
}

Using Gulp to Concatenate and Uglify files

Jun 10 2015: Note from the author of gulp-uglifyjs:

DEPRECATED: This plugin has been blacklisted as it relies on Uglify to concat the files instead of using gulp-concat, which breaks the "It should do one thing" paradigm. When I created this plugin, there was no way to get source maps to work with gulp, however now there is a gulp-sourcemaps plugin that achieves the same goal. gulp-uglifyjs still works great and gives very granular control over the Uglify execution, I'm just giving you a heads up that other options now exist.


Feb 18 2015: gulp-uglify and gulp-concat both work nicely with gulp-sourcemaps now. Just make sure to set the newLine option correctly for gulp-concat; I recommend \n;.


Original Answer (Dec 2014): Use gulp-uglifyjs instead. gulp-concat isn't necessarily safe; it needs to handle trailing semi-colons correctly. gulp-uglify also doesn't support source maps. Here's a snippet from a project I'm working on:

gulp.task('scripts', function () {
    gulp.src(scripts)
        .pipe(plumber())
        .pipe(uglify('all_the_things.js',{
            output: {
                beautify: false
            },
            outSourceMap: true,
            basePath: 'www',
            sourceRoot: '/'
        }))
        .pipe(plumber.stop())
        .pipe(gulp.dest('www/js'))
});

What do I use for a max-heap implementation in Python?

I have created a heap wrapper that inverts the values to create a max-heap, as well as a wrapper class for a min-heap to make the library more OOP-like. Here is the gist. There are three classes; Heap (abstract class), HeapMin, and HeapMax.

Methods:

isempty() -> bool; obvious
getroot() -> int; returns min/max
push() -> None; equivalent to heapq.heappush
pop() -> int; equivalent to heapq.heappop
view_min()/view_max() -> int; alias for getroot()
pushpop() -> int; equivalent to heapq.pushpop

How to "test" NoneType in python?

So how can I question a variable that is a NoneType?

Use is operator, like this

if variable is None:

Why this works?

Since None is the sole singleton object of NoneType in Python, we can use is operator to check if a variable has None in it or not.

Quoting from is docs,

The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. x is not y yields the inverse truth value.

Since there can be only one instance of None, is would be the preferred way to check None.


Hear it from the horse's mouth

Quoting Python's Coding Style Guidelines - PEP-008 (jointly defined by Guido himself),

Comparisons to singletons like None should always be done with is or is not, never the equality operators.

Limiting Powershell Get-ChildItem by File Creation Date Range

Use Where-Object, like:

Get-ChildItem 'PATH' -recurse -include @("*.tif*","*.jp2","*.pdf") | 
Where-Object { $_.CreationTime -gt "03/01/2013" -and $_.CreationTime -lt "03/31/2013" }
Select-Object FullName, CreationTime, @{Name="Mbytes";Expression={$_.Length/1Kb}}, @{Name="Age";Expression={(((Get-Date) - $_.CreationTime).Days)}} | 
Export-Csv 'PATH\scans.csv'

ImportError: No Module Named bs4 (BeautifulSoup)

Try reinstalling the module OR Try installing with beautiful soup with the below command

pip install --ignore-installed BeautifulSoup4

How can I style the border and title bar of a window in WPF?

If someone says you can't because only Windows can control the non-client area, they're wrong!

That's just a half-truth because Windows lets you specify the dimensions of the non-client area. The fact is, this is possible only throughout the Windows' kernel methods, and you're in .NET, not C/C++. Anyway, don't worry! P/Invoke was meant just for such things! Indeed, the whole of the Windows Form UI and Console application Std-I/O methods are offered using system calls. Hence, you'd have only to perform the right system calls to set the non-client area up, as documented in MSDN.

However, this is a really hard solution I came up with a lot of time ago. Luckily, as of .NET 4.5, you can use the WindowChrome class to adjust the non-client area like you want. Here you can get to start with.

In order to make things simpler and cleaner, I'll redirect you here, a guide to change the window border dimensions to whatever you want. By setting it to 0, you'll be able to implement your custom window border in place of the system's one.

I'm sorry for not posting a clear example, but later I will for sure.

How to initailize byte array of 100 bytes in java with all 0's

byte[] bytes = new byte[100];

Initializes all byte elements with default values, which for byte is 0. In fact, all elements of an array when constructed, are initialized with default values for the array element's type.

Update one MySQL table with values from another

UPDATE tobeupdated
INNER JOIN original ON (tobeupdated.value = original.value)
SET tobeupdated.id = original.id

That should do it, and really its doing exactly what yours is. However, I prefer 'JOIN' syntax for joins rather than multiple 'WHERE' conditions, I think its easier to read

As for running slow, how large are the tables? You should have indexes on tobeupdated.value and original.value

EDIT: we can also simplify the query

UPDATE tobeupdated
INNER JOIN original USING (value)
SET tobeupdated.id = original.id

USING is shorthand when both tables of a join have an identical named key such as id. ie an equi-join - http://en.wikipedia.org/wiki/Join_(SQL)#Equi-join