Programs & Examples On #Avatars

An avatar is the graphical representation of the user or the user's alter ego or character.

How to use img src in vue.js?

Try this:

<img v-bind:src="'/media/avatars/' + joke.avatar" /> 

Don't forget single quote around your path string. also in your data check you have correctly defined image variable.

joke: {
  avatar: 'image.jpg'
}

A working demo here: http://jsbin.com/pivecunode/1/edit?html,js,output

Laravel 5 - How to access image uploaded in storage within View?

If you are like me and you somehow have full file paths (I did some glob() pattern matching on required photos so I do pretty much end up with full file paths), and your storage setup is well linked (i.e. such that your paths have the string storage/app/public/), then you can use my little dirty hack below :p)

 public static function hackoutFileFromStorageFolder($fullfilePath) {
        if (strpos($fullfilePath, 'storage/app/public/')) {
           $fileParts = explode('storage/app/public/', $fullfilePath);
           if( count($fileParts) > 1){
               return $fileParts[1];
           }
        }

        return '';
    }

img tag displays wrong orientation

This problem was driving me crazy too. I was using PHP on my server side so I was not able to use @The Lazy Log(ruby) & @deweydb(python) solutions. However it pointed me to the right direction. I fixed it on the backed using Imagick's getImageOrientation().

<?php 
// Note: $image is an Imagick object, not a filename! See example use below. 
function autoRotateImage($image) { 
    $orientation = $image->getImageOrientation(); 

    switch($orientation) { 
        case imagick::ORIENTATION_BOTTOMRIGHT: 
            $image->rotateimage("#000", 180); // rotate 180 degrees 
        break; 

        case imagick::ORIENTATION_RIGHTTOP: 
            $image->rotateimage("#000", 90); // rotate 90 degrees CW 
        break; 

        case imagick::ORIENTATION_LEFTBOTTOM: 
            $image->rotateimage("#000", -90); // rotate 90 degrees CCW 
        break; 
    } 

    // Now that it's auto-rotated, make sure the EXIF data is correct in case the EXIF gets saved with the image! 
    $image->setImageOrientation(imagick::ORIENTATION_TOPLEFT); 
} 
?> 

Here is the link if you want to read more. http://php.net/manual/en/imagick.getimageorientation.php

Resize image in PHP

I would suggest an easy way:

function resize($file, $width, $height) {
    switch(pathinfo($file)['extension']) {
        case "png": return imagepng(imagescale(imagecreatefrompng($file), $width, $height), $file);
        case "gif": return imagegif(imagescale(imagecreatefromgif($file), $width, $height), $file);
        default : return imagejpeg(imagescale(imagecreatefromjpeg($file), $width, $height), $file);
    }
}

.gitignore and "The following untracked working tree files would be overwritten by checkout"

Git is telling you that it wants to create files (named public/system/images/9/... etc), but you already have existing files in that directory that aren't tracked by Git. Perhaps somebody else added those files to the Git repository, and this is the first time you have switched to that branch?

There's probably a reason why those files in your develop branch but not in your current branch. You may have to ask your collaborators why that is.

how do I get this working so I can switch branches without deleting those files?

You can't do it without making the files disappear somehow. You could rename public to my_public or something for now.

if I came back to this branch afterwards would everything be perfect as up to my latest commit?

If you commit your changes, Git won't lose them. If you don't commit your changes, then Git will try really hard not to overwrite work that you have done. That's what Git is warning you about in the first instance here (when you tried to switch branches).

What is the best way to programmatically detect porn images?

If you're really have time and money:

One way of doing it is by 1) Writing an image detection algorithm to find whether an object is human or not. This can be done by bitmasking an image to retrieve it's "contours" and see if the contours fits a human contour.

2) Data mine a lot of porn images and use data mining techniques such as the C4 algorithms or Particle Swarm Optimization to learn to detect pattern that matches porn images.

This will require that you identify how a naked man/woman contours of a human body must look like in digitized format (this can be achieved in the same way OCR image recognition algorithms works).

Hope you have fun! :-)

How can I create a carriage return in my C# string

Along with Environment.NewLine and the literal \r\n or just \n you may also use a verbatim string in C#. These begin with @ and can have embedded newlines. The only thing to keep in mind is that " needs to be escaped as "". An example:

string s = @"This is a string
that contains embedded new lines,
that will appear when this string is used."

Deadly CORS when http://localhost is the origin

Agreed! CORS should be enabled on the server-side to resolve the issue ground up. However...

For me the case was:

I desperately wanted to test my front-end(React/Angular/VUE) code locally with the REST API provided by the client with no access to the server config.

Just for testing

After trying all the steps above that didn't work I was forced to disable web security and site isolation trials on chrome along with specifying the user data directory(tried skipping this, didn't work).

For Windows

cd C:\Program Files\Google\Chrome\Application

Disable web security and site isolation trials

chrome.exe  --disable-site-isolation-trials --disable-web-security --user-data-dir="PATH_TO_PROJECT_DIRECTORY"

This finally worked! Hope this helps!

Format Date output in JSF

Use <f:convertDateTime>. You can nest this in any input and output component. Pattern rules are same as java.text.SimpleDateFormat.

<h:outputText value="#{someBean.dateField}" >
    <f:convertDateTime pattern="dd.MM.yyyy HH:mm" />
</h:outputText>

Difference between Pig and Hive? Why have both?

You can achieve similar results with pig/hive queries. The main difference lies within approach to understanding/writing/creating queries.

Pig tends to create a flow of data: small steps where in each you do some processing
Hive gives you SQL-like language to operate on your data, so transformation from RDBMS is much easier (Pig can be easier for someone who had not earlier experience with SQL)

It is also worth noting, that for Hive you can nice interface to work with this data (Beeswax for HUE, or Hive web interface), and it also gives you metastore for information about your data (schema, etc) which is useful as a central information about your data.

I use both Hive and Pig, for different queries (I use that one where I can write query faster/easier, I do it this way mostly ad-hoc queries) - they can use the same data as an input. But currently I'm doing much of my work through Beeswax.

How to check if any value is NaN in a Pandas DataFrame

import missingno as msno
msno.matrix(df)  # just to visualize. no missing value.

enter image description here

How to call stopservice() method of Service class from the calling activity class

@Juri

If you add IntentFilters for your service, you are saying you want to expose your service to other applications, then it may be stopped unexpectedly by other applications.

Why maven? What are the benefits?

Maven can be considered as complete project development tool not just build tool like Ant. You should use Eclipse IDE with maven plugin to fix all your problems.

Here are few advantages of Maven, quoted from the Benefits of using Maven page:

Henning

  • quick project setup, no complicated build.xml files, just a POM and go
  • all developers in a project use the same jar dependencies due to centralized POM.
  • getting a number of reports and metrics for a project "for free"
  • reduce the size of source distributions, because jars can be pulled from a central location

Emmanuel Venisse

  • a lot of goals are available so it isn't necessary to develop some specific build process part contrary to ANT we can reuse existing ANT tasks in build process with antrun plugin

Jesse Mcconnell

  • Promotes modular design of code. by making it simple to manage mulitple projects it allows the design to be laid out into muliple logical parts, weaving these parts together through the use of dependency tracking in pom files.
  • Enforces modular design of code. it is easy to pay lipservice to modular code, but when the code is in seperate compiling projects it is impossible to cross pollinate references between modules of code unless you specifically allow for it in your dependency management... there is no 'I'll just do this now and fix it later' implementations.
  • Dependency Management is clearly declared. with the dependency management mechanism you have to try to screw up your jar versioning...there is none of the classic problem of 'which version of this vendor jar is this?' And setting it up on an existing project rips the top off of the existing mess if it exists when you are forced to make 'unknown' versions in your repository to get things up and running...that or lie to yourself that you know the actual version of ABC.jar.
  • strong typed life cycle there is a strong defined lifecycle that a software system goes thru from the initiation of a build to the end... and the users are allowed to mix and match their system to the lifecycle instead of cobble together their own lifecycle.. this has the additional benefit of allowing people to move from one project to another and speak using the same vocabulary in terms of software building

Vincent Massol

  • Greater momentum: Ant is now legacy and not moving fast ahead. Maven is forging ahead fast and there's a potential of having lots of high-value tools around Maven (CI, Dashboard project, IDE integration, etc).

Another git process seems to be running in this repository

In case can help somebody else... I tried with command line rm -f .git/index.lock and didn't work (terminal didn't show any error). I just went directly to folder .git and delete the index.lock file.

Note: .git folder is located in your root repository and is hidden. In mac: Cmd+Shift+. to see hidden files.

Request Monitoring in Chrome

You could use Fiddler which is a good free tool.

How can I split a shell command over multiple lines when using an IF statement?

For Windows/WSL/Cygwin etc users:

Make sure that your line endings are standard Unix line feeds, i.e. \n (LF) only.

Using Windows line endings \r\n (CRLF) line endings will break the command line break.


This is because having \ at the end of a line with Windows line ending translates to \ \r \n.
As Mark correctly explains above:

The line-continuation will fail if you have whitespace after the backslash and before the newline.

This includes not just space () or tabs (\t) but also the carriage return (\r).

INNER JOIN same table

I think the problem is in your JOIN condition.

SELECT user.user_fname,
       user.user_lname,
       parent.user_fname,
       parent.user_lname
FROM users AS user
JOIN users AS parent 
  ON parent.user_id = user.user_parent_id
WHERE user.user_id = $_GET[id]

Edit: You should probably use LEFT JOIN if there are users with no parents.

Initialize 2D array

How about something like this:

for (int row = 0; row < 3; row ++)
    for (int col = 0; col < 3; col++)
        table[row][col] = (char) ('1' + row * 3 + col);

The following complete Java program:

class Test {
    public static void main(String[] args) {
        char[][] table = new char[3][3];
        for (int row = 0; row < 3; row ++)
            for (int col = 0; col < 3; col++)
                table[row][col] = (char) ('1' + row * 3 + col);

        for (int row = 0; row < 3; row ++)
            for (int col = 0; col < 3; col++)
                System.out.println (table[row][col]);
    }
}

outputs:

1
2
3
4
5
6
7
8
9

This works because the digits in Unicode are consecutive starting at \u0030 (which is what you get from '0').

The expression '1' + row * 3 + col (where you vary row and col between 0 and 2 inclusive) simply gives you a character from 1 to 9.

Obviously, this won't give you the character 10 (since that's two characters) if you go further but it works just fine for the 3x3 case. You would have to change the method of generating the array contents at that point such as with something like:

String[][] table = new String[5][5];
for (int row = 0; row < 5; row ++)
    for (int col = 0; col < 5; col++)
        table[row][col] = String.format("%d", row * 5 + col + 1);

How to get the browser language using JavaScript

Try this script to get your browser language

_x000D_
_x000D_
<script type="text/javascript">_x000D_
var userLang = navigator.language || navigator.userLanguage; _x000D_
alert ("The language is: " + userLang);_x000D_
</script>
_x000D_
_x000D_
_x000D_

Cheers

How to get the first and last date of the current year?

SELECT
   DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) AS StartOfYear,
   DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, -1) AS EndOfYear

The above query gives a datetime value for midnight at the beginning of December 31. This is about 24 hours short of the last moment of the year. If you want to include time that might occur on December 31, then you should compare to the first of the next year, with a < comparison. Or you can compare to the last few milliseconds of the current year, but this still leaves a gap if you are using something other than DATETIME (such as DATETIME2):

SELECT
   DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) AS StartOfYear,
   DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, -1) AS LastDayOfYear,
   DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, 0) AS FirstOfNextYear,
   DATEADD(ms, -3, DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, 0)) AS LastTimeOfYear

Tech Details

This works by figuring out the number of years since 1900 with DATEDIFF(yy, 0, GETDATE()) and then adding that to a date of zero = Jan 1, 1900. This can be changed to work for an arbitrary date by replacing the GETDATE() portion or an arbitrary year by replacing the DATEDIFF(...) function with "Year - 1900."

 SELECT
   DATEADD(yy, DATEDIFF(yy, 0, '20150301'), 0) AS StartOfYearForMarch2015,
   DATEADD(yy, 2015 - 1900, 0) AS StartOfYearFor2015

PHP simple foreach loop with HTML

This will work although when embedding PHP in HTML it is better practice to use the following form:

<table>
    <?php foreach($array as $key=>$value): ?>
    <tr>
        <td><?= $key; ?></td>
    </tr>
    <?php endforeach; ?>
</table>

You can find the doc for the alternative syntax on PHP.net

Show/hide forms using buttons and JavaScript

Use the following code fragment to hide the form on button click.

document.getElementById("your form id").style.display="none";

And the following code to display it:

document.getElementById("your form id").style.display="block";

Or you can use the same function for both purposes:

function asd(a)
{
    if(a==1)
        document.getElementById("asd").style.display="none";
    else
        document.getElementById("asd").style.display="block";
}

And the HTML:

<form id="asd">form </form>
<button onclick="asd(1)">Hide</button>
<button onclick="asd(2)">Show</button>

Remove legend ggplot 2.2

There might be another solution to this:
Your code was:

geom_point(aes(..., show.legend = FALSE))

You can specify the show.legend parameter after the aes call:

geom_point(aes(...), show.legend = FALSE)

then the corresponding legend should disappear

How to match, but not capture, part of a regex?

Try:

123-(?:(apple|banana|)-|)456

That will match apple, banana, or a blank string, and following it there will be a 0 or 1 hyphens. I was wrong about not having a need for a capturing group. Silly me.

When to use throws in a Java method declaration?

You're correct, in that example the throws is superfluous. It's possible that it was left there from some previous implementation - perhaps the exception was originally thrown instead of caught in the catch block.

How to easily get network path to the file you are working on?

Right click on the ribbon and choose Customize the ribbon. From the Choose commands from: drop down, select Commands not in the ribbon.

That is where I found the Document location command.

How to display two digits after decimal point in SQL Server

You can also Make use of the Following if you want to Cast and Round as well. That may help you or someone else.

SELECT CAST(ROUND(Column_Name, 2) AS DECIMAL(10,2), Name FROM Table_Name

java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries. spark Eclipse on windows 7

That's a tricky one... Your storage letter must be capical. For example "C:\..."

Load json from local file with http.get() in angular 2

For Angular 5+ only preform steps 1 and 4


In order to access your file locally in Angular 2+ you should do the following (4 steps):

[1] Inside your assets folder create a .json file, example: data.json

[2] Go to your angular.cli.json (angular.json in Angular 6+) inside your project and inside the assets array put another object (after the package.json object) like this:

{ "glob": "data.json", "input": "./", "output": "./assets/" }

full example from angular.cli.json

"apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico",
        { "glob": "package.json", "input": "../", "output": "./assets/" },
        { "glob": "data.json", "input": "./", "output": "./assets/" }
      ],

Remember, data.json is just the example file we've previously added in the assets folder (you can name your file whatever you want to)

[3] Try to access your file via localhost. It should be visible within this address, http://localhost:your_port/assets/data.json

If it's not visible then you've done something incorrectly. Make sure you can access it by typing it in the URL field in your browser before proceeding to step #4.

[4] Now preform a GET request to retrieve your .json file (you've got your full path .json URL and it should be simple)

 constructor(private http: HttpClient) {}
        // Make the HTTP request:
        this.http.get('http://localhost:port/assets/data.json')
                 .subscribe(data => console.log(data));

How to disable sort in DataGridView?

foreach (DataGridViewColumn column in dataGridView.Columns)
{
    column.SortMode = DataGridViewColumnSortMode.NotSortable;
}

What is the difference between response.sendRedirect() and request.getRequestDispatcher().forward(request,response)

Redirect and Request dispatcher are two different methods to move form one page to another. if we are using redirect to a new page actually a new request is happening from the client side itself to the new page. so we can see the change in the URL. Since redirection is a new request the old request values are not available here.

Jquery sortable 'change' event element position

This works for me:

start: function(event, ui) {
        var start_pos = ui.item.index();
        ui.item.data('start_pos', start_pos);
    },
update: function (event, ui) {
        var start_pos = ui.item.data('start_pos');
        var end_pos = ui.item.index();
        //$('#sortable li').removeClass('highlights');
    }

ERROR: Cannot open source file " "

This was the top result when googling "cannot open source file" so I figured I would share what my issue was since I had already included the correct path.

I'm not sure about other IDEs or compilers, but least for Visual Studio, make sure there isn't a space in your list of include directories. I had put a space between the ; of the last entry and the beginning of my new entry which then caused Visual Studio to disregard my inclusion.

SQL QUERY replace NULL value in a row with a value from the previous known value

In a very general sense:

UPDATE MyTable
SET MyNullValue = MyDate
WHERE MyNullValue IS NULL

How can I change the color of AlertDialog title and the color of the line under it

check this is useful for you...

public void setCustomTitle (View customTitleView)

you get detail from following link.

http://developer.android.com/reference/android/app/AlertDialog.Builder.html#setCustomTitle%28android.view.View%29

CustomDialog.java

Dialog alert = new Dialog(this);
    alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
    alert.setContentView(R.layout.title);
    TextView msg = (TextView)alert.findViewById(R.id.textView1);
    msg.setText("Hello Friends.\nIP address : 111.111.1.111");
    alert.show();

title.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Set IP address"
    android:textColor="#ff0000"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<ImageView 
    android:layout_width="fill_parent"
    android:layout_height="2dp"
    android:layout_marginTop="5dp"
    android:background="#00ff00"
    />
<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="#775500"
    android:textAppearance="?android:attr/textAppearanceLarge" />

enter image description here

Android Studio - local path doesn't exist

I just managed to fix this. I followed Adams instructions but it still would not work so I kept digging and did this on top of Adams instructions:

I went to Module Settings and in the Paths tab under Compiler output I selected Inherit project compile output path. I am running 0.3.0

How to make a hyperlink in telegram without using bots?

My phone is xiaomi Redmi note 8 with MIUI 11.0.9 . There is no option for create hyperlink :enter image description here So I use Telegram desktop or Telegram X for create hyperlink because Telegram X supports markdown. Type url and send message (in Telegram X) or there is an alternate way which is the easiest!

Select the text using Xiaomi's Word Editor and click in the three dots on the top right corner of the chat. It is usually used for accessing settings but if you select a text and click there, you can see Telegram's own Formatter!

Send POST request using NSURLSession

Teja Kumar Bethina's code changed for Swift 3:

    let urlStr = "http://url_to_manage_post_requests"
    let url = URL(string: urlStr)

    var request: URLRequest = URLRequest(url: url!)

    request.httpMethod = "POST"

    request.setValue("application/json", forHTTPHeaderField:"Content-Type")
    request.timeoutInterval = 60.0

    //additional headers
    request.setValue("deviceIDValue", forHTTPHeaderField:"DeviceId")

    let bodyStr = "string or data to add to body of request"
    let bodyData = bodyStr.data(using: String.Encoding.utf8, allowLossyConversion: true)
    request.httpBody = bodyData

    let task = URLSession.shared.dataTask(with: request) {
        (data: Data?, response: URLResponse?, error: Error?) -> Void in

        if let httpResponse = response as? HTTPURLResponse {
            print("responseCode \(httpResponse.statusCode)")
        }

        if error != nil {

            // You can handle error response here
            print("\(error)")
        } else {
            //Converting response to collection formate (array or dictionary)
            do {
                let jsonResult = (try JSONSerialization.jsonObject(with: data!, options:
                    JSONSerialization.ReadingOptions.mutableContainers))

                //success code
            } catch {
                //failure code
            }
        }
    }

    task.resume()

Skipping error in for-loop

Instead of catching the error, wouldn't it be possible to test in or before the myplotfunction() function first if the error will occur (i.e. if the breaks are unique) and only plot it for those cases where it won't appear?!

Spark difference between reduceByKey vs groupByKey vs aggregateByKey vs combineByKey

Then apart from these 4, we have

foldByKey which is same as reduceByKey but with a user defined Zero Value.

AggregateByKey takes 3 parameters as input and uses 2 functions for merging(one for merging on same partitions and another to merge values across partition. The first parameter is ZeroValue)

whereas

ReduceBykey takes 1 parameter only which is a function for merging.

CombineByKey takes 3 parameter and all 3 are functions. Similar to aggregateBykey except it can have a function for ZeroValue.

GroupByKey takes no parameter and groups everything. Also, it is an overhead for data transfer across partitions.

Jenkins/Hudson - accessing the current build number?

I've just come across this question too and found out that if anytime the build number gets corrupt because of any error-triggered hard shutdown of the jenkins instance you can set back the build number manually by just editing the file nextBuildNumber (pathToJenkins\jobs\jobxyz\nextBuildNumber) and then make a reload by using the option
Reload Configuration from Disk from the Manage Jenkins View.

What's the difference between faking, mocking, and stubbing?

the thing that you assert on it,is called a mock object and everything else that just helped the test run, is a stub.

Check if String / Record exists in DataTable

Use the Find method if item_manuf_id is a primary key:

var result = dtPs.Rows.Find("some value");

If you only want to know if the value is in there then use the Contains method.

if (dtPs.Rows.Contains("some value"))
{
  ...
}

Primary key restriction applies to Contains aswell.

Running an executable in Mac Terminal

Unix will only run commands if they are available on the system path, as you can view by the $PATH variable

echo $PATH

Executables located in directories that are not on the path cannot be run unless you specify their full location. So in your case, assuming the executable is in the current directory you are working with, then you can execute it as such

./my-exec

Where my-exec is the name of your program.

Permission denied (publickey) when deploying heroku code. fatal: The remote end hung up unexpectedly

I killed myself for 3 days trying every possible combination to try to get this to work -- I finally tried making a DSA key instead and it worked.

Try DSA instead of RSA if it's not working for you.

(I'm using Ubuntu 11.10, ruby 1.8.7, heroku 2.15.1)

Invalid length parameter passed to the LEFT or SUBSTRING function

CHARINDEX will return 0 if no spaces are in the string and then you look for a substring of -1 length.

You can tack a trailing space on to the end of the string to ensure there is always at least one space and avoid this problem.

SELECT SUBSTRING(PostCode, 1 , CHARINDEX(' ', PostCode + ' ' ) -1)

How to round a Double to the nearest Int in swift?

You may also want to check whether the double is higher than the max Int value before trying to convert the value to an Int.

let number = Double.infinity
if number >= Double(integerLiteral: Int64.max) {
  let rounded = Int.max
} else {
  let rounded = Int(number.rounded())
}

How is using "<%=request.getContextPath()%>" better than "../"

request.getContextPath()- returns root path of your application, while ../ - returns parent directory of a file.

You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.

Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.

<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>

PS- This is the one reason I can figure out. Don't know if there is any more significance to it.

SQLAlchemy equivalent to SQL "LIKE" statement

Adding to the above answer, whoever looks for a solution, you can also try 'match' operator instead of 'like'. Do not want to be biased but it perfectly worked for me in Postgresql.

Note.query.filter(Note.message.match("%somestr%")).all()

It inherits database functions such as CONTAINS and MATCH. However, it is not available in SQLite.

For more info go Common Filter Operators

What does \0 stand for?

In C, \0 denotes a character with value zero. The following are identical:

char a = 0;
char b = '\0';

The utility of this escape sequence is greater inside string literals, which are arrays of characters:

char arr[] = "abc\0def\0ghi\0";

(Note that this array has two zero characters at the end, since string literals include a hidden, implicit terminal zero.)

How to create custom view programmatically in swift having controls text field, button etc

view = MyCustomView(frame: CGRectZero)

In this line you are trying to set empty rect for your custom view. That's why you cant see your view in simulator.

Create PostgreSQL ROLE (user) if it doesn't exist

Here is a generic solution using plpgsql:

CREATE OR REPLACE FUNCTION create_role_if_not_exists(rolename NAME) RETURNS TEXT AS
$$
BEGIN
    IF NOT EXISTS (SELECT * FROM pg_roles WHERE rolname = rolename) THEN
        EXECUTE format('CREATE ROLE %I', rolename);
        RETURN 'CREATE ROLE';
    ELSE
        RETURN format('ROLE ''%I'' ALREADY EXISTS', rolename);
    END IF;
END;
$$
LANGUAGE plpgsql;

Usage:

posgres=# SELECT create_role_if_not_exists('ri');
 create_role_if_not_exists 
---------------------------
 CREATE ROLE
(1 row)
posgres=# SELECT create_role_if_not_exists('ri');
 create_role_if_not_exists 
---------------------------
 ROLE 'ri' ALREADY EXISTS
(1 row)

Timestamp to human readable format

var newDate = new Date();
newDate.setTime(unixtime*1000);
dateString = newDate.toUTCString();

Where unixtime is the time returned by your sql db. Here is a fiddle if it helps.

For example, using it for the current time:

_x000D_
_x000D_
document.write( new Date().toUTCString() );
_x000D_
_x000D_
_x000D_

Update a column in MySQL

You have to use UPDATE instead of INSERT:

For Example:

UPDATE table1 SET col_a='k1', col_b='foo' WHERE key_col='1';
UPDATE table1 SET col_a='k2', col_b='bar' WHERE key_col='2';

SQL statement to get column type

Use this query to get Schema, Table, Column,Type, max_length, is_nullable

SELECT QUOTENAME(SCHEMA_NAME(tb.[schema_id])) AS 'Schema'
    ,QUOTENAME(OBJECT_NAME(tb.[OBJECT_ID])) AS 'Table'
    ,C.NAME as 'Column'
    ,T.name AS 'Type'
    ,C.max_length
    ,C.is_nullable
FROM SYS.COLUMNS C INNER JOIN SYS.TABLES tb ON tb.[object_id] = C.[object_id]
    INNER JOIN SYS.TYPES T ON C.system_type_id = T.user_type_id
WHERE tb.[is_ms_shipped] = 0
ORDER BY tb.[Name]

PHP: Split string into array, like explode with no delimiter

What are you trying to accomplish? You can access characters in a string just like an array:

$s = 'abcd';
echo $s[0];

prints 'a'

Changing Locale within the app itself

After a good night of sleep, I found the answer on the Web (a simple Google search on the following line "getBaseContext().getResources().updateConfiguration(mConfig, getBaseContext().getResources().getDisplayMetrics());"), here it is :

link text => this link also shows screenshots of what is happening !

Density was the issue here, I needed to have this in the AndroidManifest.xml

<supports-screens
android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:anyDensity="true"
/>

The most important is the android:anyDensity =" true ".

Don't forget to add the following in the AndroidManifest.xml for every activity (for Android 4.1 and below):

android:configChanges="locale"

This version is needed when you build for Android 4.2 (API level 17) explanation here:

android:configChanges="locale|layoutDirection"

Split / Explode a column of dictionaries into separate columns with pandas

>>> df

   Station ID                        Pollutants
0        8809  {"a": "46", "b": "3", "c": "12"}
1        8810   {"a": "36", "b": "5", "c": "8"}
2        8811              {"b": "2", "c": "7"}
3        8812                       {"c": "11"}
4        8813            {"a": "82", "c": "15"}

speed comparison for a large dataset of 10 million rows

>>> df = pd.concat([df]*100000).reset_index(drop=True)
>>> df = pd.concat([df]*20).reset_index(drop=True)
>>> print(df.shape)
(10000000, 2)
def apply_drop(df):
    return df.join(df['Pollutants'].apply(pd.Series)).drop('Pollutants', axis=1)  

def json_normalise_drop(df):
    return df.join(pd.json_normalize(df.Pollutants)).drop('Pollutants', axis=1)  

def tolist_drop(df):
    return df.join(pd.DataFrame(df['Pollutants'].tolist())).drop('Pollutants', axis=1)  

def vlues_tolist_drop(df):
    return df.join(pd.DataFrame(df['Pollutants'].values.tolist())).drop('Pollutants', axis=1)  

def pop_tolist(df):
    return df.join(pd.DataFrame(df.pop('Pollutants').tolist()))  

def pop_values_tolist(df):
    return df.join(pd.DataFrame(df.pop('Pollutants').values.tolist()))

>>> %timeit apply_drop(df.copy())
1 loop, best of 3: 53min 20s per loop
>>> %timeit json_normalise_drop(df.copy())
1 loop, best of 3: 54.9 s per loop
>>> %timeit tolist_drop(df.copy())
1 loop, best of 3: 6.62 s per loop
>>> %timeit vlues_tolist_drop(df.copy())
1 loop, best of 3: 6.63 s per loop
>>> %timeit pop_tolist(df.copy())
1 loop, best of 3: 5.99 s per loop
>>> %timeit pop_values_tolist(df.copy())
1 loop, best of 3: 5.94 s per loop
+---------------------+-----------+
| apply_drop          | 53min 20s |
| json_normalise_drop |    54.9 s |
| tolist_drop         |    6.62 s |
| vlues_tolist_drop   |    6.63 s |
| pop_tolist          |    5.99 s |
| pop_values_tolist   |    5.94 s |
+---------------------+-----------+

df.join(pd.DataFrame(df.pop('Pollutants').values.tolist())) is the fastest

Establish a VPN connection in cmd

Is Powershell an option?

Start Powershell:

powershell

Create the VPN Connection: Add-VpnConnection

Add-VpnConnection [-Name] <string> [-ServerAddress] <string> [-TunnelType <string> {Pptp | L2tp | Sstp | Ikev2 | Automatic}] [-EncryptionLevel <string> {NoEncryption | Optional | Required | Maximum}] [-AuthenticationMethod <string[]> {Pap | Chap | MSChapv2 | Eap}] [-SplitTunneling] [-AllUserConnection] [-L2tpPsk <string>] [-RememberCredential] [-UseWinlogonCredential] [-EapConfigXmlStream <xml>] [-Force] [-PassThru] [-WhatIf] [-Confirm] 

Edit VPN connections: Set-VpnConnection

Set-VpnConnection [-Name] <string> [[-ServerAddress] <string>] [-TunnelType <string> {Pptp | L2tp | Sstp | Ikev2 | Automatic}] [-EncryptionLevel <string> {NoEncryption | Optional | Required | Maximum}] [-AuthenticationMethod <string[]> {Pap | Chap | MSChapv2 | Eap}] [-SplitTunneling <bool>] [-AllUserConnection] [-L2tpPsk <string>] [-RememberCredential <bool>] [-UseWinlogonCredential <bool>] [-EapConfigXmlStream <xml>] [-PassThru] [-Force] [-WhatIf] [-Confirm]

Lookup VPN Connections: Get-VpnConnection

Get-VpnConnection [[-Name] <string[]>] [-AllUserConnection]

Connect: rasdial [connectionName]

rasdial connectionname [username [password | \]] [/domain:domain*] [/phone:phonenumber] [/callback:callbacknumber] [/phonebook:phonebookpath] [/prefixsuffix**]

You can manage your VPN connections with the powershell commands above, and simply use the connection name to connect via rasdial.

The results of Get-VpnConnection can be a little verbose. This can be simplified with a simple Select-Object filter:

Get-VpnConnection | Select-Object -Property Name

More information can be found here:

Query grants for a table in postgres

Here is a script which generates grant queries for a particular table. It omits owner's privileges.

SELECT 
    format (
      'GRANT %s ON TABLE %I.%I TO %I%s;',
      string_agg(tg.privilege_type, ', '),
      tg.table_schema,
      tg.table_name,
      tg.grantee,
      CASE
        WHEN tg.is_grantable = 'YES' 
        THEN ' WITH GRANT OPTION' 
        ELSE '' 
      END
    )
  FROM information_schema.role_table_grants tg
  JOIN pg_tables t ON t.schemaname = tg.table_schema AND t.tablename = tg.table_name
  WHERE
    tg.table_schema = 'myschema' AND
    tg.table_name='mytable' AND
    t.tableowner <> tg.grantee
  GROUP BY tg.table_schema, tg.table_name, tg.grantee, tg.is_grantable;

How to format background color using twitter bootstrap?

Move your row before <div class="container marketing"> and wrap it with a new container, because current container width is 1170px (not 100%):

<div class='hero'>
  <div class="row">
   ...
  </div>
</div>

CSS:

.hero {
  background-color: #2ba6cb;
  padding: 0 90px;
}

How do I count unique visitors to my site?

I have edited the "Best answer" code, though I found a useful thing that was missing. This is will also track the ip of a user if they are using a Proxy or simply if the server has nginx installed as a proxy reverser.

I added this code to his script at the top of the function:

function getRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
$adresseip = getRealIpAddr();

Afther that I edited his code.

Find the line that says the following:

// get the user name if it is logged, or the visitors IP (and add the identifier)

    $uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;

and replace it with this:

$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $adresseip. $vst_id;

This will work.

Here is the full code if anything happens:

<?php

function getRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
$adresseip = getRealIpAddr();

// Script Online Users and Visitors - http://coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start();        // start Session, if not already started

$filetxt = 'userson.txt';  // the file in which the online users /visitors are stored
$timeon = 120;             // number of secconds to keep a user online
$sep = '^^';               // characters used to separate the user name and date-time
$vst_id = '-vst-';        // an identifier to know that it is a visitor, not logged user

/*
 If you have an user registration script,
 replace $_SESSION['nume'] with the variable in which the user name is stored.
 You can get a free registration script from:  http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/

// get the user name if it is logged, or the visitors IP (and add the identifier)

    $uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;

$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i';         // regexp to recognize the line with visitors
$nrvst = 0;                                       // to store the number of visitors

// sets the row with the current user /visitor that must be added in $filetxt (and current timestamp)

    $addrow[] = $uvon. $sep. time();

// check if the file from $filetxt exists and is writable

    if(is_writable($filetxt)) {
      // get into an array the lines added in $filetxt
      $ar_rows = file($filetxt, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
      $nrrows = count($ar_rows);

            // number of rows

  // if there is at least one line, parse the $ar_rows array

      if($nrrows>0) {
        for($i=0; $i<$nrrows; $i++) {
          // get each line and separate the user /visitor and the timestamp
          $ar_line = explode($sep, $ar_rows[$i]);
      // add in $addrow array the records in last $timeon seconds
          if($ar_line[0]!=$uvon && (intval($ar_line[1])+$timeon)>=time()) {
            $addrow[] = $ar_rows[$i];
          }
        }
      }
    }

$nruvon = count($addrow);                   // total online
$usron = '';                                    // to store the name of logged users
// traverse $addrow to get the number of visitors and users
for($i=0; $i<$nruvon; $i++) {
 if(preg_match($rgxvst, $addrow[$i])) $nrvst++;       // increment the visitors
 else {
   // gets and stores the user's name
   $ar_usron = explode($sep, $addrow[$i]);
   $usron .= '<br/> - <i>'. $ar_usron[0]. '</i>';
 }
}
$nrusr = $nruvon - $nrvst;              // gets the users (total - visitors)

// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. $nruvon. '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';

// write data in $filetxt
if(!file_put_contents($filetxt, implode("\n", $addrow))) $reout = 'Error: Recording file not exists, or is not writable';

// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";

echo $reout;             // output /display the result

Haven't tested this on the Sql script yet.

How do I manage MongoDB connections in a Node.js web application?

Here is some code that will manage your MongoDB connections.

var MongoClient = require('mongodb').MongoClient;
var url = require("../config.json")["MongoDBURL"]

var option = {
  db:{
    numberOfRetries : 5
  },
  server: {
    auto_reconnect: true,
    poolSize : 40,
    socketOptions: {
        connectTimeoutMS: 500
    }
  },
  replSet: {},
  mongos: {}
};

function MongoPool(){}

var p_db;

function initPool(cb){
  MongoClient.connect(url, option, function(err, db) {
    if (err) throw err;

    p_db = db;
    if(cb && typeof(cb) == 'function')
        cb(p_db);
  });
  return MongoPool;
}

MongoPool.initPool = initPool;

function getInstance(cb){
  if(!p_db){
    initPool(cb)
  }
  else{
    if(cb && typeof(cb) == 'function')
      cb(p_db);
  }
}
MongoPool.getInstance = getInstance;

module.exports = MongoPool;

When you start the server, call initPool

require("mongo-pool").initPool();

Then in any other module you can do the following:

var MongoPool = require("mongo-pool");
MongoPool.getInstance(function (db){
    // Query your MongoDB database.
});

This is based on MongoDB documentation. Take a look at it.

ERROR 1044 (42000): Access denied for 'root' With All Privileges

The reason i could not delete some of the users via 'drop' statement was that there is a bug in Mysql http://bugs.mysql.com/bug.php?id=62255 with hostname containing upper case letters. The solution was running following query:

DELETE FROM mysql.user where host='Some_Host_With_UpperCase_Letters';

I am still trying to figure the other issue where the root user with all permissions are unable to grant privileges to new user for particular database

Jquery Ajax beforeSend and success,error & complete

It's actually much easier with jQuery's promise API:

$.ajax(
            type: "GET",
            url: requestURL,
        ).then((success) =>
            console.dir(success)
        ).failure((failureResponse) =>
            console.dir(failureResponse)
        )

Alternatively, you can pass in of bind functions to each result callback; the order of parameters is: (success, failure). So long as you specify a function with at least 1 parameter, you get access to the response. So, for example, if you wanted to check the response text, you could simply do:

$.ajax(
            type: "GET",
            url: @get("url") + "logout",
            beforeSend: (xhr) -> xhr.setRequestHeader("token", currentToken)
        ).failure((response) -> console.log "Request was unauthorized" if response.status is 401

TypeError: sequence item 0: expected string, int found

string.join connects elements inside list of strings, not ints.

Use this generator expression instead :

values = ','.join(str(v) for v in value_list)

How to replace a character with a newline in Emacs?

M-x replace-string RET ; RET C-q C-j.

  • C-q for quoted-insert,

  • C-j is a newline.

Cheers!

select count(*) from table of mysql in php

You need to alias the aggregate using the as keyword in order to call it from mysql_fetch_assoc

$result=mysql_query("SELECT count(*) as total from Students");
$data=mysql_fetch_assoc($result);
echo $data['total'];

How to write a basic swap function in Java

Snippet-1

public int[] swap1(int[] values) {
  if (values == null || values.length != 2)
    throw new IllegalArgumentException("parameter must be an array of size 2");
  int temp = values[0];
  values[0]=values[1];
  values[1]=temp;
  return values;
}

Snippet-2

public Point swap2(java.awt.Point p) {
  if (p == null)
    throw new NullPointerException();
  int temp = p.x;
  p.x = p.y;
  p.y = temp;
  return p;
}

Usage:

int[] values = swap1(new int[]{x,y});
x = values[0];
y = values[1];

Point p = swap2(new Point(x,y));
x = p.x;
y = p.y;

How to force composer to reinstall a library?

I didn't want to delete all the packages in vendor/ directory, so here is how I did it:

  1. rm -rf vendor/package-i-messed-up
  2. composer install again

Reading RFID with Android phones

A UHF RFID reader option for both Android and iOS is available from a company called U Grok It.

It is just UHF, which is "non-NFC enabled Android", if that's what you meant. My apologies if you meant an NFC reader for Android devices that don't have an NFC reader built-in.

Their reader has a range up to 7 meters (~21 feet). It connects via the audio port, not bluetooth, which has the advantage of pairing instantly, securely, and with way less of a power draw.

They have a free native SDK for Android, iOS, Cordova, and Xamarin, as well as an Android keyboard wedge.

How do I make an Event in the Usercontrol and have it handled in the Main Form?

You need to create an event handler for the user control that is raised when an event from within the user control is fired. This will allow you to bubble the event up the chain so you can handle the event from the form.

When clicking Button1 on the UserControl, i'll fire Button1_Click which triggers UserControl_ButtonClick on the form:

User control:

[Browsable(true)] [Category("Action")] 
[Description("Invoked when user clicks button")]
public event EventHandler ButtonClick;

protected void Button1_Click(object sender, EventArgs e)
{
    //bubble the event up to the parent
    if (this.ButtonClick!= null)
        this.ButtonClick(this, e);               
}

Form:

UserControl1.ButtonClick += new EventHandler(UserControl_ButtonClick);

protected void UserControl_ButtonClick(object sender, EventArgs e)
{
    //handle the event 
}

Notes:

  • Newer Visual Studio versions suggest that instead of if (this.ButtonClick!= null) this.ButtonClick(this, e); you can use ButtonClick?.Invoke(this, e);, which does essentially the same, but is shorter.

  • The Browsable attribute makes the event visible in Visual Studio's designer (events view), Category shows it in the "Action" category, and Description provides a description for it. You can omit these attributes completely, but making it available to the designer it is much more comfortable, since VS handles it for you.

Convert UTC datetime string to local datetime

If you want to get the correct result even for the time that corresponds to an ambiguous local time (e.g., during a DST transition) and/or the local utc offset is different at different times in your local time zone then use pytz timezones:

#!/usr/bin/env python
from datetime import datetime
import pytz    # $ pip install pytz
import tzlocal # $ pip install tzlocal

local_timezone = tzlocal.get_localzone() # get pytz tzinfo
utc_time = datetime.strptime("2011-01-21 02:37:21", "%Y-%m-%d %H:%M:%S")
local_time = utc_time.replace(tzinfo=pytz.utc).astimezone(local_timezone)

The default XML namespace of the project must be the MSBuild XML namespace

@DavidG's answer is correct, but I would like to add that if you're building from the command line, the equivalent solution is to make sure that you're using the appropriate version of msbuild (in this particular case, it needs to be version 15).

Run msbuild /? to see which version you're using or where msbuild to check which location the environment takes the executable from and update (or point to the right location of) the tools if necessary.

Download the latest MSBuild tool from here.

Invalid application path

The error message might be a bug. I ignored it and everything worked for me.

IIS Invalid Application Path Screen Shot

See Here: http://forums.iis.net/t/1177952.aspx

and here http://forums.iis.net/p/1182820/2000936.aspx

Batch files: How to read a file?

The FOR-LOOP generally works, but there are some issues. The FOR doesn't accept empty lines and lines with more than ~8190 are problematic. The expansion works only reliable, if the delayed expansion is disabled.

Detection of CR/LF versus single LF seems also a little bit complicated.
Also NUL characters are problematic, as a FOR-Loop immediatly cancels the reading.

Direct binary reading seems therefore nearly impossible.

The problem with empty lines can be solved with a trick. Prefix each line with a line number, using the findstr command, and after reading, remove the prefix.

@echo off
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ t.txt"`) do (
    set "var=%%a"
    SETLOCAL EnableDelayedExpansion
    set "var=!var:*:=!"
    echo(!var!
    ENDLOCAL
)

Toggling between enable and disabled delayed expansion is neccessary for the safe working with strings, like ! or ^^^xy!z.
That's because the line set "var=%%a" is only safe with DisabledDelayedExpansion, else exclamation marks are removed and the carets are used as (secondary) escape characters and they are removed too.
But using the variable var is only safe with EnabledDelayedExpansion, as even a call %%var%% will fail with content like "&"&.

EDIT: Added set/p variant
There is a second way of reading a file with set /p, the only disadvantages are that it is limited to ~1024 characters per line and it removes control characters at the line end.
But the advantage is, you didn't need the delayed toggling and it's easier to store values in variables

@echo off
setlocal EnableDelayedExpansion
set "file=%~1"

for /f "delims=" %%n in ('find /c /v "" %file%') do set "len=%%n"
set "len=!len:*: =!"

<%file% (
  for /l %%l in (1 1 !len!) do (
    set "line="
    set /p "line="
    echo(!line!
  )
)

For reading it "binary" into a hex-representation
You could look at SO: converting a binary file to HEX representation using batch file

A non well formed numeric value encountered

This helped me a lot -

$new_date = date_format(date_create($old_date), 'Y-m-d');

Here, date_create() provides you a date object for a given date & date_format() will set it in a given format.

for example,

<?php
    $date = date_create("13-02-2013");  // DateTime Object ( [date] => 2013-02-13 00:00:00.000000 [timezone_type] => 3 [timezone] => America/New_York )
    echo date_format($date,"Y-m-d");    // 2013-02-13
?>

How do you find the sum of all the numbers in an array in Java?

There are two things to learn from this exercise :

You need to iterate through the elements of the array somehow - you can do this with a for loop or a while loop. You need to store the result of the summation in an accumulator. For this, you need to create a variable.

int accumulator = 0;
for(int i = 0; i < myArray.length; i++) {
    accumulator += myArray[i];
}

Table with 100% width with equal size columns

table {
    width: 100%;

    th, td {
        width: 1%;
    }
}

SCSS syntax

How to remove the underline for anchors(links)?

The simplest option is this:

<a style="text-decoration: none">No underline</a>

Of course, mixing CSS with HTML (i.e. inline CSS) is not a good idea, especially when you are using a tags all over the place.
That's why it's a good idea to add this to a stylesheet instead:

a {
    text-decoration: none;
}

Or even this code in a JS file:

var els = document.getElementsByTagName('a');

for (var el = 0; el < els.length; el++) {
    els[el].style["text-decoration"] = "none";
}

Jquery post, response in new window

I did it with an ajax post and then returned using a data url:

$(document).ready(function () {
    var exportClick = function () {
        $.ajax({
           url: "/api/test.php",
           type: "POST",
           dataType: "text",
           data: {
              action: "getCSV",
              filter: "name = 'smith'",
           },
           success: function(data) {
              var w = window.open('data:text/csv;charset=utf-8,' + encodeURIComponent(data));
              w.focus();
           },
           error: function () {
              alert('Problem getting data');
           },
        });
    }
});

POST request via RestTemplate in JSON

For me error occurred with this setup:

AndroidAnnotations Spring Android RestTemplate Module and ...

GsonHttpMessageConverter

Android annotations has some problems with this converted to generate POST request without parameter. Simply parameter new Object() solved it for me.

Send values from one form to another form

I've worked on various winform projects and as the applications gets more complex (more dialogs and interactions between them) then i've started to use some eventing system to help me out, because management of opening and closing windows manually will be hard to maintain and develope further.

I've used CAB for my applications, it has an eventing system but it might be an overkill in your case :) You could write your own events for simpler applications

Print: Entry, ":CFBundleIdentifier", Does Not Exist

After a couple of months trying all the answers, I finally update my OS to Sierra, Update XCode to the latest version and with that all the errors disappear. Hope this could help some folks out there!

How to enable curl in Wamp server

Left Click on the WAMP icon the system try -> PHP -> PHP Extensions -> Enable php_curl

Least common multiple for 3 or more numbers

And the Scala version:

def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
def gcd(nums: Iterable[Int]): Int = nums.reduce(gcd)
def lcm(a: Int, b: Int): Int = if (a == 0 || b == 0) 0 else a * b / gcd(a, b)
def lcm(nums: Iterable[Int]): Int = nums.reduce(lcm)

How to declare an array of strings in C++?

You can concisely initialize a vector<string> from a statically-created char* array:

char* strarray[] = {"hey", "sup", "dogg"};
vector<string> strvector(strarray, strarray + 3);

This copies all the strings, by the way, so you use twice the memory. You can use Will Dean's suggestion to replace the magic number 3 here with arraysize(str_array) -- although I remember there being some special case in which that particular version of arraysize might do Something Bad (sorry I can't remember the details immediately). But it very often works correctly.

Also, if you're really gung-ho about the one line thingy, you can define a variadic macro so that a single line such as DEFINE_STR_VEC(strvector, "hi", "there", "everyone"); works.

How to use a dot "." to access members of dictionary?

I tried this:

class dotdict(dict):
    def __getattr__(self, name):
        return self[name]

you can try __getattribute__ too.

make every dict a type of dotdict would be good enough, if you want to init this from a multi-layer dict, try implement __init__ too.

Another Repeated column in mapping for entity error

The message is clear: you have a repeated column in the mapping. That means you mapped the same database column twice. And indeed, you have:

@Column(nullable=false)
private Long customerId;

and also:

@ManyToOne(optional=false)
@JoinColumn(name="customerId",referencedColumnName="id_customer")
private Customer customer;

(and the same goes for productId/product).

You shouldn't reference other entities by their ID, but by a direct reference to the entity. Remove the customerId field, it's useless. And do the same for productId. If you want the customer ID of a sale, you just need to do this:

sale.getCustomer().getId()

How to exclude a directory from ant fileset, based on directories contents

Here's an alternative, instead of adding an incomplete.flag file to every dir you want to exclude, generate a file that contains a listing of all the directories you want to exclude and then use the excludesfile attribute. Something like this:

<fileset dir="${basedir}" excludesfile="FileWithExcludedDirs.properties">
  <include name="locale/"/>
  <exclude name="locale/*/incomplete.flag">
</fileset>

Hope it helps.

Android: how to refresh ListView contents?

Update ListView's contents by below code:

private ListView listViewBuddy;
private BuddyAdapter mBuddyAdapter;
private ArrayList<BuddyModel> buddyList = new ArrayList<BuddyModel>();

onCreate():

listViewBuddy = (ListView)findViewById(R.id.listViewBuddy);
mBuddyAdapter = new BuddyAdapter();
listViewBuddy.setAdapter(mBuddyAdapter);

onDataGet (After webservice call or from local database or otherelse):

mBuddyAdapter.setData(buddyList);
mBuddyAdapter.notifyDataSetChanged();

BaseAdapter:

private class BuddyAdapter extends BaseAdapter { 

    private ArrayList<BuddyModel> mArrayList = new ArrayList<BuddyModel>();
    private LayoutInflater mLayoutInflater= (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    private ViewHolder holder;

    public void setData(ArrayList<BuddyModel> list){
        mArrayList = list;
    }

    @Override
    public int getCount() {
        return mArrayList.size();
    }

    @Override
    public BuddyModel getItem(int position) {
        return mArrayList.get(position);
    }

    @Override
    public long getItemId(int pos) {
        return pos;
    }

    private class ViewHolder {
        private TextView txtBuddyName, txtBuddyBadge;

    }
    @SuppressLint("InflateParams")
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mLayoutInflater.inflate(R.layout.row_buddy, null);
            // bind views
            holder.txtBuddyName = (TextView) convertView.findViewById(R.id.txtBuddyName);
            holder.txtBuddyBadge = (TextView) convertView.findViewById(R.id.txtBuddyBadge);

            // set tag
            convertView.setTag(holder);
        } else {
            // get tag
            holder = (ViewHolder) convertView.getTag();
        }

        holder.txtBuddyName.setText(mArrayList.get(position).getFriendId());

        int badge = mArrayList.get(position).getCount();
        if(badge!=0){
            holder.txtBuddyBadge.setVisibility(View.VISIBLE);
            holder.txtBuddyBadge.setText(""+badge);
        }else{
            holder.txtBuddyBadge.setVisibility(View.GONE);
        }   

        return convertView;
    }
}

Whenever you want to Update Listview just call below two lines code:

 mBuddyAdapter.setData(Your_Updated_ArrayList);
 mBuddyAdapter.notifyDataSetChanged();

Done

Touch move getting stuck Ignored attempt to cancel a touchmove

I know this is an old post but I had a lot of issues trying to solve this and I finally did so I wanted to share.

My issue was that I was adding an event listener within the ontouchstart and removing it in the ontouchend functions - something like this

function onTouchStart() {
  window.addEventListener("touchmove", handleTouchMove, {
    passive: false
  });
}

function onTouchEnd() {
  window.removeEventListener("touchmove", handleTouchMove, {
    passive: true
  });
}

function handleTouchMove(e) {
  e.preventDefault();
}

For some reason adding it removing it like this was causing this issue of the event randomly not being cancelable. So to solve this I kept the listener active and toggled a boolean on whether or not it should prevent the event - something like this:

let stopScrolling = false;

window.addEventListener("touchmove", handleTouchMove, {
  passive: false
});

function handleTouchMove(e) {
  if (!stopScrolling) {
    return;
  }
  e.preventDefault();
}

function onTouchStart() {
  stopScrolling = true;
}

function onTouchEnd() {
  stopScrolling = false;
}

I was actually using React so my solution involved setting state, but I've simplified it for a more generic solution. Hopefully this helps someone!

Safely remove migration In Laravel

You likely need to delete the entry from the migrations table too.

Timer function to provide time in nano seconds using C++

Using Brock Adams's method, with a simple class:

int get_cpu_ticks()
{
    LARGE_INTEGER ticks;
    QueryPerformanceFrequency(&ticks);
    return ticks.LowPart;
}

__int64 get_cpu_clocks()
{
    struct { int32 low, high; } counter;

    __asm cpuid
    __asm push EDX
    __asm rdtsc
    __asm mov counter.low, EAX
    __asm mov counter.high, EDX
    __asm pop EDX
    __asm pop EAX

    return *(__int64 *)(&counter);
}

class cbench
{
public:
    cbench(const char *desc_in) 
         : desc(strdup(desc_in)), start(get_cpu_clocks()) { }
    ~cbench()
    {
        printf("%s took: %.4f ms\n", desc, (float)(get_cpu_clocks()-start)/get_cpu_ticks());
        if(desc) free(desc);
    }
private:
    char *desc;
    __int64 start;
};

Usage Example:

int main()
{
    {
        cbench c("test");
        ... code ...
    }
    return 0;
}

Result:

test took: 0.0002 ms

Has some function call overhead, but should be still more than fast enough :)

Get current batchfile directory

Here's what I use at the top of all my batch files. I just copy/paste from my template folder.

@echo off
:: --HAS ENDING BACKSLASH
set batdir=%~dp0
:: --MISSING ENDING BACKSLASH
:: set batdir=%CD%
pushd "%batdir%"

Setting current batch file's path to %batdir% allows you to call it in subsequent stmts in current batch file, regardless of where this batch file changes to. Using PUSHD allows you to use POPD to quickly set this batch file's path to original %batdir%. Remember, if using %batdir%ExtraDir or %batdir%\ExtraDir (depending on which version used above, ending backslash or not) you will need to enclose the entire string in double quotes if path has spaces (i.e. "%batdir%ExtraDir"). You can always use PUSHD %~dp0. [https: // ss64.com/ nt/ syntax-args .html] has more on (%~) parameters.

Note that using (::) at beginning of a line makes it a comment line. More importantly, using :: allows you to include redirectors, pipes, special chars (i.e. < > | etc) in that comment.

:: ORIG STMT WAS: dir *.* | find /v "1917" > outfile.txt

Of course, Powershell does this and lots more.

How to store standard error in a variable

This post helped me come up with a similar solution for my own purposes:

MESSAGE=`{ echo $ERROR_MESSAGE | format_logs.py --level=ERROR; } 2>&1`

Then as long as our MESSAGE is not an empty string, we pass it on to other stuff. This will let us know if our format_logs.py failed with some kind of python exception.

What is difference between png8 and png24

The main difference is that a 8-bit PNG comprises a max. of 256 colours, like GIFs. PNG-24 is a lossless format and can contain up to 16 million colours.

Can an Android Toast be longer than Toast.LENGTH_LONG?

This text will disappear in 5 seconds.

    final Toast toast = Toast.makeText(getApplicationContext(), "My Text", Toast.LENGTH_SHORT);
    toast.show();

    Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
           @Override
           public void run() {
               toast.cancel(); 
           }
    }, 5000); // Change to what you want

Edit: As Itai Spector in comment said it will be shown about 3.5 seconds, So use this code:

    int toastDuration = 5000; // in MilliSeconds
    Toast mToast = Toast.makeText(this, "My text", Toast.LENGTH_LONG);
    CountDownTimer countDownTimer;
    countDownTimer = new CountDownTimer(toastDuration, 1000) {
        public void onTick(long millisUntilFinished) {
            mToast.show();
        }

        public void onFinish() {
            mToast.cancel();
        }
    };

    mToast.show();
    countDownTimer.start();

Combining two expressions (Expression<Func<T, bool>>)

If you provider does not support Invoke and you need to combine two expression, you can use an ExpressionVisitor to replace the parameter in the second expression by the parameter in the first expression.

class ParameterUpdateVisitor : ExpressionVisitor
{
    private ParameterExpression _oldParameter;
    private ParameterExpression _newParameter;

    public ParameterUpdateVisitor(ParameterExpression oldParameter, ParameterExpression newParameter)
    {
        _oldParameter = oldParameter;
        _newParameter = newParameter;
    }

    protected override Expression VisitParameter(ParameterExpression node)
    {
        if (object.ReferenceEquals(node, _oldParameter))
            return _newParameter;

        return base.VisitParameter(node);
    }
}

static Expression<Func<T, bool>> UpdateParameter<T>(
    Expression<Func<T, bool>> expr,
    ParameterExpression newParameter)
{
    var visitor = new ParameterUpdateVisitor(expr.Parameters[0], newParameter);
    var body = visitor.Visit(expr.Body);

    return Expression.Lambda<Func<T, bool>>(body, newParameter);
}

[TestMethod]
public void ExpressionText()
{
    string text = "test";

    Expression<Func<Coco, bool>> expr1 = p => p.Item1.Contains(text);
    Expression<Func<Coco, bool>> expr2 = q => q.Item2.Contains(text);
    Expression<Func<Coco, bool>> expr3 = UpdateParameter(expr2, expr1.Parameters[0]);

    var expr4 = Expression.Lambda<Func<Recording, bool>>(
        Expression.OrElse(expr1.Body, expr3.Body), expr1.Parameters[0]);

    var func = expr4.Compile();

    Assert.IsTrue(func(new Coco { Item1 = "caca", Item2 = "test pipi" }));
}

TypeError: module.__init__() takes at most 2 arguments (3 given)

You may also do the following in Python 3.6.1

from Object import Object as Parent

and your class definition to:

class Visitor(Parent):

Vue 'export default' vs 'new Vue'

The first case (export default {...}) is ES2015 syntax for making some object definition available for use.

The second case (new Vue (...)) is standard syntax for instantiating an object that has been defined.

The first will be used in JS to bootstrap Vue, while either can be used to build up components and templates.

See https://vuejs.org/v2/guide/components-registration.html for more details.

Uncaught TypeError: Cannot read property 'value' of null

I am unsure which of them is wrong because you did not provide your HTML, but one of these does not exist:

var str = document.getElementById("cal_preview").value;
var str1 = document.getElementById("year").value;
var str2 = document.getElementById("holiday").value;
var str3 = document.getElementById("cal_option").value;

There is either no element with the id cal_preview, year, holiday, cal_option, or some combination.

Therefore, JavaScript is unable to read the value of something that does not exist.

EDIT:

If you want to check that the element exists first, you could use an if statement for each:

var str,
element = document.getElementById('cal_preview');
if (element != null) {
    str = element.value;
}
else {
    str = null;
}

You could obviously change the else statement if you want or have no else statement at all, but that is all about preference.

Converting dict to OrderedDict

Use dict.items(); it can be as simple as following:

ship = collections.OrderedDict(ship.items())

Using multiple delimiters in awk

Another one is to use the -F option but pass it regex to print the text between left and or right parenthesis ().

The file content:

528(smbw)
529(smbt)
530(smbn)
10115(smbs)

The command:

awk -F"[()]" '{print $2}' filename

result:

smbw
smbt
smbn
smbs

Using awk to just print the text between []:

Use awk -F'[][]' but awk -F'[[]]' will not work.

http://stanlo45.blogspot.com/2020/06/awk-multiple-field-separators.html

How (and why) to use display: table-cell (CSS)

It's even easier to use parent > child selector relationship so the inner div do not need to have their css classes to be defined explicitly:

_x000D_
_x000D_
.display-table {_x000D_
    display: table; _x000D_
}_x000D_
.display-table > div { _x000D_
    display: table-row; _x000D_
}_x000D_
.display-table > div > div { _x000D_
    display: table-cell;_x000D_
    padding: 5px;_x000D_
}
_x000D_
<div class="display-table">_x000D_
    <div>_x000D_
        <div>0, 0</div>_x000D_
        <div>0, 1</div>_x000D_
    </div>_x000D_
    <div>_x000D_
        <div>1, 0</div>_x000D_
        <div>1, 1</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Rownum in postgresql

Postgresql > 8.4

SELECT 
    row_number() OVER (ORDER BY col1) AS i, 
    e.col1, 
    e.col2, 
    ... 
FROM ... 

Getting a machine's external IP address with Python

Here's another alternative script.

def track_ip():
   """
   Returns Dict with the following keys:
   - ip
   - latlong
   - country
   - city
   - user-agent
   """

   conn = httplib.HTTPConnection("www.trackip.net")
   conn.request("GET", "/ip?json")
   resp = conn.getresponse()
   print resp.status, resp.reason

   if resp.status == 200:
       ip = json.loads(resp.read())
   else:
       print 'Connection Error: %s' % resp.reason

   conn.close()
   return ip

EDIT: Don't forget to import httplib and json

Getting or changing CSS class property with Javascript using DOM style

Nice. Thank you. Worked For Me.

Not sure why you loaded jQuery though. It's not used. Some of us still use dial up modems and satellite with bandwidth limitations. Less is more betterer.

<script>
        function showAnswers(){
          var cols = document.getElementsByClassName('Answer');
          for(i=0; i<cols.length; i++) {
            cols[i].style.backgroundColor = 'lime';
            cols[i].style.width = '50%';
            cols[i].style.borderRadius = '6px';         
            cols[i].style.padding = '10px';
            cols[i].style.border = '1px green solid';
            }
        }
        function hideAnswers(){
          var cols = document.getElementsByClassName('Answer');
          for(i=0; i<cols.length; i++) {
            cols[i].style.backgroundColor = 'transparent';
            cols[i].style.width = 'inheret';
            cols[i].style.borderRadius = '0';
            cols[i].style.padding = '0';
            cols[i].style.border = 'none';          
          }
        }
    </script>

MVC [HttpPost/HttpGet] for Action

Let's say you have a Login action which provides the user with a login screen, then receives the user name and password back after the user submits the form:

public ActionResult Login() {
    return View();
}

public ActionResult Login(string userName, string password) {
    // do login stuff
    return View();
}

MVC isn't being given clear instructions on which action is which, even though we can tell by looking at it. If you add [HttpGet] to the first action and [HttpPost] to the section action, MVC clearly knows which action is which.

Why? See Request Methods. Long and short: When a user views a page, that's a GET request and when a user submits a form, that's usually a POST request. HttpGet and HttpPost just restrict the action to the applicable request type.

[HttpGet]
public ActionResult Login() {
    return View();
}

[HttpPost]
public ActionResult Login(string userName, string password) {
    // do login stuff
    return View();
}

You can also combine the request method attributes if your action serves requests from multiple verbs:

[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)].

Node.js console.log() not logging anything

This can be confusing for anyone using nodejs for the first time. It is actually possible to pipe your node console output to the browser console. Take a look at connect-browser-logger on github

UPDATE: As pointed out by Yan, connect-browser-logger appears to be defunct. I would recommend NodeMonkey as detailed here : Output to Chrome console from Node.js

Call int() function on every list element?

In Python 2.x another approach is to use map:

numbers = map(int, numbers)

Note: in Python 3.x map returns a map object which you can convert to a list if you want:

numbers = list(map(int, numbers))

How can I sort a std::map first by value, then by key?

std::map will sort its elements by keys. It doesn't care about the values when sorting.

You can use std::vector<std::pair<K,V>> then sort it using std::sort followed by std::stable_sort:

std::vector<std::pair<K,V>> items;

//fill items

//sort by value using std::sort
std::sort(items.begin(), items.end(), value_comparer);

//sort by key using std::stable_sort
std::stable_sort(items.begin(), items.end(), key_comparer);

The first sort should use std::sort since it is nlog(n), and then use std::stable_sort which is n(log(n))^2 in the worst case.

Note that while std::sort is chosen for performance reason, std::stable_sort is needed for correct ordering, as you want the order-by-value to be preserved.


@gsf noted in the comment, you could use only std::sort if you choose a comparer which compares values first, and IF they're equal, sort the keys.

auto cmp = [](std::pair<K,V> const & a, std::pair<K,V> const & b) 
{ 
     return a.second != b.second?  a.second < b.second : a.first < b.first;
};
std::sort(items.begin(), items.end(), cmp);

That should be efficient.

But wait, there is a better approach: store std::pair<V,K> instead of std::pair<K,V> and then you don't need any comparer at all — the standard comparer for std::pair would be enough, as it compares first (which is V) first then second which is K:

std::vector<std::pair<V,K>> items;
//...
std::sort(items.begin(), items.end());

That should work great.

Can we overload the main method in Java?

This is perfectly legal:

public static void main(String[] args) {

}

public static void main(String argv) {
    System.out.println("hello");
}

Detect when input has a 'readonly' attribute

Check the current value of your "readonly" attribute, if it's "false" (a string) or empty (undefined or "") then it's not readonly.

$('input').each(function() {
    var readonly = $(this).attr("readonly");
    if(readonly && readonly.toLowerCase()!=='false') { // this is readonly
        alert('this is a read only field');
    }
});

Compiler warning - suggest parentheses around assignment used as truth value

It's just a 'safety' warning. It is a relatively common idiom, but also a relatively common error when you meant to have == in there. You can make the warning go away by adding another set of parentheses:

while ((list = list->next))

How to grep and replace

Be very careful when using find and sed in a git repo! If you don't exclude the binary files you can end up with this error:

error: bad index file sha1 signature 
fatal: index file corrupt

To solve this error you need to revert the sed by replacing your new_string with your old_string. This will revert your replaced strings, so you will be back to the beginning of the problem.

The correct way to search for a string and replace it is to skip find and use grep instead in order to ignore the binary files:

sed -ri -e "s/old_string/new_string/g" $(grep -Elr --binary-files=without-match "old_string" "/files_dir")

Credits for @hobs

Remove rows with all or some NAs (missing values) in data.frame

tidyr has a new function drop_na:

library(tidyr)
df %>% drop_na()
#              gene hsap mmul mmus rnor cfam
# 2 ENSG00000199674    0    2    2    2    2
# 6 ENSG00000221312    0    1    2    3    2
df %>% drop_na(rnor, cfam)
#              gene hsap mmul mmus rnor cfam
# 2 ENSG00000199674    0    2    2    2    2
# 4 ENSG00000207604    0   NA   NA    1    2
# 6 ENSG00000221312    0    1    2    3    2

How to resize images proportionally / keeping the aspect ratio?

Resize to fit the container, get scale factor, scale down percentage control

_x000D_
_x000D_
 $(function () {
            let ParentHeight = 200;
            let ParentWidth = 300;
            $("#Parent").width(ParentWidth).height(ParentHeight);
            $("#ParentHeight").html(ParentHeight);
            $("#ParentWidth").html(ParentWidth);

            var RatioOfParent = ParentHeight / ParentWidth;
            $("#ParentAspectRatio").html(RatioOfParent);

            let ChildHeight = 2000;
            let ChildWidth = 4000;
            var RatioOfChild = ChildHeight / ChildWidth;
            $("#ChildAspectRatio").html(RatioOfChild);

            let ScaleHeight = ParentHeight / ChildHeight;
            let ScaleWidth = ParentWidth / ChildWidth;
            let Scale = Math.min(ScaleHeight, ScaleWidth);

            $("#ScaleFactor").html(Scale);
            // old scale
            //ChildHeight = ChildHeight * Scale;
            //ChildWidth = ChildWidth * Scale;

            // reduce scale by 10%, you can change the percentage
            let ScaleDownPercentage = 10;
            let CalculatedScaleValue = Scale * (ScaleDownPercentage / 100);
            $("#CalculatedScaleValue").html(CalculatedScaleValue);

            // new scale
            let NewScale = (Scale - CalculatedScaleValue);
            ChildHeight = ChildHeight * NewScale;
            ChildWidth = ChildWidth * NewScale;

            $("#Child").width(ChildWidth).height(ChildHeight);
            $("#ChildHeight").html(ChildHeight);
            $("#ChildWidth").html(ChildWidth);

        });
_x000D_
        #Parent {
            background-color: grey;
        }

        #Child {
            background-color: red;
        }
 
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Parent">
    <div id="Child"></div>
</div>

<table>
    <tr>
        <td>Parent Aspect Ratio</td>
        <td id="ParentAspectRatio"></td>
    </tr>
    <tr>
        <td>Child Aspect Ratio</td>
        <td id="ChildAspectRatio"></td>
    </tr>
    <tr>
        <td>Scale Factor</td>
        <td id="ScaleFactor"></td>
    </tr>
    <tr>
        <td>Calculated Scale Value</td>
        <td id="CalculatedScaleValue"></td>
    </tr>
    <tr>
        <td>Parent Height</td>
        <td id="ParentHeight"></td>
    </tr>
    <tr>
        <td>Parent Width</td>
        <td id="ParentWidth"></td>
    </tr>
    <tr>
        <td>Child Height</td>
        <td id="ChildHeight"></td>
    </tr>
    <tr>
        <td>Child Width</td>
        <td id="ChildWidth"></td>
    </tr>
</table>
_x000D_
_x000D_
_x000D_

How do I get the current time only in JavaScript

Assign to variables and display it.

time = new Date();

var hh = time.getHours();
var mm = time.getMinutes();
var ss = time.getSeconds() 

document.getElementById("time").value = hh + ":" + mm + ":" + ss;

How can I make a HTML a href hyperlink open a new window?

<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>

Easy as that.

Or without JS

<a href="http://yahoo.com" target="_blank">test</a>

Downloading a picture via urllib and python

Python 3 version of @DiGMi's answer:

from urllib import request
f = open('00000001.jpg', 'wb')
f.write(request.urlopen("http://www.gunnerkrigg.com/comics/00000001.jpg").read())
f.close()

How to terminate a python subprocess launched with shell=True

I know this is an old question but this may help someone looking for a different method. This is what I use on windows to kill processes that I've called.

si = subprocess.STARTUPINFO()
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
subprocess.call(["taskkill", "/IM", "robocopy.exe", "/T", "/F"], startupinfo=si)

/IM is the image name, you can also do /PID if you want. /T kills the process as well as the child processes. /F force terminates it. si, as I have it set, is how you do this without showing a CMD window. This code is used in python 3.

Retrieving Property name from lambda expression

I created an extension method on ObjectStateEntry to be able to flag properties (of Entity Framework POCO classes) as modified in a type safe manner, since the default method only accepts a string. Here's my way of getting the name from the property:

public static void SetModifiedProperty<T>(this System.Data.Objects.ObjectStateEntry state, Expression<Func<T>> action)
{
    var body = (MemberExpression)action.Body;
    string propertyName = body.Member.Name;

    state.SetModifiedProperty(propertyName);
}

Check if an element is present in a Bash array

If array elements don't contain spaces, another (perhaps more readable) solution would be:

if echo ${arr[@]} | grep -q -w "d"; then 
    echo "is in array"
else 
    echo "is not in array"
fi

How to create a date object from string in javascript

var d = new Date(2011,10,30);

as months are indexed from 0 in js.

HTTP Error 404.3-Not Found in IIS 7.5

I was having trouble accessing wcf service hosted locally in IIS. Running aspnet_regiis.exe -i wasn't working.

However, I fortunately came across the following:

Rahul's blog

which informs that servicemodelreg also needs to be run:

Run Visual Studio 2008 Command Prompt as “Administrator”. Navigate to C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation. Run this command servicemodelreg –i.

Run batch file from Java code

Following is worked for me

File dir = new File("E:\\test");
        ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "Start","test.bat");
        pb.directory(dir);
        Process p = pb.start();

How can I get CMake to find my alternative Boost installation?

While configure could find my Boost installation, CMake could not.

Locate FindBoost.cmake and look for LIBRARY_HINTS to see what sub-packages it is looking for. In my case it wanted the MPI and graph libraries.

 # Compute component-specific hints.
  set(_Boost_FIND_LIBRARY_HINTS_FOR_COMPONENT "")
  if(${COMPONENT} STREQUAL "mpi" OR ${COMPONENT} STREQUAL "mpi_python" OR
     ${COMPONENT} STREQUAL "graph_parallel")
    foreach(lib ${MPI_CXX_LIBRARIES} ${MPI_C_LIBRARIES})
      if(IS_ABSOLUTE "${lib}")
        get_filename_component(libdir "${lib}" PATH)
        string(REPLACE "\\" "/" libdir "${libdir}")
        list(APPEND _Boost_FIND_LIBRARY_HINTS_FOR_COMPONENT ${libdir})
      endif()
    endforeach()
  endif()

apt-cache search ... I installed the dev packages since I was building code, and the dev package drags in all the dependencies. I'm not so sure that a standard Boost install needs Open MPI, but this is OK for now.

sudo apt-get install libboost-mpi-dev libboost-mpi-python-dev
sudo apt-get install libboost-graph-parallel-dev

How to generate the JPA entity Metamodel?

Ok, based on what I have read here, I did it with EclipseLink this way and I did not need to put the processor dependency to the project, only as an annotationProcessorPath element of the compiler plugin.

    <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <annotationProcessorPaths>
                <annotationProcessorPath>
                    <groupId>org.eclipse.persistence</groupId>
                    <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
                    <version>2.7.7</version>
                </annotationProcessorPath>
            </annotationProcessorPaths>
            <compilerArgs>
                <arg>-Aeclipselink.persistencexml=src/main/resources/META-INF/persistence.xml</arg>
            </compilerArgs>
        </configuration>
    </plugin>

HTML Tags in Javascript Alert() method

You can add HTML into an alert string, but it will not render as HTML. It will just be displayed as a plain string. Simple answer: no.

How to find which version of Oracle is installed on a Linux server (In terminal)

A bit manual searching but its an alternative way...
Find the Oracle home or where the installation files for Oracle is installed on your linux server.

cd / <-- Goto root directory
find . -print| grep -i dbm*.sql

Result varies on how you installed Oracle but mine displays this

/db/oracle

Goto the folder

less /db/oracle/db1/sqlplus/doc/README.htm

scroll down and you should see something like this

SQL*Plus Release Notes - Release 11.2.0.2

stringstream, string, and char* conversion confusion

The std::string object returned by ss.str() is a temporary object that will have a life time limited to the expression. So you cannot assign a pointer to a temporary object without getting trash.

Now, there is one exception: if you use a const reference to get the temporary object, it is legal to use it for a wider life time. For example you should do:

#include <string>
#include <sstream>
#include <iostream>

using namespace std;

int main()
{
    stringstream ss("this is a string\n");

    string str(ss.str());

    const char* cstr1 = str.c_str();

    const std::string& resultstr = ss.str();
    const char* cstr2 = resultstr.c_str();

    cout << cstr1       // Prints correctly
        << cstr2;       // No more error : cstr2 points to resultstr memory that is still alive as we used the const reference to keep it for a time.

    system("PAUSE");

    return 0;
}

That way you get the string for a longer time.

Now, you have to know that there is a kind of optimisation called RVO that say that if the compiler see an initialization via a function call and that function return a temporary, it will not do the copy but just make the assigned value be the temporary. That way you don't need to actually use a reference, it's only if you want to be sure that it will not copy that it's necessary. So doing:

 std::string resultstr = ss.str();
 const char* cstr2 = resultstr.c_str();

would be better and simpler.

Function to return only alpha-numeric characters from string?

Rather than preg_replace, you could always use PHP's filter functions using the filter_var() function with FILTER_SANITIZE_STRING.

How do I collapse sections of code in Visual Studio Code for Windows?

The default shortcut for collapse/extend are:

Ctrl + Shift + [ : "Fold"

Ctrl + Shift + Alt + [ : "Fold all"

Ctrl + Shift + ] : "Unfold"

Ctrl + Shift + Alt + ] : "Unfold all"

Or go to keybindings.json and change as you wish.

For example:

{
    "key": "cmd+k cmd+m",
    "command": "editor.foldAll",
    "when": "editorFocus"
},
{
    "key": "cmd+m cmd+k",
    "command": "editor.unfoldAll",
    "when": "editorFocus"
},

Reload .profile in bash shell script (in unix)?

The bash script runs in a separate subshell. In order to make this work you will need to source this other script as well.

Difference between binary semaphore and mutex

Their synchronization semantics are very different:

  • mutexes allow serialization of access to a given resource i.e. multiple threads wait for a lock, one at a time and as previously said, the thread owns the lock until it is done: only this particular thread can unlock it.
  • a binary semaphore is a counter with value 0 and 1: a task blocking on it until any task does a sem_post. The semaphore advertises that a resource is available, and it provides the mechanism to wait until it is signaled as being available.

As such one can see a mutex as a token passed from task to tasks and a semaphore as traffic red-light (it signals someone that it can proceed).

Finding index of character in Swift String

Swift 5

Find index of substring

let str = "abcdecd"
if let range: Range<String.Index> = str.range(of: "cd") {
    let index: Int = str.distance(from: str.startIndex, to: range.lowerBound)
    print("index: ", index) //index: 2
}
else {
    print("substring not found")
}

Find index of Character

let str = "abcdecd"
if let firstIndex = str.firstIndex(of: "c") {
    let index: Int = str.distance(from: str.startIndex, to: firstIndex)
    print("index: ", index)   //index: 2
}
else {
    print("symbol not found")
}

When is it appropriate to use C# partial classes?

If you have a sufficiently large class that doesn't lend itself to effective refactoring, separating it into multiple files helps keep things organized.

For instance, if you have a database for a site containing a discussion forum and a products system, and you don't want to create two different providers classes (NOT the same thing as a proxy class, just to be clear), you can create a single partial class in different files, like

MyProvider.cs - core logic

MyProvider.Forum.cs - methods pertaining specifically to the forum

MyProvider.Product.cs - methods for products

It's just another way to keep things organized.

Also, as others have said, it's about the only way to add methods to a generated class without running the risk of having your additions destroyed the next time the class is regenerated. This comes in handy with template-generated (T4) code, ORMs, etc.

In Perl, what is the difference between a .pm (Perl module) and .pl (Perl script) file?

At the very core, the file extension you use makes no difference as to how perl interprets those files.

However, putting modules in .pm files following a certain directory structure that follows the package name provides a convenience. So, if you have a module Example::Plot::FourD and you put it in a directory Example/Plot/FourD.pm in a path in your @INC, then use and require will do the right thing when given the package name as in use Example::Plot::FourD.

The file must return true as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with 1; unless you're sure it'll return true otherwise. But it's better just to put the 1;, in case you add more statements.

If EXPR is a bareword, the require assumes a ".pm" extension and replaces "::" with "/" in the filename for you, to make it easy to load standard modules. This form of loading of modules does not risk altering your namespace.

All use does is to figure out the filename from the package name provided, require it in a BEGIN block and invoke import on the package. There is nothing preventing you from not using use but taking those steps manually.

For example, below I put the Example::Plot::FourD package in a file called t.pl, loaded it in a script in file s.pl.

C:\Temp> cat t.pl
package Example::Plot::FourD;

use strict; use warnings;

sub new { bless {} => shift }

sub something { print "something\n" }

"Example::Plot::FourD"

C:\Temp> cat s.pl
#!/usr/bin/perl
use strict; use warnings;

BEGIN {
    require 't.pl';
}

my $p = Example::Plot::FourD->new;
$p->something;


C:\Temp> s
something

This example shows that module files do not have to end in 1, any true value will do.

Why do people hate SQL cursors so much?

The answers above have not emphasized enough the importance of locking. I'm not a big fan of cursors because they often result in table level locks.

How to analyze information from a Java core dump?

Actually, VisualVM can process application core dump.

Just invoke "File/Add VM Coredump" and will add a new application in the application explorer. You can then take thread dump or heap dump of that JVM.

Run php function on button click

You are trying to call a javascript function. If you want to call a PHP function, you have to use for example a form:

    <form action="action_page.php">
       First name:<br>
       <input type="text" name="firstname" value="Mickey">
       <br>
       Last name:<br>
       <input type="text" name="lastname" value="Mouse">
       <br><br>
       <input type="submit" value="Submit">
     </form> 

(Original Code from: http://www.w3schools.com/html/html_forms.asp)

So if you want do do a asynchron call, you could use 'Ajax' - and yeah, that's the Javascript-Way. But I think, that my code example is enough for this time :)

zsh compinit: insecure directories

Most answers come with a solution, but do not mention why this warning occurs. Here's an excerpt from ZSH's compinit:

For security reasons compinit also checks if the completion system would use files not owned by root or by the current user, or files in directories that are world- or group-writable or that are not owned by root or by the current user. If such files or directories are found, compinit will ask if the completion system should really be used. To avoid these tests and make all files found be used without asking, use the option -u, and to make compinit silently ignore all insecure files and directories use the option -i. This security check is skipped entirely when the -C option is given.

Hence, the solution implies fixing one (or all) of the following:

  • setting the current user as the owner of all the directories/subdirectories/files in cause:

    compaudit | xargs chown -R "$(whoami)"
    
  • removing write permissions for group/others for the files in cause:

    compaudit | xargs chmod go-w
    

Another approach would be to skip these checks by using

compinit -u

but I don't really suggest this, as hiding problems under a rug only solves problems in the short run.

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/

Align two inline-blocks left and right on same line

For both elements use

display: inline-block;

the for the 'nav' element use

float: right;

what does -zxvf mean in tar -zxvf <filename>?

  • z means (un)z_ip.
  • x means ex_tract files from the archive.
  • v means print the filenames v_erbosely.
  • f means the following argument is a f_ilename.

For more details, see tar's man page.

MySQL Trigger - Storing a SELECT in a variable

Or you can just include the SELECT statement in the SQL that's invoking the trigger, so its passed in as one of the columns in the trigger row(s). As long as you're certain it will infallibly return only one row (hence one value). (And, of course, it must not return a value that interacts with the logic in the trigger, but that's true in any case.)

How can I disable a button in a jQuery dialog from a function?

I found an easy way to disable (or perform any other action) on a dialog button.

    var dialog_selector = "#myDialogId";

    $(dialog_selector).parent().find("button").each(function() {
        if( $(this).text() == 'Bin Comment' ) {
            $(this).attr('disabled', true);
        }
    });

You simply select the parent of your dialog and find all buttons. Then checking the Text of your button, you can identify your buttons.

Stacked bar chart

Building on Roland's answer, using tidyr to reshape the data from wide to long:

library(tidyr)
library(ggplot2)

df <- read.table(text="Rank F1     F2     F3
1    500    250    50
2    400    100    30
3    300    155    100
4    200    90     10", header=TRUE)

df %>% 
  gather(variable, value, F1:F3) %>% 
  ggplot(aes(x = Rank, y = value, fill = variable)) + 
  geom_bar(stat = "identity")

enter image description here

Specify an SSH key for git push for a given domain

One Unix based systems (Linux, BSD, Mac OS X), the default identity is stored in the directory $HOME/.ssh, in 2 files: private key: $HOME/.ssh/id_rsa public key: $HOME/.ssh/id_rsa.pub When you use ssh without option -i, it uses the default private key to authenticate with remote system.

If you have another private key you want to use, for example $HOME/.ssh/deploy_key, you have to use ssh -i ~/.ssh/deploy_key ...

It is annoying. You can add the following lines in to your $HOME/.bash_profile : ssh-add ~/.ssh/deploy_key ssh-add ~/.ssh/id_rsa

So each time you use ssh or git or scp (basically ssh too), you don't have to use option -i anymore.

You can add as many keys as you like in the file $HOME/.bash_profile.

Casting a variable using a Type variable

If you need to cast objects at runtime without knowing destination type, you can use reflection to make a dynamic converter.

This is a simplified version (without caching generated method):

    public static class Tool
    {
            public static object CastTo<T>(object value) where T : class
            {
                return value as T;
            }

            private static readonly MethodInfo CastToInfo = typeof (Tool).GetMethod("CastTo");

            public static object DynamicCast(object source, Type targetType)
            {
                return CastToInfo.MakeGenericMethod(new[] { targetType }).Invoke(null, new[] { source });
            }
    }

then you can call it:

    var r = Tool.DynamicCast(myinstance, typeof (MyClass));

Changing java platform on which netbeans runs

In my Windows 7 box I found netbeans.conf in <Drive>:\<Program Files folder>\<NetBeans installation folder>\etc . Thanks all.

Using ZXing to create an Android barcode scanning app

If you want to include into your code and not use the IntentIntegrator that the ZXing library recommend, you can use some of these ports:

I use the first, and it works perfectly! It has a sample project to try it on.

Convert String to double in Java

Use new BigDecimal(string). This will guarantee proper calculation later.

As a rule of thumb - always use BigDecimal for sensitive calculations like money.

Example:

String doubleAsString = "23.23";
BigDecimal price = new BigDecimal(doubleAsString);
BigDecimal total = price.plus(anotherPrice);

How to get system time in Java without creating a new Date

This should work:

System.currentTimeMillis();

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

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

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

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

That encoder will add the BOM.

Python Variable Declaration

Okay, first things first.

There is no such thing as "variable declaration" or "variable initialization" in Python.

There is simply what we call "assignment", but should probably just call "naming".

Assignment means "this name on the left-hand side now refers to the result of evaluating the right-hand side, regardless of what it referred to before (if anything)".

foo = 'bar' # the name 'foo' is now a name for the string 'bar'
foo = 2 * 3 # the name 'foo' stops being a name for the string 'bar',
# and starts being a name for the integer 6, resulting from the multiplication

As such, Python's names (a better term than "variables", arguably) don't have associated types; the values do. You can re-apply the same name to anything regardless of its type, but the thing still has behaviour that's dependent upon its type. The name is simply a way to refer to the value (object). This answers your second question: You don't create variables to hold a custom type. You don't create variables to hold any particular type. You don't "create" variables at all. You give names to objects.

Second point: Python follows a very simple rule when it comes to classes, that is actually much more consistent than what languages like Java, C++ and C# do: everything declared inside the class block is part of the class. So, functions (def) written here are methods, i.e. part of the class object (not stored on a per-instance basis), just like in Java, C++ and C#; but other names here are also part of the class. Again, the names are just names, and they don't have associated types, and functions are objects too in Python. Thus:

class Example:
    data = 42
    def method(self): pass

Classes are objects too, in Python.

So now we have created an object named Example, which represents the class of all things that are Examples. This object has two user-supplied attributes (In C++, "members"; in C#, "fields or properties or methods"; in Java, "fields or methods"). One of them is named data, and it stores the integer value 42. The other is named method, and it stores a function object. (There are several more attributes that Python adds automatically.)

These attributes still aren't really part of the object, though. Fundamentally, an object is just a bundle of more names (the attribute names), until you get down to things that can't be divided up any more. Thus, values can be shared between different instances of a class, or even between objects of different classes, if you deliberately set that up.

Let's create an instance:

x = Example()

Now we have a separate object named x, which is an instance of Example. The data and method are not actually part of the object, but we can still look them up via x because of some magic that Python does behind the scenes. When we look up method, in particular, we will instead get a "bound method" (when we call it, x gets passed automatically as the self parameter, which cannot happen if we look up Example.method directly).

What happens when we try to use x.data?

When we examine it, it's looked up in the object first. If it's not found in the object, Python looks in the class.

However, when we assign to x.data, Python will create an attribute on the object. It will not replace the class' attribute.

This allows us to do object initialization. Python will automatically call the class' __init__ method on new instances when they are created, if present. In this method, we can simply assign to attributes to set initial values for that attribute on each object:

class Example:
    name = "Ignored"
    def __init__(self, name):
        self.name = name
    # rest as before

Now we must specify a name when we create an Example, and each instance has its own name. Python will ignore the class attribute Example.name whenever we look up the .name of an instance, because the instance's attribute will be found first.

One last caveat: modification (mutation) and assignment are different things!

In Python, strings are immutable. They cannot be modified. When you do:

a = 'hi '
b = a
a += 'mom'

You do not change the original 'hi ' string. That is impossible in Python. Instead, you create a new string 'hi mom', and cause a to stop being a name for 'hi ', and start being a name for 'hi mom' instead. We made b a name for 'hi ' as well, and after re-applying the a name, b is still a name for 'hi ', because 'hi ' still exists and has not been changed.

But lists can be changed:

a = [1, 2, 3]
b = a
a += [4]

Now b is [1, 2, 3, 4] as well, because we made b a name for the same thing that a named, and then we changed that thing. We did not create a new list for a to name, because Python simply treats += differently for lists.

This matters for objects because if you had a list as a class attribute, and used an instance to modify the list, then the change would be "seen" in all other instances. This is because (a) the data is actually part of the class object, and not any instance object; (b) because you were modifying the list and not doing a simple assignment, you did not create a new instance attribute hiding the class attribute.

here-document gives 'unexpected end of file' error

Please try to remove the preceeding spaces before EOF:-

/var/mail -s "$SUBJECT" "$EMAIL" <<-EOF

Using <tab> instead of <spaces> for ident AND using <<-EOF works fine.

The "-" removes the <tabs>, not <spaces>, but at least this works.

count (non-blank) lines-of-code in bash

cat 'filename' | grep '[^ ]' | wc -l

should do the trick just fine

Wait for Angular 2 to load/resolve model before rendering view/template

The package @angular/router has the Resolve property for routes. So you can easily resolve data before rendering a route view.

See: https://angular.io/docs/ts/latest/api/router/index/Resolve-interface.html

Example from docs as of today, August 28, 2017:

class Backend {
  fetchTeam(id: string) {
    return 'someTeam';
  }
}

@Injectable()
class TeamResolver implements Resolve<Team> {
  constructor(private backend: Backend) {}

  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<any>|Promise<any>|any {
    return this.backend.fetchTeam(route.params.id);
  }
}

@NgModule({
  imports: [
    RouterModule.forRoot([
      {
        path: 'team/:id',
        component: TeamCmp,
        resolve: {
          team: TeamResolver
        }
      }
    ])
  ],
  providers: [TeamResolver]
})
class AppModule {}

Now your route will not be activated until the data has been resolved and returned.

Accessing Resolved Data In Your Component

To access the resolved data from within your component at runtime, there are two methods. So depending on your needs, you can use either:

  1. route.snapshot.paramMap which returns a string, or the
  2. route.paramMap which returns an Observable you can .subscribe() to.

Example:

  // the no-observable method
  this.dataYouResolved= this.route.snapshot.paramMap.get('id');
  // console.debug(this.licenseNumber);

  // or the observable method
  this.route.paramMap
     .subscribe((params: ParamMap) => {
        // console.log(params);
        this.dataYouResolved= params.get('id');
        return params.get('dataYouResolved');
        // return null
     });
  console.debug(this.dataYouResolved);

I hope that helps.

what does "error : a nonstatic member reference must be relative to a specific object" mean?

CPMSifDlg::EncodeAndSend() method is declared as non-static and thus it must be called using an object of CPMSifDlg. e.g.

CPMSifDlg obj;
return obj.EncodeAndSend(firstName, lastName, roomNumber, userId, userFirstName, userLastName);

If EncodeAndSend doesn't use/relate any specifics of an object (i.e. this) but general for the class CPMSifDlg then declare it as static:

class CPMSifDlg {
...
  static int EncodeAndSend(...);
  ^^^^^^
};

How to rename a single column in a data.frame?

We can use rename_with to rename columns with a function (stringr functions, for example).

Consider the following data df_1:

df_1 <- data.frame(
  x = replicate(n = 3, expr = rnorm(n = 3, mean = 10, sd = 1)), 
  y = sample(x = 1:2, size = 10, replace = TRUE)
)

names(df_1)

#[1] "x.1" "x.2" "x.3" "y" 

Rename all variables with dplyr::everything():

library(tidyverse)

df_1 %>% 
  rename_with(.data = ., .cols = everything(.), 
              .fn = str_replace, pattern = '.*', 
              replacement = str_c('var', seq_along(.), sep = '_')) %>% 
  names()

#[1] "var_1" "var_2" "var_3" "var_4"

Rename by name particle with some dplyr verbs (starts_with, ends_with, contains, matches, ...).

Example with . (x variables):

df_1 %>% 
  rename_with(.data = ., .cols = contains('.'), 
              .fn = str_replace, pattern = '.*', 
              replacement = str_c('var', seq_along(.), sep = '_')) %>% 
  names()

#[1] "var_1" "var_2" "var_3" "y"

Rename by class with many functions of class test, like is.integer, is.numeric, is.factor...

Example with is.integer (y):

df_1 %>% 
  rename_with(.data = ., .cols = is.integer, 
              .fn = str_replace, pattern = '.*', 
              replacement = str_c('var', seq_along(.), sep = '_')) %>% 
  names()

#[1] "x.1"   "x.2"   "x.3"   "var_1"

The warning:

Warning messages: 1: In stri_replace_first_regex(string, pattern, fix_replacement(replacement), : longer object length is not a multiple of shorter object length 2: In names[cols] <- .fn(names[cols], ...) : number of items to replace is not a multiple of replacement length

It is not relevant, as it is just an inconsistency of seq_along(.) with the replace function.

XML Schema Validation : Cannot find the declaration of element

cvc-elt.1: Cannot find the declaration of element 'Root'. [7]

Your schemaLocation attribute on the root element should be xsi:schemaLocation, and you need to fix it to use the right namespace.

You should probably change the targetNamespace of the schema and the xmlns of the document to http://myNameSpace.com (since namespaces are supposed to be valid URIs, which Test.Namespace isn't, though urn:Test.Namespace would be ok). Once you do that it should find the schema. The point is that all three of the schema's target namespace, the document's namespace, and the namespace for which you're giving the schema location must be the same.

(though it still won't validate as your <element2> contains an <element3> in the document where the schema expects item)

Html helper for <input type="file" />

Or you could do it properly:

In your HtmlHelper Extension class:

public static MvcHtmlString FileFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
    {
        return helper.FileFor(expression, null);
    }

public static MvcHtmlString FileFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
    {
        var builder = new TagBuilder("input");

        var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));
        builder.GenerateId(id);
        builder.MergeAttribute("name", id);
        builder.MergeAttribute("type", "file");

        builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));

        // Render tag
        return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
    }

This line:

var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));

Generates an id unique to the model, you know in lists and stuff. model[0].Name etc.

Create the correct property in the model:

public HttpPostedFileBase NewFile { get; set; }

Then you need to make sure your form will send files:

@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))

Then here's your helper:

@Html.FileFor(x => x.NewFile)

jQuery - checkbox enable/disable

Change your markup slightly:

_x000D_
_x000D_
$(function() {_x000D_
  enable_cb();_x000D_
  $("#group1").click(enable_cb);_x000D_
});_x000D_
_x000D_
function enable_cb() {_x000D_
  if (this.checked) {_x000D_
    $("input.group1").removeAttr("disabled");_x000D_
  } else {_x000D_
    $("input.group1").attr("disabled", true);_x000D_
  }_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form name="frmChkForm" id="frmChkForm">_x000D_
  <input type="checkbox" name="chkcc9" id="group1">Check Me <br>_x000D_
  <input type="checkbox" name="chk9[120]" class="group1"><br>_x000D_
  <input type="checkbox" name="chk9[140]" class="group1"><br>_x000D_
  <input type="checkbox" name="chk9[150]" class="group1"><br>_x000D_
</form>
_x000D_
_x000D_
_x000D_

You can do this using attribute selectors without introducing the ID and classes but it's slower and (imho) harder to read.

Using isKindOfClass with Swift

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

    super.touchesBegan(touches, withEvent: event)
    let touch : UITouch = touches.anyObject() as UITouch

    if touch.view.isKindOfClass(UIPickerView)
    {

    }
}

Edit

As pointed out in @Kevin's answer, the correct way would be to use optional type cast operator as?. You can read more about it on the section Optional Chaining sub section Downcasting.

Edit 2

As pointed on the other answer by user @KPM, using the is operator is the right way to do it.

Opencv - Grayscale mode Vs gray color conversion

Note: This is not a duplicate, because the OP is aware that the image from cv2.imread is in BGR format (unlike the suggested duplicate question that assumed it was RGB hence the provided answers only address that issue)

To illustrate, I've opened up this same color JPEG image:

enter image description here

once using the conversion

img = cv2.imread(path)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

and another by loading it in gray scale mode

img_gray_mode = cv2.imread(path, cv2.IMREAD_GRAYSCALE)

Like you've documented, the diff between the two images is not perfectly 0, I can see diff pixels in towards the left and the bottom

enter image description here

I've summed up the diff too to see

import numpy as np
np.sum(diff)
# I got 6143, on a 494 x 750 image

I tried all cv2.imread() modes

Among all the IMREAD_ modes for cv2.imread(), only IMREAD_COLOR and IMREAD_ANYCOLOR can be converted using COLOR_BGR2GRAY, and both of them gave me the same diff against the image opened in IMREAD_GRAYSCALE

The difference doesn't seem that big. My guess is comes from the differences in the numeric calculations in the two methods (loading grayscale vs conversion to grayscale)

Naturally what you want to avoid is fine tuning your code on a particular version of the image just to find out it was suboptimal for images coming from a different source.

In brief, let's not mix the versions and types in the processing pipeline.

So I'd keep the image sources homogenous, e.g. if you have capturing the image from a video camera in BGR, then I'd use BGR as the source, and do the BGR to grayscale conversion cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Vice versa if my ultimate source is grayscale then I'd open the files and the video capture in gray scale cv2.imread(path, cv2.IMREAD_GRAYSCALE)

Spring Resttemplate exception handling

Spring cleverly treats http error codes as exceptions, and assumes that your exception handling code has the context to handle the error. To get exchange to function as you would expect it, do this:

    try {
        return restTemplate.exchange(url, httpMethod, httpEntity, String.class);
    } catch(HttpStatusCodeException e) {
        return ResponseEntity.status(e.getRawStatusCode()).headers(e.getResponseHeaders())
                .body(e.getResponseBodyAsString());
    }

This will return all the expected results from the response.

Iterating through a List Object in JSP

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

org.classes.database.Employee@d9b02

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

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

Your JSTL here

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

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

You need to add it

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

Or use the attribute empList in the forEach.

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

iPhone App Icons - Exact Radius?

I tried 228px radius for 1024x1024 and it worked :)

javax.naming.NameNotFoundException: Name is not bound in this Context. Unable to find

Ok found out the Tomcat file server.xml must be configured as well for the data source to work. So just add:

<Resource 
auth="Container" 
driverClassName="org.apache.derby.jdbc.EmbeddedDriver" 
maxActive="20" 
maxIdle="10" 
maxWait="-1" 
name="ds/flexeraDS" 
type="javax.sql.DataSource" 
url="jdbc:derby:flexeraDB;create=true" 
  />

How to write UPDATE SQL with Table alias in SQL Server 2008?

The syntax for using an alias in an update statement on SQL Server is as follows:

UPDATE Q
SET Q.TITLE = 'TEST'
FROM HOLD_TABLE Q
WHERE Q.ID = 101;

The alias should not be necessary here though.

Change font-weight of FontAwesome icons?

The author appears to have taken a freemium approach to the font library and provides Black Tie to give different weights to the Font-Awesome library.

where is create-react-app webpack config and files?

A lot of people come to this page with the goal of finding the webpack config and files in order to add their own configuration to them. Another way to achieve this without running npm run eject is to use react-app-rewired. This allows you to overwrite your webpack config file without ejecting.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

i don't see any for loop to initalize the variables.you can do something like this.

for(i=0;i<50;i++){
 /* Code which is necessary with a simple if statement*/

   }

Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android

Just recently, I also encountered similar problem, and after I did this, it works:

I edited the file in /etc/profile

sudo nano /etc/profile

export JAVA_HOME=/home/abdul/java/jdk1.8.0_131
export PATH=$PATH:$JAVA_HOME/bin

export ANDROID_HOME=/home/abdul/Android/Sdk
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/platform-tools

export GRADLE_ANDROID_HOME=/home/abdul/android-studio/gradle
export PATH=$PATH:$GRADLE_ANDROID_HOME/gradle-3.2/bin
export PATH=$PATH:$GRADLE_ANDROID_HOME/m2repository

Other info (just in case):

Not quite sure about m2repository part, in the first try it pass the grandle but there is another error (gradlew-command-failed-with-exit-code-

  1. I check if in android studio the repository is active, and it's not active, I try to activate it, and when I try it again (Cordova build Android), it download a few other file, maybe from the repository? And then when I delete the path, it still works. (also thanks to Marcin Orlowski sample so then I can understand about export path better).

I use:

  • Linux Mint Serena
  • node : v6.10.3
  • npm : 3.10.10
  • Cordova : 7.0.0
  • Android Studio : 2.3.1
  • Android SDK platform-tools : 25.0.5
  • Android SDK tools : 26.0.2

Hope it can help anyone who might have the same problem like mine and need this too.

Thanks

Ordering issue with date values when creating pivot tables

If you want to use a column with 24/11/15 (for 24th November 2015) in your Pivot that will sort correctly, you can make sure it is properly formatted by doing the following - highlight the column, go to Data – Text to Columns – click Next twice, then select “Date” and use the default of DMY (or select as applicable to your data) and click ok

When you pivot now you should see it sorting properly as we have properly formatted that column to be a date field so Excel can work with it

pythonic way to do something N times without an index variable?

Use the _ variable, as I learned when I asked this question, for example:

# A long way to do integer exponentiation
num = 2
power = 3
product = 1
for _ in xrange(power):
    product *= num
print product

passing 2 $index values within nested ng-repeat

When you are dealing with objects, you want to ignore simple id's as much as convenient.

If you change the click line to this, I think you will be well on your way:

<li class="tutorial_title {{tutorial.active}}" ng-click="loadFromMenu(tutorial)" ng-repeat="tutorial in section.tutorials">

Also, I think you may need to change

class="tutorial_title {{tutorial.active}}"

to something like

ng-class="tutorial_title {{tutorial.active}}"

See http://docs.angularjs.org/misc/faq and look for ng-class.

Equivalent of LIMIT for DB2

Support for OFFSET and LIMIT was recently added to DB2 for i 7.1 and 7.2. You need the following DB PTF group levels to get this support:

  • SF99702 level 9 for IBM i 7.2
  • SF99701 level 38 for IBM i 7.1

See here for more information: OFFSET and LIMIT documentation, DB2 for i Enhancement Wiki

Enabling/installing GD extension? --without-gd

If You're using php5.6 and Ubuntu 18.04 Then run these two commands in your terminal your errors will be solved definitely.

sudo apt-get install php5.6-gd

then restart your apache server by this command.

 sudo service apache2 restart

node.js require all files in a folder?

I have a folder /fields full of files with a single class each, ex:

fields/Text.js -> Test class
fields/Checkbox.js -> Checkbox class

Drop this in fields/index.js to export each class:

var collectExports, fs, path,
  __hasProp = {}.hasOwnProperty;

fs = require('fs');    
path = require('path');

collectExports = function(file) {
  var func, include, _results;

  if (path.extname(file) === '.js' && file !== 'index.js') {
    include = require('./' + file);
    _results = [];
    for (func in include) {
      if (!__hasProp.call(include, func)) continue;
      _results.push(exports[func] = include[func]);
    }
    return _results;
  }
};

fs.readdirSync('./fields/').forEach(collectExports);

This makes the modules act more like they would in Python:

var text = new Fields.Text()
var checkbox = new Fields.Checkbox()

Read file from line 2 or skip header row

If you want the first line and then you want to perform some operation on file this code will helpful.

with open(filename , 'r') as f:
    first_line = f.readline()
    for line in f:
            # Perform some operations

How can we draw a vertical line in the webpage?

There are no vertical lines in html that you can use but you can fake one by absolutely positioning a div outside of your container with a top:0; and bottom:0; style.

Try this:

CSS

.vr {
    width:10px;
    background-color:#000;
    position:absolute;
    top:0;
    bottom:0;
    left:150px;
}

HTML

<div class="vr">&nbsp;</div>

Demo

HTML Agility pack - parsing tables

How about something like: Using HTML Agility Pack

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(@"<html><body><p><table id=""foo""><tr><th>hello</th></tr><tr><td>world</td></tr></table></body></html>");
foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table")) {
    Console.WriteLine("Found: " + table.Id);
    foreach (HtmlNode row in table.SelectNodes("tr")) {
        Console.WriteLine("row");
        foreach (HtmlNode cell in row.SelectNodes("th|td")) {
            Console.WriteLine("cell: " + cell.InnerText);
        }
    }
}

Note that you can make it prettier with LINQ-to-Objects if you want:

var query = from table in doc.DocumentNode.SelectNodes("//table").Cast<HtmlNode>()
            from row in table.SelectNodes("tr").Cast<HtmlNode>()
            from cell in row.SelectNodes("th|td").Cast<HtmlNode>()
            select new {Table = table.Id, CellText = cell.InnerText};

foreach(var cell in query) {
    Console.WriteLine("{0}: {1}", cell.Table, cell.CellText);
}

Get year, month or day from numpy datetime64

If you upgrade to numpy 1.7 (where datetime is still labeled as experimental) the following should work.

dates/np.timedelta64(1,'Y')

Twitter Bootstrap alert message close and open again

Here is a solution based on the answer by Henrik Karlsson but with proper event triggering (based on Bootstrap sources):

$(function(){
    $('[data-hide]').on('click', function ___alert_hide(e) {
        var $this = $(this)
        var selector = $this.attr('data-target')
        if (!selector) {
            selector = $this.attr('href')
            selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
        }

        var $parent = $(selector === '#' ? [] : selector)

        if (!$parent.length) {
            $parent = $this.closest('.alert')
        }

        $parent.trigger(e = $.Event('close.bs.alert'))

        if (e.isDefaultPrevented()) return

        $parent.hide()

        $parent.trigger($.Event('closed.bs.alert'))
    })
});

The answer mostly for me, as a note.

How can I use a Python script in the command line without cd-ing to its directory? Is it the PYTHONPATH?

PYTHONPATH only affects import statements, not the top-level Python interpreter's lookup of python files given as arguments.

Needing PYTHONPATH to be set is not a great idea - as with anything dependent on environment variables, replicating things consistently across different machines gets tricky. Better is to use Python 'packages' which can be installed (using 'pip', or distutils) in system-dependent paths which Python already knows about.

Have a read of https://the-hitchhikers-guide-to-packaging.readthedocs.org/en/latest/ - 'The Hitchhiker's Guide to Packaging', and also http://docs.python.org/3/tutorial/modules.html - which explains PYTHONPATH and packages at a lower level.

Curl: Fix CURL (51) SSL error: no alternative certificate subject name matches

It usually happens when the certificate does not match with the host name.

The solution would be to contact the host and ask it to fix its certificate.
Otherwise you can turn off cURL's verification of the certificate, use the -k (or --insecure) option.
Please note that as the option said, it is insecure. You shouldn't use this option because it allows man-in-the-middle attacks and defeats the purpose of HTTPS.

More can be found in here: http://curl.haxx.se/docs/sslcerts.html

SQL WHERE.. IN clause multiple columns

select * from tab1 where (col1,col2) in (select col1,col2 from tab2)

Note:
Oracle ignores rows where one or more of the selected columns is NULL. In these cases you probably want to make use of the NVL-Funktion to map NULL to a special value (that should not be in the values);

select * from tab1
where (col1, NVL(col2, '---') in (select col1, NVL(col2, '---') from tab2)

How to insert a blob into a database using sql server management studio

There are two ways to SELECT a BLOB with TSQL:

SELECT * FROM OPENROWSET (BULK 'C:\Test\Test1.pdf', SINGLE_BLOB) a

As well as:

SELECT BulkColumn FROM OPENROWSET (BULK 'C:\Test\Test1.pdf', SINGLE_BLOB) a

Note the correlation name after the FROM clause, which is mandatory.

You can then this to INSERT by doing an INSERT SELECT.

You can also use the second version to do an UPDATE as I described in How To Update A BLOB In SQL SERVER Using TSQL .

addID in jQuery?

I've used something like this before which addresses @scunliffes concern. It finds all instances of items with a class of (in this case .button), and assigns an ID and appends its index to the id name:

_x000D_
_x000D_
$(".button").attr('id', function (index) {_x000D_
 return "button-" + index;_x000D_
});
_x000D_
_x000D_
_x000D_

So let's say you have 3 items with the class name of .button on a page. The result would be adding a unique ID to all of them (in addition to their class of "button").

In this case, #button-0, #button-1, #button-2, respectively. This can come in very handy. Simply replace ".button" in the first line with whatever class you want to target, and replace "button" in the return statement with whatever you'd like your unique ID to be. Hope this helps!

How can I declare and define multiple variables in one line using C++?

If you declare one variable/object per line not only does it solve this problem, but it makes the code clearer and prevents silly mistakes when declaring pointers.

To directly answer your question though, you have to initialize each variable to 0 explicitly. int a = 0, b = 0, c = 0;.

Class 'ViewController' has no initializers in swift

For me was a declaration incomplete. For example:

var isInverted: Bool

Instead the correct way:

var isInverted: Bool = false

How do I copy a folder from remote to local using scp?

Typical scenario,

scp -r -P port username@ip:/path-to-folder  .

explained with an sample,

scp -r -P 27000 [email protected]:/tmp/hotel_dump .

where,

port = 27000
username = "abc" , remote server username
path-to-folder = tmp/hotel_dump
. = current local directory

Spring cron expression for every day 1:01:am

For my scheduler, I am using it to fire at 6 am every day and my cron notation is:

0 0 6 * * *

If you want 1:01:am then set it to

0 1 1 * * *

Complete code for the scheduler

@Scheduled(cron="0 1 1 * * *")
public void doScheduledWork() {
    //complete scheduled work
}

** VERY IMPORTANT

To be sure about the firing time correctness of your scheduler, you have to set zone value like this (I am in Istanbul):

@Scheduled(cron="0 1 1 * * *", zone="Europe/Istanbul")
public void doScheduledWork() {
    //complete scheduled work
}

You can find the complete time zone values from here.

Note: My Spring framework version is: 4.0.7.RELEASE

WooCommerce return product object by id

Another easy way is to use the WC_Product_Factory class and then call function get_product(ID)

http://docs.woothemes.com/wc-apidocs/source-class-WC_Product_Factory.html#16-63

sample:

// assuming the list of product IDs is are stored in an array called IDs;
$_pf = new WC_Product_Factory();  
foreach ($IDs as $id) {

    $_product = $_pf->get_product($id);

    // from here $_product will be a fully functional WC Product object, 
    // you can use all functions as listed in their api
}

You can then use all the function calls as listed in their api: http://docs.woothemes.com/wc-apidocs/class-WC_Product.html

How do I select a sibling element using jQuery?

Try -

   $(this).siblings(".bidbutton").addClass("disabled").attr("disabled", "");

How to set the id attribute of a HTML element dynamically with angularjs (1.x)?

In case you came to this question but related to newer Angular version >= 2.0.

<div [id]="element.id"></div>

Can't find file executable in your configured search path for gnc gcc compiler

* How to Download and install CodeBlocks.* ( I have already downloaded )


***How to solve the CodeBlocks environment error.

  1. Go to "Settings"----"Compiler"----"Selected compiler"( GNU GCC Compiler ).

  2. Then, Selected "Toolchain executables".

  3. Now, "( C:\Program Files (x86)\CodeBlocks\MinGW )"

See Video : https://youtu.be/Tb1VnXs60Lg

Java; String replace (using regular expressions)?

"5 * x^3 - 6 * x^1 + 1".replaceAll("\\W*\\*\\W*","").replaceAll("\\^(\\d+)","<sup>$1</sup>");

please note that joining both replacements in a single regex/replacement would be a bad choice because more general expressions such as x^3 - 6 * x would fail.

Add Header and Footer for PDF using iTextsharp

We don't talk about iTextSharp anymore. You are using iText 5 for .NET. The current version is iText 7 for .NET.

Obsolete answer:

The AddHeader has been deprecated a long time ago and has been removed from iTextSharp. Adding headers and footers is now done using page events. The examples are in Java, but you can find the C# port of the examples here and here (scroll to the bottom of the page for links to the .cs files).

Make sure you read the documentation. A common mistake by many developers have made before you, is adding content in the OnStartPage. You should only add content in the OnEndPage. It's also obvious that you need to add the content at absolute coordinates (for instance using ColumnText) and that you need to reserve sufficient space for the header and footer by defining the margins of your document correctly.

Updated answer:

If you are new to iText, you should use iText 7 and use event handlers to add headers and footers. See chapter 3 of the iText 7 Jump-Start Tutorial for .NET.

When you have a PdfDocument in iText 7, you can add an event handler:

PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
pdf.addEventHandler(PdfDocumentEvent.END_PAGE, new MyEventHandler());

This is an example of the hard way to add text at an absolute position (using PdfCanvas):

protected internal class MyEventHandler : IEventHandler {
    public virtual void HandleEvent(Event @event) {
        PdfDocumentEvent docEvent = (PdfDocumentEvent)@event;
        PdfDocument pdfDoc = docEvent.GetDocument();
        PdfPage page = docEvent.GetPage();
        int pageNumber = pdfDoc.GetPageNumber(page);
        Rectangle pageSize = page.GetPageSize();
        PdfCanvas pdfCanvas = new PdfCanvas(page.NewContentStreamBefore(), page.GetResources(), pdfDoc);
        //Add header
        pdfCanvas.BeginText()
            .SetFontAndSize(C03E03_UFO.helvetica, 9)
            .MoveText(pageSize.GetWidth() / 2 - 60, pageSize.GetTop() - 20)
            .ShowText("THE TRUTH IS OUT THERE")
            .MoveText(60, -pageSize.GetTop() + 30)
            .ShowText(pageNumber.ToString())
            .EndText();
        pdfCanvas.release();
    }
}

This is a slightly higher-level way, using Canvas:

protected internal class MyEventHandler : IEventHandler {
    public virtual void HandleEvent(Event @event) {
        PdfDocumentEvent docEvent = (PdfDocumentEvent)@event;
        PdfDocument pdfDoc = docEvent.GetDocument();
        PdfPage page = docEvent.GetPage();
        int pageNumber = pdfDoc.GetPageNumber(page);
        Rectangle pageSize = page.GetPageSize();
        PdfCanvas pdfCanvas = new PdfCanvas(page.NewContentStreamBefore(), page.GetResources(), pdfDoc);
        //Add watermark
        Canvas canvas = new Canvas(pdfCanvas, pdfDoc, page.getPageSize());
        canvas.setFontColor(Color.WHITE);
        canvas.setProperty(Property.FONT_SIZE, 60);
        canvas.setProperty(Property.FONT, helveticaBold);
        canvas.showTextAligned(new Paragraph("CONFIDENTIAL"),
            298, 421, pdfDoc.getPageNumber(page),
            TextAlignment.CENTER, VerticalAlignment.MIDDLE, 45);
        pdfCanvas.release();
    }
}

There are other ways to add content at absolute positions. They are described in the different iText books.

Error inflating when extending a class

In my case, I copied my class from somewhere else and didn't notice right away that it was an abstract class. You can't inflate abstract classes.

How to show "if" condition on a sequence diagram?

In Visual Studio UML sequence this can also be described as fragments which is nicely documented here: https://msdn.microsoft.com/en-us/library/dd465153.aspx