Programs & Examples On #Maven embedder

Maven is a project development management and comprehension tool.

Get pixel's RGB using PIL

GIFs store colors as one of x number of possible colors in a palette. Read about the gif limited color palette. So PIL is giving you the palette index, rather than the color information of that palette color.

Edit: Removed link to a blog post solution that had a typo. Other answers do the same thing without the typo.

How do I pass multiple ints into a vector at once?

You can also use vector::insert.

std::vector<int> v;
int a[5] = {2, 5, 8, 11, 14};

v.insert(v.end(), a, a+5);

Edit:

Of course, in real-world programming you should use:

v.insert(v.end(), a, a+(sizeof(a)/sizeof(a[0])));  // C++03
v.insert(v.end(), std::begin(a), std::end(a));     // C++11

Remove spaces from std::string in C++

From gamedev

string.erase(std::remove_if(string.begin(), string.end(), std::isspace), string.end());

Create autoincrement key in Java DB using NetBeans IDE

If you want to use Netbeans to define tables read this https://codezone4.wordpress.com/2012/06/19/java-database-application-using-javadb-part-1/ Simply define column as integer and create database, then grab structure to a temporary file, then delete table. Right clik to tables folder and select recreate table, select saved file and edit script for auto increment.

Find html label associated with a given input

There is a labels property in the HTML5 standard which points to labels which are associated to an input element.

So you could use something like this (support for native labels property but with a fallback for retrieving labels in case the browser doesn't support it)...

var getLabelsForInputElement = function(element) {
    var labels = [];
    var id = element.id;

    if (element.labels) {
        return element.labels;
    }

    id && Array.prototype.push
        .apply(labels, document.querySelector("label[for='" + id + "']"));

    while (element = element.parentNode) {
        if (element.tagName.toLowerCase() == "label") {
            labels.push(element);
        }  
    }

    return labels;
};

// ES6
var getLabelsForInputElement = (element) => {
    let labels;
    let id = element.id;

    if (element.labels) {
        return element.labels;
    }

    if (id) {
        labels = Array.from(document.querySelector(`label[for='${id}']`)));
    }

    while (element = element.parentNode) {
        if (element.tagName.toLowerCase() == "label") {
            labels.push(element);
        }  
    }

    return labels;
};

Even easier if you're using jQuery...

var getLabelsForInputElement = function(element) {
    var labels = $();
    var id = element.id;

    if (element.labels) {
        return element.labels;
    }

    id && (labels = $("label[for='" + id  + "']")));

    labels = labels.add($(element).parents("label"));

    return labels;
};

Dictionary of dictionaries in Python?

Using collections.defaultdict is a big time-saver when you're building dicts and don't know beforehand which keys you're going to have.

Here it's used twice: for the resulting dict, and for each of the values in the dict.

import collections

def aggregate_names(errors):
    result = collections.defaultdict(lambda: collections.defaultdict(list))
    for real_name, false_name, location in errors:
        result[real_name][false_name].append(location)
    return result

Combining this with your code:

dictionary = aggregate_names(previousFunction(string))

Or to test:

EXAMPLES = [
    ('Fred', 'Frad', 123),
    ('Jim', 'Jam', 100),
    ('Fred', 'Frod', 200),
    ('Fred', 'Frad', 300)]
print aggregate_names(EXAMPLES)

List View Filter Android

In case anyone are still interested in this subject, I find that the best approach for filtering lists is to create a generic Filter class and use it with some base reflection/generics techniques contained in the Java old school SDK package. Here's what I did:

public class GenericListFilter<T> extends Filter {

    /**
     * Copycat constructor
     * @param list  the original list to be used
     */
    public GenericListFilter (List<T> list, String reflectMethodName, ArrayAdapter<T> adapter) {
        super ();

        mInternalList = new ArrayList<>(list);
        mAdapterUsed  = adapter;

        try {
            ParameterizedType stringListType = (ParameterizedType)
                    getClass().getField("mInternalList").getGenericType();
            mCompairMethod =
                    stringListType.getActualTypeArguments()[0].getClass().getMethod(reflectMethodName);
        }
        catch (Exception ex) {
            Log.w("GenericListFilter", ex.getMessage(), ex);

            try {
                if (mInternalList.size() > 0) {
                    T type = mInternalList.get(0);
                    mCompairMethod = type.getClass().getMethod(reflectMethodName);
                }
            }
            catch (Exception e) {
                Log.e("GenericListFilter", e.getMessage(), e);
            }

        }
    }

    /**
     * Let's filter the data with the given constraint
     * @param constraint
     * @return
     */
    @Override protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults results = new FilterResults();
        List<T> filteredContents = new ArrayList<>();

        if ( constraint.length() > 0 ) {
            try {
                for (T obj : mInternalList) {
                    String result = (String) mCompairMethod.invoke(obj);
                    if (result.toLowerCase().startsWith(constraint.toString().toLowerCase())) {
                        filteredContents.add(obj);
                    }
                }
            }
            catch (Exception ex) {
                Log.e("GenericListFilter", ex.getMessage(), ex);
            }
        }
        else {
            filteredContents.addAll(mInternalList);
        }

        results.values = filteredContents;
        results.count  = filteredContents.size();
        return results;
    }

    /**
     * Publish the filtering adapter list
     * @param constraint
     * @param results
     */
    @Override protected void publishResults(CharSequence constraint, FilterResults results) {
        mAdapterUsed.clear();
        mAdapterUsed.addAll((List<T>) results.values);

        if ( results.count == 0 ) {
            mAdapterUsed.notifyDataSetInvalidated();
        }
        else {
            mAdapterUsed.notifyDataSetChanged();
        }
    }

    // class properties
    private ArrayAdapter<T> mAdapterUsed;
    private List<T> mInternalList;
    private Method  mCompairMethod;
}

And afterwards, the only thing you need to do is to create the filter as a member class (possibly within the View's "onCreate") passing your adapter reference, your list, and the method to be called for filtering:

this.mFilter = new GenericFilter<MyObjectBean> (list, "getName", adapter);

The only thing missing now, is to override the "getFilter" method in the adapter class:

@Override public Filter getFilter () {
     return MyViewClass.this.mFilter;
}

All done! You should successfully filter your list - Of course, you should also implement your filter algorithm the best way that describes your need, the code bellow is just an example.. Hope it helped, take care.

How to close Browser Tab After Submitting a Form?

try onsubmit="submit(); window.close()"

fetch from origin with deleted remote branches?

You need to do the following

git fetch -p

This will update the local database of remote branches.

Tokenizing Error: java.util.regex.PatternSyntaxException, dangling metacharacter '*'

I had similar problem with regex = "?". It happens for all special characters that have some meaning in a regex. So you need to have "\\" as a prefix to your regex.

String [] separado = line.split("\\*");

CSS transition fade in

CSS Keyframes support is pretty good these days:

_x000D_
_x000D_
.fade-in {_x000D_
 opacity: 1;_x000D_
 animation-name: fadeInOpacity;_x000D_
 animation-iteration-count: 1;_x000D_
 animation-timing-function: ease-in;_x000D_
 animation-duration: 2s;_x000D_
}_x000D_
_x000D_
@keyframes fadeInOpacity {_x000D_
 0% {_x000D_
  opacity: 0;_x000D_
 }_x000D_
 100% {_x000D_
  opacity: 1;_x000D_
 }_x000D_
}
_x000D_
<h1 class="fade-in">Fade Me Down Scotty</h1>
_x000D_
_x000D_
_x000D_

How to temporarily exit Vim and go back

You can also do that by :sus to fall into shell and back by fg.

java.lang.ClassNotFoundException on working app

I have this problem sometimes with eclipse. What has corrected it for me is to go to Project Properties / Android and change the build target API to a different version and republish. I'll find that corrected it, then I can change it back to the desired build target.

or

You may need to check your proguard.cfg.

Assuming you have linked your libraries properly and that your library projects have the code you need marked for export, the next step you might want to do is to check your proguard settings and make sure you are not stripping out the classes you need.

I was struggling with this quite a bit after I had my app working going directly to the emulator or device from eclipse. The problem I was having was after the app was published (i.e. gone through proguard) and run on the device it was missing classes that were contained in the project. They were being stripped out somehow.

My problem may have been caused when I had tried to use IntelliJ and have switched back to eclipse.

Here is the proguard file that worked for me:

-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontpreverify
-verbose
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*

-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class com.android.vending.licensing.ILicensingService

-keepclasseswithmembers class * {
    native <methods>;
}

-keepclasseswithmembers class * {
    public <init>(android.content.Context, android.util.AttributeSet);
}

-keepclasseswithmembers class * {
    public <init>(android.content.Context, android.util.AttributeSet, int);
}

-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}

-keep class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator *;
}

Fine control over the font size in Seaborn plots for academic papers

You are right. This is a badly documented issue. But you can change the font size parameter (by opposition to font scale) directly after building the plot. Check the following example:

import seaborn as sns
tips = sns.load_dataset("tips")

b = sns.boxplot(x=tips["total_bill"])
b.axes.set_title("Title",fontsize=50)
b.set_xlabel("X Label",fontsize=30)
b.set_ylabel("Y Label",fontsize=20)
b.tick_params(labelsize=5)
sns.plt.show()

, which results in this:

Different font sizes for different labels

To make it consistent in between plots I think you just need to make sure the DPI is the same. By the way it' also a possibility to customize a bit the rc dictionaries since "font.size" parameter exists but I'm not too sure how to do that.

NOTE: And also I don't really understand why they changed the name of the font size variables for axis labels and ticks. Seems a bit un-intuitive.

How can I drop a table if there is a foreign key constraint in SQL Server?

1-firstly, drop the foreign key constraint after that drop the tables.

2-you can drop all foreign key via executing the following query:

DECLARE @SQL varchar(4000)=''
SELECT @SQL = 
@SQL + 'ALTER TABLE ' + s.name+'.'+t.name + ' DROP CONSTRAINT [' + RTRIM(f.name) +'];' + CHAR(13)
FROM sys.Tables t
INNER JOIN sys.foreign_keys f ON f.parent_object_id = t.object_id
INNER JOIN sys.schemas     s ON s.schema_id = f.schema_id

--EXEC (@SQL)

PRINT @SQL

if you execute the printed results @SQL, the foreign keys will be dropped.

How do I convert a IPython Notebook into a Python file via commandline?

Here is a quick and dirty way to extract the code from V3 or V4 ipynb without using ipython. It does not check cell types, etc.

import sys,json

f = open(sys.argv[1], 'r') #input.ipynb
j = json.load(f)
of = open(sys.argv[2], 'w') #output.py
if j["nbformat"] >=4:
        for i,cell in enumerate(j["cells"]):
                of.write("#cell "+str(i)+"\n")
                for line in cell["source"]:
                        of.write(line)
                of.write('\n\n')
else:
        for i,cell in enumerate(j["worksheets"][0]["cells"]):
                of.write("#cell "+str(i)+"\n")
                for line in cell["input"]:
                        of.write(line)
                of.write('\n\n')

of.close()

Hashset vs Treeset

The reason why most use HashSet is that the operations are (on average) O(1) instead of O(log n). If the set contains standard items you will not be "messing around with hash functions" as that has been done for you. If the set contains custom classes, you have to implement hashCode to use HashSet (although Effective Java shows how), but if you use a TreeSet you have to make it Comparable or supply a Comparator. This can be a problem if the class does not have a particular order.

I have sometimes used TreeSet (or actually TreeMap) for very small sets/maps (< 10 items) although I have not checked to see if there is any real gain in doing so. For large sets the difference can be considerable.

Now if you need the sorted, then TreeSet is appropriate, although even then if updates are frequent and the need for a sorted result is infrequent, sometimes copying the contents to a list or an array and sorting them can be faster.

How to access JSON Object name/value?

The JSON you are receiving is in string. You have to convert it into JSON object You have commented the most important line of code

data = JSON.parse(data);

Or if you are using jQuery

data = $.parseJSON(data)

Remove end of line characters from Java string

Given a String str:

str = str.replaceAll("\\\\r","")
str = str.replaceAll("\\\\n","")

How to sort a data frame by alphabetic order of a character variable in R?

Use order function:

set.seed(1)
DF <- data.frame(ID= sample(letters[1:26], 15, TRUE),
                 num = sample(1:100, 15, TRUE),
                 random = rnorm(15),
                 stringsAsFactors=FALSE)
DF[order(DF[,'ID']), ]
   ID num      random
10  b  27  0.61982575
12  e   2 -0.15579551
5   f  78  0.59390132
11  f  39 -0.05612874
1   g  50 -0.04493361
2   j  72 -0.01619026
14  j  87 -0.47815006
3   o 100  0.94383621
9   q  13 -1.98935170
8   r  66  0.07456498
13  r  39 -1.47075238
15  u  35  0.41794156
4   x  39  0.82122120
6   x  94  0.91897737
7   y  22  0.78213630

Another solution would be using orderByfunction from doBy package:

> library(doBy)
> orderBy(~ID, DF)

How to check the extension of a filename in a bash script?

You just can't be sure on a Unix system, that a .txt file truly is a text file. Your best bet is to use "file". Maybe try using:

file -ib "$file"

Then you can use a list of MIME types to match against or parse the first part of the MIME where you get stuff like "text", "application", etc.

Cannot find either column "dbo" or the user-defined function or aggregate "dbo.Splitfn", or the name is ambiguous

Since people will be coming from Google, make sure you're in the right database.

Running SQL in the 'master' database will often return this error.

How to enable CORS in ASP.net Core WebAPI

Based on your comment in MindingData's answer, it has nothing to do with your CORS, it's working fine.

Your Controller action is returning the wrong data. HttpCode 415 means, "Unsupported Media type". This happens when you either pass the wrong format to the controller (i.e. XML to a controller which only accepts json) or when you return a wrong type (return Xml in a controller which is declared to only return xml).

For later one check existence of [Produces("...")]attribute on your action

Filter multiple values on a string column in dplyr

This can be achieved using dplyr package, which is available in CRAN. The simple way to achieve this:

  1. Install dplyr package.
  2. Run the below code
library(dplyr) 

df<- select(filter(dat,name=='tom'| name=='Lynn'), c('days','name))

Explanation:

So, once we’ve downloaded dplyr, we create a new data frame by using two different functions from this package:

filter: the first argument is the data frame; the second argument is the condition by which we want it subsetted. The result is the entire data frame with only the rows we wanted. select: the first argument is the data frame; the second argument is the names of the columns we want selected from it. We don’t have to use the names() function, and we don’t even have to use quotation marks. We simply list the column names as objects.

1064 error in CREATE TABLE ... TYPE=MYISAM

SELECT Email, COUNT(*)
FROM user_log    
WHILE Email IS NOT NULL    
GROUP BY Email    
HAVING COUNT(*) > 1    
ORDER BY UpdateDate DESC 

MySQL said: Documentation #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'TYPE=MyISAM' at line 36


Which correction below:

CREATE TABLE users_online (
  ip varchar(15) NOT NULL default '',
  time int(11) default NULL,
  PRIMARY KEY  (ip),
  UNIQUE KEY id (ip),
  KEY id_2 (ip)
  TYPE=MyISAM;
)
#                           
# Data untuk tabel `users_online`
#

INSERT INTO users_online VALUES ('127.0.0.1', 1158666872);

Sending Multipart File as POST parameters with RestTemplate requests

I also ran into the same issue the other day. Google search got me here and several other places, but none gave the solution to this issue. I ended up saving the uploaded file (MultiPartFile) as a tmp file, then use FileSystemResource to upload it via RestTemplate. Here's the code I use,

String tempFileName = "/tmp/" + multiFile.getOriginalFileName();
FileOutputStream fo = new FileOutputStream(tempFileName);

fo.write(asset.getBytes());    
fo.close();   

parts.add("file", new FileSystemResource(tempFileName));    
String response = restTemplate.postForObject(uploadUrl, parts, String.class, authToken, path);   


//clean-up    
File f = new File(tempFileName);    
f.delete();

I am still looking for a more elegant solution to this problem.

How do you specify a byte literal in Java?

If you're passing literals in code, what's stopping you from simply declaring it ahead of time?

byte b = 0; //Set to desired value.
f(b);

jQuery to retrieve and set selected option value of html select element

I know this is old but I just had a bear of a time with Razor, could not get it to work no matter how hard I tried. Kept coming back as "undefined" no matter if I used "text" or "html" for attribute. Finally I added "data-value" attribute to the option and it read that just fine.

 <option value="1" data-value="MyText">MyText</option>

 var DisplayText = $(this).find("option:selected").attr("data-value");

How can I get enum possible values in a MySQL database?

For PHP 5.6+

$mysqli = new mysqli("example.com","username","password","database");
$result = $mysqli->query("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='table_name' AND COLUMN_NAME='column_name'");
$row = $result->fetch_assoc();
var_dump($row);

Invalid Host Header when ngrok tries to connect to React dev server

Option 1

If you do not need to use Authentication you can add configs to ngrok commands

ngrok http 9000 --host-header=rewrite

or

ngrok http 9000 --host-header="localhost:9000"

But in this case Authentication will not work on your website because ngrok rewriting headers and session is not valid for your ngrok domain

Option 2

If you are using webpack you can add the following configuration

devServer: {
    disableHostCheck: true
}

In that case Authentication header will be valid for your ngrok domain

Conversion of System.Array to List

You can do like this basically:

int[] ints = new[] { 10, 20, 10, 34, 113 };

this is your array, and than you can call your new list like this:

 var newList = new List<int>(ints);

You can do this for complex object too.

Telegram Bot - how to get a group chat id?

Using python and telethon it's very easy to get chat id. This solution is best for those who work with telegram API.

If you don't have telethon, run this:

pip install telethon

If you don't have a registered app with telegram, register one: enter image description here The link is this: https://my.telegram.org/

Then run the following code:

from telethon import InteractiveTelegramClient
from telethon.utils.tl_utils import get_display_name

client = InteractiveTelegramClient('session_id', 'YOUR_PHONE_NUMBER', api_id=1234YOURAPI_ID, api_hash='YOUR_API_HASH')

dialog_count = 10
dialogs, entities = client.get_dialogs(dialog_count)
for i, entity in enumerate(entities):
                    i += 1  # 1-based index
                    print('{}. {}. id: {}'.format(i, get_display_name(entity), entity.id))

You may want to send a message to your group so the group show up in top of the list.

Git: Could not resolve host github.com error while cloning remote repository in git

You can try these two commands,it helped me.

git config --global --unset http.proxy 
git config --global --unset https.proxy

Create an array of strings

one of the simplest ways to create a string matrix is as follow :

x = [ {'first string'} {'Second parameter} {'Third text'} {'Fourth component'} ]

how to add a jpg image in Latex

You need to use a graphics library. Put this in your preamble:

\usepackage{graphicx}

You can then add images like this:

\begin{figure}[ht!]
\centering
\includegraphics[width=90mm]{fixed_dome1.jpg}
\caption{A simple caption \label{overflow}}
\end{figure}

This is the basic template I use in my documents. The position and size should be tweaked for your needs. Refer to the guide below for more information on what parameters to use in \figure and \includegraphics. You can then refer to the image in your text using the label you gave in the figure:

And here we see figure \ref{overflow}.

Read this guide here for a more detailed instruction: http://en.wikibooks.org/wiki/LaTeX/Floats,_Figures_and_Captions

Using the grep and cut delimiter command (in bash shell scripting UNIX) - and kind of "reversing" it?

You don't need to change the delimiter to display the right part of the string with cut.

The -f switch of the cut command is the n-TH element separated by your delimiter : :, so you can just type :

 grep puddle2_1557936 | cut -d ":" -f2

Another solutions (adapt it a bit) if you want fun :

Using :

grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                        
/home/rogers.williams/folderz/puddle2

or still with look around

grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                    
/home/rogers.williams/folderz/puddle2

or with :

perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                      
/home/rogers.williams/folderz/puddle2

or using (thanks to glenn jackman)

ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

awk -F'puddle2_1557936:' '{print $2}'  <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or using only :

IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2

or using in a :

js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2

or using in a :

php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2' 
/home/rogers.williams/folderz/puddle2

What's the difference between HTML 'hidden' and 'aria-hidden' attributes?

ARIA (Accessible Rich Internet Applications) defines a way to make Web content and Web applications more accessible to people with disabilities.

The hidden attribute is new in HTML5 and tells browsers not to display the element. The aria-hidden property tells screen-readers if they should ignore the element. Have a look at the w3 docs for more details:

https://www.w3.org/WAI/PF/aria/states_and_properties#aria-hidden

Using these standards can make it easier for disabled people to use the web.

SSIS Connection not found in package

i had the same issue and niether of the above resoved it. It turns out there was an old sql task that was disabled on the bottom right corner of my ssis that i really had to look for to find. Once i deleted this all was well

Fastest way to determine if an integer's square root is an integer

Calculating square roots by Newton's method is horrendously fast ... provided that the starting value is reasonable. However there is no reasonable starting value, and in practice we end with bisection and log(2^64) behaviour.
To be really fast we need a fast way to get at a reasonable starting value, and that means we need to descend into machine language. If a processor provides an instruction like POPCNT in the Pentium, that counts the leading zeroes we can use that to have a starting value with half the significant bits. With care we can find a a fixed number of Newton steps that will always suffice. (Thus foregoing the need to loop and have very fast execution.)

A second solution is going via the floating point facility, which may have a fast sqrt calculation (like the i87 coprocessor.) Even an excursion via exp() and log() may be faster than Newton degenerated into a binary search. There is a tricky aspect to this, a processor dependant analysis of what and if refinement afterwards is necessary.

A third solution solves a slightly different problem, but is well worth mentionning because the situation is described in the question. If you want to calculate a great many square roots for numbers that differ slightly, you can use Newton iteration, if you never reinitialise the starting value, but just leave it where the previous calculation left off. I've used this with success in at least one Euler problem.

Request exceeded the limit of 10 internal redirects due to probable configuration error

This error occurred to me when I was debugging the PHP header() function:

header('Location: /aaa/bbb/ccc'); // error

If I use a relative path it works:

header('Location: aaa/bbb/ccc'); // success, but not what I wanted

However when I use an absolute path like /aaa/bbb/ccc, it gives the exact error:

Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.

It appears the header function redirects internally without going HTTP at all which is weird. After some tests and trials, I found the solution of adding exit after header():

header('Location: /aaa/bbb/ccc');
exit;

And it works properly.

ld: framework not found Pods

Step 1

The first thing that you will need to do is remove the Podfile, Podfile.lock, the Pods folder, and the generated workspace.

Step 2

Next, in the .xcodeproj, remove the references to the Pods.xcconfig files and the libPods.a file.

Step 3

Within the Build Phases project tab, delete the Check Pods Manifest.lock section (open),Copy Pods Resources section (bottom) and Embed Pod Resources(bottom).

Step4

Remove Pods.framework.

The only thing you may want to do is include some of the libraries that you were using before. You can do this by simply draging whatever folders where in the pods folders into your project (I prefer to put them into my Supporting Files folder).

It worked for me.

vba: get unique values from array

No, VBA does not have this functionality. You can use the technique of adding each item to a collection using the item as the key. Since a collection does not allow duplicate keys, the result is distinct values that you can copy to an array, if needed.

You may also want something more robust. See Distinct Values Function at http://www.cpearson.com/excel/distinctvalues.aspx

Distinct Values Function

A VBA Function that will return an array of the distinct values in a range or array of input values.

Excel has some manual methods, such as Advanced Filter, for getting a list of distinct items from an input range. The drawback of using such methods is that you must manually refresh the results when the input data changes. Moreover, these methods work only with ranges, not arrays of values, and, not being functions, cannot be called from worksheet cells or incorporated into array formulas. This page describes a VBA function called DistinctValues that accepts as input either a range or an array of data and returns as its result an array containing the distinct items from the input list. That is, the elements with all duplicates removed. The order of the input elements is preserved. The order of the elements in the output array is the same as the order in the input values. The function can be called from an array entered range on a worksheet (see this page for information about array formulas), or from in an array formula in a single worksheet cell, or from another VB function.

UILabel - Wordwrap text

If you set numberOfLines to 0 (and the label to word wrap), the label will automatically wrap and use as many of lines as needed.

If you're editing a UILabel in IB, you can enter multiple lines of text by pressing option+return to get a line break - return alone will finish editing.

Basic Apache commands for a local Windows machine

For frequent uses of this command I found it easy to add the location of C:\xampp\apache\bin to the PATH. Use whatever directory you have this installed in.

Then you can run from any directory in command line:

httpd -k restart

The answer above that suggests httpd -k -restart is actually a typo. You can see the commands by running httpd /?

Navigate to another page with a button in angular 2

You can use routerLink in the following manner,

<input type="button" value="Add Bulk Enquiry" [routerLink]="['../addBulkEnquiry']" class="btn">

or use <button [routerLink]="['./url']"> in your case, for more info you could read the entire stacktrace on github https://github.com/angular/angular/issues/9471

the other methods are also correct but they create a dependency on the component file.

Hope your concern is resolved.

Dynamically Add Images React Webpack

You do not embed the images in the bundle. They are called through the browser. So its;

var imgSrc = './image/image1.jpg';

return <img src={imgSrc} />

Iterating over dictionaries using 'for' loops

You can check the implementation of CPython's dicttype on GitHub. This is the signature of method that implements the dict iterator:

_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey,
             PyObject **pvalue, Py_hash_t *phash)

CPython dictobject.c

Change a HTML5 input's placeholder color with CSS

Try this

::-webkit-input-placeholder { /* Chrome/Opera/Safari */
  color: pink;
}
::-moz-placeholder { /* Firefox 19+ */
  color: pink;
}
:-ms-input-placeholder { /* IE 10+ */
  color: pink;
}
:-moz-placeholder { /* Firefox 18- */
  color: pink;
}

How to make a round button?

You can use google's FloatingActionButton

XMl:

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@android:drawable/ic_dialog_email" />

Java:

  @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FloatingActionButton bold = (FloatingActionButton) findViewById(R.id.fab);
    bold.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        // Do Stuff
        }
    });
}

Gradle:

    compile 'com.android.support:design:23.4.0'

adb shell command to make Android package uninstall dialog appear

Use this command in cmd:

adb shell pm uninstall -k com.packagename

For example:

adb shell pm uninstall -k com.fedmich.pagexray

The -k flag tells the package manager to keep the cache and data directories around, even though the app is removed. If you want a clean uninstall, don't specify -k.

How can I copy a file on Unix using C?

One option is that you could use system() to execute cp. This just re-uses the cp(1) command to do the work. If you only need to make another link to the file, this can be done with link() or symlink().

jquery mobile background image

With JQM 1.4.2 this one works for me (Change theme to the used one):

.ui-page-theme-b, .ui-page-theme-b .ui-panel-wrapper {
    background: transparent url(../img/xxx) !important;
    background-repeat:repeat !important;
}

Simple bubble sort c#

No, your algorithm works but your Write operation is misplaced within the outer loop.

int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };

int temp = 0;

for (int write = 0; write < arr.Length; write++) {
    for (int sort = 0; sort < arr.Length - 1; sort++) {
        if (arr[sort] > arr[sort + 1]) {
            temp = arr[sort + 1];
            arr[sort + 1] = arr[sort];
            arr[sort] = temp;
        }
    }
}

for (int i = 0; i < arr.Length; i++)
    Console.Write(arr[i] + " ");

Console.ReadKey();

Adding click event listener to elements with the same class

The problem with using querySelectorAll and a for loop is that it creates a whole new event handler for each element in the array.

Sometimes that is exactly what you want. But if you have many elements, it may be more efficient to create a single event handler and attach it to a container element. You can then use event.target to refer to the specific element which triggered the event:

document.body.addEventListener("click", function (event) {
  if (event.target.classList.contains("delete")) {
    var title = event.target.getAttribute("title");

    if (!confirm("sure u want to delete " + title)) {
      event.preventDefault();
    }
  }
});

In this example we only create one event handler which is attached to the body element. Whenever an element inside the body is clicked, the click event bubbles up to our event handler.

How to iterate through a String

If you want to use enhanced loop, you can convert the string to charArray

for (char ch : exampleString.toCharArray()) {
  System.out.println(ch);
}

Error handling in getJSON calls

$.getJSON() is a kind of abstraction of a regular AJAX call where you would have to tell that you want a JSON encoded response.

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

You can handle errors in two ways: generically (by configuring your AJAX calls before actually calling them) or specifically (with method chain).

'generic' would be something like:

$.ajaxSetup({
      "error":function() { alert("error");  }
});

And the 'specific' way:

$.getJSON("example.json", function() {
  alert("success");
})
.done(function() { alert("second success"); })
.fail(function() { alert("error"); })
.always(function() { alert("complete"); });

How to read file with space separated values in pandas

you can use regex as the delimiter:

pd.read_csv("whitespace.csv", header=None, delimiter=r"\s+")

Stopping an Android app from console

In eclipse go to the DDMS perspective and in the devices tab click the process you want to kill under the device you want to kill it on. You then just need to press the stop button and it should kill the process.

I'm not sure how you'd do this from the command line tool but there must be a way. Maybe you do it through the adb shell...

Initialize a string in C to empty string

Assuming your array called 'string' already exists, try

string[0] = '\0';

\0 is the explicit NUL terminator, required to mark the end of string.

Named regular expression group "(?P<group_name>regexp)": what does "P" stand for?

Pattern! The group names a (sub)pattern for later use in the regex. See the documentation here for details about how such groups are used.

C# Error "The type initializer for ... threw an exception

I got this error with my own code. My problem was that I had duplicate keys in the config file.

Can I assume (bool)true == (int)1 for any C++ compiler?

I've found different compilers return different results on true. I've also found that one is almost always better off comparing a bool to a bool instead of an int. Those ints tend to change value over time as your program evolves and if you assume true as 1, you can get bitten by an unrelated change elsewhere in your code.

PHP returning JSON to JQUERY AJAX CALL

You can return json in PHP this way:

header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;

What's the syntax for mod in java

The modulo operator is % (percent sign). To test for evenness or generally do modulo for a power of 2, you can also use & (the and operator) like isEven = !( a & 1 ).

Set multiple system properties Java command line

There's nothing on the Documentation that mentions about anything like that.

Here's a quote:

-Dproperty=value Set a system property value. If value is a string that contains spaces, you must enclose the string in double quotes:

java -Dfoo="some string" SomeClass

How do I configure IIS for URL Rewriting an AngularJS application in HTML5 mode?

The IIS inbound rules as shown in the question DO work. I had to clear the browser cache and add the following line in the top of my <head> section of the index.html page:

<base href="/myApplication/app/" />

This is because I have more than one application in localhost and so requests to other partials were being taken to localhost/app/view1 instead of localhost/myApplication/app/view1

Hopefully this helps someone!

How to insert a timestamp in Oracle?

Kind of depends on where the value you want to insert is coming from. If you want to insert the current time you can use CURRENT_TIMESTAMP as shown in other answers (or SYSTIMESTAMP).

If you have a time as a string and want to convert it to a timestamp, use an expression like

to_timestamp(:timestamp_as_string,'MM/DD/YYYY HH24:MI:SS.FF3')

The time format components are, I hope, self-explanatory, except that FF3 means 3 digits of sub-second precision. You can go as high as 6 digits of precision.

If you are inserting from an application, the best answer may depend on how the date/time value is stored in your language. For instance you can map certain Java objects directly to a TIMESTAMP column, but you need to understand the JDBC type mappings.

How to get the browser to navigate to URL in JavaScript

Try these:

  1. window.location.href = 'http://www.google.com';
  2. window.location.assign("http://www.w3schools.com");
  3. window.location = 'http://www.google.com';

For more see this link: other ways to reload the page with JavaScript

Resolving LNK4098: defaultlib 'MSVCRT' conflicts with

IMO this link from Yochai Timmer was very good and relevant but painful to read. I wrote a summary.

Yochai, if you ever read this, please see the note at the end.


For the original post read : warning LNK4098: defaultlib "LIBCD" conflicts with use of other libs

Error

LINK : warning LNK4098: defaultlib "LIBCD" conflicts with use of other libs; use /NODEFAULTLIB:library

Meaning

one part of the system was compiled to use a single threaded standard (libc) library with debug information (libcd) which is statically linked

while another part of the system was compiled to use a multi-threaded standard library without debug information which resides in a DLL and uses dynamic linking

How to resolve

  • Ignore the warning, after all it is only a warning. However, your program now contains multiple instances of the same functions.

  • Use the linker option /NODEFAULTLIB:lib. This is not a complete solution, even if you can get your program to link this way you are ignoring a warning sign: the code has been compiled for different environments, some of your code may be compiled for a single threaded model while other code is multi-threaded.

  • [...] trawl through all your libraries and ensure they have the correct link settings

In the latter, as it in mentioned in the original post, two common problems can arise :

  • You have a third party library which is linked differently to your application.

  • You have other directives embedded in your code: normally this is the MFC. If any modules in your system link against MFC all your modules must nominally link against the same version of MFC.

For those cases, ensure you understand the problem and decide among the solutions.


Note : I wanted to include that summary of Yochai Timmer's link into his own answer but since some people have trouble to review edits properly I had to write it in a separate answer. Sorry

Postgresql -bash: psql: command not found

perhaps psql isn't in the PATH of the postgres user. Use the locate command to find where psql is and ensure that it's path is in the PATH for the postgres user.

Angular 2 Routing run in new tab

In my use case, I wanted to asynchronously retrieve a url, and then follow that url to an external resource in a new window. A directive seemed overkill because I don't need reusability, so I simply did:

<button (click)="navigateToResource()">Navigate</button>

And in my component.ts

navigateToResource(): void {
  this.service.getUrl((result: any) => window.open(result.url));
}


Note:

Routing to a link indirectly like this will likely trigger the browser's popup blocker.

JavaFX How to set scene background image

You can change style directly for scene using .root class:

.root {
    -fx-background-image: url("https://www.google.com/images/srpr/logo3w.png");
}

Add this to CSS and load it as "Uluk Biy" described in his answer.

How to convert signed to unsigned integer in python

Python doesn't have builtin unsigned types. You can use mathematical operations to compute a new int representing the value you would get in C, but there is no "unsigned value" of a Python int. The Python int is an abstraction of an integer value, not a direct access to a fixed-byte-size integer.

How do I see if Wi-Fi is connected on Android?

The NetworkInfo class is deprecated as of API level 29, along with the related access methods like ConnectivityManager#getNetworkInfo() and ConnectivityManager#getActiveNetworkInfo().

The documentation now suggests people to use the ConnectivityManager.NetworkCallback API for asynchronized callback monitoring, or use ConnectivityManager#getNetworkCapabilities or ConnectivityManager#getLinkProperties for synchronized access of network information

Callers should instead use the ConnectivityManager.NetworkCallback API to learn about connectivity changes, or switch to use ConnectivityManager#getNetworkCapabilities or ConnectivityManager#getLinkProperties to get information synchronously.


To check if WiFi is connected, here's the code that I use:

Kotlin:

val connMgr = applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
connMgr?: return false
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    val network: Network = connMgr.activeNetwork ?: return false
    val capabilities = connMgr.getNetworkCapabilities(network)
    return capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
} else {
    val networkInfo = connMgr.activeNetworkInfo ?: return false
    return networkInfo.isConnected && networkInfo.type == ConnectivityManager.TYPE_WIFI
}

Java:

ConnectivityManager connMgr = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (connMgr == null) {
    return false;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    Network network = connMgr.getActiveNetwork();
    if (network == null) return false;
    NetworkCapabilities capabilities = connMgr.getNetworkCapabilities(network);
    return capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
} else {
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    return networkInfo.isConnected() && networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
}

Remember to also add permission ACCESS_NETWORK_STATE to your Manifest file.

What's the difference between compiled and interpreted language?

It is a very murky distinction, and in fact generally not a property of a language itself, but rather of the program you are using to execute code in that language.

However, most languages are used primarily in one form or the other, and yes, Java is essentially always compiled, while javascript is essentially always interpreted.

To compile source code is to run a program on it that generates a binary, executable file that, when run, has the behavior defined by the source. For instance, javac compiles human-readbale .java files into machine-readable .class files.

To interpret source code is run a program on it that produces the defined behavior right away, without generating an intermediary file. For instance, when your web browser loads stackoverflow.com, it interprets a bunch of javascript (which you can look at by viewing the page source) and produces lots of the nice effects these pages have - for instance, upvoting, or the little notifier bars across the top.

How to change an application icon programmatically in Android?

AndroidManifest.xml example:

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name="com.pritesh.resourceidentifierexample.MainActivity"
                  android:label="@string/app_name"
                  android:launchMode="singleTask">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <!--<category android:name="android.intent.category.LAUNCHER"/>-->
            </intent-filter>
        </activity>

        <activity-alias android:label="RED"
                        android:icon="@drawable/ic_android_red"
                        android:name="com.pritesh.resourceidentifierexample.MainActivity-Red"
                        android:enabled="true"
                        android:targetActivity="com.pritesh.resourceidentifierexample.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity-alias>

        <activity-alias android:label="GREEN"
                        android:icon="@drawable/ic_android_green"
                        android:name="com.pritesh.resourceidentifierexample.MainActivity-Green"
                        android:enabled="false"
                        android:targetActivity="com.pritesh.resourceidentifierexample.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity-alias>

        <activity-alias android:label="BLUE"
                        android:icon="@drawable/ic_android_blue"
                        android:name="com.pritesh.resourceidentifierexample.MainActivity-Blue"
                        android:enabled="false"
                        android:targetActivity="com.pritesh.resourceidentifierexample.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity-alias>

    </application>

Then follow below given code in MainActivity:

ImageView imageView = (ImageView)findViewById(R.id.imageView);
            int imageResourceId;
            String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
            int hours = new Time(System.currentTimeMillis()).getHours();
            Log.d("DATE", "onCreate: "  + hours);

            getPackageManager().setComponentEnabledSetting(
                    getComponentName(), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);

            if(hours == 13)
            {
                imageResourceId = this.getResources().getIdentifier("ic_android_red", "drawable", this.getPackageName());
                getPackageManager().setComponentEnabledSetting(
                        new ComponentName("com.pritesh.resourceidentifierexample", "com.pritesh.resourceidentifierexample.MainActivity-Red"),
                        PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
            }else if(hours == 14)
            {
                imageResourceId = this.getResources().getIdentifier("ic_android_green", "drawable", this.getPackageName());
                getPackageManager().setComponentEnabledSetting(
                        new ComponentName("com.pritesh.resourceidentifierexample", "com.pritesh.resourceidentifierexample.MainActivity-Green"),
                        PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);

            }else
            {
                imageResourceId = this.getResources().getIdentifier("ic_android_blue", "drawable", this.getPackageName());
                getPackageManager().setComponentEnabledSetting(
                        new ComponentName("com.pritesh.resourceidentifierexample", "com.pritesh.resourceidentifierexample.MainActivity-Blue"),
                        PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);

            }

            imageView.setImageResource(imageResourceId);

Single statement across multiple lines in VB.NET without the underscore character

No, you have to use the underscore, but I believe that VB.NET 10 will allow multiple lines w/o the underscore, only requiring if it can't figure out where the end should be.

Can functions be passed as parameters?

Here is a simple example:

    package main

    import "fmt"

    func plusTwo() (func(v int) (int)) {
        return func(v int) (int) {
            return v+2
        }
    }

    func plusX(x int) (func(v int) (int)) {
       return func(v int) (int) {
           return v+x
       }
    }

    func main() {
        p := plusTwo()
        fmt.Printf("3+2: %d\n", p(3))

        px := plusX(3)
        fmt.Printf("3+3: %d\n", px(3))
    }

Simple DateTime sql query

SELECT * 
  FROM TABLENAME 
 WHERE [DateTime] >= '2011-04-12 12:00:00 AM'
   AND [DateTime] <= '2011-05-25 3:35:04 AM'

If this doesn't work, please script out your table and post it here. this will help us get you the correct answer quickly.

Add/remove class with jquery based on vertical scroll?

Its my code

jQuery(document).ready(function(e) {
    var WindowHeight = jQuery(window).height();

    var load_element = 0;

    //position of element
    var scroll_position = jQuery('.product-bottom').offset().top;

    var screen_height = jQuery(window).height();
    var activation_offset = 0;
    var max_scroll_height = jQuery('body').height() + screen_height;

    var scroll_activation_point = scroll_position - (screen_height * activation_offset);

    jQuery(window).on('scroll', function(e) {

        var y_scroll_pos = window.pageYOffset;
        var element_in_view = y_scroll_pos > scroll_activation_point;
        var has_reached_bottom_of_page = max_scroll_height <= y_scroll_pos && !element_in_view;

        if (element_in_view || has_reached_bottom_of_page) {
            jQuery('.product-bottom').addClass("change");
        } else {
            jQuery('.product-bottom').removeClass("change");
        }

    });

});

Its working Fine

How to make link not change color after visited?

Text decoration affects the underline, not the color.

To set the visited color to the same as the default, try:

a { 
    color: blue;
}

Or

a {
    text-decoration: none;
}
a:link, a:visited {
    color: blue;
}
a:hover {
    color: red;
}

Capturing window.onbeforeunload

you just cant do alert() in onbeforeunload, anything else works

Eclipse error ... cannot be resolved to a type

Project -> Build Path -> Configure Build Path
Select Java Build path on the left menu, and select "Source"
 click on Excluded and then Include(All) and then click OK
    Cause : The issue might because u might have deleted the CLASS files 
 or dependencies on the project

For maven users:

Right click on the project

Maven

Update Project

jasmine: Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL

Works after removing the scope reference and the function arguments:

"use strict";

describe("Request Notification Channel", function() {
    var requestNotificationChannel, rootScope;

    beforeEach(function() {
        module("messageAppModule");

        inject(function($injector, _requestNotificationChannel_) {
            rootScope = $injector.get("$rootScope");
            requestNotificationChannel = _requestNotificationChannel_;
        })
        spyOn(rootScope, "$broadcast");
    });


    it("should broadcast delete message notification with provided params", function() {
        requestNotificationChannel.deleteMessage(1, 4);
        expect(rootScope.$broadcast).toHaveBeenCalledWith("_DELETE_MESSAGE_", { id: 1, index: 4} );
    });
});

How do I open workbook programmatically as read-only?

Does this work?

Workbooks.Open Filename:=filepath, ReadOnly:=True

Or, as pointed out in a comment, to keep a reference to the opened workbook:

Dim book As Workbook
Set book = Workbooks.Open(Filename:=filepath, ReadOnly:=True)

How to add a hook to the application context initialization event?

Spring has some standard events which you can handle.

To do that, you must create and register a bean that implements the ApplicationListener interface, something like this:

package test.pack.age;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

public class ApplicationListenerBean implements ApplicationListener {

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ContextRefreshedEvent) {
            ApplicationContext applicationContext = ((ContextRefreshedEvent) event).getApplicationContext();
            // now you can do applicationContext.getBean(...)
            // ...
        }
    }
}

You then register this bean within your servlet.xml or applicationContext.xml file:

<bean id="eventListenerBean" class="test.pack.age.ApplicationListenerBean" />

and Spring will notify it when the application context is initialized.

In Spring 3 (if you are using this version), the ApplicationListener class is generic and you can declare the event type that you are interested in, and the event will be filtered accordingly. You can simplify a bit your bean code like this:

public class ApplicationListenerBean implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext applicationContext = event.getApplicationContext();
        // now you can do applicationContext.getBean(...)
        // ...
    }
}

SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?

Here is a simple example for others visiting this old post, but is confused by the example in the question and the other answer:

Delivery -> Package (One -> Many)

CREATE TABLE Delivery(
    Id INT IDENTITY PRIMARY KEY,
    NoteNumber NVARCHAR(255) NOT NULL
)

CREATE TABLE Package(
    Id INT IDENTITY PRIMARY KEY,
    Status INT NOT NULL DEFAULT 0,
    Delivery_Id INT NOT NULL,
    CONSTRAINT FK_Package_Delivery_Id FOREIGN KEY (Delivery_Id) REFERENCES Delivery (Id) ON DELETE CASCADE
)

The entry with the foreign key Delivery_Id (Package) is deleted with the referenced entity in the FK relationship (Delivery).

So when a Delivery is deleted the Packages referencing it will also be deleted. If a Package is deleted nothing happens to any deliveries.

Finding duplicate values in a SQL table

SELECT * FROM users u where rowid = (select max(rowid) from users u1 where
u.email=u1.email);

All possible array initialization syntaxes

var contacts = new[]
{
    new 
    {
        Name = " Eugene Zabokritski",
        PhoneNumbers = new[] { "206-555-0108", "425-555-0001" }
    },
    new 
    {
        Name = " Hanying Feng",
        PhoneNumbers = new[] { "650-555-0199" }
    }
};

How to add "Maven Managed Dependencies" library in build path eclipse?

from the command line type:

mvn eclipse:eclipse

this will add all the dependencies you have in your pom.xml into eclipse...

however, if you haven't done any of this before you may need to do one other, one time only step.

Close eclipse, then run the following command from the shell:

mvn -Declipse.workspace=<eclipse workspace> eclipse:add-maven-repo

sample:

mvn -Declipse.workspace=/home/ft/workspaces/wksp1/ eclipse:add-maven-repo

How to set height property for SPAN

Give it a display:inline-block in CSS - that should let it do what you want.
In terms of compatibility: IE6/7 will work with this, as quirks mode suggests:

IE 6/7 accepts the value only on elements with a natural display: inline.

Is it possible to cherry-pick a commit from another git repository?

See How to create and apply a patch with Git. (From the wording of your question, I assumed that this other repository is for an entirely different codebase. If it's a repository for the same code base, you should add it as a remote as suggested by @CharlesB. Even if it is for another code base, I guess you could still add it as a remote, but you might not want to get the entire branch into your repository...)

Is there a REAL performance difference between INT and VARCHAR primary keys?

Depends on the length.. If the varchar will be 20 characters, and the int is 4, then if you use an int, your index will have FIVE times as many nodes per page of index space on disk... That means that traversing the index will require one fifth as many physical and/or logical reads..

So, if performance is an issue, given the opportunity, always use an integral non-meaningful key (called a surrogate) for your tables, and for Foreign Keys that reference the rows in these tables...

At the same time, to guarantee data consistency, every table where it matters should also have a meaningful non-numeric alternate key, (or unique Index) to ensure that duplicate rows cannot be inserted (duplicate based on meaningful table attributes) .

For the specific use you are talking about (like state lookups ) it really doesn't matter because the size of the table is so small.. In general there is no impact on performance from indices on tables with less than a few thousand rows...

How can I interrupt a running code in R with a keyboard command?

I know this is old, but I ran into the same issue. I'm on a Mac/Ubuntu and switch back and forth. What I have found is that just sending a simple interrupt signal to the main R process does exactly what you're looking for. I've ran scripts that went on for as long as 24 hours and the signal interrupt works very well. You should be able to run kill in terminal:

$ kill -2 pid

You can find the pid by running

$ps aux | grep exec/R

Not sure about Windows since I'm not ever on there, but I can't imagine there's not an option to do this as well in Command Prompt/Task Manager

Hope this helps!

JPA mapping: "QuerySyntaxException: foobar is not mapped..."

I got the same error while using other one entity, He was annotating the class wrongly by using the table name inside the @Entity annotation without using the @Table annotation

The correct format should be

@Entity //default name similar to class name 'FooBar' OR @Entity( name = "foobar" ) for differnt entity name
@Table( name = "foobar" ) // Table name 
public class FooBar{

Can't concatenate 2 arrays in PHP

Try saying

$array[] = array('Item 2'); 

Although it looks like you're trying to add an array into an array, thus $array[][] but that's not what your title suggests.

How to get autocomplete in jupyter notebook without using tab?

The auto-completion with Jupyter Notebook is so weak, even with hinterland extension. Thanks for the idea of deep-learning-based code auto-completion. I developed a Jupyter Notebook Extension based on TabNine which provides code auto-completion based on Deep Learning. Here's the Github link of my work: jupyter-tabnine.

It's available on pypi index now. Simply issue following commands, then enjoy it:)

pip3 install jupyter-tabnine
jupyter nbextension install --py jupyter_tabnine
jupyter nbextension enable --py jupyter_tabnine
jupyter serverextension enable --py jupyter_tabnine

demo

Copy a file in a sane, safe and efficient way

I'm not quite sure what a "good way" of copying a file is, but assuming "good" means "fast", I could broaden the subject a little.

Current operating systems have long been optimized to deal with run of the mill file copy. No clever bit of code will beat that. It is possible that some variant of your copy techniques will prove faster in some test scenario, but they most likely would fare worse in other cases.

Typically, the sendfile function probably returns before the write has been committed, thus giving the impression of being faster than the rest. I haven't read the code, but it is most certainly because it allocates its own dedicated buffer, trading memory for time. And the reason why it won't work for files bigger than 2Gb.

As long as you're dealing with a small number of files, everything occurs inside various buffers (the C++ runtime's first if you use iostream, the OS internal ones, apparently a file-sized extra buffer in the case of sendfile). Actual storage media is only accessed once enough data has been moved around to be worth the trouble of spinning a hard disk.

I suppose you could slightly improve performances in specific cases. Off the top of my head:

  • If you're copying a huge file on the same disk, using a buffer bigger than the OS's might improve things a bit (but we're probably talking about gigabytes here).
  • If you want to copy the same file on two different physical destinations you will probably be faster opening the three files at once than calling two copy_file sequentially (though you'll hardly notice the difference as long as the file fits in the OS cache)
  • If you're dealing with lots of tiny files on an HDD you might want to read them in batches to minimize seeking time (though the OS already caches directory entries to avoid seeking like crazy and tiny files will likely reduce disk bandwidth dramatically anyway).

But all that is outside the scope of a general purpose file copy function.

So in my arguably seasoned programmer's opinion, a C++ file copy should just use the C++17 file_copy dedicated function, unless more is known about the context where the file copy occurs and some clever strategies can be devised to outsmart the OS.

Convert UTC date time to local date time

I've created one function which converts all the timezones into local time.

I did not used getTimezoneOffset(), because it does not returns proper offset value

Requirements:

1. npm i moment-timezone

function utcToLocal(utcdateTime, tz) {
    var zone = moment.tz(tz).format("Z") // Actual zone value e:g +5:30
    var zoneValue = zone.replace(/[^0-9: ]/g, "") // Zone value without + - chars
    var operator = zone && zone.split("") && zone.split("")[0] === "-" ? "-" : "+" // operator for addition subtraction
    var localDateTime
    var hours = zoneValue.split(":")[0]
    var minutes = zoneValue.split(":")[1]
    if (operator === "-") {
        localDateTime = moment(utcdateTime).subtract(hours, "hours").subtract(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
    } else if (operator) {
        localDateTime = moment(utcdateTime).add(hours, "hours").add(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
    } else {
        localDateTime = "Invalid Timezone Operator"
    }
    return localDateTime
}

utcToLocal("2019-11-14 07:15:37", "Asia/Kolkata")

//Returns "2019-11-14 12:45:37"

Python pip install module is not found. How to link python to pip location?

Here is something I learnt after a long time of having issues with pip when I had several versions of Python installed (valid especially for OS X users which are probably using brew to install python blends.)

I assume that most python developers do have at the beginning of their scripts:

#!/bin/env python

You may be surprised to find out that this is not necessarily the same python as the one you run from the command line >python

To be sure you install the package using the correct pip instance for your python interpreter you need to run something like:

>/bin/env python -m pip install --upgrade mymodule

Searching for file in directories recursively

You should have the loop over the files either before or after the loop over the directories, but not nested inside it as you have done.

foreach (string f in Directory.GetFiles(d, "*.xml"))
{
    string extension = Path.GetExtension(f);
    if (extension != null && (extension.Equals(".xml")))
    {
        fileList.Add(f);
    }
} 

foreach (string d in Directory.GetDirectories(sDir))
{
    DirSearch(d);
}

How do I detect whether 32-bit Java is installed on x64 Windows, only looking at the filesystem and registry?

Check this key for 32 bits and 64 bits Windows machines.

 HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment

and this for Windows 64 bits with 32 Bits JRE.

 HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Runtime Environment

This will work for the oracle-sun JRE.

Using python's eval() vs. ast.literal_eval()?

ast.literal_eval() only considers a small subset of Python's syntax to be valid:

The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

Passing __import__('os').system('rm -rf /a-path-you-really-care-about') into ast.literal_eval() will raise an error, but eval() will happily delete your files.

Since it looks like you're only letting the user input a plain dictionary, use ast.literal_eval(). It safely does what you want and nothing more.

Using only CSS, show div on hover over <a>

Based on the main answer, this is an example, useful to display an information tooltip when clicking on a ? near a link:

_x000D_
_x000D_
document.onclick = function() { document.getElementById("tooltip").style.display = 'none'; };_x000D_
_x000D_
document.getElementById("tooltip").onclick = function(e) { e.stopPropagation(); }_x000D_
_x000D_
document.getElementById("help").onclick = function(e) { document.getElementById("tooltip").style.display = 'block';_x000D_
e.stopPropagation(); };
_x000D_
#help { opacity: 0; margin-left: 0.1em; padding: 0.4em; }_x000D_
    _x000D_
a:hover + #help, #help:hover { opacity: 0.5; cursor: pointer; }_x000D_
_x000D_
#tooltip { border: 1px solid black; display: none; padding: 0.75em; width: 50%; text-align: center; font-family: sans-serif; font-size:0.8em; }
_x000D_
<a href="">Delete all obsolete informations</a><span id="help">?</span>_x000D_
<div id="tooltip">All data older than 2 weeks will be deleted.</div>
_x000D_
_x000D_
_x000D_

How to remove files from git staging area?

I tried all these method but none worked for me. I removed .git file using rm -rf .git form the local repository and then again did git init and git add and routine commands. It worked.

How to change owner of PostgreSql database?

ALTER DATABASE name OWNER TO new_owner;

See the Postgresql manual's entry on this for more details.

Fit background image to div

you also use this:

background-size:contain;
height: 0;
width: 100%;
padding-top: 66,64%; 

I don't know your div-values, but let's assume you've got those.

height: auto;
max-width: 600px;

Again, those are just random numbers. It could quite hard to make the background-image (if you would want to) with a fixed width for the div, so better use max-width. And actually it isn't complicated to fill a div with an background-image, just make sure you style the parent element the right way, so the image has a place it can go into.

Chris

How do I import a Swift file from another Swift file?

In Objective-C, if you wanted to use a class in another file you had to import it:

#import "SomeClass.h"

However, in Swift, you don't have to import at all. Simply use it as if it was already imported.

Example

// This is a file named SomeClass.swift

class SomeClass : NSObject {

}

// This is a different file, named OtherClass.swift

class OtherClass : NSObject {
    let object = SomeClass()
}

As you can see, no import was needed. Hope this helps.

Pass variable to function in jquery AJAX success callback

I've meet the probleme recently. The trouble is coming when the filename lenght is greather than 20 characters. So the bypass is to change your filename length, but the trick is also a good one.

$.ajaxSetup({async: false}); // passage en mode synchrone
$.ajax({
   url: pathpays,
   success: function(data) {
      //debug(data);
      $(data).find("a:contains(.png),a:contains(.jpg)").each(function() {
         var image = $(this).attr("href");
         // will loop through
         debug("Found a file: " + image);
         text +=  '<img class="arrondie" src="' + pathpays + image + '" />';
      });
      text = text + '</div>';
      //debug(text);
   }
});

After more investigation the trouble is coming from ajax request: Put an eye to the html code returned by ajax:

<a href="Paris-Palais-de-la-cite%20-%20Copie.jpg">Paris-Palais-de-la-c..&gt;</a>
</td>
<td align="right">2015-09-05 09:50 </td>
<td align="right">4.3K</td>
<td>&nbsp;</td>
</tr>

As you can see the filename is splitted after the character 20, so the $(data).find("a:contains(.png)) is not able to find the correct extention.

But if you check the value of the href parameter it contents the fullname of the file.

I dont know if I can to ask to ajax to return the full filename in the text area?

Hope to be clear

I've found the right test to gather all files:

$(data).find("[href$='.jpg'],[href$='.png']").each(function() {  
var image = $(this).attr("href");

Swipe ListView item From right to left show delete button

An app is available that demonstrates a listview that combines both swiping-to-delete and dragging to reorder items. The code is based on Chet Haase's code for swiping-to-delete and Daniel Olshansky's code for dragging-to-reorder.

Chet's code deletes an item immediately. I improved on this by making it function more like Gmail where swiping reveals a bottom view that indicates that the item is deleted but provides an Undo button where the user has the possibility to undo the deletion. Chet's code also has a bug in it. If you have less items in the listview than the height of the listview is and you delete the last item, the last item appears to not be deleted. This was fixed in my code.

Daniel's code requires pressing long on an item. Many users find this unintuitive as it tends to be a hidden function. Instead, I modified the code to allow for a "Move" button. You simply press on the button and drag the item. This is more in line with the way the Google News app works when you reorder news topics.

The source code along with a demo app is available at: https://github.com/JohannBlake/ListViewOrderAndSwipe

Chet and Daniel are both from Google.

Chet's video on deleting items can be viewed at: https://www.youtube.com/watch?v=YCHNAi9kJI4

Daniel's video on reordering items can be viewed at: https://www.youtube.com/watch?v=_BZIvjMgH-Q

A considerable amount of work went into gluing all this together to provide a seemless UI experience, so I'd appreciate a Like or Up Vote. Please also star the project in Github.

PowerShell Remoting giving "Access is Denied" error

Running the command prompt or Powershell ISE as an administrator fixed this for me.

convert datetime to date format dd/mm/yyyy

As everyone else said, but remember CultureInfo.InvariantCulture!

string s = dt.ToString("dd/M/yyyy", CultureInfo.InvariantCulture)

OR escape the '/'.

Very Simple Image Slider/Slideshow with left and right button. No autoplay

Very simple code to make jquery slider Here is two div first is the slider viewer and second is the image list container. Just copy paste the code and customise with css.

    <div class="featured-image" style="height:300px">
     <img id="thumbnail" src="01.jpg"/>
    </div>

    <div class="post-margin" style="margin:10px 0px; padding:0px;" id="thumblist">
    <img src='01.jpg'>
    <img src='02.jpg'>
    <img src='03.jpg'>
    <img src='04.jpg'>
    </div>

    <script type="text/javascript">
            function changeThumbnail()
            {
            $("#thumbnail").fadeOut(200);
            var path=$("#thumbnail").attr('src');
            var arr= new Array(); var i=0;
            $("#thumblist img").each(function(index, element) {
               arr[i]=$(this).attr('src');
               i++;
            });
            var index= arr.indexOf(path);
            if(index==(arr.length-1))
            path=arr[0];
            else
            path=arr[index+1];
            $("#thumbnail").attr('src',path).fadeIn(200);
            setTimeout(changeThumbnail, 5000);  
            }
            setTimeout(changeThumbnail, 5000);
    </script>

Rename package in Android Studio

  1. Open the file:

    app ? manifests ? AndroidManifest.xml

    Enter image description here

    Highlight each part in the package name that you want to modify (don't highlight entire package name) then:

    • Mouse right click ? Refactor ? Rename ? Rename package
    • type the new name and press (Refactor)

    Do these steps in each part of the package name.

    Enter image description here

  2. Open (Gradle Script) >> (build.gradle(Modul:app))

    and update the applicationId to your package name

    Enter image description here

  3. Open the menu (build) and choose (Rebuild Project).

Get column index from label in a data frame

This seems to be an efficient way to list vars with column number:

cbind(names(df)) 

Output:

     [,1]
[1,] "A" 
[2,] "B" 
[3,] "C" 

Sometimes I like to copy variables with position into my code so I use this function:

varnums<- function(x) {w=as.data.frame(c(1:length(colnames(x))),
          paste0('# ',colnames(x)))
names(w)= c("# Var/Pos")
w}
varnums(df)

Output:

# Var/Pos
# A         1
# B         2
# C         3

What is http multipart request?

As the official specification says, "one or more different sets of data are combined in a single body". So when photos and music are handled as multipart messages as mentioned in the question, probably there is some plain text metadata associated as well, thus making the request containing different types of data (binary, text), which implies the usage of multipart.

Full examples of using pySerial package

http://web.archive.org/web/20131107050923/http://www.roman10.net/serial-port-communication-in-python/comment-page-1/

#!/usr/bin/python

import serial, time
#initialization and open the port

#possible timeout values:
#    1. None: wait forever, block call
#    2. 0: non-blocking mode, return immediately
#    3. x, x is bigger than 0, float allowed, timeout block call

ser = serial.Serial()
#ser.port = "/dev/ttyUSB0"
ser.port = "/dev/ttyUSB7"
#ser.port = "/dev/ttyS2"
ser.baudrate = 9600
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
#ser.timeout = None          #block read
ser.timeout = 1            #non-block read
#ser.timeout = 2              #timeout block read
ser.xonxoff = False     #disable software flow control
ser.rtscts = False     #disable hardware (RTS/CTS) flow control
ser.dsrdtr = False       #disable hardware (DSR/DTR) flow control
ser.writeTimeout = 2     #timeout for write

try: 
    ser.open()
except Exception, e:
    print "error open serial port: " + str(e)
    exit()

if ser.isOpen():

    try:
        ser.flushInput() #flush input buffer, discarding all its contents
        ser.flushOutput()#flush output buffer, aborting current output 
                 #and discard all that is in buffer

        #write data
        ser.write("AT+CSQ")
        print("write data: AT+CSQ")

       time.sleep(0.5)  #give the serial port sometime to receive the data

       numOfLines = 0

       while True:
          response = ser.readline()
          print("read data: " + response)

        numOfLines = numOfLines + 1

        if (numOfLines >= 5):
            break

        ser.close()
    except Exception, e1:
        print "error communicating...: " + str(e1)

else:
    print "cannot open serial port "

HTML colspan in CSS

You could always position:absolute; things and specify widths. It's not a very fluid way of doing it, but it would work.

Retrofit and GET using parameters

@QueryMap worked for me instead of FieldMap

If you have a bunch of GET params, another way to pass them into your url is a HashMap.

class YourActivity extends Activity {

private static final String BASEPATH = "http://www.example.com";

private interface API {
    @GET("/thing")
    void getMyThing(@QueryMap Map<String, String> params, new Callback<String> callback);
}

public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.your_layout);

   RestAdapter rest = new RestAdapter.Builder().setEndpoint(BASEPATH).build();
   API service = rest.create(API.class);

   Map<String, String> params = new HashMap<String, String>();
   params.put("key1", "val1");
   params.put("key2", "val2");
   // ... as much as you need.

   service.getMyThing(params, new Callback<String>() {
       // ... do some stuff here.
   });
}
}

The URL called will be http://www.example.com/thing/?key1=val1&key2=val2

What does O(log n) mean exactly?

If you plot a logarithmic function on a graphical calculator or something similar, you'll see that it rises really slowly -- even more slowly than a linear function.

This is why algorithms with a logarithmic time complexity are highly sought after: even for really big n (let's say n = 10^8, for example), they perform more than acceptably.

installing vmware tools: location of GCC binary?

sudo apt-get install build-essential is enough to get it working.

Gulp command not found after install

I had similar problem I did the following steps and it worked.Go to mac terminal and execute the commands,

1.npm config set prefix /usr/local

2.sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share}

This two commands will set the npm path right and you no longer have to use sudo in npm. Next uninstall the gulp

  1. npm uninstall gulp

  2. Installl gulp again without sudo, npm install gulp -g

This should work!!

What is a CSRF token? What is its importance and how does it work?

The root of it all is to make sure that the requests are coming from the actual users of the site. A csrf token is generated for the forms and Must be tied to the user's sessions. It is used to send requests to the server, in which the token validates them. This is one way of protecting against csrf, another would be checking the referrer header.

How to Set Variables in a Laravel Blade Template

You may use the package I have published: https://github.com/sineld/bladeset

Then you easily set your variable:

@set('myVariable', $existing_variable)

// or

@set("myVariable", "Hello, World!")

How to break out from a ruby block?

Perhaps you can use the built-in methods for finding particular items in an Array, instead of each-ing targets and doing everything by hand. A few examples:

class Array
  def first_frog
    detect {|i| i =~ /frog/ }
  end

  def last_frog
    select {|i| i =~ /frog/ }.last
  end
end

p ["dog", "cat", "godzilla", "dogfrog", "woot", "catfrog"].first_frog
# => "dogfrog"
p ["hats", "coats"].first_frog
# => nil
p ["houses", "frogcars", "bottles", "superfrogs"].last_frog
# => "superfrogs"

One example would be doing something like this:

class Bar
  def do_things
    Foo.some_method(x) do |i|
      # only valid `targets` here, yay.
    end
  end
end

class Foo
  def self.failed
    @failed ||= []
  end

  def self.some_method(targets, &block)
    targets.reject {|t| t.do_something.bad? }.each(&block)
  end
end

How to change color and font on ListView

use them in Java code like this:

 color = getResources().getColor(R.color.mycolor);

The getResources() method returns the ResourceManager class for the current activity, and getColor() asks the manager to look up a color given a resource ID

error: expected unqualified-id before ‘.’ token //(struct)

ReducedForm is a type, so you cannot say

ReducedForm.iSimplifiedNumerator = iNumerator/iGreatCommDivisor;

You can only use the . operator on an instance:

ReducedForm rf;
rf.iSimplifiedNumerator = iNumerator/iGreatCommDivisor;

How do I make a splash screen?

This is the best post I've seen on splash screens: http://saulmm.github.io/avoding-android-cold-starts

Saúl Molinero goes into two different options for splash screens: Taking advantage of the window background to animate into your initial screen and displaying placeholder UI (which is a popular choice that Google uses for most of their apps these days).

I refer to this post every time I need to consider cold start time and avoiding user dropoff due to long startup times.

Hope this helps!

How to print a string multiple times?

EDIT: Old answer erased in response to updated question.

You just store the string in a variable:

separator = "!" * int(raw_input("Enter number: "))
print separator
do_stuff()
print separator
other_stuff()
print separator

rbind error: "names do not match previous names"

rbind() needs the two object names to be the same. For example, the first object names: ID Age, the next object names: ID Gender,if you want to use rbind(), it will print out:

names do not match previous names

Run MySQLDump without Locking Tables

The answer varies depending on what storage engine you're using. The ideal scenario is if you're using InnoDB. In that case you can use the --single-transaction flag, which will give you a coherent snapshot of the database at the time that the dump begins.

Show/hide image with JavaScript

Here is a working example: http://jsfiddle.net/rVBzt/ (using jQuery)

<img id="tiger" src="https://twimg0-a.akamaihd.net/profile_images/2642324404/46d743534606515238a9a12cfb4b264a.jpeg">

<a id="toggle">click to toggle</a>

img {display: none;}

a {cursor: pointer; color: blue;}

$('#toggle').click(function() {
    $('#tiger').toggle();
});

How to play video with AVPlayerViewController (AVKit) in Swift

This worked for me in Swift 5

Just added sample video to the project from Sample Videos

Added action Buttons for playing videos from Website and Local with the following swift code example

import UIKit
import AVKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //TODO : Make Sure Add and copy "SampleVideo.mp4" file in project before play
    }

    @IBAction func playWebVideo(_ sender: Any) {

        guard let url = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4") else {
            return
        }
        // Create an AVPlayer, passing it the HTTP Live Streaming URL.
        let player = AVPlayer(url: url)
        let controller = AVPlayerViewController()
        controller.player = player
        present(controller, animated: true) {
            player.play()
        }
    }

    @IBAction func playLocalVideo(_ sender: Any) {

        guard let path = Bundle.main.path(forResource: "SampleVideo", ofType: "mp4") else {
            return
        }
        let videoURL = NSURL(fileURLWithPath: path)

        // Create an AVPlayer, passing it the local video url path
        let player = AVPlayer(url: videoURL as URL)
        let controller = AVPlayerViewController()
        controller.player = player
        present(controller, animated: true) {
            player.play()
        }
    }

}

fatal error LNK1104: cannot open file 'libboost_system-vc110-mt-gd-1_51.lib'

This is the simplest way for an amateur like me who is studying C++ on their own:

First Unzip the boost library to any directory of your choice. I recommend c:\directory.

  1. Open your visual C++.
  2. Create a new project.
  3. Right click on the project.
  4. Click on property.
  5. Click on C/C++.
  6. Click on general.
  7. Select additional include library.
  8. Include the library destination. e.g. c:\boost_1_57_0.
  9. Click on pre-compiler header.
  10. Click on create/use pre-compiled header.
  11. Select not using pre-compiled header.

Then go over to the link library were you experienced your problems.

  1. Go to were the extracted file was c:\boost_1_57_0.
  2. Click on booststrap.bat (don't bother to type on the command window just wait and don't close the window that is the place I had my problem that took me two weeks to solve. After a while the booststrap will run and produce the same file, but now with two different names: b2, and bjam.
  3. Click on b2 and wait it to run.
  4. Click on bjam and wait it to run. Then a folder will be produce called stage.
  5. Right click on the project.
  6. Click on property.
  7. Click on linker.
  8. Click on general.
  9. Click on include additional library directory.
  10. Select the part of the library e.g. c:\boost_1_57_0\stage\lib.

And you are good to go!

Python multiprocessing PicklingError: Can't pickle <type 'function'>

Can't pickle <type 'function'>: attribute lookup __builtin__.function failed

This error will also come if you have any inbuilt function inside the model object that was passed to the async job.

So make sure to check the model objects that are passed doesn't have inbuilt functions. (In our case we were using FieldTracker() function of django-model-utils inside the model to track a certain field). Here is the link to relevant GitHub issue.

Can I use complex HTML with Twitter Bootstrap's Tooltip?

set "html" option to true if you want to have html into tooltip. Actual html is determined by option "title" (link's title attribute shouldn't be set)

$('#example1').tooltip({placement: 'bottom', title: '<p class="testtooltip">par</p>', html: true});

Live sample

error::make_unique is not a member of ‘std’

If you have latest compiler, you can change the following in your build settings:

 C++ Language Dialect    C++14[-std=c++14]

This works for me.

Typescript: Type 'string | undefined' is not assignable to type 'string'

try to find out what the actual value is beforehand. If person has a valid name, assign it to name1, else assign undefined.

let name1: string = (person.name) ? person.name : undefined;

the MySQL service on local computer started and then stopped

I had this issue after my database was working fine for long time. It turned out it was some data corruption.

In the error log I had:

2017-02-07T10:11:42.270567Z 0 [ERROR] InnoDB: Ignoring the redo log due to missing MLOG_CHECKPOINT between the checkpoint 44002250712 and the end 44002250240.
2017-02-07T10:11:42.270606Z 0 [ERROR] InnoDB: Plugin initialization aborted with error Generic error
2017-02-07T10:11:42.577436Z 0 [ERROR] Plugin 'InnoDB' init function returned error.
2017-02-07T10:11:42.577470Z 0 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2017-02-07T10:11:42.577484Z 0 [ERROR] Failed to initialize plugins.
2017-02-07T10:11:42.577488Z 0 [ERROR] Aborting

Then I had to delete the 2 ib_logfile* files, and it restarted again.

How to install Visual C++ Build tools?

The current version (2019/03/07) is Build Tools for Visual Studio 2017. It's an online installer, you need to include at least the individual components:

  • VC++ 2017 version xx.x tools
  • Windows SDK to use standard libraries.

printing a two dimensional array in python

A combination of list comprehensions and str joins can do the job:

inf = float('inf')
A = [[0,1,4,inf,3],
     [1,0,2,inf,4],
     [4,2,0,1,5],
     [inf,inf,1,0,3],
     [3,4,5,3,0]]

print('\n'.join([''.join(['{:4}'.format(item) for item in row]) 
      for row in A]))

yields

   0   1   4 inf   3
   1   0   2 inf   4
   4   2   0   1   5
 inf inf   1   0   3
   3   4   5   3   0

Using for-loops with indices is usually avoidable in Python, and is not considered "Pythonic" because it is less readable than its Pythonic cousin (see below). However, you could do this:

for i in range(n):
    for j in range(n):
        print '{:4}'.format(A[i][j]),
    print

The more Pythonic cousin would be:

for row in A:
    for val in row:
        print '{:4}'.format(val),
    print

However, this uses 30 print statements, whereas my original answer uses just one.

How to create a jQuery function (a new jQuery method or plugin)?

Yes, methods you apply to elements selected using jquery, are called jquery plugins and there is a good amount of info on authoring within the jquery docs.

Its worth noting that jquery is just javascript, so there is nothing special about a "jquery method".

Saving lists to txt file

Framework 4: no need to use StreamWriter:

System.IO.File.WriteAllLines("SavedLists.txt", Lists.verbList);

How to convert a 3D point into 2D perspective projection?

I see this question is a bit old, but I decided to give an answer anyway for those who find this question by searching.
The standard way to represent 2D/3D transformations nowadays is by using homogeneous coordinates. [x,y,w] for 2D, and [x,y,z,w] for 3D. Since you have three axes in 3D as well as translation, that information fits perfectly in a 4x4 transformation matrix. I will use column-major matrix notation in this explanation. All matrices are 4x4 unless noted otherwise.
The stages from 3D points and to a rasterized point, line or polygon looks like this:

  1. Transform your 3D points with the inverse camera matrix, followed with whatever transformations they need. If you have surface normals, transform them as well but with w set to zero, as you don't want to translate normals. The matrix you transform normals with must be isotropic; scaling and shearing makes the normals malformed.
  2. Transform the point with a clip space matrix. This matrix scales x and y with the field-of-view and aspect ratio, scales z by the near and far clipping planes, and plugs the 'old' z into w. After the transformation, you should divide x, y and z by w. This is called the perspective divide.
  3. Now your vertices are in clip space, and you want to perform clipping so you don't render any pixels outside the viewport bounds. Sutherland-Hodgeman clipping is the most widespread clipping algorithm in use.
  4. Transform x and y with respect to w and the half-width and half-height. Your x and y coordinates are now in viewport coordinates. w is discarded, but 1/w and z is usually saved because 1/w is required to do perspective-correct interpolation across the polygon surface, and z is stored in the z-buffer and used for depth testing.

This stage is the actual projection, because z isn't used as a component in the position any more.

The algorithms:

Calculation of field-of-view

This calculates the field-of view. Whether tan takes radians or degrees is irrelevant, but angle must match. Notice that the result reaches infinity as angle nears 180 degrees. This is a singularity, as it is impossible to have a focal point that wide. If you want numerical stability, keep angle less or equal to 179 degrees.

fov = 1.0 / tan(angle/2.0)

Also notice that 1.0 / tan(45) = 1. Someone else here suggested to just divide by z. The result here is clear. You would get a 90 degree FOV and an aspect ratio of 1:1. Using homogeneous coordinates like this has several other advantages as well; we can for example perform clipping against the near and far planes without treating it as a special case.

Calculation of the clip matrix

This is the layout of the clip matrix. aspectRatio is Width/Height. So the FOV for the x component is scaled based on FOV for y. Far and near are coefficients which are the distances for the near and far clipping planes.

[fov * aspectRatio][        0        ][        0              ][        0       ]
[        0        ][       fov       ][        0              ][        0       ]
[        0        ][        0        ][(far+near)/(far-near)  ][        1       ]
[        0        ][        0        ][(2*near*far)/(near-far)][        0       ]

Screen Projection

After clipping, this is the final transformation to get our screen coordinates.

new_x = (x * Width ) / (2.0 * w) + halfWidth;
new_y = (y * Height) / (2.0 * w) + halfHeight;

Trivial example implementation in C++

#include <vector>
#include <cmath>
#include <stdexcept>
#include <algorithm>

struct Vector
{
    Vector() : x(0),y(0),z(0),w(1){}
    Vector(float a, float b, float c) : x(a),y(b),z(c),w(1){}

    /* Assume proper operator overloads here, with vectors and scalars */
    float Length() const
    {
        return std::sqrt(x*x + y*y + z*z);
    }
    
    Vector Unit() const
    {
        const float epsilon = 1e-6;
        float mag = Length();
        if(mag < epsilon){
            std::out_of_range e("");
            throw e;
        }
        return *this / mag;
    }
};

inline float Dot(const Vector& v1, const Vector& v2)
{
    return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;
}

class Matrix
{
    public:
    Matrix() : data(16)
    {
        Identity();
    }
    void Identity()
    {
        std::fill(data.begin(), data.end(), float(0));
        data[0] = data[5] = data[10] = data[15] = 1.0f;
    }
    float& operator[](size_t index)
    {
        if(index >= 16){
            std::out_of_range e("");
            throw e;
        }
        return data[index];
    }
    Matrix operator*(const Matrix& m) const
    {
        Matrix dst;
        int col;
        for(int y=0; y<4; ++y){
            col = y*4;
            for(int x=0; x<4; ++x){
                for(int i=0; i<4; ++i){
                    dst[x+col] += m[i+col]*data[x+i*4];
                }
            }
        }
        return dst;
    }
    Matrix& operator*=(const Matrix& m)
    {
        *this = (*this) * m;
        return *this;
    }

    /* The interesting stuff */
    void SetupClipMatrix(float fov, float aspectRatio, float near, float far)
    {
        Identity();
        float f = 1.0f / std::tan(fov * 0.5f);
        data[0] = f*aspectRatio;
        data[5] = f;
        data[10] = (far+near) / (far-near);
        data[11] = 1.0f; /* this 'plugs' the old z into w */
        data[14] = (2.0f*near*far) / (near-far);
        data[15] = 0.0f;
    }

    std::vector<float> data;
};

inline Vector operator*(const Vector& v, const Matrix& m)
{
    Vector dst;
    dst.x = v.x*m[0] + v.y*m[4] + v.z*m[8 ] + v.w*m[12];
    dst.y = v.x*m[1] + v.y*m[5] + v.z*m[9 ] + v.w*m[13];
    dst.z = v.x*m[2] + v.y*m[6] + v.z*m[10] + v.w*m[14];
    dst.w = v.x*m[3] + v.y*m[7] + v.z*m[11] + v.w*m[15];
    return dst;
}

typedef std::vector<Vector> VecArr;
VecArr ProjectAndClip(int width, int height, float near, float far, const VecArr& vertex)
{
    float halfWidth = (float)width * 0.5f;
    float halfHeight = (float)height * 0.5f;
    float aspect = (float)width / (float)height;
    Vector v;
    Matrix clipMatrix;
    VecArr dst;
    clipMatrix.SetupClipMatrix(60.0f * (M_PI / 180.0f), aspect, near, far);
    /*  Here, after the perspective divide, you perform Sutherland-Hodgeman clipping 
        by checking if the x, y and z components are inside the range of [-w, w].
        One checks each vector component seperately against each plane. Per-vertex
        data like colours, normals and texture coordinates need to be linearly
        interpolated for clipped edges to reflect the change. If the edge (v0,v1)
        is tested against the positive x plane, and v1 is outside, the interpolant
        becomes: (v1.x - w) / (v1.x - v0.x)
        I skip this stage all together to be brief.
    */
    for(VecArr::iterator i=vertex.begin(); i!=vertex.end(); ++i){
        v = (*i) * clipMatrix;
        v /= v.w; /* Don't get confused here. I assume the divide leaves v.w alone.*/
        dst.push_back(v);
    }

    /* TODO: Clipping here */

    for(VecArr::iterator i=dst.begin(); i!=dst.end(); ++i){
        i->x = (i->x * (float)width) / (2.0f * i->w) + halfWidth;
        i->y = (i->y * (float)height) / (2.0f * i->w) + halfHeight;
    }
    return dst;
}

If you still ponder about this, the OpenGL specification is a really nice reference for the maths involved. The DevMaster forums at http://www.devmaster.net/ have a lot of nice articles related to software rasterizers as well.

How to get the hours difference between two date objects?

Use the timestamp you get by calling valueOf on the date object:

var diff = date2.valueOf() - date1.valueOf();
var diffInHours = diff/1000/60/60; // Convert milliseconds to hours

Elasticsearch : Root mapping definition has unsupported parameters index : not_analyzed

I hope the above answer works for elastic search <7.0 but in 7.0 we cannot specify doc type and it is no longer supported. And in that case if we specify doc type we get similar error.

I you are making use of Elastic search 7.0 and Nest C# lastest version(6.6). There are some breaking changes with ES 7.0 which is causing this issue. This is because we cannot specify doc type and in the version 6.6 of NEST they are using doctype. So in order to solve that untill NEST 7.0 is released, we need to download their beta package

Please go through this link for fixing it

https://xyzcoder.github.io/elasticsearch/nest/2019/04/12/es-70-and-nest-mapping-error.html

EDIT: NEST 7.0 is now released. NEST 7.0 works with Elastic 7.0. See the release notes here for details.

rsync: how can I configure it to create target directory on server?

from rsync manual (man rsync)

--mkpath create the destination's path component

How to call a mysql stored procedure, with arguments, from command line?

With quotes around the date:

mysql> CALL insertEvent('2012.01.01 12:12:12');

How to add new line in Markdown presentation?

You could use &nbsp; in R markdown to create a new blank line.

For example, in your .Rmd file:

I want 3 new lines: 

&nbsp;
&nbsp;
&nbsp;

End of file. 

jquery - return value using ajax result on success

There are many ways to get jQuery AJAX response. I am sharing with you two common approaches:

First:

use async=false and within function return ajax-object and later get response ajax-object.responseText

/**
 * jQuery ajax method with async = false, to return response
 * @param  {mix}  selector - your selector
 * @return {mix}           - your ajax response/error
 */
function isSession(selector) {
    return $.ajax({
        type: "POST",
        url: '/order.html',
        data: {
            issession: 1,
            selector: selector
        },
        dataType: "html",
        async: !1,
        error: function() {
            alert("Error occured")
        }
    });
}
// global param
var selector = !0;
// get return ajax object
var ajaxObj = isSession(selector);
// store ajax response in var
var ajaxResponse = ajaxObj.responseText;
// check ajax response
console.log(ajaxResponse);
// your ajax callback function for success
ajaxObj.success(function(response) {
    alert(response);
});

Second:

use $.extend method and make a new function like ajax

/**
 * xResponse function
 *
 * xResponse method is made to return jQuery ajax response
 * 
 * @param  {string} url   [your url or file]
 * @param  {object} your ajax param
 * @return {mix}       [ajax response]
 */
$.extend({
    xResponse: function(url, data) {
        // local var
        var theResponse = null;
        // jQuery ajax
        $.ajax({
            url: url,
            type: 'POST',
            data: data,
            dataType: "html",
            async: false,
            success: function(respText) {
                theResponse = respText;
            }
        });
        // Return the response text
        return theResponse;
    }
});

// set ajax response in var
var xData = $.xResponse('temp.html', {issession: 1,selector: true});

// see response in console
console.log(xData);

you can make it as large as you want...

Print "\n" or newline characters as part of the output on terminal

Use repr

>>> string = "abcd\n"
>>> print(repr(string))
'abcd\n'

Firefox and SSL: sec_error_unknown_issuer

Just had the same problem with a Comodo Wildcard SSL cert. After reading the docs the solution is to ensure you include the certificate chain file they send you in your config i.e.

SSLCertificateChainFile /etc/ssl/crt/yourSERVERNAME.ca-bundle

Full details on Comodo site

Could not load file or assembly CrystalDecisions.ReportAppServer.ClientDoc

You simply need to install Crystal Report Report Run Time downloads on Deployment Server. If problem still appears, then place check asp_client folder in your project main folder.

Bootstrap 3 - Responsive mp4-video

using that code wil give you a responsive video player with full control

<div class="embed-responsive embed-responsive-16by9">
    <iframe class="embed-responsive-item" width="640" height="480" src="https://www.youtube-nocookie.com/embed/Lw_e0vF1IB4" frameborder="0" allowfullscreen></iframe>
</div>

Solutions for INSERT OR UPDATE on SQL Server

I usually do what several of the other posters have said with regard to checking for it existing first and then doing whatever the correct path is. One thing you should remember when doing this is that the execution plan cached by sql could be nonoptimal for one path or the other. I believe the best way to do this is to call two different stored procedures.

FirstSP:
If Exists
   Call SecondSP (UpdateProc)
Else
   Call ThirdSP (InsertProc)

Now, I don't follow my own advice very often, so take it with a grain of salt.

Unexpected token }

You have endless loop in place:

function save() {
    var filename = id('filename').value;
    var name = id('name').value;
    var text = id('text').value;
    save(filename, name, text);
}

No idea what you're trying to accomplish with that endless loop but first of all get rid of it and see if things are working.

Email and phone Number Validation in android

in Kotlin you can use Extension function to validate input

// for Email validation

 fun String.isValidEmail(): Boolean =
        this.isNotEmpty() && Patterns.EMAIL_ADDRESS.matcher(this).matches()

// for Phone validation

fun String.isValidMobile(phone: String): Boolean {
    return Patterns.PHONE.matcher(phone).matches()
}

How to use Sublime over SSH

I'm on Windows and have used 4 methods: SFTP, WinSCP, Unison and Sublime Text on Linux with X11 forwarding over SSH to Windows (yes you can do this without messy configs and using a free tool).

The fourth way is the best if you can install software on your Linux machine.

The fourth way:

MobaXterm

  1. Install MobaXterm on Windows
  2. SSH to your Linux box from MobaXterm
  3. On your linux box, install Sublime Text 3. Here's how to on Ubuntu
  4. At the command prompt, start sublime with subl
  5. That's it! You now have sublime text running on Linux, but with its window running on your Windows desktop. This is possible because MobaXterm handles the X11 forwarding over SSH for you so you don't have to do anything funky to get it going. There might be a teeny amount of a delay, but your files will never be out of sync, because you're editing them right on the Linux machine.

Note: When invoking subl if it complains for a certain library - ensure you install them to successfully invoke sublimetext from mobaxterm.

If you can't install software on your Linux box, the best is Unison. Why?

  • It's free
  • It's fast
  • It's reliable and doesn't care which editor you use
  • You can create custom ignore lists

SFTP

Setup: Install the SFTP Sublime Text package. This package requires a license.

  1. Create a new folder
  2. Open it as a Sublime Text Project.
  3. In the sidebar, right click on the folder and select Map Remote.
  4. Edit the sftp-config.json file
  5. Right click the folder in step 1 select download.
  6. Work locally.

In the sftp-config, I usually set:

"upload_on_save": true,
"sync_down_on_open": true,

This, in addition to an SSH terminal to the machine gives me a fairly seamless remote editing experience.

WinSCP

  1. Install and run WinSCP
  2. Go to Preferences (Ctrl+Alt+P) and click on Transfer, then on Add. Name the preset.
  3. Set the transfer mode to binary (you don't want line conversions)
  4. Set file modification to "No change"
  5. Click the Edit button next to File Mask and setup your include and exclude files and folders (useful for when you have a .git/.svn folder present or you want to exclude build products from being synchronized).
  6. Click OK
  7. Connect to your remote server and navigate to the folder of interest
  8. Choose an empty folder on your local machine.
  9. Select your newly created Transfer settings preset.
  10. Finally, hit Ctrl+U (Commands > Keep remote directory up to date) and make sure "Synchronize on start" and "Update subdirectories" are checked.

From then on, WinSCP will keep your changes synchronized.

Work in the local folder using SublimeText. Just make sure that Sublime Text is set to guess the line endings from the file that is being edited.

Unison

I have found that if source tree is massive (around a few hundred MB with a deep hierarchy), then the WinSCP method described above might be a bit slow. You can get much better performance using Unison. The down side is that Unison is not automatic (you need to trigger it with a keypress) and requires a server component to be running on your linux machine. The up side is that the transfers are incredibly fast, it is very reliable and ignoring files, folders and extensions are incredibly easy to setup.

"R cannot be resolved to a variable"?

It is possible you have an error in your *.xml files: layouts and etc.

Styling every 3rd item of a list using CSS?

Yes, you can use what's known as :nth-child selectors.

In this case you would use:

li:nth-child(3n) {
// Styling for every third element here.
}

:nth-child(3n):

3(0) = 0
3(1) = 3
3(2) = 6
3(3) = 9
3(4) = 12

:nth-child() is compatible in Chrome, Firefox, and IE9+.

For a work around to use :nth-child() amongst other pseudo-classes/attribute selectors in IE6 through to IE8, see this link.

Remove files from Git commit

Using git GUI can simplify removing a file from the prior commit.

Assuming that this isn't a shared branch and you don't mind rewriting history, then run:

git gui citool --amend

You can un-check the file that was mistakenly committed and then click "Commit".

enter image description here

The file is removed from the commit, but will be kept on disk. So if you un-checked the file after mistakenly adding it, it will show in your untracked files list (and if you un-checked the file after mistakenly modifying it it will show in your changes not staged for commit list).

JRE 1.7 - java version - returns: java/lang/NoClassDefFoundError: java/lang/Object

This problem stems from an improper Java installation.

Possibility 1

NOTE: This scenario only applies to Java 8 and prior. Beginning with Java 9, the JRE is structured differently. rt.jar and friends no longer exist, and Pack200 is no longer used.

The Java standard library is contained in various JARs, such as rt.jar, deploy.jar, jsse.jar, etc. When the JRE is packaged, these critical JAR files are compressed with Pack200 and stored as rt.pack, deploy.pack, jsse.pack, etc. The Java installer is supposed to uncompress them. If you are experiencing this error, apparently that didn't happen.

You need to manually run unpack200 on all .pack files in the JRE's lib/ and lib/ext/ folders.

Windows

To unpack one .pack file (for example rt.pack), run:

"%JAVA_HOME%\bin\unpack200" -r -v rt.pack rt.jar

To recursively unpack all .pack files, from the JRE root run:

for /r %f in (*.pack) do "%JAVA_HOME%\bin\unpack200.exe" -r -q "%f" "%~pf%~nf.jar"

*nix

To unpack one .pack file (for example rt.pack), run:

/usr/bin/unpack200 -r -v rt.pack rt.jar

To recursively unpack all .pack files, from the JRE root run:

find -iname "*.pack" -exec sh -c "/usr/bin/unpack200 -r -q {} \$(echo {} | sed 's/\(.*\.\)pack/\1jar/')" \;

Possibility 2

You misinstalled Java in some other way. Perhaps you installed without admin rights, or tried to simply extract files out of the installer. Try again with the installer and/or more privileges. Or, if you don't want to use the installer, use the .tar.gz Java package instead.

How do I create an iCal-type .ics file that can be downloaded by other users?

There is also this tool you can use. It supports multi-events .ics file creation. It also supports timezone as well.

http://apps.marudot.com/ical/

How do I use modulus for float/double?

fmod is the standard C function for handling floating-point modulus; I imagine your source was saying that Java handles floating-point modulus the same as C's fmod function. In Java you can use the % operator on doubles the same as on integers:

int x = 5 % 3; // x = 2
double y = .5 % .3; // y = .2

Difference Between One-to-Many, Many-to-One and Many-to-Many?

One-to-many

The one-to-many table relationship looks like this:

One-to-many

In a relational database system, a one-to-many table relationship associates two tables based on a Foreign Key column in the child table referencing the Primary Key of one record in the parent table.

In the table diagram above, the post_id column in the post_comment table has a Foreign Key relationship with the post table id Primary Key column:

    ALTER TABLE
        post_comment
    ADD CONSTRAINT
        fk_post_comment_post_id
    FOREIGN KEY (post_id) REFERENCES post

@ManyToOne annotation

In JPA, the best way to map the one-to-many table relationship is to use the @ManyToOne annotation.

In our case, the PostComment child entity maps the post_id Foreign Key column using the @ManyToOne annotation:

    @Entity(name = "PostComment")
    @Table(name = "post_comment")
    public class PostComment {
    
        @Id
        @GeneratedValue
        private Long id;
    
        private String review;
    
        @ManyToOne(fetch = FetchType.LAZY)
        private Post post;
        
    }

Using the JPA @OneToMany annotation

Just because you have the option of using the @OneToMany annotation, it doesn't mean it should be the default option for all the one-to-many database relationships.

The problem with JPA collections is that we can only use them when their element count is rather low.

The best way to map a @OneToMany association is to rely on the @ManyToOne side to propagate all entity state changes:

    @Entity(name = "Post")
    @Table(name = "post")
    public class Post {
    
        @Id
        @GeneratedValue
        private Long id;
    
        private String title;
    
        @OneToMany(
            mappedBy = "post", 
            cascade = CascadeType.ALL, 
            orphanRemoval = true
        )
        private List<PostComment> comments = new ArrayList<>();
    
        //Constructors, getters and setters removed for brevity
    
        public void addComment(PostComment comment) {
            comments.add(comment);
            comment.setPost(this);
        }
    
        public void removeComment(PostComment comment) {
            comments.remove(comment);
            comment.setPost(null);
        }
    }

The parent Post entity features two utility methods (e.g. addComment and removeComment) which are used to synchronize both sides of the bidirectional association.

You should provide these methods whenever you are working with a bidirectional association as, otherwise, you risk very subtle state propagation issues.

The unidirectional @OneToMany association is to be avoided as it's less efficient than using @ManyToOne or the bidirectional @OneToMany association.

One-to-one

The one-to-one table relationship looks as follows:

One-to-one

In a relational database system, a one-to-one table relationship links two tables based on a Primary Key column in the child which is also a Foreign Key referencing the Primary Key of the parent table row.

Therefore, we can say that the child table shares the Primary Key with the parent table.

In the table diagram above, the id column in the post_details table has also a Foreign Key relationship with the post table id Primary Key column:

    ALTER TABLE
        post_details
    ADD CONSTRAINT
        fk_post_details_id
    FOREIGN KEY (id) REFERENCES post

Using the JPA @OneToOne with @MapsId annotations

The best way to map a @OneToOne relationship is to use @MapsId. This way, you don't even need a bidirectional association since you can always fetch the PostDetails entity by using the Post entity identifier.

The mapping looks like this:

@Entity(name = "PostDetails")
@Table(name = "post_details")
public class PostDetails {

    @Id
    private Long id;

    @Column(name = "created_on")
    private Date createdOn;

    @Column(name = "created_by")
    private String createdBy;

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    @JoinColumn(name = "id")
    private Post post;

    public PostDetails() {}

    public PostDetails(String createdBy) {
        createdOn = new Date();
        this.createdBy = createdBy;
    }

    //Getters and setters omitted for brevity
}

This way, the id property serves as both Primary Key and Foreign Key. You'll notice that the @Id column no longer uses a @GeneratedValue annotation since the identifier is populated with the identifier of the post association.

Many-to-many

The many-to-many table relationship looks as follows:

Many-to-many

In a relational database system, a many-to-many table relationship links two parent tables via a child table which contains two Foreign Key columns referencing the Primary Key columns of the two parent tables.

In the table diagram above, the post_id column in the post_tag table has also a Foreign Key relationship with the post table id Primary Key column:

    ALTER TABLE
        post_tag
    ADD CONSTRAINT
        fk_post_tag_post_id
    FOREIGN KEY (post_id) REFERENCES post

And, the tag_id column in the post_tag table has a Foreign Key relationship with the tag table id Primary Key column:

    ALTER TABLE
        post_tag
    ADD CONSTRAINT
        fk_post_tag_tag_id
    FOREIGN KEY (tag_id) REFERENCES tag

Using the JPA @ManyToMany mapping

This is how you can map the many-to-many table relationship with JPA and Hibernate:

    @Entity(name = "Post")
    @Table(name = "post")
    public class Post {

        @Id
        @GeneratedValue
        private Long id;

        private String title;

        @ManyToMany(cascade = { 
            CascadeType.PERSIST, 
            CascadeType.MERGE
        })
        @JoinTable(name = "post_tag",
            joinColumns = @JoinColumn(name = "post_id"),
            inverseJoinColumns = @JoinColumn(name = "tag_id")
        )
        private Set<Tag> tags = new HashSet<>();

        //Getters and setters ommitted for brevity

        public void addTag(Tag tag) {
            tags.add(tag);
            tag.getPosts().add(this);
        }

        public void removeTag(Tag tag) {
            tags.remove(tag);
            tag.getPosts().remove(this);
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof Post)) return false;
            return id != null && id.equals(((Post) o).getId());
        }

        @Override
        public int hashCode() {
            return getClass().hashCode();
        }
    }

    @Entity(name = "Tag")
    @Table(name = "tag")
    public class Tag {

        @Id
        @GeneratedValue
        private Long id;

        @NaturalId
        private String name;

        @ManyToMany(mappedBy = "tags")
        private Set<Post> posts = new HashSet<>();

        //Getters and setters ommitted for brevity

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Tag tag = (Tag) o;
            return Objects.equals(name, tag.name);
        }

        @Override
        public int hashCode() {
            return Objects.hash(name);
        }
    }
  1. The tags association in the Post entity only defines the PERSIST and MERGE cascade types. The REMOVE entity state transition doesn't make any sense for a @ManyToMany JPA association since it could trigger a chain deletion that would ultimately wipe both sides of the association.
  2. The add/remove utility methods are mandatory if you use bidirectional associations so that you can make sure that both sides of the association are in sync.
  3. The Post entity uses the entity identifier for equality since it lacks any unique business key. You can use the entity identifier for equality as long as you make sure that it stays consistent across all entity state transitions.
  4. The Tag entity has a unique business key which is marked with the Hibernate-specific @NaturalId annotation. When that's the case, the unique business key is the best candidate for equality checks.
  5. The mappedBy attribute of the posts association in the Tag entity marks that, in this bidirectional relationship, the Post entity owns the association. This is needed since only one side can own a relationship, and changes are only propagated to the database from this particular side.
  6. The Set is to be preferred, as using a List with @ManyToMany is less efficient.

Why would anybody use C over C++?

In addition to several other points mentioned already:

Less surprise

that is, it is much easier to see what a piece of code will do do exactly . In C++ you need to approach guru level to be able to know exactly what code the compiler generates (try a combination of templates, multiple inheritance, auto generated constructors, virtual functions and mix in a bit of namespace magic and argument dependent lookup).

In many cases this magic is nice, but for example in real-time systems it can really screw up your day.

jQuery - multiple $(document).ready ...?

Execution is top-down. First come, first served.

If execution sequence is important, combine them.

Google Chrome redirecting localhost to https

Open Chrome Developer Tools -> go to Network -> select Disable Cache -> reload

Change drive in git bash for windows

In order to navigate to a different drive just use

cd /E/Study/Codes

It will solve your problem.

JS: Uncaught TypeError: object is not a function (onclick)

I was able to figure it out by following the answer in this thread: https://stackoverflow.com/a/8968495/1543447

Basically, I renamed all values, function names, and element names to different values so they wouldn't conflict - and it worked!

How do I exit the results of 'git diff' in Git Bash on windows?

Using WIN + Q worked for me. Just q alone gave me "command not found" and eventually it jumped back into the git diff insanity.

Adding asterisk to required fields in Bootstrap 3

Assuming this is what the HTML looks like

<div class="form-group required">
   <label class="col-md-2 control-label">E-mail</label>
   <div class="col-md-4"><input class="form-control" id="id_email" name="email" placeholder="E-mail" required="required" title="" type="email" /></div>
</div>

To display an asterisk on the right of the label:

.form-group.required .control-label:after { 
    color: #d00;
    content: "*";
    position: absolute;
    margin-left: 8px;
    top:7px;
}

Or to the left of the label:

.form-group.required .control-label:before{
   color: red;
   content: "*";
   position: absolute;
   margin-left: -15px;
}

To make a nice big red asterisks you can add these lines:

font-family: 'Glyphicons Halflings';
font-weight: normal;
font-size: 14px;

Or if you are using Font Awesome add these lines (and change the content line):

font-family: 'FontAwesome';
font-weight: normal;
font-size: 14px;
content: "\f069";

Cannot resolve symbol AppCompatActivity - Support v7 libraries aren't recognized?

If the given solutions does not work, create a new project with 'KOTLIN' as the language even if your work is on java. Then replace the 'main' folder of the new project with the 'main' folder of the old.

List of standard lengths for database fields

Some probably correct column lengths

                            Min Max

Hostname                    1   255
Domain Name                 4   253
Email Address               7   254
Email Address [1]           3   254
Telephone Number            10  15      
Telephone Number [2]        3   26  
HTTP(S) URL w domain name   11  2083        
URL [3]                     6   2083    
Postal Code [4]             2   11
IP Address (incl ipv6)      7   45
Longitude                   numeric 9,6
Latitude                    numeric 8,6
Money[5]                    numeric 19,4

[1] Allow local domains or TLD-only domains
[2] Allow short numbers like 911 and extensions like 16045551212x12345
[3] Allow local domains, tv:// scheme
[4] http://en.wikipedia.org/wiki/List_of_postal_codes. Use max 12 if storing dash or space
[5] http://stackoverflow.com/questions/224462/storing-money-in-a-decimal-column-what-precision-and-scale

A long rant on personal names

A personal name is either a Polynym (a name with multiple sortable components), a Mononym (a name with only one component), or a Pictonym (a name represented by a picture - this exists due to people like Prince).

A person can have multiple names, playing roles, such as LEGAL, MARITAL, MAIDEN, PREFERRED, SOBRIQUET, PSEUDONYM, etc. You might have business rules, such as "a person can only have one legal name at a time, but multiple pseudonyms at a time".

Some examples:

names: [
  {
    type:"POLYNYM",
    role:"LEGAL",
    given:"George",
    middle:"Herman",
    moniker:"Babe",
    surname:"Ruth",
    generation:"JUNIOR"
  },
  {
    type:"MONONYM",
    role:"SOBRIQUET",
    mononym:"The Bambino" /* mononyms can be more than one word, but only one component */
  },
  {
    type:"MONONYM",
    role:"SOBRIQUET",
    mononym:"The Sultan of Swat"
  }
]

or

names: [
  {
    type:"POLYNYM",
    role:"PREFERRED",
    given:"Malcolm",
    surname:"X"
  },
  {
    type:"POLYNYM",
    role:"BIRTH",
    given:"Malcolm",
    surname:"Little"
  },
  {
    type:"POLYNYM",
    role:"LEGAL",
    given:"Malik",
    surname:"El-Shabazz"
  }
]

or

names:[
  {
    type:"POLYNYM",
    role:"LEGAL",
    given:"Prince",
    middle:"Rogers",
    surname:"Nelson"
  },
  {
    type:"MONONYM",
    role:"SOBRIQUET",
    mononym:"Prince"
  },
  {
    type:"PICTONYM",
    role:"LEGAL",
    url:"http://upload.wikimedia.org/wikipedia/en/thumb/a/af/Prince_logo.svg/130px-Prince_logo.svg.png"
  }
]

or

names:[
  {
    type:"POLYNYM",
    role:"LEGAL",
    given:"Juan Pablo",
    surname:"Fernández de Calderón",
    secondarySurname:"García-Iglesias" /* hispanic people often have two surnames. it can be impolite to use the wrong one. Portuguese and Spaniards differ as to which surname is important */
  }
]

Given names, middle names, surnames can be multiple words such as "Billy Bob" Thornton, or Ralph "Vaughn Williams".

How to properly use unit-testing's assertRaises() with NoneType objects?

The problem is the TypeError gets raised 'before' assertRaises gets called since the arguments to assertRaises need to be evaluated before the method can be called. You need to pass a lambda expression like:

self.assertRaises(TypeError, lambda: self.testListNone[:1])

pip install failing with: OSError: [Errno 13] Permission denied on directory

So, I got this same exact error for a completely different reason. Due to a totally separate, but known Homebrew + pip bug, I had followed this workaround listed on Google Cloud's help docs, where you create a .pydistutils.cfg file in your home directory. This file has special config that you're only supposed to use for your install of certain libraries. I should have removed that disutils.cfg file after installing the packages, but I forgot to do so. So the fix for me was actually just...

rm ~/.pydistutils.cfg.

And then everything worked as normal. Of course, if you have some config in that file for a real reason, then you won't want to just straight rm that file. But in case anyone else did that workaround, and forgot to remove that file, this did the trick for me!

convert from Color to brush

If you happen to be working with a application which has a mix of Windows Forms and WPF you might have the additional complication of trying to convert a System.Drawing.Color to a System.Windows.Media.Color. I'm not sure if there is an easier way to do this, but I did it this way:

System.Drawing.Color MyColor = System.Drawing.Color.Red;
System.Windows.Media.Color = ConvertColorType(MyColor);

System.Windows.Media.Color ConvertColorType(System.Drawing.Color color)
{
  byte AVal = color.A;
  byte RVal = color.R;
  byte GVal = color.G;
  byte BVal = color.B;

  return System.Media.Color.FromArgb(AVal, RVal, GVal, BVal);
}

Then you can use one of the techniques mentioned previously to convert to a Brush.

SQL Server principal "dbo" does not exist,

I resolved this issue by setting database owner. My database did not have had any owner before this issue. Execute this command in your database to set owner to sysadmin account:

use [YourDatabaseName] EXEC sp_changedbowner 'sa'

How to get selenium to wait for ajax response?

Below is my code for fetch. Took me while researching because jQuery.active doesn't work with fetch. Here is the answer helped me proxy fetch, but its only for ajax not fetch mock for selenium

public static void customPatchXMLHttpRequest(WebDriver driver) {
    try {
        if (driver instanceof JavascriptExecutor) {
            JavascriptExecutor jsDriver = (JavascriptExecutor) driver;
            Object numberOfAjaxConnections = jsDriver.executeScript("return window.openHTTPs");
            if (numberOfAjaxConnections instanceof Long) {
                return;
            }
            String script = "  (function() {" + "var oldFetch = fetch;"
                    + "window.openHTTPs = 0; console.log('starting xhttps');" + "fetch = function(input,init ){ "
                    + "window.openHTTPs++; "

                    + "return oldFetch(input,init).then( function (response) {"
                    + "      if (response.status >= 200 && response.status < 300) {"
                    + "          window.openHTTPs--;  console.log('Call completed. Remaining active calls: '+ window.openHTTPs); return response;"
                    + "      } else {"
                    + "          window.openHTTPs--; console.log('Call fails. Remaining active calls: ' + window.openHTTPs);  return response;"
                    + "      };})" + "};" + "var oldOpen = XMLHttpRequest.prototype.open;"
                    + "XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {"
                    + "window.openHTTPs++; console.log('xml ajax called');"
                    + "this.addEventListener('readystatechange', function() {" + "if(this.readyState == 4) {"
                    + "window.openHTTPs--; console.log('xml ajax complete');" + "}" + "}, false);"
                    + "oldOpen.call(this, method, url, async, user, pass);" + "}" +

                    "})();";
            jsDriver.executeScript(script);
        } else {
            System.out.println("Web driver: " + driver + " cannot execute javascript");
        }
    } catch (Exception e) {
        System.out.println(e);
    }
}

Deleting elements from std::set while iterating

I think using the STL method 'remove_if' from could help to prevent some weird issue when trying to attempt to delete the object that is wrapped by the iterator.

This solution may be less efficient.

Let's say we have some kind of container, like vector or a list called m_bullets:

Bullet::Ptr is a shared_pr<Bullet>

'it' is the iterator that 'remove_if' returns, the third argument is a lambda function that is executed on every element of the container. Because the container contains Bullet::Ptr, the lambda function needs to get that type(or a reference to that type) passed as an argument.

 auto it = std::remove_if(m_bullets.begin(), m_bullets.end(), [](Bullet::Ptr bullet){
    // dead bullets need to be removed from the container
    if (!bullet->isAlive()) {
        // lambda function returns true, thus this element is 'removed'
        return true;
    }
    else{
        // in the other case, that the bullet is still alive and we can do
        // stuff with it, like rendering and what not.
        bullet->render(); // while checking, we do render work at the same time
        // then we could either do another check or directly say that we don't
        // want the bullet to be removed.
        return false;
    }
});
// The interesting part is, that all of those objects were not really
// completely removed, as the space of the deleted objects does still 
// exist and needs to be removed if you do not want to manually fill it later 
// on with any other objects.
// erase dead bullets
m_bullets.erase(it, m_bullets.end());

'remove_if' removes the container where the lambda function returned true and shifts that content to the beginning of the container. The 'it' points to an undefined object that can be considered garbage. Objects from 'it' to m_bullets.end() can be erased, as they occupy memory, but contain garbage, thus the 'erase' method is called on that range.

How to convert int to float in C?

Change your code to:

int total=0, number=0;
float percentage=0.0f;

percentage=((float)number/total)*100f;
printf("%.2f", (double)percentage);

How to view the assembly behind the code using Visual C++?

There are several approaches:

  1. You can normally see assembly code while debugging C++ in visual studio (and eclipse too). For this in Visual Studio put a breakpoint on code in question and when debugger hits it rigth click and find "Go To Assembly" ( or press CTRL+ALT+D )

  2. Second approach is to generate assembly listings while compiling. For this go to project settings -> C/C++ -> Output Files -> ASM List Location and fill in file name. Also select "Assembly Output" to "Assembly With Source Code".

  3. Compile the program and use any third-party debugger. You can use OllyDbg or WinDbg for this. Also you can use IDA (interactive disassembler). But this is hardcore way of doing it.

CocoaPods Errors on Project Build

I had the same problem recently. I have tried every possible advice, nothing except this plugin has worked for me:

https://github.com/kylef/cocoapods-deintegrate

After the cleaning up of the current cocoapods integration, what's left to be deleted are Podfile, Podfile.lock and the .xcworkspace. Then just install all over again.

I hope I will help someone with this.

Using reCAPTCHA on localhost

Please note that as of 2016, ReCaptcha doesn't naively support localhost anymore. From the FAQ:

localhost domains are no longer supported by default. If you wish to continue supporting them for development you can add them to the list of supported domains for your site key. Go to the admin console to update your list of supported domains. We advise to use a separate key for development and production and to not allow localhost on your production site key.

So just add localhost to your list of domains for your site and you'll be good.

How to import functions from different js file in a Vue+webpack+vue-loader project

After a few hours of messing around I eventually got something that works, partially answered in a similar issue here: How do I include a JavaScript file in another JavaScript file?

BUT there was an import that was screwing the rest of it up:

Use require in .vue files

<script>
  var mylib = require('./mylib');
  export default {
  ....

Exports in mylib

 exports.myfunc = () => {....}

Avoid import

The actual issue in my case (which I didn't think was relevant!) was that mylib.js was itself using other dependencies. The resulting error seems to have nothing to do with this, and there was no transpiling error from webpack but anyway I had:

import models from './model/models'
import axios from 'axios'

This works so long as I'm not using mylib in a .vue component. However as soon as I use mylib there, the error described in this issue arises.

I changed to:

let models = require('./model/models');
let axios = require('axios');

And all works as expected.

Cast to generic type in C#

You can't do that. You could try telling your problem from a more high level point of view (i.e. what exactly do you want to accomplish with the casted variable) for a different solution.

You could go with something like this:

 public abstract class Message { 
     // ...
 }
 public class Message<T> : Message {
 }

 public abstract class MessageProcessor {
     public abstract void ProcessMessage(Message msg);
 }
 public class SayMessageProcessor : MessageProcessor {
     public override void ProcessMessage(Message msg) {
         ProcessMessage((Message<Say>)msg);
     }
     public void ProcessMessage(Message<Say> msg) {
         // do the actual processing
     }
 }

 // Dispatcher logic:
 Dictionary<Type, MessageProcessor> messageProcessors = {
    { typeof(Say), new SayMessageProcessor() },
    { typeof(string), new StringMessageProcessor() }
 }; // properly initialized

 messageProcessors[msg.GetType().GetGenericArguments()[0]].ProcessMessage(msg);

Example on ToggleButton

<ToggleButton 
    android:id="@+id/togglebutton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textOn="Vibrate on"
    android:textOff="Vibrate off"
    android:onClick="onToggleClicked"/>

Within the Activity that hosts this layout, the following method handles the click event:

public void onToggleClicked(View view) {
    // Is the toggle on?
    boolean on = ((ToggleButton) view).isChecked();

    if (on) {
        // Enable vibrate
    } else {
        // Disable vibrate
    }
}

Eclipse hangs on loading workbench

Pretty old question but the most simple answer isn't yet posted.
Here it is :
1) In [workspace]\.metadata\.plugins\org.eclipse.e4.workbench delete workbench.xmi file.
In most cases it's enough - try to load Eclipse.
Still you have to re-configure your specific perspective settings (if any)

2) Now getting problems with building projects that worked perfectly? As of my experience following steps help:
- uncheck Projects->Build automatically
- switch to Java perspective (if not yet): Window -> Open perspective -> Java
- locate Problems view or open it: Window -> Show view -> Problems
- right-click on problem groups and select Delete. Be sure to delete Lint errors
- clean the workspace: Project -> Clean... with option Clean all projects
- check Projects->Build automatically
- if problems persist for some projects: right-click project, select Properties -> Android and make sure appropriate Project Build Target is chosen

3) It was always sufficient for me. But if you still get problems - try @george post recommendations

Default session timeout for Apache Tomcat applications

Open $CATALINA_BASE/conf/web.xml and find this

<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly   -->
<!-- created sessions by modifying the value below.                       -->

<session-config>
  <session-timeout>30</session-timeout>
</session-config>

all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.

This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different

Add left/right horizontal padding to UILabel

If you want to add padding to UILabel but not want to subclass it you can put your label in a UIView and give paddings with autolayout like:

Padding with UIView and autolayout

Result:

Result

How to remove title bar from the android activity?

You can try:

<activity android:name=".YourActivityName"
          android:theme="@style/Theme.Design.NoActionBar">

that works for me

jQuery jump or scroll to certain position, div or target on the page from button onclick

I would style a link to look like a button, because that way there is a no-js fallback.


So this is how you could animate the jump using jquery. No-js fallback is a normal jump without animation.

Original example:

jsfiddle

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $(".jumper").on("click", function( e ) {_x000D_
_x000D_
    e.preventDefault();_x000D_
_x000D_
    $("body, html").animate({ _x000D_
      scrollTop: $( $(this).attr('href') ).offset().top _x000D_
    }, 600);_x000D_
_x000D_
  });_x000D_
});
_x000D_
#long {_x000D_
  height: 500px;_x000D_
  background-color: blue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!-- Links that trigger the jumping -->_x000D_
<a class="jumper" href="#pliip">Pliip</a>_x000D_
<a class="jumper" href="#ploop">Ploop</a>_x000D_
<div id="long">...</div>_x000D_
<!-- Landing elements -->_x000D_
<div id="pliip">pliip</div>_x000D_
<div id="ploop">ploop</div>
_x000D_
_x000D_
_x000D_


New example with actual button styles for the links, just to prove a point.

Everything is essentially the same, except that I changed the class .jumper to .button and I added css styling to make the links look like buttons.

Button styles example

How to access Spring MVC model object in javascript file?

JavaScript is run on the client side. Your model does not exist on the client side, it only exists on the server side while you are rendering your .jsp.

If you want data from the model to be available to client side code (ie. javascript), you will need to store it somewhere in the rendered page. For example, you can use your Jsp to write JavaScript assigning your model to JavaScript variables.

Update:

A simple example

<%-- SomeJsp.jsp --%>
<script>var paramOne =<c:out value="${paramOne}"/></script>

How can the Euclidean distance be calculated with NumPy?

It can be done like the following. I don't know how fast it is, but it's not using NumPy.

from math import sqrt
a = (1, 2, 3) # Data point 1
b = (4, 5, 6) # Data point 2
print sqrt(sum( (a - b)**2 for a, b in zip(a, b)))