Programs & Examples On #Matlab engine

MATLAB Engine is a library to call MATLAB® software from standalone programs, for example written in C/C++ or Fortran.

Pass arguments into C program from command line

In C, this is done using arguments passed to your main() function:

int main(int argc, char *argv[])
{
    int i = 0;
    for (i = 0; i < argc; i++) {
        printf("argv[%d] = %s\n", i, argv[i]);
    }
    return 0;
}

More information can be found online such as this Arguments to main article.

How to print a percentage value in python?

Then you'd want to do this instead:

print str(int(1.0/3.0*100))+'%'

The .0 denotes them as floats and int() rounds them to integers afterwards again.

How do I fix this "TypeError: 'str' object is not callable" error?

this part :

"Your new price is: $"(float(price)

asks python to call this string:

"Your new price is: $"

just like you would a function: function( some_args) which will ALWAYS trigger the error:

TypeError: 'str' object is not callable

What's the console.log() of java?

Use the Android logging utility.

http://developer.android.com/reference/android/util/Log.html

Log has a bunch of static methods for accessing the different log levels. The common thread is that they always accept at least a tag and a log message.

Tags are a way of filtering output in your log messages. You can use them to wade through the thousands of log messages you'll see and find the ones you're specifically looking for.

You use the Log functions in Android by accessing the Log.x objects (where the x method is the log level). For example:

Log.d("MyTagGoesHere", "This is my log message at the debug level here");
Log.e("MyTagGoesHere", "This is my log message at the error level here");

I usually make it a point to make the tag my class name so I know where the log message was generated too. Saves a lot of time later on in the game.

You can see your log messages using the logcat tool for android:

adb logcat

Or by opening the eclipse Logcat view by going to the menu bar

Window->Show View->Other then select the Android menu and the LogCat view

Nodejs cannot find installed module on Windows

For windows, everybody said you should set environment variables for nodejs and npm modules, but do you know why? For some modules, they have command line tool, after installed the module, there'are [module].cmd file in C:\Program Files\nodejs, and it's used for launch in window command. So if you don't add the path containing the cmd file to environment variables %PATH% , you won't launch them successfully through command window.

How to embed a Google Drive folder in a website

At the time of writing this answer, there was no method to embed which let the user navigate inside folders and view the files without her leaving the website (the method in other answers, makes everything open in a new tab on google drive website), so I made my own tool for it. To embed a drive, paste the iframe code below in your HTML:

<iframe src="https://googledriveembedder.collegefam.com/?key=YOUR_API_KEY&folderid=FOLDER_ID_WHIHCH_IS_PUBLICLY_VIEWABLE" style="border:none;" width="100%"></iframe>

In the above code, you need to have your own API key and the folder ID. You can set the height as per your wish.

To get the API key:

1.) Go to https://console.developers.google.com/ Create a new project.

2.) From the menu button, go to 'APIs and Services' --> 'Dashboard' --> Click on 'Enable APIs and Services'.

3.) Search for 'Google Drive API', enable it. Then go to "credentials' tab, and create credentials. Keep your API key unrestricted.

4.) Copy the newly generated API key.

To get the folder ID:

1.)Go to the google drive folder you want to embed (for example, drive.google.com/drive/u/0/folders/1v7cGug_e3lNT0YjhvtYrwKV7dGY-Nyh5u [this is not a real folder]) Ensure that the folder is publicly shared and visible to anyone.

2.) Copy the part after 'folders/', this is your folder ID.

Now put both the API key and folder id in the above code and embed.

Note: To hide the download button for files, add '&allowdl=no' at the end of the iframe's src URL.

I made the widget keeping mobile users in mind, however it suits both mobile and desktop. If you run into issues, leave a comment here. I have attached some screenshots of the content of the iframe here.

The file preview looks like this The content of the iframe looks like this

Moving Panel in Visual Studio Code to right side

"Wokbench.panel.defaultLocation": "right"

Open settings using CTRL+., search for terminal and you should see this setting at the top. From the drop down below the settings explanation, choose right. See the screenshot below.

enter image description here

How to add elements of a Java8 stream into an existing List

Erik Allik already gave very good reasons, why you will most likely not want to collect elements of a stream into an existing List.

Anyway, you can use the following one-liner, if you really need this functionality.

But as Stuart Marks explains in his answer, you should never do this, if the streams might be parallel streams - use at your own risk...

list.stream().collect(Collectors.toCollection(() -> myExistingList));

Hibernate Criteria Restrictions AND / OR combination

For the new Criteria since version Hibernate 5.2:

CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<SomeClass> criteriaQuery = criteriaBuilder.createQuery(SomeClass.class);

Root<SomeClass> root = criteriaQuery.from(SomeClass.class);

Path<Object> expressionA = root.get("A");
Path<Object> expressionB = root.get("B");

Predicate predicateAEqualX = criteriaBuilder.equal(expressionA, "X");
Predicate predicateBInXY = expressionB.in("X",Y);
Predicate predicateLeft = criteriaBuilder.and(predicateAEqualX, predicateBInXY);

Predicate predicateAEqualY = criteriaBuilder.equal(expressionA, Y);
Predicate predicateBEqualZ = criteriaBuilder.equal(expressionB, "Z");
Predicate predicateRight = criteriaBuilder.and(predicateAEqualY, predicateBEqualZ);

Predicate predicateResult = criteriaBuilder.or(predicateLeft, predicateRight);

criteriaQuery
        .select(root)
        .where(predicateResult);

List<SomeClass> list = getSession()
        .createQuery(criteriaQuery)
        .getResultList();  

type checking in javascript

Quite a few utility libraries such as YourJS offer functions for determining if something is an array or if something is an integer or a lot of other types as well. YourJS defines isInt by checking if the value is a number and then if it is divisible by 1:

function isInt(x) {
  return typeOf(x, 'Number') && x % 1 == 0;
}

The above snippet was taken from this YourJS snippet and thusly only works because typeOf is defined by the library. You can download a minimalistic version of YourJS which mainly only has type checking functions such as typeOf(), isInt() and isArray(): http://yourjs.com/snippets/build/34,2

ALTER TABLE add constraint

ALTER TABLE `User`
ADD CONSTRAINT `user_properties_foreign`
FOREIGN KEY (`properties`)
REFERENCES `Properties` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;

Eclipse CDT: no rule to make target all

I got this same error after renaming and moving around source files. None of the proposed solutions worked for me and I tracked the error to be the meta-files under Debug directory not being updated. Deleting the entire Debug directory and re-build the project solved the problem for me.

How can you dynamically create variables via a while loop?

vars()['meta_anio_2012'] = 'translate'

Angular 4 checkbox change value

Give a try on this,

Template

<input (change)="fieldsChange($event)" value="angular" type="checkbox"/>

Ts File

fieldsChange(values:any):void {
  console.log(values.currentTarget.checked);
}

change PATH permanently on Ubuntu

Try to add export PATH=$PATH:/home/me/play in ~/.bashrc file.

Refresh certain row of UITableView based on Int in Swift

Swift 4

let indexPathRow:Int = 0    
let indexPosition = IndexPath(row: indexPathRow, section: 0)
tableView.reloadRows(at: [indexPosition], with: .none)

Reading local text file into a JavaScript array

Using Node.js

sync mode:

var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")

async mode:

var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
    var textByLine = text.split("\n")
});

UPDATE

As of at least Node 6, readFileSync returns a Buffer, so it must first be converted to a string in order for split to work:

var text = fs.readFileSync("./mytext.txt").toString('utf-8');

Or

var text = fs.readFileSync("./mytext.txt", "utf-8");

Oracle insert from select into table with more columns

Just add in the '0' in your select.

INSERT INTO table_name (a,b,c,d)
    SELECT
       other_table.a AS a,
       other_table.b AS b,
       other_table.c AS c,
       '0' AS d
    FROM other_table

How can I add a username and password to Jenkins?

Go to Manage Jenkins > Configure Global Security and select the Enable Security checkbox.

For the basic username/password authentication, I would recommend selecting Jenkins Own User Database for the security realm and then selecting Logged in Users can do anything or a matrix based strategy (in case when you have multiple users with different permissions) for the Authorization.

How do I get the color from a hexadecimal color code using .NET?

If you don't want to use the ColorTranslator, you can do it in easily:

string colorcode = "#FFFFFF00";
int argb = Int32.Parse(colorcode.Replace("#", ""), NumberStyles.HexNumber);
Color clr = Color.FromArgb(argb);

The colorcode is just the hexadecimal representation of the ARGB value.

EDIT

If you need to use 4 values instead of a single integer, you can use this (combining several comments):

string colorcode = "#FFFFFF00";    
colorcode = colorcode.TrimStart('#');

Color col; // from System.Drawing or System.Windows.Media
if (colorcode.Length == 6)
    col = Color.FromArgb(255, // hardcoded opaque
                int.Parse(colorcode.Substring(0,2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(2,2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(4,2), NumberStyles.HexNumber));
else // assuming length of 8
    col = Color.FromArgb(
                int.Parse(colorcode.Substring(0, 2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(2, 2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(4, 2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(6, 2), NumberStyles.HexNumber));

Note 1: NumberStyles is in System.Globalization.
Note 2: please provide your own error checking (colorcode should be a hexadecimal value of either 6 or 8 characters)

Reading JSON POST using PHP

you can put your json in a parameter and send it instead of put only your json in header:

$post_string= 'json_param=' . json_encode($data);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $post_string);
curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/');  // Set the url path we want to call

//execute post
$result = curl_exec($curl);

//see the results
$json=json_decode($result,true);
curl_close($curl);
print_r($json);

on the service side you can get your json string as a parameter:

$json_string = $_POST['json_param'];
$obj = json_decode($json_string);

then you can use your converted data as object.

How do I check if a type is a subtype OR the type of an object?

Apparently, no.

Here's the options:

Type.IsSubclassOf

As you've already found out, this will not work if the two types are the same, here's a sample LINQPad program that demonstrates:

void Main()
{
    typeof(Derived).IsSubclassOf(typeof(Base)).Dump();
    typeof(Base).IsSubclassOf(typeof(Base)).Dump();
}

public class Base { }
public class Derived : Base { }

Output:

True
False

Which indicates that Derived is a subclass of Base, but that Baseis (obviously) not a subclass of itself.

Type.IsAssignableFrom

Now, this will answer your particular question, but it will also give you false positives. As Eric Lippert has pointed out in the comments, while the method will indeed return True for the two above questions, it will also return True for these, which you probably don't want:

void Main()
{
    typeof(Base).IsAssignableFrom(typeof(Derived)).Dump();
    typeof(Base).IsAssignableFrom(typeof(Base)).Dump();
    typeof(int[]).IsAssignableFrom(typeof(uint[])).Dump();
}

public class Base { }
public class Derived : Base { }

Here you get the following output:

True
True
True

The last True there would indicate, if the method only answered the question asked, that uint[] inherits from int[] or that they're the same type, which clearly is not the case.

So IsAssignableFrom is not entirely correct either.

is and as

The "problem" with is and as in the context of your question is that they will require you to operate on the objects and write one of the types directly in code, and not work with Type objects.

In other words, this won't compile:

SubClass is BaseClass
^--+---^
   |
   +-- need object reference here

nor will this:

typeof(SubClass) is typeof(BaseClass)
                    ^-------+-------^
                            |
                            +-- need type name here, not Type object

nor will this:

typeof(SubClass) is BaseClass
^------+-------^
       |
       +-- this returns a Type object, And "System.Type" does not
           inherit from BaseClass

Conclusion

While the above methods might fit your needs, the only correct answer to your question (as I see it) is that you will need an extra check:

typeof(Derived).IsSubclassOf(typeof(Base)) || typeof(Derived) == typeof(Base);

which of course makes more sense in a method:

public bool IsSameOrSubclass(Type potentialBase, Type potentialDescendant)
{
    return potentialDescendant.IsSubclassOf(potentialBase)
           || potentialDescendant == potentialBase;
}

How can I call a shell command in my Perl script?

There are a lot of ways you can call a shell command from a Perl script, such as:

  1. back tick ls which captures the output and gives back to you.
  2. system system('ls');
  3. open

Refer #17 here: Perl programming tips

Pylint "unresolved import" error in Visual Studio Code

I have faced this problem in three ways. Although for each of them a solution is available in the answers to this question, I just thought to put it all together.

  1. First I got an "Unresolved Import" while importing some modules and I noticed that my installations were happening in global pip instead of the virtual environment.

    This issue was because of the Python interpreter. You need to select the interpreter in Visual Studio Code using Shift + Ctrl + P and then type Select Python Interpreter. Select your venv interpreter here.

  2. The second issue was: The above change did not resolve my issue completely. This time it was because of file settings.json. If you don't have the settings.json file in your project directory, create one and add the following line in that:

        {
            "python.pythonPath": "apis/bin/python"
        }
    

    This will basically tell Visual Studio Code to use the Python interpreter that is in your venv.

  3. The third issue was while importing a custom Python module or file in another program. For this you need to understand the folder structure. As Python in venv is inside bin, you'll need to specify the folder of your module (most of the time the application folder). In my case it was app,

        from app.models import setup_db
    

    Verbally, import setup_db from models.py resides in the app folder.

XSLT counting elements with a given value

Your xpath is just a little off:

count(//Property/long[text()=$parPropId])

Edit: Cerebrus quite rightly points out that the code in your OP (using the implicit value of a node) is absolutely fine for your purposes. In fact, since it's quite likely you want to work with the "Property" node rather than the "long" node, it's probably superior to ask for //Property[long=$parPropId] than the text() xpath, though you could make a case for the latter on readability grounds.

What can I say, I'm a bit tired today :)

What is the { get; set; } syntax in C#?

This is the short way of doing this:

public class Genre
{
    private string _name;

    public string Name
    {
      get => _name;
      set => _name = value;
    }
}

Git: force user and password prompt

This is most likely because you have multiple accounts, like one private, one for work with GitHub.

SOLUTION On Windows, go to Start > Credential Manager > Windows Credentials and remove GitHub creds, then try pulling or pushing again and you will be prompted to relogin into GitHub

SOLUTION OnMac, issue following on terminal:

git remote set-url origin https://[email protected]/username/repo-name.git

by replacing 'username' with your GitHub username in both places and providing your GitHub repo name.

Is it possible to get element from HashMap by its position?

you can use below code to get key : String [] keys = (String[]) item.keySet().toArray(new String[0]);

and get object or list that insert in HashMap with key of this item like this : item.get(keys[position]);

Sending a JSON HTTP POST request from Android

try some thing like blow:

SString otherParametersUrServiceNeed =  "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";

URL url = new URL(request); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection();   
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("POST"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);

   JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

wr.writeBytes(jsonParam.toString());

wr.flush();
wr.close();

References :

  1. http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
  2. Java - sending HTTP parameters via POST method easily

How often should you use git-gc?

You can do it without any interruption, with the new (Git 2.0 Q2 2014) setting gc.autodetach.

See commit 4c4ac4d and commit 9f673f9 (Nguy?n Thái Ng?c Duy, aka pclouds):

gc --auto takes time and can block the user temporarily (but not any less annoyingly).
Make it run in background on systems that support it.
The only thing lost with running in background is printouts. But gc output is not really interesting.
You can keep it in foreground by changing gc.autodetach.


Since that 2.0 release, there was a bug though: git 2.7 (Q4 2015) will make sure to not lose the error message.
See commit 329e6e8 (19 Sep 2015) by Nguy?n Thái Ng?c Duy (pclouds).
(Merged by Junio C Hamano -- gitster -- in commit 076c827, 15 Oct 2015)

gc: save log from daemonized gc --auto and print it next time

While commit 9f673f9 (gc: config option for running --auto in background - 2014-02-08) helps reduce some complaints about 'gc --auto' hogging the terminal, it creates another set of problems.

The latest in this set is, as the result of daemonizing, stderr is closed and all warnings are lost. This warning at the end of cmd_gc() is particularly important because it tells the user how to avoid "gc --auto" running repeatedly.
Because stderr is closed, the user does not know, naturally they complain about 'gc --auto' wasting CPU.

Daemonized gc now saves stderr to $GIT_DIR/gc.log.
Following gc --auto will not run and gc.log printed out until the user removes gc.log
.

link_to image tag. how to add class to a tag

The whole :action =>, :controller => bit that I've seen around a lot didn't work for me.

Spent hours digging and this method definitely worked for me in a loop.

<%=link_to( image_tag(participant.user.profile_pic.url(:small)), user_path(participant.user), :class=>"work") %>

Ruby on Rails using link_to with image_tag

Also, I'm using Rails 4.

How to customize a Spinner in Android

Try this

i was facing lot of issues when i was trying other solution...... After lot of R&D now i got solution

  1. create custom_spinner.xml in layout folder and paste this code

     <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorGray">
    <TextView
    android:id="@+id/tv_spinnervalue"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/colorWhite"
    android:gravity="center"
    android:layout_alignParentLeft="true"
    android:textSize="@dimen/_18dp"
    android:layout_marginTop="@dimen/_3dp"/>
    <ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:background="@drawable/men_icon"/>
    </RelativeLayout>
    
  2. in your activity

    Spinner spinner =(Spinner)view.findViewById(R.id.sp_colorpalates);
    String[] years = {"1996","1997","1998","1998"};
    spinner.setAdapter(new SpinnerAdapter(this, R.layout.custom_spinner, years));
    
  3. create a new class of adapter

    public class SpinnerAdapter extends ArrayAdapter<String> {
    private String[] objects;
    
    public SpinnerAdapter(Context context, int textViewResourceId, String[] objects) {
        super(context, textViewResourceId, objects);
        this.objects=objects;
    }
    
    @Override
    public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }
    
    @NonNull
    @Override
    public View getView(int position, View convertView, @NonNull ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }
    
    private View getCustomView(final int position, View convertView, ViewGroup parent) {
        View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_spinner, parent, false);
        final TextView label=(TextView)row.findViewById(R.id.tv_spinnervalue);
        label.setText(objects[position]);
        return row;
    }
    }
    

Manually raising (throwing) an exception in Python

How do I manually throw/raise an exception in Python?

Use the most specific Exception constructor that semantically fits your issue.

Be specific in your message, e.g.:

raise ValueError('A very specific bad thing happened.')

Don't raise generic exceptions

Avoid raising a generic Exception. To catch it, you'll have to catch all other more specific exceptions that subclass it.

Problem 1: Hiding bugs

raise Exception('I know Python!') # Don't! If you catch, likely to hide bugs.

For example:

def demo_bad_catch():
    try:
        raise ValueError('Represents a hidden bug, do not catch this')
        raise Exception('This is the exception you expect to handle')
    except Exception as error:
        print('Caught this error: ' + repr(error))

>>> demo_bad_catch()
Caught this error: ValueError('Represents a hidden bug, do not catch this',)

Problem 2: Won't catch

And more specific catches won't catch the general exception:

def demo_no_catch():
    try:
        raise Exception('general exceptions not caught by specific handling')
    except ValueError as e:
        print('we will not catch exception: Exception')
 

>>> demo_no_catch()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in demo_no_catch
Exception: general exceptions not caught by specific handling

Best Practices: raise statement

Instead, use the most specific Exception constructor that semantically fits your issue.

raise ValueError('A very specific bad thing happened')

which also handily allows an arbitrary number of arguments to be passed to the constructor:

raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz') 

These arguments are accessed by the args attribute on the Exception object. For example:

try:
    some_code_that_may_raise_our_value_error()
except ValueError as err:
    print(err.args)

prints

('message', 'foo', 'bar', 'baz')    

In Python 2.5, an actual message attribute was added to BaseException in favor of encouraging users to subclass Exceptions and stop using args, but the introduction of message and the original deprecation of args has been retracted.

Best Practices: except clause

When inside an except clause, you might want to, for example, log that a specific type of error happened, and then re-raise. The best way to do this while preserving the stack trace is to use a bare raise statement. For example:

logger = logging.getLogger(__name__)

try:
    do_something_in_app_that_breaks_easily()
except AppError as error:
    logger.error(error)
    raise                 # just this!
    # raise AppError      # Don't do this, you'll lose the stack trace!

Don't modify your errors... but if you insist.

You can preserve the stacktrace (and error value) with sys.exc_info(), but this is way more error prone and has compatibility problems between Python 2 and 3, prefer to use a bare raise to re-raise.

To explain - the sys.exc_info() returns the type, value, and traceback.

type, value, traceback = sys.exc_info()

This is the syntax in Python 2 - note this is not compatible with Python 3:

raise AppError, error, sys.exc_info()[2] # avoid this.
# Equivalently, as error *is* the second object:
raise sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]

If you want to, you can modify what happens with your new raise - e.g. setting new args for the instance:

def error():
    raise ValueError('oops!')

def catch_error_modify_message():
    try:
        error()
    except ValueError:
        error_type, error_instance, traceback = sys.exc_info()
        error_instance.args = (error_instance.args[0] + ' <modification>',)
        raise error_type, error_instance, traceback

And we have preserved the whole traceback while modifying the args. Note that this is not a best practice and it is invalid syntax in Python 3 (making keeping compatibility much harder to work around).

>>> catch_error_modify_message()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in catch_error_modify_message
  File "<stdin>", line 2, in error
ValueError: oops! <modification>

In Python 3:

raise error.with_traceback(sys.exc_info()[2])

Again: avoid manually manipulating tracebacks. It's less efficient and more error prone. And if you're using threading and sys.exc_info you may even get the wrong traceback (especially if you're using exception handling for control flow - which I'd personally tend to avoid.)

Python 3, Exception chaining

In Python 3, you can chain Exceptions, which preserve tracebacks:

raise RuntimeError('specific message') from error

Be aware:

  • this does allow changing the error type raised, and
  • this is not compatible with Python 2.

Deprecated Methods:

These can easily hide and even get into production code. You want to raise an exception, and doing them will raise an exception, but not the one intended!

Valid in Python 2, but not in Python 3 is the following:

raise ValueError, 'message' # Don't do this, it's deprecated!

Only valid in much older versions of Python (2.4 and lower), you may still see people raising strings:

raise 'message' # really really wrong. don't do this.

In all modern versions, this will actually raise a TypeError, because you're not raising a BaseException type. If you're not checking for the right exception and don't have a reviewer that's aware of the issue, it could get into production.

Example Usage

I raise Exceptions to warn consumers of my API if they're using it incorrectly:

def api_func(foo):
    '''foo should be either 'baz' or 'bar'. returns something very useful.'''
    if foo not in _ALLOWED_ARGS:
        raise ValueError('{foo} wrong, use "baz" or "bar"'.format(foo=repr(foo)))

Create your own error types when apropos

"I want to make an error on purpose, so that it would go into the except"

You can create your own error types, if you want to indicate something specific is wrong with your application, just subclass the appropriate point in the exception hierarchy:

class MyAppLookupError(LookupError):
    '''raise this when there's a lookup error for my app'''

and usage:

if important_key not in resource_dict and not ok_to_be_missing:
    raise MyAppLookupError('resource is missing, and that is not ok.')

How to revert the last migration?

Here is my solution, since the above solution do not really cover the use-case, when you use RunPython.

You can access the table via the ORM with

from django.db.migrations.recorder import MigrationRecorder

>>> MigrationRecorder.Migration.objects.all()
>>> MigrationRecorder.Migration.objects.latest('id')
Out[5]: <Migration: Migration 0050_auto_20170603_1814 for model>
>>> MigrationRecorder.Migration.objects.latest('id').delete()
Out[4]: (1, {u'migrations.Migration': 1})

So you can query the tables and delete those entries that are relevant for you. This way you can modify in detail. With RynPython migrations you also need to take care of the data that was added/changed/removed. The above example only displays, how you access the table via Djang ORM.

Is there an ignore command for git like there is for svn?

Using the answers already provided, you can roll your own git ignore command using an alias. Either add this to your ~/.gitconfig file:

ignore = !sh -c 'echo $1 >> .gitignore' -

Or run this command from the (*nix) shell of your choice:

git config --global alias.ignore '!sh -c "echo $1 >> .gitignore" -'

You can likewise create a git exclude command by replacing ignore with exclude and .gitignore with .git/info/exclude in the above.

(If you don't already understand the difference between these two files having read the answers here, see this question.)

How to build an APK file in Eclipse?

When you run your application, your phone should be detected and you should be given the option to run on your phone instead of on the emulator.

More instructions on getting your phone recognized: http://developer.android.com/guide/developing/device.html

When you want to export a signed version of the APK file (for uploading to the market or putting on a website), right-click on the project in Eclipse, choose export, and then choose "Export Android Application".

More details: http://developer.android.com/guide/publishing/app-signing.html#ExportWizard

How do I escape ampersands in batch files?

& is used to separate commands. Therefore you can use ^ to escape the &.

How can I make an svg scale with its parent container?

Another simple way is

transform: scale(1.5);

How to convert list of numpy arrays into single numpy array?

In general you can concatenate a whole sequence of arrays along any axis:

numpy.concatenate( LIST, axis=0 )

but you do have to worry about the shape and dimensionality of each array in the list (for a 2-dimensional 3x5 output, you need to ensure that they are all 2-dimensional n-by-5 arrays already). If you want to concatenate 1-dimensional arrays as the rows of a 2-dimensional output, you need to expand their dimensionality.

As Jorge's answer points out, there is also the function stack, introduced in numpy 1.10:

numpy.stack( LIST, axis=0 )

This takes the complementary approach: it creates a new view of each input array and adds an extra dimension (in this case, on the left, so each n-element 1D array becomes a 1-by-n 2D array) before concatenating. It will only work if all the input arrays have the same shape—even along the axis of concatenation.

vstack (or equivalently row_stack) is often an easier-to-use solution because it will take a sequence of 1- and/or 2-dimensional arrays and expand the dimensionality automatically where necessary and only where necessary, before concatenating the whole list together. Where a new dimension is required, it is added on the left. Again, you can concatenate a whole list at once without needing to iterate:

numpy.vstack( LIST )

This flexible behavior is also exhibited by the syntactic shortcut numpy.r_[ array1, ...., arrayN ] (note the square brackets). This is good for concatenating a few explicitly-named arrays but is no good for your situation because this syntax will not accept a sequence of arrays, like your LIST.

There is also an analogous function column_stack and shortcut c_[...], for horizontal (column-wise) stacking, as well as an almost-analogous function hstack—although for some reason the latter is less flexible (it is stricter about input arrays' dimensionality, and tries to concatenate 1-D arrays end-to-end instead of treating them as columns).

Finally, in the specific case of vertical stacking of 1-D arrays, the following also works:

numpy.array( LIST )

...because arrays can be constructed out of a sequence of other arrays, adding a new dimension to the beginning.

what is the difference between OLE DB and ODBC data sources?

ODBC:- Only for relational databases (Sql Server, Oracle etc)

OLE DB:- For both relational and non-relational databases. (Oracle, Sql-Server, Excel, raw files, etc)

How Can I Override Style Info from a CSS Class in the Body of a Page?

if you can access the head add <style> /*...some style */ </style> the way Hussein showed you
and the ultra hacky <style> </style> in the html it will work but its ugly. or javascript it the best way if you can use it in you case

matrix multiplication algorithm time complexity

Using linear algebra, there exist algorithms that achieve better complexity than the naive O(n3). Solvay Strassen algorithm achieves a complexity of O(n2.807) by reducing the number of multiplications required for each 2x2 sub-matrix from 8 to 7.

The fastest known matrix multiplication algorithm is Coppersmith-Winograd algorithm with a complexity of O(n2.3737). Unless the matrix is huge, these algorithms do not result in a vast difference in computation time. In practice, it is easier and faster to use parallel algorithms for matrix multiplication.

How to combine class and ID in CSS selector?

There's nothing wrong with combining an id and a class on one element, but you shouldn't need to identify it by both for one rule. If you really want to you can do:

#content.sectionA{some rules}

You don't need the div in front of the ID as others have suggested.

In general, CSS rules specific to that element should be set with the ID, and those are going to carry a greater weight than those of just the class. Rules specified by the class would be properties that apply to multiple items that you don't want to change in multiple places anytime you need to adjust.

That boils down to this:

 .sectionA{some general rules here}
 #content{specific rules, and overrides for things in .sectionA}

Make sense?

Can a unit test project load the target application's app.config file?

This is a bit old but I found a better solution for this. I was trying the chosen answer here but looks like .testrunconfig is already obsolete.

1. For Unit Tests, Wrap the config is an Interface (IConfig)

for Unit tests, config really shouldn't be part of what your testing so create a mock which you can inject. In this example I was using Moq.

Mock<IConfig> _configMock;
_configMock.Setup(config => config.ConfigKey).Returns("ConfigValue");
var SUT = new SUT(_configMock.Object);

2. For Integration test, dynamically add the config you need

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if(config.AppSettings.Settings[configName] != null)
{
    config.AppSettings.Settings.Remove(configName);
}
config.AppSettings.Settings.Add(configName, configValue);
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("appSettings");

VBA changing active workbook

Use ThisWorkbook which will refer to the original workbook which holds the code.

Alternatively at code start

Dim Wb As Workbook
Set Wb = ActiveWorkbook

sample code that activates all open books before returning to ThisWorkbook

Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
    Wb2.Activate
Next
Wb.Activate
End Sub

Adjusting HttpWebRequest Connection Timeout in C#

Sorry for tacking on to an old thread, but I think something that was said above may be incorrect/misleading.

From what I can tell .Timeout is NOT the connection time, it is the TOTAL time allowed for the entire life of the HttpWebRequest and response. Proof:

I Set:

.Timeout=5000
.ReadWriteTimeout=32000

The connect and post time for the HttpWebRequest took 26ms

but the subsequent call HttpWebRequest.GetResponse() timed out in 4974ms thus proving that the 5000ms was the time limit for the whole send request/get response set of calls.

I didn't verify if the DNS name resolution was measured as part of the time as this is irrelevant to me since none of this works the way I really need it to work--my intention was to time out quicker when connecting to systems that weren't accepting connections as shown by them failing during the connect phase of the request.

For example: I'm willing to wait 30 seconds on a connection request that has a chance of returning a result, but I only want to burn 10 seconds waiting to send a request to a host that is misbehaving.

PHP Function Comments

Functions:

/**
 * Does something interesting
 *
 * @param Place   $where  Where something interesting takes place
 * @param integer $repeat How many times something interesting should happen
 * 
 * @throws Some_Exception_Class If something interesting cannot happen
 * @author Monkey Coder <[email protected]>
 * @return Status
 */ 

Classes:

/**
 * Short description for class
 *
 * Long description for class (if any)...
 *
 * @copyright  2006 Zend Technologies
 * @license    http://www.zend.com/license/3_0.txt   PHP License 3.0
 * @version    Release: @package_version@
 * @link       http://dev.zend.com/package/PackageName
 * @since      Class available since Release 1.2.0
 */ 

Sample File:

<?php

/**
 * Short description for file
 *
 * Long description for file (if any)...
 *
 * PHP version 5.6
 *
 * LICENSE: This source file is subject to version 3.01 of the PHP license
 * that is available through the world-wide-web at the following URI:
 * http://www.php.net/license/3_01.txt.  If you did not receive a copy of
 * the PHP License and are unable to obtain it through the web, please
 * send a note to [email protected] so we can mail you a copy immediately.
 *
 * @category   CategoryName
 * @package    PackageName
 * @author     Original Author <[email protected]>
 * @author     Another Author <[email protected]>
 * @copyright  1997-2005 The PHP Group
 * @license    http://www.php.net/license/3_01.txt  PHP License 3.01
 * @version    SVN: $Id$
 * @link       http://pear.php.net/package/PackageName
 * @see        NetOther, Net_Sample::Net_Sample()
 * @since      File available since Release 1.2.0
 * @deprecated File deprecated in Release 2.0.0
 */

/**
 * This is a "Docblock Comment," also known as a "docblock."  The class'
 * docblock, below, contains a complete description of how to write these.
 */
require_once 'PEAR.php';

// {{{ constants

/**
 * Methods return this if they succeed
 */
define('NET_SAMPLE_OK', 1);

// }}}
// {{{ GLOBALS

/**
 * The number of objects created
 * @global int $GLOBALS['_NET_SAMPLE_Count']
 */
$GLOBALS['_NET_SAMPLE_Count'] = 0;

// }}}
// {{{ Net_Sample

/**
 * An example of how to write code to PEAR's standards
 *
 * Docblock comments start with "/**" at the top.  Notice how the "/"
 * lines up with the normal indenting and the asterisks on subsequent rows
 * are in line with the first asterisk.  The last line of comment text
 * should be immediately followed on the next line by the closing asterisk
 * and slash and then the item you are commenting on should be on the next
 * line below that.  Don't add extra lines.  Please put a blank line
 * between paragraphs as well as between the end of the description and
 * the start of the @tags.  Wrap comments before 80 columns in order to
 * ease readability for a wide variety of users.
 *
 * Docblocks can only be used for programming constructs which allow them
 * (classes, properties, methods, defines, includes, globals).  See the
 * phpDocumentor documentation for more information.
 * http://phpdoc.org/tutorial_phpDocumentor.howto.pkg.html
 *
 * The Javadoc Style Guide is an excellent resource for figuring out
 * how to say what needs to be said in docblock comments.  Much of what is
 * written here is a summary of what is found there, though there are some
 * cases where what's said here overrides what is said there.
 * http://java.sun.com/j2se/javadoc/writingdoccomments/index.html#styleguide
 *
 * The first line of any docblock is the summary.  Make them one short
 * sentence, without a period at the end.  Summaries for classes, properties
 * and constants should omit the subject and simply state the object,
 * because they are describing things rather than actions or behaviors.
 *
 * Below are the tags commonly used for classes. @category through @version
 * are required.  The remainder should only be used when necessary.
 * Please use them in the order they appear here.  phpDocumentor has
 * several other tags available, feel free to use them.
 *
 * @category   CategoryName
 * @package    PackageName
 * @author     Original Author <[email protected]>
 * @author     Another Author <[email protected]>
 * @copyright  1997-2005 The PHP Group
 * @license    http://www.php.net/license/3_01.txt  PHP License 3.01
 * @version    Release: @package_version@
 * @link       http://pear.php.net/package/PackageName
 * @see        NetOther, Net_Sample::Net_Sample()
 * @since      Class available since Release 1.2.0
 * @deprecated Class deprecated in Release 2.0.0
 */
class Net_Sample
{
    // {{{ properties

    /**
     * The status of foo's universe
     * Potential values are 'good', 'fair', 'poor' and 'unknown'.
     * @var string $foo
     */
    public $foo = 'unknown';

    /**
     * The status of life
     * Note that names of private properties or methods must be
     * preceeded by an underscore.
     * @var bool $_good
     */
    private $_good = true;

    // }}}
    // {{{ setFoo()

    /**
     * Registers the status of foo's universe
     *
     * Summaries for methods should use 3rd person declarative rather
     * than 2nd person imperative, beginning with a verb phrase.
     *
     * Summaries should add description beyond the method's name. The
     * best method names are "self-documenting", meaning they tell you
     * basically what the method does.  If the summary merely repeats
     * the method name in sentence form, it is not providing more
     * information.
     *
     * Summary Examples:
     *   + Sets the label              (preferred)
     *   + Set the label               (avoid)
     *   + This method sets the label  (avoid)
     *
     * Below are the tags commonly used for methods.  A @param tag is
     * required for each parameter the method has.  The @return
     * and @access tags are mandatory.  The @throws tag is required if
     * the method uses exceptions.  @static is required if the method can
     * be called statically.  The remainder should only be used when
     * necessary.  Please use them in the order they appear here.
     * phpDocumentor has several other tags available, feel free to use
     * them.
     *
     * The @param tag contains the data type, then the parameter's
     * name, followed by a description.  By convention, the first noun in
     * the description is the data type of the parameter.  Articles like
     * "a", "an", and  "the" can precede the noun.  The descriptions
     * should start with a phrase.  If further description is necessary,
     * follow with sentences.  Having two spaces between the name and the
     * description aids readability.
     *
     * When writing a phrase, do not capitalize and do not end with a
     * period:
     *   + the string to be tested
     *
     * When writing a phrase followed by a sentence, do not capitalize the
     * phrase, but end it with a period to distinguish it from the start
     * of the next sentence:
     *   + the string to be tested. Must use UTF-8 encoding.
     *
     * Return tags should contain the data type then a description of
     * the data returned.  The data type can be any of PHP's data types
     * (int, float, bool, string, array, object, resource, mixed)
     * and should contain the type primarily returned.  For example, if
     * a method returns an object when things work correctly but false
     * when an error happens, say 'object' rather than 'mixed.'  Use
     * 'void' if nothing is returned.
     *
     * Here's an example of how to format examples:
     * <code>
     * require_once 'Net/Sample.php';
     *
     * $s = new Net_Sample();
     * if (PEAR::isError($s)) {
     *     echo $s->getMessage() . "\n";
     * }
     * </code>
     *
     * Here is an example for non-php example or sample:
     * <samp>
     * pear install net_sample
     * </samp>
     *
     * @param string $arg1 the string to quote
     * @param int    $arg2 an integer of how many problems happened.
     *                     Indent to the description's starting point
     *                     for long ones.
     *
     * @return int the integer of the set mode used. FALSE if foo
     *             foo could not be set.
     * @throws exceptionclass [description]
     *
     * @access public
     * @static
     * @see Net_Sample::$foo, Net_Other::someMethod()
     * @since Method available since Release 1.2.0
     * @deprecated Method deprecated in Release 2.0.0
     */
    function setFoo($arg1, $arg2 = 0)
    {
        /*
         * This is a "Block Comment."  The format is the same as
         * Docblock Comments except there is only one asterisk at the
         * top.  phpDocumentor doesn't parse these.
         */
        if ($arg1 == 'good' || $arg1 == 'fair') {
            $this->foo = $arg1;
            return 1;
        } elseif ($arg1 == 'poor' && $arg2 > 1) {
            $this->foo = 'poor';
            return 2;
        } else {
            return false;
        }
    }

    // }}}
}

// }}}

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * c-hanging-comment-ender-p: nil
 * End:
 */

?>

Source: PEAR Docblock Comment standards

MySQL Sum() multiple columns

SELECT student, (SUM(mark1)+SUM(mark2)+SUM(mark3)....+SUM(markn)) AS Total
 FROM your_table
 GROUP BY student

What is [Serializable] and when should I use it?

Serialization

Serialization is the process of converting an object or a set of objects graph into a stream, it is a byte array in the case of binary serialization

Uses of Serialization

  1. To save the state of an object into a file, database etc. and use it latter.
  2. To send an object from one process to another (App Domain) on the same machine and also send it over wire to a process running on another machine.
  3. To create a clone of the original object as a backup while working on the main object.
  4. A set of objects can easily be copied to the system’s clipboard and then pasted into the same or another application

Below are some useful custom attributes that are used during serialization of an object

[Serializable] -> It is used when we mark an object’s serializable [NonSerialized] -> It is used when we do not want to serialize an object’s field. [OnSerializing] -> It is used when we want to perform some action while serializing an object [OnSerialized] -> It is used when we want to perform some action after serialized an object into stream.

Below is the example of serialization

[Serializable]
    internal class DemoForSerializable
    {
        internal string Fname = string.Empty;
        internal string Lname = string.Empty;

        internal Stream SerializeToMS(DemoForSerializable demo)
        {
            DemoForSerializable objSer = new DemoForSerializable();
            MemoryStream ms = new MemoryStream();
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(ms, objSer);
            return ms;
        }

        [OnSerializing]
        private void OnSerializing(StreamingContext context) {
            Fname = "sheo";
            Lname = "Dayal";
        }
        [OnSerialized]
        private void OnSerialized(StreamingContext context)
        {
       // Do some work after serialized object
        }

    }

Here is the calling code

class Program
    {
        string fname = string.Empty;
        string Lname = string.Empty; 

       static void Main(string[] args)
        {
            DemoForSerializable demo = new DemoForSerializable();

            Stream ms = demo.SerializeToMS(demo);
            ms.Position = 0;

            DemoForSerializable demo1 = new BinaryFormatter().Deserialize(ms) as DemoForSerializable;

            Console.WriteLine(demo1.Fname);
            Console.WriteLine(demo1.Lname);
            Console.ReadLine();
        }

    }

Get the Application Context In Fragment In Android?

you can define a global variable :

private Context globalContext = null;

and in the onCreate method, initialize it :

globalContext = this.getActivity();

And by that you can use the "globalContext" variable in all your fragment functions/methods.

Good luck.

Java Equivalent of C# async/await?

As it was mentioned, there is no direct equivalent, but very close approximation could be created with Java bytecode modifications (for both async/await-like instructions and underlying continuations implementation).

I'm working right now on a project that implements async/await on top of JavaFlow continuation library, please check https://github.com/vsilaev/java-async-await

No Maven mojo is created yet, but you may run examples with supplied Java agent. Here is how async/await code looks like:

public class AsyncAwaitNioFileChannelDemo {

public static void main(final String[] argv) throws Exception {

    ...
    final AsyncAwaitNioFileChannelDemo demo = new AsyncAwaitNioFileChannelDemo();
    final CompletionStage<String> result = demo.processFile("./.project");
    System.out.println("Returned to caller " + LocalTime.now());
    ...
}


public @async CompletionStage<String> processFile(final String fileName) throws IOException {
    final Path path = Paths.get(new File(fileName).toURI());
    try (
            final AsyncFileChannel file = new AsyncFileChannel(
                path, Collections.singleton(StandardOpenOption.READ), null
            );              
            final FileLock lock = await(file.lockAll(true))
        ) {

        System.out.println("In process, shared lock: " + lock);
        final ByteBuffer buffer = ByteBuffer.allocateDirect((int)file.size());

        await( file.read(buffer, 0L) );
        System.out.println("In process, bytes read: " + buffer);
        buffer.rewind();

        final String result = processBytes(buffer);

        return asyncResult(result);

    } catch (final IOException ex) {
        ex.printStackTrace(System.out);
        throw ex;
    }
}

@async is the annotation that flags a method as asynchronously executable, await() is a function that waits on CompletableFuture using continuations and a call to "return asyncResult(someValue)" is what finalizes associated CompletableFuture/Continuation

As with C#, control flow is preserved and exception handling may be done in regular manner (try/catch like in sequentially executed code)

Remove duplicates from dataframe, based on two columns A,B, keeping row with max value in another column C

You can do this simply by using pandas drop duplicates function

df.drop_duplicates(['A','B'],keep= 'last')

How can I clone a private GitLab repository?

Before doing

git clone https://example.com/root/test.git

make sure that you have added ssh key in your system. Follow this : https://gitlab.com/profile/keys .

Once added run the above command. It will prompt for your gitlab username and password and on authentication, it will be cloned.

What is the meaning of "Failed building wheel for X" in pip install?

It might be helpful to address this question from a package deployment perspective.

There are many tutorials out there that explain how to publish a package to PyPi. Below are a couple I have used;

medium
real python

My experience is that most of these tutorials only have you use the .tar of the source, not a wheel. Thus, when installing packages created using these tutorials, I've received the "Failed to build wheel" error.

I later found the link on PyPi to the Python Software Foundation's docs PSF Docs. I discovered that their setup and build process is slightly different, and does indeed included building a wheel file.

After using the officially documented method, I no longer received the error when installing my packages.

So, the error might simply be a matter of how the developer packaged and deployed the project. None of us were born knowing how to use PyPi, and if they happened upon the wrong tutorial -- well, you can fill in the blanks.

I'm sure that is not the only reason for the error, but I'm willing to bet that is a major reason for it.

Upload files with FTP using PowerShell

You can simply handle file uploads through PowerShell, like this. Complete project is available on Github here https://github.com/edouardkombo/PowerShellFtp

#Directory where to find pictures to upload
$Dir= 'c:\fff\medias\'

#Directory where to save uploaded pictures
$saveDir = 'c:\fff\save\'

#ftp server params
$ftp = 'ftp://10.0.1.11:21/'
$user = 'user'
$pass = 'pass'

#Connect to ftp webclient
$webclient = New-Object System.Net.WebClient 
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)  

#Initialize var for infinite loop
$i=0

#Infinite loop
while($i -eq 0){ 

    #Pause 1 seconde before continue
    Start-Sleep -sec 1

    #Search for pictures in directory
    foreach($item in (dir $Dir "*.jpg"))
    {
        #Set default network status to 1
        $onNetwork = "1"

        #Get picture creation dateTime...
        $pictureDateTime = (Get-ChildItem $item.fullName).CreationTime

        #Convert dateTime to timeStamp
        $pictureTimeStamp = (Get-Date $pictureDateTime).ToFileTime()

        #Get actual timeStamp
        $timeStamp = (Get-Date).ToFileTime() 

        #Get picture lifeTime
        $pictureLifeTime = $timeStamp - $pictureTimeStamp

        #We only treat pictures that are fully written on the disk
        #So, we put a 2 second delay to ensure even big pictures have been fully wirtten   in the disk
        if($pictureLifeTime -gt "2") {    

            #If upload fails, we set network status at 0
            try{

                $uri = New-Object System.Uri($ftp+$item.Name)

                $webclient.UploadFile($uri, $item.FullName)

            } catch [Exception] {

                $onNetwork = "0"
                write-host $_.Exception.Message;
            }

            #If upload succeeded, we do further actions
            if($onNetwork -eq "1"){
                "Copying $item..."
                Copy-Item -path $item.fullName -destination $saveDir$item 

                "Deleting $item..."
                Remove-Item $item.fullName
            }


        }  
    }
}   

Android error while retrieving information from server 'RPC:s-5:AEC-0' in Google Play?

To fix this issue you need to remove your Google account, then add it again. To do this follow these instructions:

http://support.google.com/android/bin/answer.py?hl=en&answer=1663649

(Or just find the account under Settings > Personal > Accounts and Sync > Click the Google Account > Click Menu button > Click Remove Account > Confirm deletion.)

Regex for quoted string with escaping quotes

/"(?:[^"\\]|\\.)*"/

Works in The Regex Coach and PCRE Workbench.

Example of test in JavaScript:

_x000D_
_x000D_
    var s = ' function(){ return " Is big \\"problem\\", \\no? "; }';_x000D_
    var m = s.match(/"(?:[^"\\]|\\.)*"/);_x000D_
    if (m != null)_x000D_
        alert(m);
_x000D_
_x000D_
_x000D_

How does cellForRowAtIndexPath work?

1) The function returns a cell for a table view yes? So, the returned object is of type UITableViewCell. These are the objects that you see in the table's rows. This function basically returns a cell, for a table view. But you might ask, how the function would know what cell to return for what row, which is answered in the 2nd question

2)NSIndexPath is essentially two things-

  • Your Section
  • Your row

Because your table might be divided to many sections and each with its own rows, this NSIndexPath will help you identify precisely which section and which row. They are both integers. If you're a beginner, I would say try with just one section.

It is called if you implement the UITableViewDataSource protocol in your view controller. A simpler way would be to add a UITableViewController class. I strongly recommend this because it Apple has some code written for you to easily implement the functions that can describe a table. Anyway, if you choose to implement this protocol yourself, you need to create a UITableViewCell object and return it for whatever row. Have a look at its class reference to understand re-usablity because the cells that are displayed in the table view are reused again and again(this is a very efficient design btw).

As for when you have two table views, look at the method. The table view is passed to it, so you should not have a problem with respect to that.

How do you get the file size in C#?

MSDN FileInfo.Length says that it is "the size of the current file in bytes."

My typical Google search for something like this is: msdn FileInfo

Why is January month 0 in Java Calendar?

In Java 8, there is a new Date/Time API JSR 310 that is more sane. The spec lead is the same as the primary author of JodaTime and they share many similar concepts and patterns.

Adding input elements dynamically to form

Try this JQuery code to dynamically include form, field, and delete/remove behavior:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
    var max_fields = 10;_x000D_
    var wrapper = $(".container1");_x000D_
    var add_button = $(".add_form_field");_x000D_
_x000D_
    var x = 1;_x000D_
    $(add_button).click(function(e) {_x000D_
        e.preventDefault();_x000D_
        if (x < max_fields) {_x000D_
            x++;_x000D_
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box_x000D_
        } else {_x000D_
            alert('You Reached the limits')_x000D_
        }_x000D_
    });_x000D_
_x000D_
    $(wrapper).on("click", ".delete", function(e) {_x000D_
        e.preventDefault();_x000D_
        $(this).parent('div').remove();_x000D_
        x--;_x000D_
    })_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="container1">_x000D_
    <button class="add_form_field">Add New Field &nbsp; _x000D_
      <span style="font-size:16px; font-weight:bold;">+ </span>_x000D_
    </button>_x000D_
    <div><input type="text" name="mytext[]"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Refer Demo Here

How to read a string one letter at a time in python

I can't leave this question in this state with that final code in the question hanging over me...

dan: here's a much neater and shorter version of your code. It would be a good idea to look at how this is done and code more this way in future. I realise you probably have no further need of this code, but learning how you should do it is a good idea. Some things to note:

  • There are only two comments - and even the second is not really necessary for someone familiar with Python, they'll realise NL is being stripped. Only write comments where it adds value.

  • The with statement (recommended in another answer) removes the bother of closing the file through the context handler.

  • Use a dictionary instead of two lists.

  • A generator comprehension ((x for y in z)) is used to do the translation in one line.

  • Wrap as little code as you can in a try/except block to reduce the probability of catching an exception you didn't mean to.

  • Use the input() argument rather than print()ing first - Use '\n' to get the new line you want.

  • Don't write code across multiple lines or with intermediate variables like this just for the sake of it:

    a = a.b()
    a = a.c()
    b = a.x()
    c = b.y()
    

    Instead, write these constructs like this, chaining the calls as is perfectly valid:

    a = a.b().c()
    c = a.x().y()
    

code = {}
with open('morseCode.txt', 'r') as morse_code_file:
    # line format is <letter>:<morse code translation>
    for line in morse_code_file:
        line = line.rstrip()  # Remove NL
        code[line[0]] = line[2:]

user_input = input("Enter a string to convert to morse code or press <enter> to quit\n")
while user_input:
    try:
        print(''.join(code[x] for x in user_input.replace(' ', '').upper()))
    except KeyError:
        print("Error in input. Only alphanumeric characters, a comma, and period allowed")

    user_input = input("Try again or press <enter> to quit\n")

How to load local html file into UIWebView

UIWebView *web=[[UIWebView alloc]initWithFrame:self.view.frame];
    //[self.view addSubview:web];
    NSString *filePath=[[NSBundle mainBundle]pathForResource:@"browser_demo" ofType:@"html" inDirectory:nil];
    [web loadRequest:[NSURLRequest requestWhttp://stackoverflow.com/review/first-postsithURL:[NSURL fileURLWithPath:filePath]]];

Django datetime issues (default=datetime.now())

The datetime.now() is evaluated when the class is created, not when new record is being added to the database.

To achieve what you want define this field as:

date = models.DateTimeField(auto_now_add=True)

This way the date field will be set to current date for each new record.

Difference between OpenJDK and Adoptium/AdoptOpenJDK

Update: AdoptOpenJDK has changed its name to Adoptium, as part of its move to the Eclipse Foundation.


OpenJDK ? source code
Adoptium/AdoptOpenJDK ? builds

Difference between OpenJDK and AdoptOpenJDK

The first provides source-code, the other provides builds of that source-code.

Several vendors of Java & OpenJDK

Adoptium of the Eclipse Foundation, formerly known as AdoptOpenJDK, is only one of several vendors distributing implementations of the Java platform. These include:

  • Eclipse Foundation (Adoptium/AdoptOpenJDK)
  • Azul Systems
  • Oracle
  • Red Hat / IBM
  • BellSoft
  • SAP
  • Amazon AWS
  • … and more

See this flowchart of mine to help guide you in picking a vendor for an implementation of the Java platform. Click/tap to zoom.

Flowchart guiding you in choosing a vendor for a Java 11 implementation

Another resource: This comparison matrix by Azul Systems is useful, and seems true and fair to my mind.

Here is a list of considerations and motivations to consider in choosing a vendor and implementation.

Motivations in choosing a vendor for Java

Some vendors offer you a choice of JIT technologies.

Diagram showing history of HotSpot & JRockit merging, and OpenJ9 both available in AdoptOpenJDK

To understand more about this Java ecosystem, read Java Is Still Free

Why does JS code "var a = document.querySelector('a[data-a=1]');" cause error?

From the selectors specification:

Attribute values must be CSS identifiers or strings.

Identifiers cannot start with a number. Strings must be quoted.

1 is therefore neither a valid identifier nor a string.

Use "1" (which is a string) instead.

var a = document.querySelector('a[data-a="1"]');

Trigger an action after selection select2

As per my usage above v.4 this gonna work

$('#selectID').on("select2:select", function(e) { 
    //var value = e.params.data;  Using {id,text format}
});

And for less then v.4 this gonna work:

$('#selectID').on("change", function(e) { 
   //var value = e.params.data; Using {id,text} format
});

Centos/Linux setting logrotate to maximum file size for all logs

As mentioned by Zeeshan, the logrotate options size, minsize, maxsize are triggers for rotation.

To better explain it. You can run logrotate as often as you like, but unless a threshold is reached such as the filesize being reached or the appropriate time passed, the logs will not be rotated.

The size options do not ensure that your rotated logs are also of the specified size. To get them to be close to the specified size you need to call the logrotate program sufficiently often. This is critical.

For log files that build up very quickly (e.g. in the hundreds of MB a day), unless you want them to be very large you will need to ensure logrotate is called often! this is critical.

Therefore to stop your disk filling up with multi-gigabyte log files you need to ensure logrotate is called often enough, otherwise the log rotation will not work as well as you want.

on Ubuntu, you can easily switch to hourly rotation by moving the script /etc/cron.daily/logrotate to /etc/cron.hourly/logrotate

Or add

*/5 * * * * /etc/cron.daily/logrotate 

To your /etc/crontab file. To run it every 5 minutes.

The size option ignores the daily, weekly, monthly time options. But minsize & maxsize take it into account.

The man page is a little confusing there. Here's my explanation.

minsize rotates only when the file has reached an appropriate size and the set time period has passed. e.g. minsize 50MB + daily If file reaches 50MB before daily time ticked over, it'll keep growing until the next day.

maxsize will rotate when the log reaches a set size or the appropriate time has passed. e.g. maxsize 50MB + daily. If file is 50MB and we're not at the next day yet, the log will be rotated. If the file is only 20MB and we roll over to the next day then the file will be rotated.

size will rotate when the log > size. Regardless of whether hourly/daily/weekly/monthly is specified. So if you have size 100M - it means when your log file is > 100M the log will be rotated if logrotate is run when this condition is true. Once it's rotated, the main log will be 0, and a subsequent run will do nothing.

So in the op's case. Specficially 50MB max I'd use something like the following:

/var/log/logpath/*.log {
    maxsize 50M
    hourly
    missingok
    rotate 8
    compress
    notifempty
    nocreate
}

Which means he'd create 8hrs of logs max. And there would be 8 of them at no more than 50MB each. Since he's saying that he's getting multi gigabytes each day and assuming they build up at a fairly constant rate, and maxsize is used he'll end up with around close to the max reached for each file. So they will be likely close to 50MB each. Given the volume they build, he would need to ensure that logrotate is run often enough to meet the target size.

Since I've put hourly there, we'd need logrotate to be run a minimum of every hour. But since they build up to say 2 gigabytes per day and we want 50MB... assuming a constant rate that's 83MB per hour. So you can imagine if we run logrotate every hour, despite setting maxsize to 50 we'll end up with 83MB log's in that case. So in this instance set the running to every 30 minutes or less should be sufficient.

Ensure logrotate is run every 30 mins.

*/30 * * * * /etc/cron.daily/logrotate 

how to call javascript function in html.actionlink in asp.net mvc?

<a onclick="MyFunc()">blabla..</a>

There is nothing more in @Html.ActionLink that you could utilize in this case. And razor is evel by itself, drop it from where you can.

what is .subscribe in angular?

.subscribe is not an Angular2 thing.

It's a method that comes from rxjs library which Angular is using internally.

If you can imagine yourself subscribing to a newsletter, every time there is a new newsletter, they will send it to your home (the method inside subscribe gets called).

That's what happens when you subscribing to a source of magazines ( which is called an Observable in rxjs library)

All the AJAX calls in Angular are using rxjs internally and in order to use any of them, you've got to use the method name, e.g get, and then call subscribe on it, because get returns and Observable.

Also, when writing this code <button (click)="doSomething()">, Angular is using Observables internally and subscribes you to that source of event, which in this case is a click event.

Back to our analogy of Observables and newsletter stores, after you've subscribed, as soon as and as long as there is a new magazine, they'll send it to you unless you go and unsubscribe from them for which you have to remember the subscription number or id, which in rxjs case it would be like :

 let subscription = magazineStore.getMagazines().subscribe(
   (newMagazine)=>{

         console.log('newMagazine',newMagazine);

    }); 

And when you don't want to get the magazines anymore:

   subscription.unsubscribe();

Also, the same goes for

 this.route.paramMap

which is returning an Observable and then you're subscribing to it.

My personal view is rxjs was one of the greatest things that were brought to JavaScript world and it's even better in Angular.

There are 150~ rxjs methods ( very similar to lodash methods) and the one that you're using is called switchMap

Lightweight Javascript DB for use in Node.js

LevelUP aims to expose the features of LevelDB in a Node.js-friendly way.

https://github.com/rvagg/node-levelup

You can also look at UnQLite. with a node.js binding node-unqlite

https://github.com/symisc/unqlite

check if jquery has been loaded, then load it if false

Method 1:

if (window.jQuery) {  
    // jQuery is loaded  
} else {
    // jQuery is not loaded
}

Method 2:

if (typeof jQuery == 'undefined') {  
    // jQuery is not loaded
} else {
    // jQuery is loaded
}

If jquery.js file is not loaded, we can force load it like so:

if (!window.jQuery) {
  var jq = document.createElement('script'); jq.type = 'text/javascript';
  // Path to jquery.js file, eg. Google hosted version
  jq.src = '/path-to-your/jquery.min.js';
  document.getElementsByTagName('head')[0].appendChild(jq);
}

How to parse freeform street/postal address out of text, and into components

UPDATE: Geocode.xyz now works worldwide. For examples see https://geocode.xyz

For USA, Mexico and Canada, see geocoder.ca.

For example:

Input: something going on near the intersection of main and arthur kill rd new york

Output:

<geodata>
  <latt>40.5123510000</latt>
  <longt>-74.2500500000</longt>
  <AreaCode>347,718</AreaCode>
  <TimeZone>America/New_York</TimeZone>
  <standard>
    <street1>main</street1>
    <street2>arthur kill</street2>
    <stnumber/>
    <staddress/>
    <city>STATEN ISLAND</city>
    <prov>NY</prov>
    <postal>11385</postal>
    <confidence>0.9</confidence>
  </standard>
</geodata>

You may also check the results in the web interface or get output as Json or Jsonp. eg. I'm looking for restaurants around 123 Main Street, New York

Base64 PNG data to HTML5 canvas

By the looks of it you need to actually pass drawImage an image object like so

_x000D_
_x000D_
var canvas = document.getElementById("c");_x000D_
var ctx = canvas.getContext("2d");_x000D_
_x000D_
var image = new Image();_x000D_
image.onload = function() {_x000D_
  ctx.drawImage(image, 0, 0);_x000D_
};_x000D_
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
_x000D_
<canvas id="c"></canvas>
_x000D_
_x000D_
_x000D_

I've tried it in chrome and it works fine.

How to get date in BAT file

%date% will give you the date.

%time% will give you the time.

The date and time /t commands may give you more detail.

Which type of folder structure should be used with Angular 2?

Maybe something like this structure:

|-- app
     |-- modules
       |-- home
           |-- [+] components
           |-- pages
              |-- home
              |-- home.component.ts|html|scss|spec
           |-- home-routing.module.ts
           |-- home.module.ts
     |-- core
       |-- authentication
           |-- authentication.service.ts|spec.ts
       |-- footer
           |-- footer.component.ts|html|scss|spec.ts
       |-- guards
           |-- auth.guard.ts
           |-- no-auth-guard.ts
           |-- admin-guard.ts 
       |-- http
           |-- user
               |-- user.service.ts|spec.ts
           |-- api.service.ts|spec.ts
       |-- interceptors
           |-- api-prefix.interceptor.ts
           |-- error-handler.interceptor.ts
           |-- http.token.interceptor.ts
       |-- mocks
           |-- user.mock.ts
       |-- services
           |-- srv1.service.ts|spec.ts
           |-- srv2.service.ts|spec.ts
       |-- header
           |-- header.component.ts|html|scss|spec.ts
       |-- core.module.ts
       |-- ensureModuleLoadedOnceGuard.ts
       |-- logger.service.ts
     |-- shared
          |-- components
              |-- loader
                  |-- loader.component.ts|html|scss|spec.ts
          |-- buttons
              |-- favorite-button
                  |-- favorite-button.component.ts|html|scss|spec.ts
              |-- collapse-button
                  |-- collapse-button.component.ts|html|scss|spec.ts
          |-- directives
              |-- auth.directive.ts|spec.ts
          |-- pipes
              |-- capitalize.pipe.ts
              |-- safe.pipe.ts
     |-- configs
         |-- app-settings.config.ts
         |-- dt-norwegian.config.ts
     |-- scss
          |-- [+] partials
          |-- _base.scss
          |-- styles.scss
     |-- assets

How to get current relative directory of your Makefile?

I like the chosen answer, but I think it would be more helpful to actually show it working than explain it.

/tmp/makefile_path_test.sh

#!/bin/bash -eu

# Create a testing dir
temp_dir=/tmp/makefile_path_test
proj_dir=$temp_dir/dir1/dir2/dir3
mkdir -p $proj_dir

# Create the Makefile in $proj_dir
# (Because of this, $proj_dir is what $(path) should evaluate to.)
cat > $proj_dir/Makefile <<'EOF'
path := $(patsubst %/,%,$(dir $(abspath $(lastword $(MAKEFILE_LIST)))))
cwd  := $(shell pwd)

all:
    @echo "MAKEFILE_LIST: $(MAKEFILE_LIST)"
    @echo "         path: $(path)"
    @echo "          cwd: $(cwd)"
    @echo ""
EOF

# See/debug each command
set -x

# Test using the Makefile in the current directory
cd $proj_dir
make

# Test passing a Makefile
cd $temp_dir
make -f $proj_dir/Makefile

# Cleanup
rm -rf $temp_dir

Output:

+ cd /tmp/makefile_path_test/dir1/dir2/dir3
+ make
MAKEFILE_LIST:  Makefile
         path: /private/tmp/makefile_path_test/dir1/dir2/dir3
          cwd: /tmp/makefile_path_test/dir1/dir2/dir3

+ cd /tmp/makefile_path_test
+ make -f /tmp/makefile_path_test/dir1/dir2/dir3/Makefile
MAKEFILE_LIST:  /tmp/makefile_path_test/dir1/dir2/dir3/Makefile
         path: /tmp/makefile_path_test/dir1/dir2/dir3
          cwd: /tmp/makefile_path_test

+ rm -rf /tmp/makefile_path_test

NOTE: The function $(patsubst %/,%,[path/goes/here/]) is used to strip the trailing slash.

Biggest differences of Thrift vs Protocol Buffers?

They both offer many of the same features; however, there are some differences:

  • Thrift supports 'exceptions'
  • Protocol Buffers have much better documentation/examples
  • Thrift has a builtin Set type
  • Protocol Buffers allow "extensions" - you can extend an external proto to add extra fields, while still allowing external code to operate on the values. There is no way to do this in Thrift
  • I find Protocol Buffers much easier to read

Basically, they are fairly equivalent (with Protocol Buffers slightly more efficient from what I have read).

How can I switch themes in Visual Studio 2012

Slightly off topic, but for those of you that want to modify the built-in colors of the Dark/Light themes you can use this little tool I wrote for Visual Studio 2012.

More info here:

Modify Visual Studio 2012 Dark (and Light) Themes

Source Code

Capture iOS Simulator video for App Preview

The Apple's Simulator User Guide states in Taking a Screenshot or Recording a Video Using the Command Line paragraph:

You can take a screenshot or record a video of the simulator window using the xcrun command-line utility.


To record a video, use the recordVideo operation in your Terminal:

xcrun simctl io booted recordVideo <filename>.<extension>

Note that the file will be created in the current directory of your Terminal.


If you want to save the video file in your Desktop folder, use the following command:

xcrun simctl io booted recordVideo ~/Desktop/<filename>.<extension>

To stop recording, press Control-C in Terminal.

How to make borders collapse (on a div)?

Instead using border use box-shadow:

  box-shadow: 
    2px 0 0 0 #888, 
    0 2px 0 0 #888, 
    2px 2px 0 0 #888,   /* Just to fix the corner */
    2px 0 0 0 #888 inset, 
    0 2px 0 0 #888 inset;

Demo: http://codepen.io/Hawkun/pen/rsIEp

Command for restarting all running docker containers?

If you have docker-compose, all you need to do is:

docker-compose restart 

And you get nice print out of the container's name along with its status of the restart (done/error)

Here is the official guide for installing: https://docs.docker.com/compose/install/

What are -moz- and -webkit-?

These are the vendor-prefixed properties offered by the relevant rendering engines (-webkit for Chrome, Safari; -moz for Firefox, -o for Opera, -ms for Internet Explorer). Typically they're used to implement new, or proprietary CSS features, prior to final clarification/definition by the W3.

This allows properties to be set specific to each individual browser/rendering engine in order for inconsistencies between implementations to be safely accounted for. The prefixes will, over time, be removed (at least in theory) as the unprefixed, the final version, of the property is implemented in that browser.

To that end it's usually considered good practice to specify the vendor-prefixed version first and then the non-prefixed version, in order that the non-prefixed property will override the vendor-prefixed property-settings once it's implemented; for example:

.elementClass {
    -moz-border-radius: 2em;
    -ms-border-radius: 2em;
    -o-border-radius: 2em;
    -webkit-border-radius: 2em;
    border-radius: 2em;
}

Specifically, to address the CSS in your question, the lines you quote:

-webkit-column-count: 3;
-webkit-column-gap: 10px;
-webkit-column-fill: auto;
-moz-column-count: 3;
-moz-column-gap: 10px;
-moz-column-fill: auto;

Specify the column-count, column-gap and column-fill properties for Webkit browsers and Firefox.

References:

How to append to the end of an empty list?

You don't need the assignment operator. append returns None.

How to close off a Git Branch?

after complete the code first merge branch to master then delete that branch

git checkout master
git merge <branch-name>
git branch -d <branch-name>

What IDE to use for Python?

Results

Spreadsheet version

spreadsheet screenshot

Alternatively, in plain text: (also available as a a screenshot)

                         Bracket Matching -.  .- Line Numbering
                          Smart Indent -.  |  |  .- UML Editing / Viewing
         Source Control Integration -.  |  |  |  |  .- Code Folding
                    Error Markup -.  |  |  |  |  |  |  .- Code Templates
  Integrated Python Debugging -.  |  |  |  |  |  |  |  |  .- Unit Testing
    Multi-Language Support -.  |  |  |  |  |  |  |  |  |  |  .- GUI Designer (Qt, Eric, etc)
   Auto Code Completion -.  |  |  |  |  |  |  |  |  |  |  |  |  .- Integrated DB Support
     Commercial/Free -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  .- Refactoring
   Cross Platform -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom              |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |  |  |  |  |*many plugins
Editra            |Y |F |Y |Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |
Emacs             |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
Eric Ide          |Y |F |Y |  |Y |Y |  |Y |  |Y |  |Y |  |Y |  |  |  |
Geany             |Y |F |Y*|Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |*very limited
Gedit             |Y |F |Y¹|Y |  |  |  |Y |Y |Y |  |  |Y²|  |  |  |  |¹with plugin; ²sort of
Idle              |Y |F |Y |  |Y |  |  |Y |Y |  |  |  |  |  |  |  |  |
IntelliJ          |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit             |Y |F |  |Y |  |  |  |  |Y |Y |  |Y |  |  |  |  |  |
KDevelop          |Y |F |Y*|Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |*no type inference
Komodo            |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |Y |  |
NetBeans*         |Y |F |Y |Y |Y |  |Y |Y |Y |Y |Y |Y |Y |Y |  |  |Y |*pre-v7.0
Notepad++         |W |F |Y |Y |  |Y*|Y*|Y*|Y |Y |  |Y |Y*|  |  |  |  |*with plugin
Pfaide            |W |C |Y |Y |  |  |  |Y |Y |Y |  |Y |Y |  |  |  |  |
PIDA              |LW|F |Y |Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |VIM based
PTVS              |W |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |  |  |Y*|  |Y |*WPF bsed
PyCharm           |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse)   |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
PyScripter        |W |F |Y |  |Y |Y |  |Y |Y |Y |  |Y |Y |Y |  |  |  |
PythonWin         |W |F |Y |  |Y |  |  |Y |Y |  |  |Y |  |  |  |  |  |
SciTE             |Y |F¹|  |Y |  |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |¹Mac version is
ScriptDev         |W |C |Y |Y |Y |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |    commercial
Spyder            |Y |F |Y |  |Y |Y |  |Y |Y |Y |  |  |  |  |  |  |  |
Sublime Text      |Y |CF|Y |Y |  |Y |Y |Y |Y |Y |  |Y |Y |Y*|  |  |  |extensible w/Python,
TextMate          |M |F |  |Y |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |    *PythonTestRunner
UliPad            |Y |F |Y |Y |Y |  |  |Y |Y |  |  |  |Y |Y |  |  |  |
Vim               |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |
Visual Studio     |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde           |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |*support for C
Zeus              |W |C |  |  |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
   Cross Platform -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
     Commercial/Free -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  '- Refactoring
   Auto Code Completion -'  |  |  |  |  |  |  |  |  |  |  |  |  '- Integrated DB Support
    Multi-Language Support -'  |  |  |  |  |  |  |  |  |  |  '- GUI Designer (Qt, Eric, etc)
  Integrated Python Debugging -'  |  |  |  |  |  |  |  |  '- Unit Testing
                    Error Markup -'  |  |  |  |  |  |  '- Code Templates
         Source Control Integration -'  |  |  |  |  '- Code Folding
                          Smart Indent -'  |  |  '- UML Editing / Viewing
                         Bracket Matching -'  '- Line Numbering

Acronyms used:

 L  - Linux
 W  - Windows
 M  - Mac
 C  - Commercial
 F  - Free
 CF - Commercial with Free limited edition
 ?  - To be confirmed

I don't mention basics like syntax highlighting as I expect these by default.


This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.

PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?

We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments

Submit edits to the spreadsheet

Jupyter Notebook not saving: '_xsrf' argument missing from post

In My Case, I have a close tab of Home Page. After Re-opening the Jupyter.The Error was automatically gone and We can save the file.

Which comment style should I use in batch files?

This page tell that using "::" will be faster under certain constraints Just a thing to consider when choosing

How do I escape only single quotes?

After a long time fighting with this problem, I think I have found a better solution.

The combination of two functions makes it possible to escape a string to use as HTML.

One, to escape double quote if you use the string inside a JavaScript function call; and a second one to escape the single quote, avoiding those simple quotes that go around the argument.

Solution:

mysql_real_escape_string(htmlspecialchars($string))

Solve:

  • a PHP line created to call a JavaScript function like

echo 'onclick="javascript_function(\'' . mysql_real_escape_string(htmlspecialchars($string))"

How to clear jQuery validation error messages?

If you want to do it without using a separate variable then

$("#myForm").data('validator').resetForm();

Round double in two decimal places in C#?

you can try one from below.there are many way for this.

1. 
 value=Math.Round(123.4567, 2, MidpointRounding.AwayFromZero) //"123.46"
2.
 inputvalue=Math.Round(123.4567, 2)  //"123.46"
3. 
 String.Format("{0:0.00}", 123.4567);      // "123.46"
4. 
string.Format("{0:F2}", 123.456789);     //123.46
string.Format("{0:F3}", 123.456789);     //123.457
string.Format("{0:F4}", 123.456789);     //123.4568

JSON string to JS object

You can use this library from JSON.org to translate your string into a JSON object.

var var1_obj = JSON.parse(var1);

Or you can use the jquery-json library as well.

var var1_obj = $.toJSON(var1);

Android Webview - Webpage should fit the device screen

int PIC_WIDTH= webView.getRight()-webView.getLeft();

PHP: date function to get month of the current date

$unixtime = strtotime($test);
echo date('m', $unixtime); //month
echo date('d', $unixtime); 
echo date('y', $unixtime );

Generate a Hash from string in Javascript

I needed a similar function (but different) to generate a unique-ish ID based on the username and current time. So:

window.newId = ->
  # create a number based on the username
  unless window.userNumber?
    window.userNumber = 0
  for c,i in window.MyNamespace.userName
    char = window.MyNamespace.userName.charCodeAt(i)
    window.MyNamespace.userNumber+=char
  ((window.MyNamespace.userNumber + Math.floor(Math.random() * 1e15) + new Date().getMilliseconds()).toString(36)).toUpperCase()

Produces:

2DVFXJGEKL
6IZPAKFQFL
ORGOENVMG
... etc 

edit Jun 2015: For new code I use shortid: https://www.npmjs.com/package/shortid

How do I remove carriage returns with Ruby?

You can use this :

my_string.strip.gsub(/\s+/, ' ')

How do I launch a Git Bash window with particular working directory using a script?

I'm not familiar with Git Bash but assuming that it is a git shell (such as git-sh) residing in /path/to/my/gitshell and your favorite terminal program is called `myterm' you can script the following:

(cd dir1; myterm -e /path/to/my/gitshell) &
(cd dir2; myterm -e /path/to/my/gitshell) &
...

Note that the parameter -e for execution may be named differently with your favorite terminal program.

Could not load file or assembly '***.dll' or one of its dependencies

An easier way to determine what dependencies a native DLL has is to use Dependency Walker - http://www.dependencywalker.com/

I analysed the native DLL and discovered that it depended on MSVCR120.DLL and MSVCP120.DLL, both of which were not installed on my staging server in the System32 directory. I installed the C++ runtime on my staging server and the issue was resolved.

Change label text using JavaScript

Try this:

<label id="lbltipAddedComment"></label>
<script type="text/javascript"> 
      document.getElementById('<%= lbltipAddedComment.ClientID %>').innerHTML = 'your tip has been submitted!';
</script>

Posting a File and Associated Data to a RESTful WebService preferably as JSON

Here is my approach API (i use example) - as you can see, you I don't use any file_id (uploaded file identifier to the server) in API:

  1. Create photo object on server:

     POST: /projects/{project_id}/photos   
     body: { name: "some_schema.jpg", comment: "blah"}
     response: photo_id
    
  2. Upload file (note that file is in singular form because it is only one per photo):

     POST: /projects/{project_id}/photos/{photo_id}/file
     body: file to upload
     response: -
    

And then for instance:

  1. Read photos list

     GET: /projects/{project_id}/photos
     response: [ photo, photo, photo, ... ] (array of objects)
    
  2. Read some photo details

     GET: /projects/{project_id}/photos/{photo_id}
     response: { id: 666, name: 'some_schema.jpg', comment:'blah'} (photo object)
    
  3. Read photo file

     GET: /projects/{project_id}/photos/{photo_id}/file
     response: file content
    

So the conclusion is that, first you create an object (photo) by POST, and then you send second request with the file (again POST). To not have problems with CACHE in this approach we assume that we can only delete old photos and add new - no update binary photo files (because new binary file is in fact... NEW photo). However if you need to be able to update binary files and cache them, then in point 4 return also fileId and change 5 to GET: /projects/{project_id}/photos/{photo_id}/files/{fileId}.

Java read file and store text in an array

int count = -1;
String[] content = new String[200];
while(inFile1.hasNext()){

    content[++count] = inFile1.nextLine();
}

EDIT

Looks like you want to create a float array, for that create a float array

int count = -1;
Float[] content = new Float[200];
while(inFile1.hasNext()){

    content[++count] = Float.parseFloat(inFile1.nextLine());
}

then your float array would look like

content[0] = 70.3
content[1] = 70.8
content[2] = 73.8
content[3] = 77.0 and so on

How do I base64 encode (decode) in C?

Here's the one I'm using:

#include <stdint.h>
#include <stdlib.h>


static char encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
                                'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
                                'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
                                'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
                                'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
                                'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
                                'w', 'x', 'y', 'z', '0', '1', '2', '3',
                                '4', '5', '6', '7', '8', '9', '+', '/'};
static char *decoding_table = NULL;
static int mod_table[] = {0, 2, 1};


char *base64_encode(const unsigned char *data,
                    size_t input_length,
                    size_t *output_length) {

    *output_length = 4 * ((input_length + 2) / 3);

    char *encoded_data = malloc(*output_length);
    if (encoded_data == NULL) return NULL;

    for (int i = 0, j = 0; i < input_length;) {

        uint32_t octet_a = i < input_length ? (unsigned char)data[i++] : 0;
        uint32_t octet_b = i < input_length ? (unsigned char)data[i++] : 0;
        uint32_t octet_c = i < input_length ? (unsigned char)data[i++] : 0;

        uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;

        encoded_data[j++] = encoding_table[(triple >> 3 * 6) & 0x3F];
        encoded_data[j++] = encoding_table[(triple >> 2 * 6) & 0x3F];
        encoded_data[j++] = encoding_table[(triple >> 1 * 6) & 0x3F];
        encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F];
    }

    for (int i = 0; i < mod_table[input_length % 3]; i++)
        encoded_data[*output_length - 1 - i] = '=';

    return encoded_data;
}


unsigned char *base64_decode(const char *data,
                             size_t input_length,
                             size_t *output_length) {

    if (decoding_table == NULL) build_decoding_table();

    if (input_length % 4 != 0) return NULL;

    *output_length = input_length / 4 * 3;
    if (data[input_length - 1] == '=') (*output_length)--;
    if (data[input_length - 2] == '=') (*output_length)--;

    unsigned char *decoded_data = malloc(*output_length);
    if (decoded_data == NULL) return NULL;

    for (int i = 0, j = 0; i < input_length;) {

        uint32_t sextet_a = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
        uint32_t sextet_b = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
        uint32_t sextet_c = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
        uint32_t sextet_d = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];

        uint32_t triple = (sextet_a << 3 * 6)
        + (sextet_b << 2 * 6)
        + (sextet_c << 1 * 6)
        + (sextet_d << 0 * 6);

        if (j < *output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF;
        if (j < *output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF;
        if (j < *output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF;
    }

    return decoded_data;
}


void build_decoding_table() {

    decoding_table = malloc(256);

    for (int i = 0; i < 64; i++)
        decoding_table[(unsigned char) encoding_table[i]] = i;
}


void base64_cleanup() {
    free(decoding_table);
}

Keep in mind that this doesn't do any error-checking while decoding - non base 64 encoded data will get processed.

How to TryParse for Enum value?

Here is a custom implementation of EnumTryParse. Unlike other common implementations, it also supports enum marked with the Flags attribute.

    /// <summary>
    /// Converts the string representation of an enum to its Enum equivalent value. A return value indicates whether the operation succeeded.
    /// This method does not rely on Enum.Parse and therefore will never raise any first or second chance exception.
    /// </summary>
    /// <param name="type">The enum target type. May not be null.</param>
    /// <param name="input">The input text. May be null.</param>
    /// <param name="value">When this method returns, contains Enum equivalent value to the enum contained in input, if the conversion succeeded.</param>
    /// <returns>
    /// true if s was converted successfully; otherwise, false.
    /// </returns>
    public static bool EnumTryParse(Type type, string input, out object value)
    {
        if (type == null)
            throw new ArgumentNullException("type");

        if (!type.IsEnum)
            throw new ArgumentException(null, "type");

        if (input == null)
        {
            value = Activator.CreateInstance(type);
            return false;
        }

        input = input.Trim();
        if (input.Length == 0)
        {
            value = Activator.CreateInstance(type);
            return false;
        }

        string[] names = Enum.GetNames(type);
        if (names.Length == 0)
        {
            value = Activator.CreateInstance(type);
            return false;
        }

        Type underlyingType = Enum.GetUnderlyingType(type);
        Array values = Enum.GetValues(type);
        // some enums like System.CodeDom.MemberAttributes *are* flags but are not declared with Flags...
        if ((!type.IsDefined(typeof(FlagsAttribute), true)) && (input.IndexOfAny(_enumSeperators) < 0))
            return EnumToObject(type, underlyingType, names, values, input, out value);

        // multi value enum
        string[] tokens = input.Split(_enumSeperators, StringSplitOptions.RemoveEmptyEntries);
        if (tokens.Length == 0)
        {
            value = Activator.CreateInstance(type);
            return false;
        }

        ulong ul = 0;
        foreach (string tok in tokens)
        {
            string token = tok.Trim(); // NOTE: we don't consider empty tokens as errors
            if (token.Length == 0)
                continue;

            object tokenValue;
            if (!EnumToObject(type, underlyingType, names, values, token, out tokenValue))
            {
                value = Activator.CreateInstance(type);
                return false;
            }

            ulong tokenUl;
            switch (Convert.GetTypeCode(tokenValue))
            {
                case TypeCode.Int16:
                case TypeCode.Int32:
                case TypeCode.Int64:
                case TypeCode.SByte:
                    tokenUl = (ulong)Convert.ToInt64(tokenValue, CultureInfo.InvariantCulture);
                    break;

                //case TypeCode.Byte:
                //case TypeCode.UInt16:
                //case TypeCode.UInt32:
                //case TypeCode.UInt64:
                default:
                    tokenUl = Convert.ToUInt64(tokenValue, CultureInfo.InvariantCulture);
                    break;
            }

            ul |= tokenUl;
        }
        value = Enum.ToObject(type, ul);
        return true;
    }

    private static char[] _enumSeperators = new char[] { ',', ';', '+', '|', ' ' };

    private static object EnumToObject(Type underlyingType, string input)
    {
        if (underlyingType == typeof(int))
        {
            int s;
            if (int.TryParse(input, out s))
                return s;
        }

        if (underlyingType == typeof(uint))
        {
            uint s;
            if (uint.TryParse(input, out s))
                return s;
        }

        if (underlyingType == typeof(ulong))
        {
            ulong s;
            if (ulong.TryParse(input, out s))
                return s;
        }

        if (underlyingType == typeof(long))
        {
            long s;
            if (long.TryParse(input, out s))
                return s;
        }

        if (underlyingType == typeof(short))
        {
            short s;
            if (short.TryParse(input, out s))
                return s;
        }

        if (underlyingType == typeof(ushort))
        {
            ushort s;
            if (ushort.TryParse(input, out s))
                return s;
        }

        if (underlyingType == typeof(byte))
        {
            byte s;
            if (byte.TryParse(input, out s))
                return s;
        }

        if (underlyingType == typeof(sbyte))
        {
            sbyte s;
            if (sbyte.TryParse(input, out s))
                return s;
        }

        return null;
    }

    private static bool EnumToObject(Type type, Type underlyingType, string[] names, Array values, string input, out object value)
    {
        for (int i = 0; i < names.Length; i++)
        {
            if (string.Compare(names[i], input, StringComparison.OrdinalIgnoreCase) == 0)
            {
                value = values.GetValue(i);
                return true;
            }
        }

        if ((char.IsDigit(input[0]) || (input[0] == '-')) || (input[0] == '+'))
        {
            object obj = EnumToObject(underlyingType, input);
            if (obj == null)
            {
                value = Activator.CreateInstance(type);
                return false;
            }
            value = obj;
            return true;
        }

        value = Activator.CreateInstance(type);
        return false;
    }

What to do on TransactionTooLargeException

sometime Activity include some Fragment when Activityneed to totally recreate Fragments content, if the sportFragmentManager.fragments without clear history fragments

    val fragments = sportFragmentManager.fragments
    val transaction = sportFragmentManager.beginTransaction()
    for (frag in fragments){
        transaction.remove(frag)
    }
    transaction.commitAllowingStateLoss()

serveral times recreate Fragments the Activity will happen (debug use tooLargeTool)

 W/ActivityStopInfo: Bundle stats:
 W/ActivityStopInfo:   android:viewHierarchyState [size=2304]
 W/ActivityStopInfo:     android:views [size=2256]
 W/ActivityStopInfo:   android:support:fragments [size=519072]
 W/ActivityStopInfo: PersistableBundle stats:
 W/ActivityStopInfo:   [null]

Get value of multiselect box using jQuery or pure JS

I think the answer may be easier to understand like this:

_x000D_
_x000D_
$('#empid').on('change',function() {_x000D_
  alert($(this).val());_x000D_
  console.log($(this).val());_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>_x000D_
<select id="empid" name="empname" multiple="multiple">_x000D_
  <option value="0">Potato</option>_x000D_
  <option value="1">Carrot</option>_x000D_
  <option value="2">Apple</option>_x000D_
  <option value="3">Raisins</option>_x000D_
  <option value="4">Peanut</option>_x000D_
</select>_x000D_
<br />_x000D_
Hold CTRL / CMD for selecting multiple fields
_x000D_
_x000D_
_x000D_

If you select "Carrot" and "Raisins" in the list, the output will be "1,3".

Differences between CHMOD 755 vs 750 permissions set

0755 = User:rwx Group:r-x World:r-x

0750 = User:rwx Group:r-x World:--- (i.e. World: no access)

r = read
w = write
x = execute (traverse for directories)

CFLAGS vs CPPFLAGS

To add to those who have mentioned the implicit rules, it's best to see what make has defined implicitly and for your env using:

make -p

For instance:

%.o: %.c
    $(COMPILE.c) $(OUTPUT_OPTION) $<

which expands

COMPILE.c = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c

This will also print # environment data. Here, you will find GCC's include path among other useful info.

C_INCLUDE_PATH=/usr/include

In make, when it comes to search, the paths are many, the light is one... or something to that effect.

  1. C_INCLUDE_PATH is system-wide, set it in your shell's *.rc.
  2. $(CPPFLAGS) is for the preprocessor include path.
  3. If you need to add a general search path for make, use:
VPATH = my_dir_to_search

... or even more specific

vpath %.c src
vpath %.h include

make uses VPATH as a general search path so use cautiously. If a file exists in more than one location listed in VPATH, make will take the first occurrence in the list.

CSS3 Transition - Fade out effect

This is the working code for your question.
Enjoy Coding....

<html>
   <head>

      <style>

         .animated {
            background-color: green;
            background-position: left top;
            padding-top:95px;
            margin-bottom:60px;
            -webkit-animation-duration: 10s;animation-duration: 10s;
            -webkit-animation-fill-mode: both;animation-fill-mode: both;
         }

         @-webkit-keyframes fadeOut {
            0% {opacity: 1;}
            100% {opacity: 0;}
         }

         @keyframes fadeOut {
            0% {opacity: 1;}
            100% {opacity: 0;}
         }

         .fadeOut {
            -webkit-animation-name: fadeOut;
            animation-name: fadeOut;
         }
      </style>

   </head>
   <body>

      <div id="animated-example" class="animated fadeOut"></div>

   </body>
</html>

HTTP Error 500.22 - Internal Server Error (An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.)

Set Application pool to classic .NET appool and make sure that Classic .Net apppool working on Classic managed piple line .

python: order a list of numbers without built-in sort, min, max function

def bubble_sort(seq):
    """Inefficiently sort the mutable sequence (list) in place.
       seq MUST BE A MUTABLE SEQUENCE.

       As with list.sort() and random.shuffle this does NOT return 
    """
    changed = True
    while changed:
        changed = False
        for i in xrange(len(seq) - 1):
            if seq[i] > seq[i+1]:
                seq[i], seq[i+1] = seq[i+1], seq[i]
                changed = True
    return None

if __name__ == "__main__":
   """Sample usage and simple test suite"""

   from random import shuffle

   testset = range(100)
   testcase = testset[:] # make a copy
   shuffle(testcase)
   assert testcase != testset  # we've shuffled it
   bubble_sort(testcase)
   assert testcase == testset  # we've unshuffled it back into a copy

From : http://rosettacode.org/wiki/Bubble_Sort#Python

Postgres: check if array field contains value?

This worked for me

let exampleArray = [1, 2, 3, 4, 5];
let exampleToString = exampleArray.toString(); //convert to toString
let query = `Select * from table_name where column_name in (${exampleToString})`; //Execute the query to get response

I have got the same problem, then after an hour of effort I got to know that the array should not be directly accessed in the query. So I then found that the data should be sent in the paranthesis it self, then again I have converted that array to string using toString method in js. So I have worked by executing the above query and got my expected result

How do I convert from int to String?

It depends on how you want to use your String. This can help:

String total =  Integer.toString(123) + Double.toString(456.789);

how to set font size based on container size?

I had a similar issue but I had to consider other issues that @apaul34208 example did not tackle. In my case;

  • I have a container that changed size depending on the viewport using media queries
  • Text inside is dynamically generated
  • I want to scale up as well as down

Not the most elegant of examples but it does the trick for me. Consider using throttling the window resize (https://lodash.com/)

_x000D_
_x000D_
var TextFit = function(){_x000D_
 var container = $('.container');_x000D_
  container.each(function(){_x000D_
    var container_width = $(this).width(),_x000D_
      width_offset = parseInt($(this).data('width-offset')),_x000D_
        font_container = $(this).find('.font-container');_x000D_
 _x000D_
     if ( width_offset > 0 ) {_x000D_
         container_width -= width_offset;_x000D_
     }_x000D_
                _x000D_
    font_container.each(function(){_x000D_
      var font_container_width = $(this).width(),_x000D_
          font_size = parseFloat( $(this).css('font-size') );_x000D_
_x000D_
      var diff = Math.max(container_width, font_container_width) - Math.min(container_width, font_container_width);_x000D_
 _x000D_
      var diff_percentage = Math.round( ( diff / Math.max(container_width, font_container_width) ) * 100 );_x000D_
      _x000D_
      if (diff_percentage !== 0){_x000D_
          if ( container_width > font_container_width ) {_x000D_
            new_font_size = font_size + Math.round( ( font_size / 100 ) * diff_percentage );_x000D_
          } else if ( container_width < font_container_width ) {_x000D_
            new_font_size = font_size - Math.round( ( font_size / 100 ) * diff_percentage );_x000D_
          }_x000D_
      }_x000D_
      $(this).css('font-size', new_font_size + 'px');_x000D_
    });_x000D_
  });_x000D_
}_x000D_
_x000D_
$(function(){_x000D_
  TextFit();_x000D_
  $(window).resize(function(){_x000D_
   TextFit();_x000D_
  });_x000D_
});
_x000D_
.container {_x000D_
  width:341px;_x000D_
  height:341px;_x000D_
  background-color:#000;_x000D_
  padding:20px;_x000D_
 }_x000D_
 .font-container {_x000D_
  font-size:131px;_x000D_
  text-align:center;_x000D_
  color:#fff;_x000D_
 }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="container" data-width-offset="10">_x000D_
 <span class="font-container">£5000</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

https://jsfiddle.net/Merch80/b8hoctfb/7/

phpMyAdmin access denied for user 'root'@'localhost' (using password: NO)

@guzuer

Change the value of

$cfg['Servers'][$i]['user'] = 'groot';
$cfg['Servers'][$i]['password']='groot';

in your ~/xampp/phpMyAdmin/config.inc.php

Here my username is groot and password is groot.

At the time of writing this answer, I had this issue and i fixed it by looking up your question.

Credit card expiration dates - Inclusive or exclusive?

How do time zones factor in this analysis. Does a card expire in New York before California? Does it depend on the billing or shipping addresses?

Highlight label if checkbox is checked

You can't do this with CSS alone. Using jQuery you can do

HTML

<label id="lab">Checkbox</label>
<input id="check" type="checkbox" />

CSS

.highlight{
    background:yellow;
}

jQuery

$('#check').click(function(){
    $('#lab').toggleClass('highlight')
})

This will work in all browsers

Check working example at http://jsfiddle.net/LgADZ/

Mailx send html message

I had successfully used the following on Arch Linux (where the -a flag is used for attachments) for several years:

mailx -s "The Subject $( echo -e "\nContent-Type: text/html" [email protected] < email.html

This appended the Content-Type header to the subject header, which worked great until a recent update. Now the new line is filtered out of the -s subject. Presumably, this was done to improve security.

Instead of relying on hacking the subject line, I now use a bash subshell:

(
    echo -e "Content-Type: text/html\n"
    cat mail.html
 ) | mail -s "The Subject" -t [email protected]

And since we are really only using mailx's subject flag, it seems there is no reason not to switch to sendmail as suggested by @dogbane:

(
    echo "To: [email protected]"
    echo "Subject: The Subject"
    echo "Content-Type: text/html"
    echo
    cat mail.html
) | sendmail -t

The use of bash subshells avoids having to create a temporary file.

How can I decrypt MySQL passwords

How can I decrypt MySQL passwords

You can't really because they are hashed and not encrypted.

Here's the essence of the PASSWORD function that current MySQL uses. You can execute it from the sql terminal:

mysql> SELECT SHA1(UNHEX(SHA1("password")));

+------------------------------------------+
| SHA1(UNHEX(SHA1("password")))            |
+------------------------------------------+
| 2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
+------------------------------------------+
1 row in set (0.00 sec)

How can I change or retrieve these?

If you are having trouble logging in on a debian or ubuntu system, first try this (thanks to tohuwawohu at https://askubuntu.com/questions/120718/cant-log-to-mysql):

$ sudo cat /etc/mysql/debian.conf | grep -i password
...
password: QWERTY12345...

Then, log in with the debian maintenance user:

$ mysql -u debian-sys-maint -p
password:

Finally, change the user's password:

mysql> UPDATE mysql.user SET Password=PASSWORD('new password') WHERE User='root';
mysql> FLUSH PRIVILEGES;
mysql> quit;

When I look in the PHPmyAdmin the passwords are encrypted

Related, if you need to dump the user database for the relevant information, try:

mysql> SELECT User,Host,Password FROM mysql.user;
+------------------+-----------+----------------------+
| User             | Host      | Password             |
+------------------+-----------+----------------------+
| root             | localhost | *0123456789ABCDEF... |
| root             | 127.0.0.1 | *0123456789ABCDEF... |
| root             | ::1       | *0123456789ABCDEF... |
| debian-sys-maint | localhost | *ABCDEF0123456789... |
+------------------+-----------+----------------------+

And yes, those passwords are NOT salted. So an attacker can prebuild the tables and apply them to all MySQL installations. In addition, the adversary can learn which users have the same passwords.

Needles to say, the folks at mySQL are not following best practices. John Steven did an excellent paper on Password Storage Best Practice at OWASP's Password Storage Cheat Sheet. In fairness to the MySQL folks, they may be doing it because of pain points in the architecture, design or implementation (I simply don't know).


If you use the PASSWORD and UPDATE commands and the change does not work, then see http://dev.mysql.com/doc/refman/5.0/en/resetting-permissions.html. Even though the page is named "resetting permissions", its really about how to change a password. (Its befuddling the MySQL password change procedure is so broken that you have to jump through the hoops, but it is what it is).

How to find elements with 'value=x'?

$('#attached_docs [value="123"]').find ... .remove();

it should do your need however, you cannot duplicate id! remember it

ToList()-- does it create a new list?

ToList will create a brand new list.

If the items in the list are value types, they will be directly updated, if they are reference types, any changes will be reflected back in the referenced objects.

How to get current language code with Swift?

Swift 5.3:

let languagePrefix = Locale.preferredLanguages[0]
print(languagePrefix)

Remove Trailing Spaces and Update in Columns in SQL Server

If we also want to handle white spaces and unwanted tabs-

Check and Try the below script (Unit Tested)-

--Declaring
DECLARE @Tbl TABLE(col_1 VARCHAR(100));

--Test Samples
INSERT INTO @Tbl (col_1)
VALUES
('  EY     y            
Salem')
, ('  EY     P    ort       Chennai   ')
, ('  EY     Old           Park   ')
, ('  EY   ')
, ('  EY   ')
,(''),(null),('d                           
    f');

SELECT col_1 AS INPUT,
    LTRIM(RTRIM(
    REPLACE(
    REPLACE(
    REPLACE(
    REPLACE(
    REPLACE(
        REPLACE(
        REPLACE(
        REPLACE(
        REPLACE(
        REPLACE(
        REPLACE(col_1,CHAR(10),' ')
        ,CHAR(11),' ')
        ,CHAR(12),' ')
        ,CHAR(13),' ')
        ,CHAR(14),' ')
        ,CHAR(160),' ')
        ,CHAR(13)+CHAR(10),' ')
    ,CHAR(9),' ')
    ,' ',CHAR(17)+CHAR(18))
    ,CHAR(18)+CHAR(17),'')
    ,CHAR(17)+CHAR(18),' ')
    )) AS [OUTPUT]
FROM @Tbl;

How to maximize a plt.show() window using Python

I found this for full screen mode on Ubuntu

#Show full screen
mng = plt.get_current_fig_manager()
mng.full_screen_toggle()

PostgreSQL database default location on Linux

/var/lib/postgresql/[version]/data/

At least in Gentoo Linux and Ubuntu 14.04 by default.

You can find postgresql.conf and look at param data_directory. If it is commented then database directory is the same as this config file directory.

C - reading command line parameters

When you write your main function, you typically see one of two definitions:

  • int main(void)
  • int main(int argc, char **argv)

The second form will allow you to access the command line arguments passed to the program, and the number of arguments specified (arguments are separated by spaces).

The arguments to main are:

  • int argc - the number of arguments passed into your program when it was run. It is at least 1.
  • char **argv - this is a pointer-to-char *. It can alternatively be this: char *argv[], which means 'array of char *'. This is an array of C-style-string pointers.

Basic Example

For example, you could do this to print out the arguments passed to your C program:

#include <stdio.h>

int main(int argc, char **argv)
{
    for (int i = 0; i < argc; ++i)
    {
        printf("argv[%d]: %s\n", i, argv[i]);
    }
}

I'm using GCC 4.5 to compile a file I called args.c. It'll compile and build a default a.out executable.

[birryree@lilun c_code]$ gcc -std=c99 args.c

Now run it...

[birryree@lilun c_code]$ ./a.out hello there
argv[0]: ./a.out
argv[1]: hello
argv[2]: there

So you can see that in argv, argv[0] is the name of the program you ran (this is not standards-defined behavior, but is common. Your arguments start at argv[1] and beyond.

So basically, if you wanted a single parameter, you could say...

./myprogram integral


A Simple Case for You

And you could check if argv[1] was integral, maybe like strcmp("integral", argv[1]) == 0.

So in your code...

#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
    if (argc < 2) // no arguments were passed
    {
        // do something
    }

    if (strcmp("integral", argv[1]) == 0)
    {
        runIntegral(...); //or something
    }
    else
    {
        // do something else.
    }
}

Better command line parsing

Of course, this was all very rudimentary, and as your program gets more complex, you'll likely want more advanced command line handling. For that, you could use a library like GNU getopt.

Java: Reading integers from a file into an array

It looks like Java is trying to convert an empty string into a number. Do you have an empty line at the end of the series of numbers?

You could probably fix the code like this

String s = in.readLine();
int i = 0;

while (s != null) {
    // Skip empty lines.
    s = s.trim();
    if (s.length() == 0) {
        continue;
    }

    tall[i] = Integer.parseInt(s); // This is line 19.
    System.out.println(tall[i]);
    s = in.readLine();
    i++;
}

in.close();

HTML embedded PDF iframe

Try this out.

_x000D_
_x000D_
<iframe src="https://docs.google.com/viewerng/viewer?url=http://infolab.stanford.edu/pub/papers/google.pdf&embedded=true" frameborder="0" height="100%" width="100%">_x000D_
</iframe>
_x000D_
_x000D_
_x000D_

In Perl, how can I read an entire file into a string?

Use

 $/ = undef;

before $document = <FILE>;. $/ is the input record separator, which is a newline by default. By redefining it to undef, you are saying there is no field separator. This is called "slurp" mode.

Other solutions like undef $/ and local $/ (but not my $/) redeclare $/ and thus produce the same effect.

How to change href of <a> tag on button click through javascript

remove href attribute:

<a id="" onclick="f1()">jhhghj</a>

if link styles are important then:

<a href="javascript:void(f1())">jhhghj</a>

dropzone.js - how to do something after ALL files are uploaded

this.on("totaluploadprogress", function(totalBytes, totalBytesSent){


                    if(totalBytes == 100) {

                        //all done! call func here
                    }
                });

rmagick gem install "Can't find Magick-config"

Ubuntu 15.10

Note that if you try to install this gem in ubuntu 15.10, then error can happened:

Can't install RMagick 2.13.1. Can't find Magick-config in ...

All you need is preload PATH variable with additional path to ImageMagick lib.

PATH="/usr/lib/x86_64-linux-gnu/ImageMagick-6.8.9/bin-Q16:$PATH"

then run gem install rmagick

source of solution

Spring Boot default H2 jdbc connection (and H2 console)

I had only below properties in /resources/application.properties. After running spring boot, using this URL(http://localhost:8080/h2-console/), the table in H2 console was visible and read to view the table data, also you can run simple SQL commands. One thing, in your java code, while fetching data, the column names are upper-case, even though schema.sql is using lower-case names :)

spring.datasource.initialize=true
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=- 1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true

More Pythonic Way to Run a Process X Times

How about?

while BoolIter(N, default=True, falseIndex=N-1):
    print 'some thing'

or in a more ugly way:

for _ in BoolIter(N):
    print 'doing somthing'

or if you want to catch the last time through:

for lastIteration in BoolIter(N, default=False, trueIndex=N-1):
    if not lastIteration:
        print 'still going'
    else:
        print 'last time'

where:

class BoolIter(object):

    def __init__(self, n, default=False, falseIndex=None, trueIndex=None, falseIndexes=[], trueIndexes=[], emitObject=False):
        self.n = n
        self.i = None
        self._default = default
        self._falseIndexes=set(falseIndexes)
        self._trueIndexes=set(trueIndexes)
        if falseIndex is not None:
            self._falseIndexes.add(falseIndex)
        if trueIndex is not None:
            self._trueIndexes.add(trueIndex)
        self._emitObject = emitObject


    def __iter__(self):
        return self

    def next(self):
        if self.i is None:
            self.i = 0
        else:
            self.i += 1
        if self.i == self.n:
            raise StopIteration
        if self._emitObject:
            return self
        else:
            return self.__nonzero__()

    def __nonzero__(self):
        i = self.i
        if i in self._trueIndexes:
            return True
        if i in self._falseIndexes:
            return False
        return self._default

    def __bool__(self):
        return self.__nonzero__()

horizontal line and right way to code it in html, css

In HTML5, the <hr> tag defines a thematic break. In HTML 4.01, the <hr> tag represents a horizontal rule.

http://www.w3schools.com/tags/tag_hr.asp

So after definition, I would prefer <hr>

Angular.js ng-repeat filter by property having one of multiple values (OR of values)

Here is a way to do it while passing in an extra argument:

https://stackoverflow.com/a/17813797/4533488 (thanks to Denis Pshenov)

<div ng-repeat="group in groups">
    <li ng-repeat="friend in friends | filter:weDontLike(group.enemy.name)">
        <span>{{friend.name}}</span>
    <li>
</div>

With the backend:

$scope.weDontLike = function(name) {
    return function(friend) {
        return friend.name != name;
    }
}

.


And yet another way with an in-template filter only:

https://stackoverflow.com/a/12528093/4533488 (thanks to mikel)

<div ng:app>
  <div ng-controller="HelloCntl">
    <ul>
       <li ng-repeat="friend in friends | filter:{name:'!Adam'}">
            <span>{{friend.name}}</span>
            <span>{{friend.phone}}</span>
        </li>
    </ul>
</div>

What does `unsigned` in MySQL mean and when to use it?

MySQL says:

All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.

When do I use it ?

Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED data type.

A common mistake is to use a primary key that is an auto-increment INT starting at zero, yet the type is SIGNED, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.

How to get numbers after decimal point?

Float numbers are not stored in decimal (base10) format. Have a read through the python documentation on this to satisfy yourself why. Therefore, to get a base10 representation from a float is not advisable.

Now there are tools which allow storage of numeric data in decimal format. Below is an example using the Decimal library.

from decimal import *

x = Decimal('0.341343214124443151466')
str(x)[-2:] == '66'  # True

y = 0.341343214124443151466
str(y)[-2:] == '66'  # False

How to search JSON data in MySQL?

for MySQL all (and 5.7)

SELECT LOWER(TRIM(BOTH 0x22 FROM TRIM(BOTH 0x20 FROM SUBSTRING(SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"'),LOCATE(0x2C,SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"')+1,LENGTH(json_filed)))),LOCATE(0x22,SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"'),LOCATE(0x2C,SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"')+1,LENGTH(json_filed))))),LENGTH(json_filed))))) AS result FROM `table`;

Remove char at specific index - python

Try this code:

s = input() 
a = int(input()) 
b = s.replace(s[a],'')
print(b)

ARG or ENV, which one to use in this case?

From Dockerfile reference:

  • The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag.

  • The ENV instruction sets the environment variable <key> to the value <value>.
    The environment variables set using ENV will persist when a container is run from the resulting image.

So if you need build-time customization, ARG is your best choice.
If you need run-time customization (to run the same image with different settings), ENV is well-suited.

If I want to add let's say 20 (a random number) of extensions or any other feature that can be enable|disable

Given the number of combinations involved, using ENV to set those features at runtime is best here.

But you can combine both by:

  • building an image with a specific ARG
  • using that ARG as an ENV

That is, with a Dockerfile including:

ARG var
ENV var=${var}

You can then either build an image with a specific var value at build-time (docker build --build-arg var=xxx), or run a container with a specific runtime value (docker run -e var=yyy)

How do I disable text selection with CSS or JavaScript?

UPDATE January, 2017:

According to Can I use, the user-select is currently supported in all browsers except Internet Explorer 9 and earlier versions (but sadly still needs a vendor prefix).


All of the correct CSS variations are:

_x000D_
_x000D_
.noselect {_x000D_
  -webkit-touch-callout: none; /* iOS Safari */_x000D_
    -webkit-user-select: none; /* Safari */_x000D_
     -khtml-user-select: none; /* Konqueror HTML */_x000D_
       -moz-user-select: none; /* Firefox */_x000D_
        -ms-user-select: none; /* Internet Explorer/Edge */_x000D_
            user-select: none; /* Non-prefixed version, currently_x000D_
                                  supported by Chrome and Opera */_x000D_
}
_x000D_
<p>_x000D_
  Selectable text._x000D_
</p>_x000D_
<p class="noselect">_x000D_
  Unselectable text._x000D_
</p>
_x000D_
_x000D_
_x000D_


Note that it's a non-standard feature (i.e. not a part of any specification). It is not guaranteed to work everywhere, and there might be differences in implementation among browsers and in the future browsers can drop support for it.


More information can be found in Mozilla Developer Network documentation.

C fopen vs open

First, there is no particularly good reason to use fdopen if fopen is an option and open is the other possible choice. You shouldn't have used open to open the file in the first place if you want a FILE *. So including fdopen in that list is incorrect and confusing because it isn't very much like the others. I will now proceed to ignore it because the important distinction here is between a C standard FILE * and an OS-specific file descriptor.

There are four main reasons to use fopen instead of open.

  1. fopen provides you with buffering IO that may turn out to be a lot faster than what you're doing with open.
  2. fopen does line ending translation if the file is not opened in binary mode, which can be very helpful if your program is ever ported to a non-Unix environment (though the world appears to be converging on LF-only (except IETF text-based networking protocols like SMTP and HTTP and such)).
  3. A FILE * gives you the ability to use fscanf and other stdio functions.
  4. Your code may someday need to be ported to some other platform that only supports ANSI C and does not support the open function.

In my opinion the line ending translation more often gets in your way than helps you, and the parsing of fscanf is so weak that you inevitably end up tossing it out in favor of something more useful.

And most platforms that support C have an open function.

That leaves the buffering question. In places where you are mainly reading or writing a file sequentially, the buffering support is really helpful and a big speed improvement. But it can lead to some interesting problems in which data does not end up in the file when you expect it to be there. You have to remember to fclose or fflush at the appropriate times.

If you're doing seeks (aka fsetpos or fseek the second of which is slightly trickier to use in a standards compliant way), the usefulness of buffering quickly goes down.

Of course, my bias is that I tend to work with sockets a whole lot, and there the fact that you really want to be doing non-blocking IO (which FILE * totally fails to support in any reasonable way) with no buffering at all and often have complex parsing requirements really color my perceptions.

How can I pass an argument to a PowerShell script?

Create a PowerShell script with the following code in the file.

param([string]$path)
Get-ChildItem $path | Where-Object {$_.LinkType -eq 'SymbolicLink'} | select name, target

This creates a script with a path parameter. It will list all symbolic links within the path provided as well as the specified target of the symbolic link.

How to select first parent DIV using jQuery?

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

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

EDIT:

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

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

Laravel view not found exception

In my case I was calling View::make('User/index'), where in fact my view was in user directory and it was called index.blade.php. Ergo after I changed it to View@make('user.index') all started working.

SyntaxError: Use of const in strict mode?

n stable wouldn't do the trick for me. On the other hand,

nvm install stable

That actually got me to last nodejs version. Apparently n stable won't get pass v0.12.14 for me. I really don't know why.

Note: nvm is Node Version Manager, you can install it from its github page. Thanks @isaiah for noting that nvm is not a known command.

How to Get the HTTP Post data in C#?

You are missing a step. You need to log / store the values on your server (mailgun is a client). Then you need to retrieve those values on your server (your pc with your web browser will be a client). These will be two totally different aspx files (or the same one with different parameters).

aspx page 1 (the one that mailgun has):

var val = Request.Form["recipient"];
var file = new File(filename);
file.write(val);
close(file);

aspx page 2:

var contents = "";
if (File.exists(filename))
  var file = File.open(filename);
  contents = file.readtoend();
  file.close()

Request.write(contents);

passing several arguments to FUN of lapply (and others *apply)

As suggested by Alan, function 'mapply' applies a function to multiple Multiple Lists or Vector Arguments:

mapply(myfun, arg1, arg2)

See man page: https://stat.ethz.ch/R-manual/R-devel/library/base/html/mapply.html

Push eclipse project to GitHub with EGit

Simple Steps:

-Open Eclipse.

  • Select Project which you want to push on github->rightclick.
  • select Team->share Project->Git->Create repository->finish.(it will ask to login in Git account(popup).
  • Right click again to Project->Team->commit. you are done

Using Java with Nvidia GPUs (CUDA)

First of all, you should be aware of the fact that CUDA will not automagically make computations faster. On the one hand, because GPU programming is an art, and it can be very, very challenging to get it right. On the other hand, because GPUs are well-suited only for certain kinds of computations.

This may sound confusing, because you can basically compute anything on the GPU. The key point is, of course, whether you will achieve a good speedup or not. The most important classification here is whether a problem is task parallel or data parallel. The first one refers, roughly speaking, to problems where several threads are working on their own tasks, more or less independently. The second one refers to problems where many threads are all doing the same - but on different parts of the data.

The latter is the kind of problem that GPUs are good at: They have many cores, and all the cores do the same, but operate on different parts of the input data.

You mentioned that you have "simple math but with huge amount of data". Although this may sound like a perfectly data-parallel problem and thus like it was well-suited for a GPU, there is another aspect to consider: GPUs are ridiculously fast in terms of theoretical computational power (FLOPS, Floating Point Operations Per Second). But they are often throttled down by the memory bandwidth.

This leads to another classification of problems. Namely whether problems are memory bound or compute bound.

The first one refers to problems where the number of instructions that are done for each data element is low. For example, consider a parallel vector addition: You'll have to read two data elements, then perform a single addition, and then write the sum into the result vector. You will not see a speedup when doing this on the GPU, because the single addition does not compensate for the efforts of reading/writing the memory.

The second term, "compute bound", refers to problems where the number of instructions is high compared to the number of memory reads/writes. For example, consider a matrix multiplication: The number of instructions will be O(n^3) when n is the size of the matrix. In this case, one can expect that the GPU will outperform a CPU at a certain matrix size. Another example could be when many complex trigonometric computations (sine/cosine etc) are performed on "few" data elements.

As a rule of thumb: You can assume that reading/writing one data element from the "main" GPU memory has a latency of about 500 instructions....

Therefore, another key point for the performance of GPUs is data locality: If you have to read or write data (and in most cases, you will have to ;-)), then you should make sure that the data is kept as close as possible to the GPU cores. GPUs thus have certain memory areas (referred to as "local memory" or "shared memory") that usually is only a few KB in size, but particularly efficient for data that is about to be involved in a computation.

So to emphasize this again: GPU programming is an art, that is only remotely related to parallel programming on the CPU. Things like Threads in Java, with all the concurrency infrastructure like ThreadPoolExecutors, ForkJoinPools etc. might give the impression that you just have to split your work somehow and distribute it among several processors. On the GPU, you may encounter challenges on a much lower level: Occupancy, register pressure, shared memory pressure, memory coalescing ... just to name a few.

However, when you have a data-parallel, compute-bound problem to solve, the GPU is the way to go.


A general remark: Your specifically asked for CUDA. But I'd strongly recommend you to also have a look at OpenCL. It has several advantages. First of all, it's an vendor-independent, open industry standard, and there are implementations of OpenCL by AMD, Apple, Intel and NVIDIA. Additionally, there is a much broader support for OpenCL in the Java world. The only case where I'd rather settle for CUDA is when you want to use the CUDA runtime libraries, like CUFFT for FFT or CUBLAS for BLAS (Matrix/Vector operations). Although there are approaches for providing similar libraries for OpenCL, they can not directly be used from Java side, unless you create your own JNI bindings for these libraries.


You might also find it interesting to hear that in October 2012, the OpenJDK HotSpot group started the project "Sumatra": http://openjdk.java.net/projects/sumatra/ . The goal of this project is to provide GPU support directly in the JVM, with support from the JIT. The current status and first results can be seen in their mailing list at http://mail.openjdk.java.net/mailman/listinfo/sumatra-dev


However, a while ago, I collected some resources related to "Java on the GPU" in general. I'll summarize these again here, in no particular order.

(Disclaimer: I'm the author of http://jcuda.org/ and http://jocl.org/ )

(Byte)code translation and OpenCL code generation:

https://github.com/aparapi/aparapi : An open-source library that is created and actively maintained by AMD. In a special "Kernel" class, one can override a specific method which should be executed in parallel. The byte code of this method is loaded at runtime using an own bytecode reader. The code is translated into OpenCL code, which is then compiled using the OpenCL compiler. The result can then be executed on the OpenCL device, which may be a GPU or a CPU. If the compilation into OpenCL is not possible (or no OpenCL is available), the code will still be executed in parallel, using a Thread Pool.

https://github.com/pcpratts/rootbeer1 : An open-source library for converting parts of Java into CUDA programs. It offers dedicated interfaces that may be implemented to indicate that a certain class should be executed on the GPU. In contrast to Aparapi, it tries to automatically serialize the "relevant" data (that is, the complete relevant part of the object graph!) into a representation that is suitable for the GPU.

https://code.google.com/archive/p/java-gpu/ : A library for translating annotated Java code (with some limitations) into CUDA code, which is then compiled into a library that executes the code on the GPU. The Library was developed in the context of a PhD thesis, which contains profound background information about the translation process.

https://github.com/ochafik/ScalaCL : Scala bindings for OpenCL. Allows special Scala collections to be processed in parallel with OpenCL. The functions that are called on the elements of the collections can be usual Scala functions (with some limitations) which are then translated into OpenCL kernels.

Language extensions

http://www.ateji.com/px/index.html : A language extension for Java that allows parallel constructs (e.g. parallel for loops, OpenMP style) which are then executed on the GPU with OpenCL. Unfortunately, this very promising project is no longer maintained.

http://www.habanero.rice.edu/Publications.html (JCUDA) : A library that can translate special Java Code (called JCUDA code) into Java- and CUDA-C code, which can then be compiled and executed on the GPU. However, the library does not seem to be publicly available.

https://www2.informatik.uni-erlangen.de/EN/research/JavaOpenMP/index.html : Java language extension for for OpenMP constructs, with a CUDA backend

Java OpenCL/CUDA binding libraries

https://github.com/ochafik/JavaCL : Java bindings for OpenCL: An object-oriented OpenCL library, based on auto-generated low-level bindings

http://jogamp.org/jocl/www/ : Java bindings for OpenCL: An object-oriented OpenCL library, based on auto-generated low-level bindings

http://www.lwjgl.org/ : Java bindings for OpenCL: Auto-generated low-level bindings and object-oriented convenience classes

http://jocl.org/ : Java bindings for OpenCL: Low-level bindings that are a 1:1 mapping of the original OpenCL API

http://jcuda.org/ : Java bindings for CUDA: Low-level bindings that are a 1:1 mapping of the original CUDA API

Miscellaneous

http://sourceforge.net/projects/jopencl/ : Java bindings for OpenCL. Seem to be no longer maintained since 2010

http://www.hoopoe-cloud.com/ : Java bindings for CUDA. Seem to be no longer maintained


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

According to the C99 spec,

  • NULL expands to a null pointer constant, which is not required to be, but typically is of type void *
  • '\0' is a character constant; character constants are of type int, so it's equivalen to plain 0
  • "\0" is a null-terminated string literal and equivalent to the compound literal (char [2]){ 0, 0 }

NULL, '\0' and 0 are all null pointer constants, so they'll all yield null pointers on conversion, whereas "\0" yields a non-null char * (which should be treated as const as modification is undefined); as this pointer may be different for each occurence of the literal, it can't be used as sentinel value.

Although you may use any integer constant expression of value 0 as a null pointer constant (eg '\0' or sizeof foo - sizeof foo + (int)0.0), you should use NULL to make your intentions clear.

The view or its master was not found or no view engine supports the searched locations

In my case, I needed to use RedirectToAction to solve the problem.

[HttpGet]
[ControleDeAcessoAuthorize("Report/ExportToPDF")]
public ActionResult ExportToPDF(int id, string month, string output)
{
    try
    {
        // Validate
        if (output != "PDF")
        {
            throw new Exception("Invalid output.");
        }
        else
        {
            ...// code to generate report in PDF format
        }
    }
    catch (Exception ex)
    {
        return RedirectToAction("Error");
    }
}

[ControleDeAcessoAuthorize("Report/Error")]
public ActionResult Error()
{
    return View();
}

Logger slf4j advantages of formatting with {} instead of string concatenation

Another alternative is String.format(). We are using it in jcabi-log (static utility wrapper around slf4j).

Logger.debug(this, "some variable = %s", value);

It's much more maintainable and extendable. Besides, it's easy to translate.

How to copy text from a div to clipboard

Create a element to be appended to the document. Set its value to the string that we want to copy to the clipboard. Append said element to the current HTML document. Use HTMLInputElement.select() to select the contents of the element. Use Document.execCommand('copy') to copy the contents of the to the clipboard. Remove the element from the document

function copyToClipboard(containertext) {
    var el = document.createElement('textarea');
    el.value = containertext;
    el.text = containertext;
    el.setAttribute('id', 'copyText');
    el.setAttribute('readonly', '');
    el.style.position = 'absolute';
    el.style.left = '-9999px';
    document.body.appendChild(el);
    var coptTextArea = document.getElementById('copyText');
    $('#copyText').text(containertext);
    coptTextArea.select();
    document.execCommand('copy');
    document.body.removeChild(el);
    /* Alert the copied text */
    alert("Copied : "+containertext, 1000);
}

MySQL said: Documentation #1045 - Access denied for user 'root'@'localhost' (using password: NO)

If you are using XAMPP rather than WAMP, the path you go to is:

C:\xampp\phpMyAdmin\config.inc.php

How to convert a factor to integer\numeric without loss of information?

It is possible only in the case when the factor labels match the original values. I will explain it with an example.

Assume the data is vector x:

x <- c(20, 10, 30, 20, 10, 40, 10, 40)

Now I will create a factor with four labels:

f <- factor(x, levels = c(10, 20, 30, 40), labels = c("A", "B", "C", "D"))

1) x is with type double, f is with type integer. This is the first unavoidable loss of information. Factors are always stored as integers.

> typeof(x)
[1] "double"
> typeof(f)
[1] "integer"

2) It is not possible to revert back to the original values (10, 20, 30, 40) having only f available. We can see that f holds only integer values 1, 2, 3, 4 and two attributes - the list of labels ("A", "B", "C", "D") and the class attribute "factor". Nothing more.

> str(f)
 Factor w/ 4 levels "A","B","C","D": 2 1 3 2 1 4 1 4
> attributes(f)
$levels
[1] "A" "B" "C" "D"

$class
[1] "factor"

To revert back to the original values we have to know the values of levels used in creating the factor. In this case c(10, 20, 30, 40). If we know the original levels (in correct order), we can revert back to the original values.

> orig_levels <- c(10, 20, 30, 40)
> x1 <- orig_levels[f]
> all.equal(x, x1)
[1] TRUE

And this will work only in case when labels have been defined for all possible values in the original data.

So if you will need the original values, you have to keep them. Otherwise there is a high chance it will not be possible to get back to them only from a factor.

How to sum a list of integers with java streams?

I have declared a list of Integers.

ArrayList<Integer> numberList = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5));

You can try using these different ways below.

Using mapToInt

int sum = numberList.stream().mapToInt(Integer::intValue).sum();

Using summarizingInt

int sum = numberList.stream().collect(Collectors.summarizingInt(Integer::intValue)).getSum();

Using reduce

int sum = numberList.stream().reduce(Integer::sum).get().intValue();

Chart creating dynamically. in .net, c#

Add a reference to System.Windows.Form.DataVisualization, then add the appropriate using statement:

using System.Windows.Forms.DataVisualization.Charting;

private void CreateChart()
{
    var series = new Series("Finance");

    // Frist parameter is X-Axis and Second is Collection of Y- Axis
    series.Points.DataBindXY(new[] { 2001, 2002, 2003, 2004 }, new[] { 100, 200, 90, 150 });
    chart1.Series.Add(series);

}

Replace multiple characters in one replace call

Please try:

  • replace multi string

    var str = "http://www.abc.xyz.com"; str = str.replace(/http:|www|.com/g, ''); //str is "//.abc.xyz"

  • replace multi chars

    var str = "a.b.c.d,e,f,g,h"; str = str.replace(/[.,]/g, ''); //str is "abcdefgh";

Good luck!

Pod install is staying on "Setting up CocoaPods Master repo"

The issue is that you haven't got command line tools installed, I believe. Try run in terminal:

sudo gem update --system

after that download command line tools from Apple just search for 'Command Line Tools' and download the right version for your OS. Once you install it run in terminal:

sudo gem install cocoapods
pod setup

How do I replace NA values with zeros in an R dataframe?

if you want to assign a new name after changing the NAs in a specific column in this case column V3, use you can do also like this

my.data.frame$the.new.column.name <- ifelse(is.na(my.data.frame$V3),0,1)

ArrayList: how does the size increase?

Sun's JDK6:

I believe that it grows to 15 elements. Not coding it out, but looking at the grow() code in the jdk.

int newCapacity then = 10 + (10 >> 1) = 15.

/**
 * Increases the capacity to ensure that it can hold at least the
 * number of elements specified by the minimum capacity argument.
 *
 * @param minCapacity the desired minimum capacity
 */
private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    int newCapacity = oldCapacity + (oldCapacity >> 1);
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);
    // minCapacity is usually close to size, so this is a win:
    elementData = Arrays.copyOf(elementData, newCapacity);
}

From the Javadoc, it says this is from Java 2 and on, so its a safe bet in the Sun JDK.

EDIT : for those who didn't get what's the connection between multiplying factor 1.5 and int newCapacity = oldCapacity + (oldCapacity >> 1);

>> is right shift operator which reduces a number to its half. Thus,
int newCapacity = oldCapacity + (oldCapacity >> 1);
=> int newCapacity = oldCapacity + 0.5*oldCapacity;
=> int newCapacity = 1.5*oldCapacity ;

Delaying AngularJS route change until model loaded to prevent flicker

I have had a complex multi-level sliding panel interface, with disabled screen layer. Creating directive on disable screen layer that would create click event to execute the state like

$state.go('account.stream.social.view');

were producing a flicking effect. history.back() instead of it worked ok, however its not always back in history in my case. SO what I find out is that if I simply create attribute href on my disable screen instead of state.go , worked like a charm.

<a class="disable-screen" back></a>

Directive 'back'

app.directive('back', [ '$rootScope', function($rootScope) {

    return {
        restrict : 'A',
        link : function(scope, element, attrs) {
            element.attr('href', $rootScope.previousState.replace(/\./gi, '/'));
        }
    };

} ]);

app.js I just save previous state

app.run(function($rootScope, $state) {      

    $rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams) {         

        $rootScope.previousState = fromState.name;
        $rootScope.currentState = toState.name;


    });
});

Using .NET, how can you find the mime type of a file based on the file signature not the extension

I found several problems of running this code:

UInt32 mimetype;
FindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0);

If you will try to run it with x64/Win10 you will get

AccessViolationException "Attempted to read or write protected memory.
This is often an indication that other memory is corrupt"

Thanks to this post PtrToStringUni doesnt work in windows 10 and @xanatos

I modified my solution to run under x64 and .NET Core 2.1:

   [DllImport("urlmon.dll", CharSet = CharSet.Unicode, ExactSpelling = true, 
    SetLastError = false)]
    static extern int FindMimeFromData(IntPtr pBC,
        [MarshalAs(UnmanagedType.LPWStr)] string pwzUrl,
        [MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.I1, 
        SizeParamIndex=3)]
        byte[] pBuffer,
        int cbSize,
        [MarshalAs(UnmanagedType.LPWStr)] string pwzMimeProposed,
        int dwMimeFlags,
        out IntPtr ppwzMimeOut,
        int dwReserved);

   string getMimeFromFile(byte[] fileSource)
   {
            byte[] buffer = new byte[256];
            using (Stream stream = new MemoryStream(fileSource))
            {
                if (stream.Length >= 256)
                    stream.Read(buffer, 0, 256);
                else
                    stream.Read(buffer, 0, (int)stream.Length);
            }

            try
            {
                IntPtr mimeTypePtr;
                FindMimeFromData(IntPtr.Zero, null, buffer, buffer.Length,
                    null, 0, out mimeTypePtr, 0);

                string mime = Marshal.PtrToStringUni(mimeTypePtr);
                Marshal.FreeCoTaskMem(mimeTypePtr);
                return mime;
            }
            catch (Exception ex)
            {
                return "unknown/unknown";
            }
   }

Thanks

Using 24 hour time in bootstrap timepicker

It looks like you have to set the option for the format with data-date-*. This example works for me with 24h support.

<div class="form-group">
    <div class="input-group date timepicker"
        data-date-format="HH:mm"
        data-date-useseconds="false"
        data-date-pickDate="false">

        <input type="text" name="" />
        <div class="input-group-addon">
            <i class="fa fa-clock-o"></i>
        </div>
    </div>
</div>

Is it possible to decrypt SHA1

SHA1 is a cryptographic hash function, so the intention of the design was to avoid what you are trying to do.

However, breaking a SHA1 hash is technically possible. You can do so by just trying to guess what was hashed. This brute-force approach is of course not efficient, but that's pretty much the only way.

So to answer your question: yes, it is possible, but you need significant computing power. Some researchers estimate that it costs $70k - $120k.

As far as we can tell today, there is also no other way but to guess the hashed input. This is because operations such as mod eliminate information from your input. Suppose you calculate mod 5 and you get 0. What was the input? Was it 0, 5 or 500? You see, you can't really 'go back' in this case.

Trying to check if username already exists in MySQL database using PHP

change your query to like.

$username = mysql_real_escape_string($username); // escape string before passing it to query.
$query = mysql_query("SELECT username FROM Users WHERE username='".$username."'");

However, MySQL is deprecated. You should instead use MySQLi or PDO

How do you run your own code alongside Tkinter's event loop?

The solution posted by Bjorn results in a "RuntimeError: Calling Tcl from different appartment" message on my computer (RedHat Enterprise 5, python 2.6.1). Bjorn might not have gotten this message, since, according to one place I checked, mishandling threading with Tkinter is unpredictable and platform-dependent.

The problem seems to be that app.start() counts as a reference to Tk, since app contains Tk elements. I fixed this by replacing app.start() with a self.start() inside __init__. I also made it so that all Tk references are either inside the function that calls mainloop() or are inside functions that are called by the function that calls mainloop() (this is apparently critical to avoid the "different apartment" error).

Finally, I added a protocol handler with a callback, since without this the program exits with an error when the Tk window is closed by the user.

The revised code is as follows:

# Run tkinter code in another thread

import tkinter as tk
import threading

class App(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)
        self.start()

    def callback(self):
        self.root.quit()

    def run(self):
        self.root = tk.Tk()
        self.root.protocol("WM_DELETE_WINDOW", self.callback)

        label = tk.Label(self.root, text="Hello World")
        label.pack()

        self.root.mainloop()


app = App()
print('Now we can continue running code while mainloop runs!')

for i in range(100000):
    print(i)

How do I set up DNS for an apex domain (no www) pointing to a Heroku app?

I am now using Google Apps (for Email) and Heroku as web server. I am using Google Apps 301 Permanent Redirect feature to redirect the naked domain to WWW.your_domain.com

You can find the step-by-step instructions here https://stackoverflow.com/a/20115583/1440255

Styling text input caret

Here are some vendors you might me looking for

::-webkit-input-placeholder {color: tomato}
::-moz-placeholder          {color: tomato;} /* Firefox 19+ */
:-moz-placeholder           {color: tomato;} /* Firefox 18- */
:-ms-input-placeholder      {color: tomato;}

You can also style different states, such as focus

:focus::-webkit-input-placeholder {color: transparent}
:focus::-moz-placeholder          {color: transparent}
:focus:-moz-placeholder           {color: transparent}
:focus:-ms-input-placeholder      {color: transparent}

You can also do certain transitions on it, like

::-VENDOR-input-placeholder       {text-indent: 0px;   transition: text-indent 0.3s ease;}
:focus::-VENDOR-input-placeholder  {text-indent: 500px; transition: text-indent 0.3s ease;}

What is so bad about singletons?

The singleton pattern is not a problem in itself. The problem is that the pattern is often used by people developing software with object-oriented tools without having a solid grasp of OO concepts. When singletons are introduced in this context they tend to grow into unmanageable classes that contain helper methods for every little use.

Singletons are also a problem from a testing perspective. They tend to make isolated unit-tests difficult to write. Inversion of control (IoC) and dependency injection are patterns meant to overcome this problem in an object-oriented manner that lends itself to unit testing.

In a garbage collected environment singletons can quickly become an issue with regard to memory management.

There is also the multi-threaded scenario where singletons can become a bottleneck as well as a synchronization issue.

How do I access command line arguments in Python?

Some additional things that I can think of.

As @allsyed said sys.argv gives a list of components (including program name), so if you want to know the number of elements passed through command line you can use len() to determine it. Based on this, you can design exception/error messages if user didn't pass specific number of parameters.

Also if you looking for a better way to handle command line arguments, I would suggest you look at https://docs.python.org/2/howto/argparse.html

How to solve "Plugin execution not covered by lifecycle configuration" for Spring Data Maven Builds

Change the Maven preferences for plugin execution from error to ignore

Are multi-line strings allowed in JSON?

This is a really old question, but I came across this on a search and I think I know the source of your problem.

JSON does not allow "real" newlines in its data; it can only have escaped newlines. See the answer from @YOU. According to the question, it looks like you attempted to escape line breaks in Python two ways: by using the line continuation character ("\") or by using "\n" as an escape.

But keep in mind: if you are using a string in python, special escaped characters ("\t", "\n") are translated into REAL control characters! The "\n" will be replaced with the ASCII control character representing a newline character, which is precisely the character that is illegal in JSON. (As for the line continuation character, it simply takes the newline out.)

So what you need to do is to prevent Python from escaping characters. You can do this by using a raw string (put r in front of the string, as in r"abc\ndef", or by including an extra slash in front of the newline ("abc\\ndef").

Both of the above will, instead of replacing "\n" with the real newline ASCII control character, will leave "\n" as two literal characters, which then JSON can interpret as a newline escape.

Angular 2 - View not updating after model changes

It might be that the code in your service somehow breaks out of Angular's zone. This breaks change detection. This should work:

import {Component, OnInit, NgZone} from 'angular2/core';

export class RecentDetectionComponent implements OnInit {

    recentDetections: Array<RecentDetection>;

    constructor(private zone:NgZone, // <== added
        private recentDetectionService: RecentDetectionService) {
        this.recentDetections = new Array<RecentDetection>();
    }

    getRecentDetections(): void {
        this.recentDetectionService.getJsonFromApi()
            .subscribe(recent => { 
                 this.zone.run(() => { // <== added
                     this.recentDetections = recent;
                     console.log(this.recentDetections[0].macAddress) 
                 });
        });
    }

    ngOnInit() {
        this.getRecentDetections();
        let timer = Observable.timer(2000, 5000);
        timer.subscribe(() => this.getRecentDetections());
    }
}

For other ways to invoke change detection see Triggering change detection manually in Angular

Alternative ways to invoke change detection are

ChangeDetectorRef.detectChanges()

to immediately run change detection for the current component and its children

ChangeDetectorRef.markForCheck()

to include the current component the next time Angular runs change detection

ApplicationRef.tick()

to run change detection for the whole application

How do you round UP a number in Python?

If working with integers, one way of rounding up is to take advantage of the fact that // rounds down: Just do the division on the negative number, then negate the answer. No import, floating point, or conditional needed.

rounded_up = -(-numerator // denominator)

For example:

>>> print(-(-101 // 5))
21

Java, Check if integer is multiple of a number

Use modulo

whenever a number x is a multiple of some number y, then always x % y equal to 0, which can be used as a check. So use

if (j % 4 == 0) 

How do I change select2 box height

Quick and easy, add this to your page:

<style>
    .select2-results {
        max-height: 500px;
    }
</style>

How to SUM two fields within an SQL query

SUM is an aggregate function. It will calculate the total for each group. + is used for calculating two or more columns in a row.

Consider this example,

ID  VALUE1  VALUE2
===================
1   1       2
1   2       2
2   3       4
2   4       5

 

SELECT  ID, SUM(VALUE1), SUM(VALUE2)
FROM    tableName
GROUP   BY ID

will result

ID, SUM(VALUE1), SUM(VALUE2)
1   3           4
2   7           9

 

SELECT  ID, VALUE1 + VALUE2
FROM    TableName

will result

ID, VALUE1 + VALUE2
1   3
1   4
2   7
2   9

 

SELECT  ID, SUM(VALUE1 + VALUE2)
FROM    tableName
GROUP   BY ID

will result

ID, SUM(VALUE1 + VALUE2)
1   7
2   16

Negate if condition in bash script

Better

if ! wget -q --spider --tries=10 --timeout=20 google.com
then
  echo 'Sorry you are Offline'
  exit 1
fi

How to use regex in XPath "contains" function

XPath 1.0 doesn't handle regex natively, you could try something like

//*[starts-with(@id, 'sometext') and ends-with(@id, '_text')]

(as pointed out by paul t, //*[boolean(number(substring-before(substring-after(@id, "sometext"), "_text")))] could be used to perform the same check your original regex does, if you need to check for middle digits as well)

In XPath 2.0, try

//*[matches(@id, 'sometext\d+_text')]

How to have a drop down <select> field in a rails form?

You can take a look at the Rails documentation . Anyways , in your form :

  <%= f.collection_select :provider_id, Provider.order(:name),:id,:name, include_blank: true %>

As you can guess , you should predefine email-providers in another model -Provider , to have where to select them from .

Get Substring between two characters using javascript

Get string between two substrings (contains more than 1 character)

function substrInBetween(whole_str, str1, str2){
   if (whole_str.indexOf(str1) === -1 || whole_str.indexOf(str2) === -1) {
       return undefined; // or ""
  }
  strlength1 = str1.length;
  return whole_str.substring(
                whole_str.indexOf(str1) + strlength1, 
                whole_str.indexOf(str2)
               );

   }

Note I use indexOf() instead of lastIndexOf() so it will check for first occurences of those strings

How to post JSON to PHP with curl

Jordans analysis of why the $_POST-array isn't populated is correct. However, you can use

$data = file_get_contents("php://input");

to just retrieve the http body and handle it yourself. See PHP input/output streams.

From a protocol perspective this is actually more correct, since you're not really processing http multipart form data anyway. Also, use application/json as content-type when posting your request.

How can I add an element after another element?

First of all, input element shouldn't have a closing tag (from http://www.w3.org/TR/html401/interact/forms.html#edef-INPUT : End tag: forbidden ).

Second thing, you need the after(), not append() function.

One command to create a directory and file inside it linux command

This might work:

mkdir {{FOLDER NAME}}
cd {{FOLDER NAME}}
touch {{FOLDER NAME}}/file.txt

What data type to use in MySQL to store images?

Perfect answer for your question can be found on MYSQL site itself.refer their manual(without using PHP)

http://forums.mysql.com/read.php?20,17671,27914

According to them use LONGBLOB datatype. with that you can only store images less than 1MB only by default,although it can be changed by editing server config file.i would also recommend using MySQL workBench for ease of database management

Python - Locating the position of a regex match in a string?

re.Match objects have a number of methods to help you with this:

>>> m = re.search("is", String)
>>> m.span()
(2, 4)
>>> m.start()
2
>>> m.end()
4

react-native :app:installDebug FAILED

For me, restarting my phone did the trick.

How do you clear the console screen in C?

printf("\e[1;1H\e[2J");

This function will work on ANSI terminals, demands POSIX. I assume there is a version that might also work on window's console, since it also supports ANSI escape sequences.

#include <unistd.h>

void clearScreen()
{
  const char *CLEAR_SCREEN_ANSI = "\e[1;1H\e[2J";
  write(STDOUT_FILENO, CLEAR_SCREEN_ANSI, 12);
}

There are some other alternatives, some of which don't move the cursor to {1,1}.

PostgreSQL Error: Relation already exists

You cannot create a table with a name that is identical to an existing table or view in the cluster. To modify an existing table, use ALTER TABLE (link), or to drop all data currently in the table and create an empty table with the desired schema, issue DROP TABLE before CREATE TABLE.

It could be that the sequence you are creating is the culprit. In PostgreSQL, sequences are implemented as a table with a particular set of columns. If you already have the sequence defined, you should probably skip creating it. Unfortunately, there's no equivalent in CREATE SEQUENCE to the IF NOT EXISTS construct available in CREATE TABLE. By the looks of it, you might be creating your schema unconditionally, anyways, so it's reasonable to use

DROP TABLE IF EXISTS csd_relationship;
DROP SEQUENCE IF EXISTS csd_relationship_csd_relationship_id_seq;

before the rest of your schema update; In case it isn't obvious, This will delete all of the data in the csd_relationship table, if there is any

draw diagonal lines in div background with CSS

All other answers to this 3-year old question require CSS3 (or SVG). However, it can also be done with nothing but lame old CSS2:

_x000D_
_x000D_
.crossed {_x000D_
    position: relative;_x000D_
    width: 300px;_x000D_
    height: 300px;_x000D_
}_x000D_
_x000D_
.crossed:before {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    right: 0;_x000D_
    top: 1px;_x000D_
    bottom: 1px;_x000D_
    border-width: 149px;_x000D_
    border-style: solid;_x000D_
    border-color: black white;_x000D_
}_x000D_
_x000D_
.crossed:after {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 1px;_x000D_
    right: 1px;_x000D_
    top: 0;_x000D_
    bottom: 0;_x000D_
    border-width: 149px;_x000D_
    border-style: solid;_x000D_
    border-color: white transparent;_x000D_
}
_x000D_
<div class='crossed'></div>
_x000D_
_x000D_
_x000D_

Explanation, as requested:

Rather than actually drawing diagonal lines, it occurred to me we can instead color the so-called negative space triangles adjacent to where we want to see these lines. The trick I came up with to accomplish this exploits the fact that multi-colored CSS borders are bevelled diagonally:

_x000D_
_x000D_
.borders {_x000D_
    width: 200px;_x000D_
    height: 100px;_x000D_
    background-color: black;_x000D_
    border-width: 40px;_x000D_
    border-style: solid;_x000D_
    border-color: red blue green yellow;_x000D_
}
_x000D_
<div class='borders'></div>
_x000D_
_x000D_
_x000D_

To make things fit the way we want, we choose an inner rectangle with dimensions 0 and LINE_THICKNESS pixels, and another one with those dimensions reversed:

_x000D_
_x000D_
.r1 { width: 10px;_x000D_
      height: 0;_x000D_
      border-width: 40px;_x000D_
      border-style: solid;_x000D_
      border-color: red blue;_x000D_
      margin-bottom: 10px; }_x000D_
.r2 { width: 0;_x000D_
      height: 10px;_x000D_
      border-width: 40px;_x000D_
      border-style: solid;_x000D_
      border-color: blue transparent; }
_x000D_
<div class='r1'></div><div class='r2'></div>
_x000D_
_x000D_
_x000D_

Finally, use the :before and :after pseudo-selectors and position relative/absolute as a neat way to insert the borders of both of the above rectangles on top of each other into your HTML element of choice, to produce a diagonal cross. Note that results probably look best with a thin LINE_THICKNESS value, such as 1px.

JSP : JSTL's <c:out> tag

c:out also has an attribute for assigning a default value if the value of person.name happens to be null.

Source: out (TLDDoc Generated Documentation)

Using sed to mass rename files

Some examples that work for me:

$ tree -L 1 -F .
.
+-- A.Show.2020.1400MB.txt
+-- Some Show S01E01 the Loreming.txt

0 directories, 2 files

## remove "1400MB" (I: ignore case) ...

$ for f in *; do mv 2>/dev/null -v "$f" "`echo $f | sed -r 's/.[0-9]{1,}mb//I'`"; done;
renamed 'A.Show.2020.1400MB.txt' -> 'A.Show.2020.txt'

## change "S01E01 the" to "S01E01 The"
## \U& : change (here: regex-selected) text to uppercase;
##       note also: no need here for `\1` in that regex expression

$ for f in *; do mv 2>/dev/null "$f" "`echo $f | sed -r "s/([0-9] [a-z])/\U&/"`"; done

$ tree -L 1 -F .
.
+-- A.Show.2020.txt
+-- Some Show S01E01 The Loreming.txt

0 directories, 2 files
$ 

EOFException - how to handle?

You can use while(in.available() != 0) instead of while(true).