I needed something similar, and came up with using the :before (or :after) pseudoclasses:
#mydiv {
background-color: #fbb;
margin-top: 100px;
position: relative;
}
#mydiv:before {
content: "";
background-color: #bfb;
top: -100px;
height: 100px;
width: 100%;
position: absolute;
}
Voila! No need to fight with Gradle :)
In brief, $@
expands to the positional arguments passed from the caller to either a function or a script. Its meaning is context-dependent: Inside a function, it expands to the arguments passed to such function. If used in a script (not inside the scope a function), it expands to the arguments passed to such script.
$ cat my-sh
#! /bin/sh
echo "$@"
$ ./my-sh "Hi!"
Hi!
$ put () ( echo "$@" )
$ put "Hi!"
Hi!
Now, another topic that is of paramount importance when understanding how $@
behaves in the shell is word splitting. The shell splits tokens based on the contents of the IFS
variable. Its default value is \t\n
; i.e., whitespace, tab, and newline.
Expanding "$@"
gives you a pristine copy of the arguments passed. However, expanding $@
will not always. More specifically, if the arguments contain characters from IFS
, they will split.
Most of the time what you will want to use is "$@"
, not $@
.
That's because endOf
mutates the original value.
Relevant quote:
Mutates the original moment by setting it to the end of a unit of time.
Here's an example function that gives you the output you want:
function getMonthDateRange(year, month) {
var moment = require('moment');
// month in moment is 0 based, so 9 is actually october, subtract 1 to compensate
// array is 'year', 'month', 'day', etc
var startDate = moment([year, month - 1]);
// Clone the value before .endOf()
var endDate = moment(startDate).endOf('month');
// just for demonstration:
console.log(startDate.toDate());
console.log(endDate.toDate());
// make sure to call toDate() for plain JavaScript date type
return { start: startDate, end: endDate };
}
References:
For Eclipse version 4.3.0.v20130605-2000. You can use the Java (default) perspective. In this perspective, it provides the Package Explorer view.
To use the Java (default) perspective: Window -> Open Perspective -> Other... -> Java (default) -> Ok
If you already use the Java (default) perspective but accidentally close the Package Explorer view, you can open it by; Window -> Show View -> Package Explorer (Alt+Shift+Q,P)
If the Package Explorer still doesn't appear in the Java (default) perspective, I suggest you to right-click on the Java (default) perspective button that is located in the top-right of the Eclipse IDE and then select Reset. The Java (default) perspective will show the Package Explorer view, Code pane, Outline view, Problems, JavaDoc and Declaration View.
private static void saveArrayToFile(String fileName, int[] array) throws IOException {
Files.write( // write to file
Paths.get(fileName), // get path from file
Collections.singleton(Arrays.toString(array)), // transform array to collection using singleton
Charset.forName("UTF-8") // formatting
);
}
Oracle 11g provides a PIVOT
operation that does what you want.
Oracle 11g solution
select * from
(select id, k, v from _kv)
pivot(max(v) for k in ('name', 'age', 'gender', 'status')
(Note: I do not have a copy of 11g to test this on so I have not verified its functionality)
I obtained this solution from: http://orafaq.com/wiki/PIVOT
EDIT -- pivot xml option (also Oracle 11g)
Apparently there is also a pivot xml
option for when you do not know all the possible column headings that you may need. (see the XML TYPE section near the bottom of the page located at http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html)
select * from
(select id, k, v from _kv)
pivot xml (max(v)
for k in (any) )
(Note: As before I do not have a copy of 11g to test this on so I have not verified its functionality)
Edit2: Changed v
in the pivot
and pivot xml
statements to max(v)
since it is supposed to be aggregated as mentioned in one of the comments. I also added the in
clause which is not optional for pivot
. Of course, having to specify the values in the in
clause defeats the goal of having a completely dynamic pivot/crosstab query as was the desire of this question's poster.
You can press q to exit.
git hist
is using a pager tool so you can scroll up and down the results before returning to the console.
Culprit is preflight request using OPTIONS method
For HTTP request methods that can cause side-effects on user data (in particular, for HTTP methods other than GET, or for POST usage with certain MIME types), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTP OPTIONS request method, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method.
Web specification refer to: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
I resolved the problem by adding following lines in Nginx conf.
location / {
if ($request_method = OPTIONS ) {
add_header Access-Control-Allow-Origin "*";
add_header Access-Control-Allow-Methods "POST, GET, PUT, UPDATE, DELETE, OPTIONS";
add_header Access-Control-Allow-Headers "Authorization";
add_header Access-Control-Allow-Credentials "true";
add_header Content-Length 0;
add_header Content-Type text/plain;
return 200;
}
location ~ ^/(xxxx)$ {
if ($request_method = OPTIONS) {
rewrite ^(.*)$ / last;
}
}
You can do these conversions also with the .NET Framework:
JSON to XML: by using System.Runtime.Serialization.Json
var xml = XDocument.Load(JsonReaderWriterFactory.CreateJsonReader(
Encoding.ASCII.GetBytes(jsonString), new XmlDictionaryReaderQuotas()));
XML to JSON: by using System.Web.Script.Serialization
var json = new JavaScriptSerializer().Serialize(GetXmlData(XElement.Parse(xmlString)));
private static Dictionary<string, object> GetXmlData(XElement xml)
{
var attr = xml.Attributes().ToDictionary(d => d.Name.LocalName, d => (object)d.Value);
if (xml.HasElements) attr.Add("_value", xml.Elements().Select(e => GetXmlData(e)));
else if (!xml.IsEmpty) attr.Add("_value", xml.Value);
return new Dictionary<string, object> { { xml.Name.LocalName, attr } };
}
just use
{
text-decoration-line: underline;
text-underline-offset: 2px;
}
Because LINQ
can do everything...:
string test = "key1=value1&key2=value2&key3=value3";
var count = test.Where(x => x == '&').Count();
Or if you like, you can use the Count
overload that takes a predicate :
var count = test.Count(x => x == '&');
For the sake of bandwidth saving, we shouldn't include <div>
for each of <label>
and <input>
pair
This solution may serve you better and may increase readability
<div class="form">
<label for="product_name">Name</label>
<input id="product_name" name="product[name]" size="30" type="text" value="4">
<label for="product_stock">Stock</label>
<input id="product_stock" name="product[stock]" size="30" type="text" value="-1">
<label for="price_amount">Amount</label>
<input id="price_amount" name="price[amount]" size="30" type="text" value="6.0">
</div>
The css for above form would be
.form > label
{
float: left;
clear: right;
}
.form > input
{
float: right;
}
I believe the output would be as following:
Most likely that your key alias does not exist for your keystore file.
This answer should fix your signing issue ;)
Here's a short complete html example. See demo http://jsfiddle.net/CU585/
<!DOCTYPE html><html><head><title>resizable columns</title>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/themes/smoothness/jquery-ui.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/jquery-ui.min.js"></script>
<style>
th {border: 1px solid black;}
table{border-collapse: collapse;}
.ui-icon, .ui-widget-content .ui-icon {background-image: none;}
</style>
<body>
<table>
<tr><th>head 1</th><th>head 2</th></tr><tr><td>a1</td><td>b1</td></tr></table><script>
$( "th" ).resizable();
</script></body></html>
Use argon2i. The argon2 password hashing function has won the Password Hashing Competition.
Other reasonable choices, if using argon2 is not available, are scrypt, bcrypt and PBKDF2. Wikipedia has pages for these functions:
MD5, SHA1 and SHA256 are message digests, not password-hashing functions. They are not suitable for this purpose.
Switching from MD5 to SHA1 or SHA512 will not improve the security of the construction so much. Computing a SHA256 or SHA512 hash is very fast. An attacker with common hardware could still try tens of millions (with a single CPU) or even billions (with a single GPU) of hashes per second. Good password hashing functions include a work factor to slow down dictionary attacks.
Here is a suggestion for PHP programmers: read the PHP FAQ then use password_hash().
most simple solution would be to set a boolean var. if to true where you do the insert statement and then in the outter loop check this and insert the tweet there if the boolean is true...
If not all of your document scrolls, say, when you have a scrolling div
within the document, then the above solutions won't work without adaptations. Here's how to check whether the div's scrollbar has hit the bottom:
$('#someScrollingDiv').on('scroll', function() {
let div = $(this).get(0);
if(div.scrollTop + div.clientHeight >= div.scrollHeight) {
// do the lazy loading here
}
});
You can also do:
export type UserEvent = Event & { UserId: string; };
Based on cletus's answer you may create new extension.
public static class StringExtensions
{
public static bool IsAlphaNumeric(this string str)
{
if (string.IsNullOrEmpty(str))
return false;
Regex r = new Regex("^[a-zA-Z0-9]*$");
return r.IsMatch(str);
}
}
The standard numpy function for what you want is np.column_stack
:
>>> np.column_stack(([1, 2, 3], [4, 5, 6]))
array([[1, 4],
[2, 5],
[3, 6]])
So with your portfolio
and index
arrays, doing
np.column_stack((portfolio, index))
would yield something like:
[[portfolio_value1, index_value1],
[portfolio_value2, index_value2],
[portfolio_value3, index_value3],
...]
First I will check the python3
path where it lives
And then in the VS Code settings just add that path, for example:
"python.pythonPath": "/usr/local/bin/python3"
There's an official gulp recipe for this using minimist.
https://github.com/gulpjs/gulp/blob/master/docs/recipes/pass-arguments-from-cli.md
The basics are using minimist to separate the cli arguments and combine them with known options:
var options = minimist(process.argv.slice(2), knownOptions);
Which would parse something like
$ gulp scripts --env development
More complete info in the recipe.
I had this symbol _
in the head of one table and the code didn't run, so I had to delete.
Create your own 9-patch image and set it as the background of the toggle button.
Static libraries do not link with other static libraries. The only way to do this is to use your librarian/archiver tool (for example ar on Linux) to create a single new static library by concatenating the multiple libraries.
Edit: In response to your update, the only way I know to select only the symbols that are required is to manually create the library from the subset of the .o files that contain them. This is difficult, time consuming and error prone. I'm not aware of any tools to help do this (not to say they don't exist), but it would make quite an interesting project to produce one.
@jim mcnamara: try using parentheses for around NF
, i. e. $(NF-1)
and $(NF)
instead of $NF-1
and $NF
(works on Mac OS X 10.6.8 for FreeBSD awk
and gawk
).
echo '
1 2
2 3
one
one two three
' | gawk '{if (NF >= 2) print $(NF-1), $(NF);}'
# output:
# 1 2
# 2 3
# two three
DISCLAIMER: Please read comments below carefully, and I assume you've already read the accepted answer. As I said nearly 5 years ago:
if anyone has any comments to add for situations when this is NOT an adequate or optimal solution then please comment below
Right click on the database name.
Select Tasks ? Shrink ? Database
Then click OK!
I usually open the Windows Explorer directory containing the database files, so I can immediately see the effect.
I was actually quite surprised this worked! Normally I've used DBCC before, but I just tried that and it didn't shrink anything, so I tried the GUI (2005) and it worked great - freeing up 17 GB in 10 seconds
In Full recovery mode this might not work, so you have to either back up the log first, or change to Simple recovery, then shrink the file. [thanks @onupdatecascade for this]
--
PS: I appreciate what some have commented regarding the dangers of this, but in my environment I didn't have any issues doing this myself especially since I always do a full backup first. So please take into consideration what your environment is, and how this affects your backup strategy and job security before continuing. All I was doing was pointing people to a feature provided by Microsoft!
You can use the re.sub() function to remove these characters:
>>> import re
>>> re.sub("[^a-zA-Z]+", "", "ABC12abc345def")
'ABCabcdef'
re.sub(MATCH PATTERN, REPLACE STRING, STRING TO SEARCH)
"[^a-zA-Z]+"
- look for any group of characters that are NOT
a-zA-z.""
- Replace the matched characters with ""You can use either h()
or html_escape()
, but most people use h()
by convention. h()
is short for html_escape()
in rails.
In your controller:
@stuff = "<b>Hello World!</b>"
In your view:
<%=h @stuff %>
If you view the HTML source: you will see the output without actually bolding the data. I.e. it is encoded as <b>Hello World!</b>
.
It will appear an be displayed as <b>Hello World!</b>
//display sample reg form in notepad.txt
using (StreamWriter stream = new FileInfo("D:\\tt.txt").AppendText())//ur file location//.AppendText())
{
stream.WriteLine("Name :" + textBox1.Text);//display textbox data in notepad
stream.WriteLine("DOB : " + dateTimePicker1.Text);//display datepicker data in notepad
stream.WriteLine("DEP:" + comboBox1.SelectedItem.ToString());
stream.WriteLine("EXM :" + listBox1.SelectedItem.ToString());
}
I guess you probably are running the preview of VS2013 Ultimate, because it is not present in my professional preview. But looking online I found that the feature is called Code Information Indicators
or CodeLens
, and can be located under
Tools ? Options ? Text Editor ? All Languages ? CodeLens
(for RC/final version)
or
Tools ? Options ? Text Editor ? All Languages ? Code Information Indicators
(for preview version)
That was according to this link. It seems to be pretty well hidden.
In Visual Studio 2013 RTM, you can also get to the CodeLens options by right clicking the indicators themselves in the editor:
documented in the Q&A section of the msdn CodeLens documentation
At its simplest, the difference is one of plurality:
I used to forget which one is which and end up having to look it up many times. To fix this problem, imagine rolling back as several rotations then hopefully the fact that rollback is plural will help you (and me!) remember which one is which. Backout sounds 'less plural' than rollback to me. Imagine backing out of a single parking space.
So, the mnemonic is:
I hope this helps!
The other name of sklearn in anaconda is scikit-learn. simply open your anaconda navigator, go to the environments, select your environment, for example tensorflow or whatever you want to work with, search for scikit_learn in the list of uninstalled packages, apply it and then you can import sklearn in your jupyter.
Simply with command line:
javac MyApp.java
jar -cf myJar.jar MyApp.class
Sure IDEs avoid using command line terminal
#include <QFile>
#include <QCoreApplication>
#include <QTextStream>
int main(int argc, char *argv[])
{
// Create a new file
QFile file("out.txt");
file.open(QIODevice::WriteOnly | QIODevice::Text);
QTextStream out(&file);
out << "This file is generated by Qt\n";
// optional, as QFile destructor will already do it:
file.close();
//this would normally start the event loop, but is not needed for this
//minimal example:
//return app.exec();
return 0;
}
From root folder run
find . | grep .git
Review the matches and confirm it only contains those files you want to delete and adjust to suit. Once satisfied, run
find . | grep .git | xargs rm -rf
Regex.Replace
does not modify its first argument (recall that strings are immutable in .NET) so the call
Regex.Replace(LastName, @"\s+", "");
leaves the LastName
string unchanged. You need to call it like this:
LastName = Regex.Replace(LastName, @"\s+", "");
All three of your regular expressions would have worked. However, the first regex would remove all plus characters as well, which I imagine would be unintentional.
Found a Fix:
First ensure that printing is working from Report Manager (open a report in Report Manager and print from there).
If it works go to Step 3, if you received the same error you need to install the following patches on the Report Server.
KB954606 - Security Update for SQL Server SP2
ReportViewer 2005 SP1
http://www.microsoft.com/downloads/details.aspx?familyid=82833F27-081D-4B72-83EF-2836360A904D
Download and install the following update:
KB954607 - Security Update for SQL Server SP2
encodeURIComponent works fine for me. we can give the url like this in ajax call.The code shown below:
$.ajax({
cache: false,
type: "POST",
url: "http://atandra.mivamerchantdev.com//mm5/json.mvc?Store_Code=ATA&Function=Module&Module_Code=thub_connector&Module_Function=THUB_Request",
data: "strChannelName=" + $('#txtupdstorename').val() + "&ServiceUrl=" + encodeURIComponent($('#txtupdserviceurl').val()),
dataType: "HTML",
success: function (data) {
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
It may be of interest that both Outlook and Outlook Express can generate these multipart image email formats, if you insert the image files using the Insert / Picture menu function.
Obviously the email type must be set to HTML (not plain text).
Any other method (e.g. drag/drop, or any command-line invocation) results in the image(s) being sent as an attachment.
If you then send such an email to yourself, you can see how it is formatted! :)
FWIW, I am looking for a standalone windows executable which does inline images from the command line mode, but there seem to be none. It's a path which many have gone up... One can do it with say Outlook Express, by passing it an appropriately formatted .eml file.
In my experience, these errors happen this way:
try:
code_that_executes_bad_query()
# transaction on DB is now bad
except:
pass
# transaction on db is still bad
code_that_executes_working_query() # raises transaction error
There nothing wrong with the second query, but since the real error was caught, the second query is the one that raises the (much less informative) error.
edit: this only happens if the except
clause catches IntegrityError
(or any other low level database exception), If you catch something like DoesNotExist
this error will not come up, because DoesNotExist
does not corrupt the transaction.
The lesson here is don't do try/except/pass.
You can also use following query :
DELETE FROM Student, Enrollment USING Student INNER JOIN Enrollment ON Student.studentId = Enrollment.studentId WHERE Student.studentId= 51;
Here is complete article about streaming android camera video to a webpage.
Android Streaming Live Camera Video to Web Page
The following works:
git add -A .
git stash
git stash drop stash@{0}
Please note that this will discard both your unstaged and staged local changes. So you should commit anything you want to keep, before you run these commands.
A typical use case: You moved a lot of files or directories around, and then want to get back to the original state.
That will work just fine. You can export an entire calendar with File
> Export…
, or individual events by dragging them to the Finder.
iCalendar (.ics
) files are human-readable, so you can always pop it open in a text editor to make sure no private events made it in there. They consist of nested sections with start with BEGIN:
and end with END:
. You'll mostly find VEVENT
sections (each of which represents an event) and VTIMEZONE
sections, each of which represents a time zone that's referenced from one or more events.
Yes, you can define a constructor inside a class declaration like this:
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
This is asking for your MySQL username and password.
You should enter these details, which will default to "root" and "" (i.e.: nothing) if you've not specified a password.
All of the previous answers are talking about git branch -m
. Of course, it's easy to operate, but for me, it may be a little hard to remember another Git command. So I tried to get the work done by the command I was familiar with. Yeah, you may guessed it.
I use git branch -b <new_branch_name>
. And if you don't want to save the old branch now you can execute git branch -D <old_branch_name>
to remove it.
I know it may be a little tedious, but it's easier to understand and remember. I hope it‘s helpful for you.
You're looking for the zip builtin function. From the docs:
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
Without more details as to what the question is exactly asking, I am going to answer the title of the question,
Create an Array
:
String[] myArray = new String[2];
int[] intArray = new int[2];
// or can be declared as follows
String[] myArray = {"this", "is", "my", "array"};
int[] intArray = {1,2,3,4};
Create an ArrayList
:
ArrayList<String> myList = new ArrayList<String>();
myList.add("Hello");
myList.add("World");
ArrayList<Integer> myNum = new ArrayList<Integer>();
myNum.add(1);
myNum.add(2);
This means, create an ArrayList
of String
and Integer
objects. You cannot use int
because thats a primitive data types, see the link for a list of primitive data types.
Create a Stack
:
Stack myStack = new Stack();
// add any type of elements (String, int, etc..)
myStack.push("Hello");
myStack.push(1);
Create an Queue
: (using LinkedList)
Queue<String> myQueue = new LinkedList<String>();
Queue<Integer> myNumbers = new LinkedList<Integer>();
myQueue.add("Hello");
myQueue.add("World");
myNumbers.add(1);
myNumbers.add(2);
Same thing as an ArrayList
, this declaration means create an Queue
of String
and Integer
objects.
In response to your comment from the other given answer,
i am pretty confused now, why are using string. and what does
<String>
means
We are using String
only as a pure example, but you can add any other object, but the main point is that you use an object not a primitive type. Each primitive data type has their own primitive wrapper class, see link for list of primitive data type's wrapper class.
I have posted some links to explain the difference between the two, but here are a list of primitive types
byte
short
char
int
long
boolean
double
float
Which means, you are not allowed to make an ArrayList
of integer's like so:
ArrayList<int> numbers = new ArrayList<int>();
^ should be an object, int is not an object, but Integer is!
ArrayList<Integer> numbers = new ArrayList<Integer>();
^ perfectly valid
Also, you can use your own objects, here is my Monster
object I created,
public class Monster {
String name = null;
String location = null;
int age = 0;
public Monster(String name, String loc, int age) {
this.name = name;
this.loc = location;
this.age = age;
}
public void printDetails() {
System.out.println(name + " is from " + location +
" and is " + age + " old.");
}
}
Here we have a Monster
object, but now in our Main.java
class we want to keep a record of all our Monster
's that we create, so let's add them to an ArrayList
public class Main {
ArrayList<Monster> myMonsters = new ArrayList<Monster>();
public Main() {
Monster yetti = new Monster("Yetti", "The Mountains", 77);
Monster lochness = new Monster("Lochness Monster", "Scotland", 20);
myMonsters.add(yetti); // <-- added Yetti to our list
myMonsters.add(lochness); // <--added Lochness to our list
for (Monster m : myMonsters) {
m.printDetails();
}
}
public static void main(String[] args) {
new Main();
}
}
(I helped my girlfriend's brother with a Java game, and he had to do something along those lines as well, but I hope the example was well demonstrated)
The first example isn't thread safe - if two threads call getInstance at the same time, that static is going to be a PITA. Some form of mutex would help.
It should be simpler!
Duration.between(startLocalDateTime, endLocalDateTime).toMillis();
You can convert millis to whatever unit you like:
String.format("%d minutes %d seconds",
TimeUnit.MILLISECONDS.toMinutes(millis),
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
I was getting this exception and the "solution" I found was through Netbeans IDE, simply:
I don't know WHY this worked, but it did!
PowerShell 3 has the $PSScriptRoot
automatic variable:
Contains the directory from which a script is being run.
In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.
Don't be fooled by the poor wording. PSScriptRoot
is the directory of the current file.
In PowerShell 2, you can calculate the value of $PSScriptRoot
yourself:
# PowerShell v2
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
For Windows 10,
Modify my.ini
file in C:\ProgramData\MySQL\MySQL Server 8.0\
[mysqld]
default_authentication_plugin=mysql_native_password
Restart the MySQL Service.
Login to MySQL on the command line, and execute the following commands in MySQL:
Create a new user.
CREATE USER 'user'@'localhost' IDENTIFIED BY 'password';
Grant all privileges.
GRANT ALL PRIVILEGES ON * .* TO 'user'@'localhost';
Open MySQL workbench, and open a new connection using the new user credentials.
I was facing the same issue and this worked.
In database, Cardinality number of rows in the table.
image source
As Alex Brault points out, especially on Windows, the absolute path (with drive letter and all) is unambiguous and often better.
Shouldn't your OpenFileDialog use a regular tree-browser structure?
To get some nomenclature in place, the RefDir is the directory relative to which you want to specify the path; the AbsName is the absolute path name that you want to map; and the RelPath is the resulting relative path.
Take the first of these options that matches:
To illustrate the last rule (which is, of course, by far the most complex), start with:
RefDir = D:\Abc\Def\Ghi
AbsName = D:\Abc\Default\Karma\Crucible
Then
LCP = D:\Abc
(RefDir - LCP) = Def\Ghi
(Absname - LCP) = Default\Karma\Crucible
RelPath = ..\..\Default\Karma\Crucible
While I was typing, DavidK produced an answer which suggests that you are not the first to need this feature and that there is a standard function to do this job. Use it. But there's no harm in being able to think your way through from first principles, either.
Except that Unix systems do not support drive letters (so everything is always located under the same root directory, and the first bullet therefore is irrelevant), the same technique could be used on Unix.
As Kristian has pointed out, good control over z-values will often solve your problems.
If that does not work you can take a look at CSS Box Shadow Bottom Only on using overflow hidden to hide excess shadow.
I would also have in mind that the box-shadow property can accept a comma-separated list of shadows like this:
box-shadow: 0px 10px 5px #888, 0px -10px 5px #888;
This will give you some control over the "amount" of shadow in each direction.
Have a look at http://www.css3.info/preview/box-shadow/ for more information about box-shadow.
Hope this was what you were looking for!
It's a hint to the compiler that the variable will be heavily used and that you recommend it be kept in a processor register if possible.
Most modern compilers do that automatically, and are better at picking them than us humans.
$.browser
was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.
You can have it on github using the command
git clone https://github.com/coreutils/coreutils.git
You can find all the source codes in the src folder.
You need to have git installed.
Things have changed since 2012, ls
source code has now 5309 lines
This might be your script-free solution: http://davidwalsh.name/css-transform-rotate
It's supported in all browsers prefixed and, in IE10-11 and all still-used Firefox versions, unprefixed.
That means that if you don't care for old IEs (the bane of web designers) you can skip the -ms-
and -moz-
prefixes to economize space.
However, the Webkit browsers (Chrome, Safari, most mobile navigators) still need -webkit-
, and there's a still-big cult following of pre-Next Opera and using -o-
is sensate.
Cast the dtype
of the col to str
and you can perform vectorised slicing calling str
:
In [29]:
df['new_col'] = df['First'].astype(str).str[0]
df
Out[29]:
First Second new_col
0 123 234 1
1 22 4353 2
2 32 355 3
3 453 453 4
4 45 345 4
5 453 453 4
6 56 56 5
if you need to you can cast the dtype
back again calling astype(int)
on the column
ddlData.SelectedIndex
will contain the int
value To select the specific value into DropDown
:
ddlData.SelectedIndex=ddlData.Items.IndexOf(ddlData.Items.FindByText("value"));
return
type of ddlData.Items.IndexOf(ddlData.Items.FindByText("value"));
is int
.
A Protocol?
I found this, it appears to be a local setting for a computer...
It doesn't work because you are using fill_parent as the width. The weight is used to distribute the remaining empty space or take away space when the total sum is larger than the LinearLayout. Set your widths to 0dip instead and it will work.
If you don't want to use DI or Factories. You can refactor your class in a little tricky way:
public class Foo {
private Bar bar;
public void foo(Bar bar){
this.bar = (bar != null) ? bar : new Bar();
bar.someMethod();
this.bar = null; // for simulating local scope
}
}
And your test class:
@RunWith(MockitoJUnitRunner.class)
public class FooTest {
@Mock Bar barMock;
Foo foo;
@Test
public void testFoo() {
foo = new Foo();
foo.foo(barMock);
verify(barMock, times(1)).someMethod();
}
}
Then the class that is calling your foo method will do it like this:
public class thirdClass {
public void someOtherMethod() {
Foo myFoo = new Foo();
myFoo.foo(null);
}
}
As you can see when calling the method this way, you don't need to import the Bar class in any other class that is calling your foo method which is maybe something you want.
Of course the downside is that you are allowing the caller to set the Bar Object.
Hope it helps.
Swift 4
You have 2 ways in order to change the size of CollectionView.
First way -> add this protocol UICollectionViewDelegateFlowLayout
for
In my case I want to divided cell into 3 part in one line. I did this code below
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource ,UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
// In this function is the code you must implement to your code project if you want to change size of Collection view
let width = (view.frame.width-20)/3
return CGSize(width: width, height: width)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return collectionData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath)
if let label = cell.viewWithTag(100) as? UILabel {
label.text = collectionData[indexPath.row]
}
return cell
}
}
Second way -> you don't have to add UICollectionViewDelegateFlowLayout but you have to write some code in viewDidload function instead as code below
class ViewController: UIViewController {
@IBOutlet weak var collectionView1: UICollectionView!
var collectionData = ["1.", "2.", "3.", "4.", "5.", "6.", "7.", "8.", "9.", "10.", "11.", "12."]
override func viewDidLoad() {
super.viewDidLoad()
let width = (view.frame.width-20)/3
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSize(width: width, height: width)
}
}
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return collectionData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath)
if let label = cell.viewWithTag(100) as? UILabel {
label.text = collectionData[indexPath.row]
}
return cell
}
}
Whatever you write a code as the first way or second way you will get the same result as above. I wrote it. It worked for me
When you normalize a matrix using NORM_L1, you are dividing every pixel value by the sum of absolute values of all the pixels in the image. As a result, all pixel values become much less than 1 and you get a black image. Try NORM_MINMAX instead of NORM_L1.
The best way is to copy all the files and folders inside a directory on your local file system by: docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH
SRC_PATH
is on container
DEST_PATH
is on localhost
Then do docker-compose down
attach a volume to the same DEST_PATH
and run Docker containers by using docker-compose up -d
Add volume by following in docker-compose.yml
volumes:
- DEST_PATH:SRC_PATH
Check the nginx folder permission and set appache permission for that:
chown -R www-data:www-data /var/lib/nginx
This is my solution for my scenario:
<div class="btn-group btn-group-justified">
<a class="btn btn-default" ng-class="{'btn-success': hover.left, 'btn-danger': hover.right}" ng-click="setMatch(-1)" role="button" ng-mouseenter="hover.left = true;" ng-mouseleave="hover.left = false;">
<i class="fa fa-thumbs-o-up fa-5x pull-left" ng-class="{'fa-rotate-90': !hover.left && !hover.right, 'fa-flip-vertical': hover.right}"></i>
{{ song.name }}
</a>
<a class="btn btn-default" ng-class="{'btn-success': hover.right, 'btn-danger': hover.left}" ng-click="setMatch(1)" role="button" ng-mouseenter="hover.right = true;" ng-mouseleave="hover.right = false;">
<i class="fa fa-thumbs-o-up fa-5x pull-right" ng-class="{'fa-rotate-270': !hover.left && !hover.right, 'fa-flip-vertical': hover.left}"></i>
{{ match.name }}
</a>
</div>
default state:
on hover:
Use the DATEPART function to extract the month from the date.
So you would do something like this:
SELECT DATEPART(month, Closing_Date) AS Closing_Month, COUNT(Status) AS TotalCount
FROM t
GROUP BY DATEPART(month, Closing_Date)
Ahh. Because I missed the point of you initial post, here is an example which also ITERATES. The first example did not. In this case, I retreive an ADODB recordset, then load the data into a collection, which is returned by the function to client code:
EDIT: Not sure what I screwed up in pasting the code, but the formatting is a little screwball. Sorry!
Public Function StatesCollection() As Collection
Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim colReturn As New Collection
Set colReturn = New Collection
Dim SQL As String
SQL = _
"SELECT tblState.State, tblState.StateName " & _
"FROM tblState"
Set cn = New ADODB.Connection
Set cmd = New ADODB.Command
With cn
.Provider = DataConnection.MyADOProvider
.ConnectionString = DataConnection.MyADOConnectionString
.Open
End With
With cmd
.CommandText = SQL
.ActiveConnection = cn
End With
Set rs = cmd.Execute
With rs
If Not .EOF Then
Do Until .EOF
colReturn.Add Nz(!State, "")
.MoveNext
Loop
End If
.Close
End With
cn.Close
Set rs = Nothing
Set cn = Nothing
Set StatesCollection = colReturn
End Function
Not pre-processor directive, but this was what I was looking for when i came to this question;
NSString *model = [[UIDevice currentDevice] model];
if ([model isEqualToString:@"iPhone Simulator"]) {
//device is simulator
}
screen -X -S SCREENID kill
alternatively, you can use the following command
screen -S SCREENNAME -p 0 -X quit
You can view the list of the screen sessions by executing screen -ls
Thought I knew I had read about that in the standard; but can't find it. Keeps looking. Old; answering heading; not Q-tex ;P:
The following program would determine that:
#include <stdio.h>
#include <stdint.h>
int is_big_endian(void)
{
union {
uint32_t i;
char c[4];
} e = { 0x01000000 };
return e.c[0];
}
int main(void)
{
printf("System is %s-endian.\n",
is_big_endian() ? "big" : "little");
return 0;
}
You also have this approach; from Quake II:
byte swaptest[2] = {1,0};
if ( *(short *)swaptest == 1) {
bigendien = false;
And !is_big_endian()
is not 100% to be little as it can be mixed/middle.
Believe this can be checked using same approach only change value from 0x01000000
to i.e. 0x01020304
giving:
switch(e.c[0]) {
case 0x01: BIG
case 0x02: MIX
default: LITTLE
But not entirely sure about that one ...
I think you probably got confused with the concept of index, as @CB Bailey commented:
The staging area is the index.
You can simply consider staging directory and index as the same thing.
So, just like @Tim Henigan's answer, I guess:
you simply want to "undo" the
git add
that was done for that file.
Here is my answer:
Commonly, there are two ways to undo a stage operation, as other answers already mentioned:
git reset HEAD <file>
and
git rm --cached <file>
But what is the difference?
Assume the file has been staged and exists in working directory too, use git rm --cached <file>
if you want to remove it from staging directory, and keep the file in working directory. But notice that this operation will not only remove the file from staging directory but also mark the file as deleted
in staging directory, if you use
git status
after this operation, you will see this :
deleted: <file>
It's a record of removing the file from staging directory. If you don't want to keep that record and just simply want to undo a previous stage operation of a file, use git reset HEAD <file>
instead.
-------- END OF ANSWER --------
PS: I have noticed some answers mentioned:
git checkout -- <file>
This command is for the situation when the file has been staged, but the file has been modified in working directory after it was staged, use this operation to restore the file in working directory from staging directory. In other words, after this operation, changes happen in your working directory, NOT your staging directory.
If you use %pylab inline
you can (on a new line) insert the following command:
%pylab inline
pylab.rcParams['figure.figsize'] = (10, 6)
This will set all figures in your document (unless otherwise specified) to be of the size (10, 6)
, where the first entry is the width and the second is the height.
See this SO post for more details. https://stackoverflow.com/a/17231361/1419668
You can use the *
operator before an iterable to expand it within the function call. For example:
timeseries_list = [timeseries1 timeseries2 ...]
r = scikits.timeseries.lib.reportlib.Report(*timeseries_list)
(notice the *
before timeseries_list
)
From the python documentation:
If the syntax *expression appears in the function call, expression must evaluate to an iterable. Elements from this iterable are treated as if they were additional positional arguments; if there are positional arguments x1, ..., xN, and expression evaluates to a sequence y1, ..., yM, this is equivalent to a call with M+N positional arguments x1, ..., xN, y1, ..., yM.
This is also covered in the python tutorial, in a section titled Unpacking argument lists, where it also shows how to do a similar thing with dictionaries for keyword arguments with the **
operator.
To avoid using integer values to identify the VideoCapture
properties, one can use, e.g., cv2.cv.CV_CAP_PROP_FPS
in OpenCV 2.4 and cv2.CAP_PROP_FPS
in OpenCV 3.0. (See also Stefan's comment below.)
Here a utility function that works for both OpenCV 2.4 and 3.0:
# returns OpenCV VideoCapture property id given, e.g., "FPS"
def capPropId(prop):
return getattr(cv2 if OPCV3 else cv2.cv,
("" if OPCV3 else "CV_") + "CAP_PROP_" + prop)
OPCV3
is set earlier in my utilities code like this:
from pkg_resources import parse_version
OPCV3 = parse_version(cv2.__version__) >= parse_version('3')
If you're wanting to use this functionality for a GreaseMonkey script to automatically check a checkbox on a page, keep in mind that simply setting the checked property may not trigger the associated action. In that case, "clicking" the checkbox probably will (and set the checked property as well).
$("#id").click()
git remote add coworker git://path/to/coworkers/repo.git
git fetch coworker
git checkout --track coworker/foo
This will setup a local branch foo
, tracking the remote branch coworker/foo
. So when your co-worker has made some changes, you can easily pull them:
git checkout foo
git pull
Response to comments:
Cool :) And if I'd like to make my own changes to that branch, should I create a second local branch "bar" from "foo" and work there instead of directly on my "foo"?
You don't need to create a new branch, even though I recommend it. You might as well commit directly to foo
and have your co-worker pull your branch. But that branch already exists and your branch foo
need to be setup as an upstream branch to it:
git branch --set-upstream foo colin/foo
assuming colin
is your repository (a remote to your co-workers repository) defined in similar way:
git remote add colin git://path/to/colins/repo.git
select * from xyz where (1=(CASE WHEN @AnnualFeeType = 'All' THEN 1 ELSE 0 END) OR AnnualFeeType = @AnnualFeeType)
Please try this command node --version or node -v, either of which should return something like v4.4.5
.
Note Wording changed in response to the commments. Thanks @slekse
That is not an error, it is a warning. It means the branch you are about to delete contains commits that are not reachable from any of: its upstream branch, or HEAD (currently checked out revision). In other words, when you might lose commits¹.
In practice it means that you probably amended, rebased or filtered commits and they don't seem identical.
Therefore you could avoid the warning by checking out a branch that does contain the commits that you're about un-reference by deleting that other branch.²
You will want to verify that you in fact aren't missing any vital commits:
git log --graph --left-right --cherry-pick --oneline master...experiment
This will give you a list of any nonshared between the branches. In case you are curious, there might be a difference without --cherry-pick
and this difference could well be the reason for the warning you get:
--cherry-pick
Omit any commit that introduces the same change as another commit on the "other side" when the set of commits are limited with symmetric difference. For example, if you have two branches, A and B, a usual way to list all commits on only one side of them is with --left-right, like the example above in the description of that option. It however shows the commits that were cherry-picked from the other branch (for example, "3rd on b" may be cherry-picked from branch A). With this option, such pairs of commits are excluded from the output.
¹ they're really only garbage collected after a while, by default. Also, the git-branch
command does not check the revision tree of all branches. The warning is there to avoid obvious mistakes.
² (My preference here is to just force the deletion instead, but you might want to have the extra reassurance).
The following is easy to remember
ls -ltrapR
list directory contents
-l use a long listing format
-t sort by modification time, newest first
-r, --reverse reverse order while sorting
-a, --all do not ignore entries starting with .
-p, --indicator-style=slash append / indicator to directories
-R, --recursive list subdirectories recursively
This is a "problem" on the client side, not really an Oracle problem.
It's the client application which formats and displays the date this way.
In your case it's SQL*Plus which does this formatting.
Other SQL clients have other defaults.
Window -> Perspective -> Reset
Reset the IDE
Window -> Show View -> Project Explorer
I have seen some solutions here worth noting, as Omer Eldan posted. but here follows. ASP C#
using System.Data;
using System.Web.UI.HtmlControls;
public static Table DataTableToHTMLTable(DataTable dt, bool includeHeaders)
{
Table tbl = new Table();
TableRow tr = null;
TableCell cell = null;
int rows = dt.Rows.Count;
int cols = dt.Columns.Count;
if (includeHeaders)
{
TableHeaderRow htr = new TableHeaderRow();
TableHeaderCell hcell = null;
for (int i = 0; i < cols; i++)
{
hcell = new TableHeaderCell();
hcell.Text = dt.Columns[i].ColumnName.ToString();
htr.Cells.Add(hcell);
}
tbl.Rows.Add(htr);
}
for (int j = 0; j < rows; j++)
{
tr = new TableRow();
for (int k = 0; k < cols; k++)
{
cell = new TableCell();
cell.Text = dt.Rows[j][k].ToString();
tr.Cells.Add(cell);
}
tbl.Rows.Add(tr);
}
return tbl;
}
why this solution? Because you can easily just add this to a panel ie:
panel.Controls.Add(DataTableToHTMLTable(dtExample,true));
Second question , why do you have one column datatables and not just array's? Are you sure that these DataTables are uniform, because if the data is jagged then it's no use. If You really have to join these DataTables, there is many examples of Linq operations, or just use (beware though of same name columns as this will conflict in both linq operations and this solution if not handled):
public DataTable joinUniformTable(DataTable dt1, DataTable dt2)
{
int dt2ColsCount = dt2.Columns.Count;
int dt1lRowsCount = dt1.Rows.Count;
DataColumn column;
for (int i = 0; i < dt2ColsCount; i++)
{
column = new DataColumn();
string colName = dt2.Columns[i].ColumnName;
System.Type colType = dt2.Columns[i].DataType;
column.ColumnName = colName;
column.DataType = colType;
dt1.Columns.Add(column);
for (int j = 0; j < dt1lRowsCount; j++)
{
dt1.Rows[j][colName] = dt2.Rows[j][colName];
}
}
return dt1;
}
and your solution would look something like:
panel.Controls.Add(DataTableToHTMLTable(joinUniformTable(joinUniformTable(LivDT,BathDT),BedDT),true));
interpret the rest, and have fun.
I the following error message when faced this same problem:
The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'GroupJoin'.
Solved when I used the same property name, it worked.
(...)
join enderecoST in db.PessoaEnderecos on
new
{
CD_PESSOA = nf.CD_PESSOA_ST,
CD_ENDERECO_PESSOA = nf.CD_ENDERECO_PESSOA_ST
} equals
new
{
enderecoST.CD_PESSOA,
enderecoST.CD_ENDERECO_PESSOA
} into eST
(...)
tsc
requires a config file or .ts(x) files to compile.
To solve both of your issues, create a file called tsconfig.json
with the following contents:
{
"compilerOptions": {
"outFile": "../../built/local/tsc.js"
},
"exclude": [
"node_modules"
]
}
Also, modify your npm run with this
tsc --config /path/to/a/tsconfig.json
Here's what worked for me:
select visits, activations, simulations, simulations/activations
as sims_per_visit, activations/visits*100
as adoption_rate, simulations/activations*100
as completion_rate, duration/60
as minutes, m1 as month, Wk1 as week, Yr1 as year
from
(
(select count(*) as visits, year(stamp) as Yr1, week(stamp) as Wk1, month(stamp)
as m1 from sessions group by week(stamp), year(stamp)) as t3
join
(select count(*) as activations, year(stamp) as Yr2, week(stamp) as Wk2,
month(stamp) as m2 from sessions where activated='1' group by week(stamp),
year(stamp)) as t4
join
(select count(*) as simulations, year(stamp) as Yr3 , week(stamp) as Wk3,
month(stamp) as m3 from sessions where simulations>'0' group by week(stamp),
year(stamp)) as t5
join
(select avg(duration) as duration, year(stamp) as Yr4 , week(stamp) as Wk4,
month(stamp) as m4 from sessions where activated='1' group by week(stamp),
year(stamp)) as t6
)
where Yr1=Yr2 and Wk1=Wk2 and Wk1=Wk3 and Yr1=Yr3 and Yr1=Yr4 and Wk1=Wk4
I used joins, not unions (I needed different columns for each query, a join puts it all in the same column) and I dropped the quotation marks (compared to what Liam was doing) because they were giving me errors.
Thanks! I couldn't have pulled that off without this page! PS: Sorry I don't know how you're getting your statements formatted with colors. etc.
@Guffa 's answer is excellent, just point out that maybe is cleaner with an IF statement
select count(IF(Position = 'Manager', 1, NULL)) as ManagerCount
from ...
I take different approach, you may agree or not but I want to control from .properties file instead of compiled Java code
endpoint.url = https://yourHost/resource?requestParam1={0}&requestParam2={1}
Java code goes here, you can write if or switch condition to find out if endpoint URL in .properties file has @PathVariable (contains {}) or @RequestParam (yourURL?key=value) etc... then invoke method accordingly... that way its dynamic and not need to code change in future one stop shop...
I'm trying to give more of idea than actual code here ...try to write generic method each for @RequestParam, and @PathVariable etc... then call accordingly when needed
@Value("${endpoint.url}")
private String endpointURL;
// you can use variable args feature in Java
public String requestParamMethodNameHere(String value1, String value2) {
RestTemplate restTemplate = new RestTemplate();
restTemplate
.getMessageConverters()
.add(new MappingJackson2HttpMessageConverter());
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
HttpEntity<String> entity = new HttpEntity<>(headers);
try {
String formatted_URL = MessageFormat.format(endpointURL, value1, value2);
ResponseEntity<String> response = restTemplate.exchange(
formatted_URL ,
HttpMethod.GET,
entity,
String.class);
return response.getBody();
} catch (Exception e) { e.printStackTrace(); }
It took me a while to find out what is going on, but here is the summary. I hope this save people a lot of time.
Apple are not playing nice with Wi-Fi Direct, not in the same way that Android is. The Multipeer Connectivity Framework that Apple provides combines both BLE and WiFi Direct together and will only work with Apple devices and not any device that is using Wi-Fi Direct.
It states the following in this documentation - "The Multipeer Connectivity framework provides support for discovering services provided by nearby iOS devices using infrastructure Wi-Fi networks, peer-to-peer Wi-Fi, and Bluetooth personal area networks and subsequently communicating with those services by sending message-based data, streaming data, and resources (such as files)."
Additionally, Wi-Fi direct in this mode between i-Devices will need iPhone 5 and above.
There are apps that use a form of Wi-Fi Direct on the App Store, but these are using their own libraries.
SolidColorBrush brush = new SolidColorBrush( Color.FromArgb(255,255,139,0) )
Use git rebase --interactive
to edit that earlier commit, run git reset HEAD~
, and then git add -p
to add some, then make a commit, then add some more and make another commit, as many times as you like. When you're done, run git rebase --continue
, and you'll have all the split commits earlier in your stack.
Important: Note that you can play around and make all the changes you want, and not have to worry about losing old changes, because you can always run git reflog
to find the point in your project that contains the changes you want, (let's call it a8c4ab
), and then git reset a8c4ab
.
Here's a series of commands to show how it works:
mkdir git-test; cd git-test; git init
now add a file A
vi A
add this line:
one
git commit -am one
then add this line to A:
two
git commit -am two
then add this line to A:
three
git commit -am three
now the file A looks like this:
one
two
three
and our git log
looks like the following (well, I use git log --pretty=oneline --pretty="%h %cn %cr ---- %s"
bfb8e46 Rose Perrone 4 seconds ago ---- three
2b613bc Rose Perrone 14 seconds ago ---- two
9aac58f Rose Perrone 24 seconds ago ---- one
Let's say we want to split the second commit, two
.
git rebase --interactive HEAD~2
This brings up a message that looks like this:
pick 2b613bc two
pick bfb8e46 three
Change the first pick
to an e
to edit that commit.
git reset HEAD~
git diff
shows us that we just unstaged the commit we made for the second commit:
diff --git a/A b/A
index 5626abf..814f4a4 100644
--- a/A
+++ b/A
@@ -1 +1,2 @@
one
+two
Let's stage that change, and add "and a third" to that line in file A
.
git add .
This is usually the point during an interactive rebase where we would run git rebase --continue
, because we usually just want to go back in our stack of commits to edit an earlier commit. But this time, we want to create a new commit. So we'll run git commit -am 'two and a third'
. Now we edit file A
and add the line two and two thirds
.
git add .
git commit -am 'two and two thirds'
git rebase --continue
We have a conflict with our commit, three
, so let's resolve it:
We'll change
one
<<<<<<< HEAD
two and a third
two and two thirds
=======
two
three
>>>>>>> bfb8e46... three
to
one
two and a third
two and two thirds
three
git add .; git rebase --continue
Now our git log -p
looks like this:
commit e59ca35bae8360439823d66d459238779e5b4892
Author: Rose Perrone <[email protected]>
Date: Sun Jul 7 13:57:00 2013 -0700
three
diff --git a/A b/A
index 5aef867..dd8fb63 100644
--- a/A
+++ b/A
@@ -1,3 +1,4 @@
one
two and a third
two and two thirds
+three
commit 4a283ba9bf83ef664541b467acdd0bb4d770ab8e
Author: Rose Perrone <[email protected]>
Date: Sun Jul 7 14:07:07 2013 -0700
two and two thirds
diff --git a/A b/A
index 575010a..5aef867 100644
--- a/A
+++ b/A
@@ -1,2 +1,3 @@
one
two and a third
+two and two thirds
commit 704d323ca1bc7c45ed8b1714d924adcdc83dfa44
Author: Rose Perrone <[email protected]>
Date: Sun Jul 7 14:06:40 2013 -0700
two and a third
diff --git a/A b/A
index 5626abf..575010a 100644
--- a/A
+++ b/A
@@ -1 +1,2 @@
one
+two and a third
commit 9aac58f3893488ec643fecab3c85f5a2f481586f
Author: Rose Perrone <[email protected]>
Date: Sun Jul 7 13:56:40 2013 -0700
one
diff --git a/A b/A
new file mode 100644
index 0000000..5626abf
--- /dev/null
+++ b/A
@@ -0,0 +1 @@
+one
The <style>
tag belongs in the <head>
section, separate from all the content.
Here's an alternative:
<svg ...>
<switch>
<g requiredFeatures="http://www.w3.org/Graphics/SVG/feature/1.2/#TextFlow">
<textArea width="200" height="auto">
Text goes here
</textArea>
</g>
<foreignObject width="200" height="200"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<p xmlns="http://www.w3.org/1999/xhtml">Text goes here</p>
</foreignObject>
<text x="20" y="20">No automatic linewrapping.</text>
</switch>
</svg>
Noting that even though foreignObject may be reported as being supported with that featurestring, there's no guarantee that HTML can be displayed because that's not required by the SVG 1.1 specification. There is no featurestring for html-in-foreignobject support at the moment. However, it is still supported in many browsers, so it's likely to become required in the future, perhaps with a corresponding featurestring.
Note that the 'textArea' element in SVG Tiny 1.2 supports all the standard svg features, e.g advanced filling etc, and that you can specify either of width or height as auto, meaning that the text can flow freely in that direction. ForeignObject acts as clipping viewport.
Note: while the above example is valid SVG 1.1 content, in SVG 2 the 'requiredFeatures' attribute has been removed, which means the 'switch' element will try to render the first 'g' element regardless of having support for SVG 1.2 'textArea' elements. See SVG2 switch element spec.
I happened to run with the same issue in iOS 7 (with some devices no simulators).
Looks like Safari in iOS 7 has a lower storage quota, which apparently is reached by having a long history log.
I guess the best practice will be to catch the exception.
The Modernizr project has an easy patch, you should try something similar: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js
This should do the trick as well:
find . -type f -print -exec cat {} \;
Means:
find = linux `find` command finds filenames, see `man find` for more info
. = in current directory
-type f = only files, not directories
-print = show found file
-exec = additionally execute another linux command
cat = linux `cat` command, see `man cat`, displays file contents
{} = placeholder for the currently found filename
\; = tell `find` command that it ends now here
You further can combine searches trough boolean operators like -and
or -or
. find -ls
is nice, too.
Unchecking "Is Library" in the project Properties worked for me.
SAP is a company and offers a full Enterprise Resource Planning (ERP) system, business platform, and the associated modules (financials, general ledger, &c).
ABAP is the primary programming language used to write SAP software and customizations. It would do it injustice to think of it as COBOL and SQL on steroids, but that gives you an idea. ABAP runs within the SAP system.
SAP and ABAP abstract the DB and run atop various underlying DBMSs.
SAP produces other things as well and even publicly says they dabble in Java and even produce a J2EE container, but tried-and-true SAP is ABAP through-and-through.
use this one
//for getting length of object
int length = jsonObject.length();
or
//for getting length of array
int length = jsonArray.length();
sudo nano /etc/nginx/nginx.conf
Then add a line in the http section
http {
client_max_body_size 100M;
}
don't use MB only M.
systemctl restart nginx
then for php location
sudo gedit /etc/php5/fpm/php.ini
for nowdays maximum use php 7.0 or higher
sudo nano /etc/php/7.2/fpm/php.ini //7.3,7.2 or 7.1 which php you use
check those increasing by your desire .
memory_limit = 128M
post_max_size = 20M
upload_max_filesize = 10M
restart php-fpm
service php-fpm restart
Static variable in a header file:
say 'common.h'
has
static int zzz;
This variable 'zzz'
has internal linkage (This same variable can not be accessed in other translation units). Each translation unit which includes 'common.h'
has it's own unique object of name 'zzz'
.
Static variable in a class:
Static variable in a class is not a part of the subobject of the class. There is only one copy of a static data member shared by all the objects of the class.
$9.4.2/6 - "Static data members of a class in namespace scope have external linkage (3.5).A local class shall not have static data members."
So let's say 'myclass.h'
has
struct myclass{
static int zzz; // this is only a declaration
};
and myclass.cpp
has
#include "myclass.h"
int myclass::zzz = 0 // this is a definition,
// should be done once and only once
and "hisclass.cpp"
has
#include "myclass.h"
void f(){myclass::zzz = 2;} // myclass::zzz is always the same in any
// translation unit
and "ourclass.cpp"
has
#include "myclass.h"
void g(){myclass::zzz = 2;} // myclass::zzz is always the same in any
// translation unit
So, class static members are not limited to only 2 translation units. They need to be defined only once in any one of the translation units.
Note: usage of 'static' to declare file scope variable is deprecated and unnamed namespace is a superior alternate
Writing Java servlets is easy if you use Java EE 7
@WebServlet("/hello-world")
public class HelloWorld extends HttpServlet {
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response) {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Hello World");
out.flush();
}
}
Since servlet 3.0
The good news is the deployment descriptor is no longer required!
Read the tutorial for Java Servlets.
very simple
$('#label-ID').text("label value which you want to set");
This worked for me :
e.Row.Cells["cell no "].HorizontalAlign = HorizontalAlign.Center;
But 'css text-align = center '
didn't worked for me
hope it will help you
Edit: now there is yet an easier way to do this - when creating your group, just mention the full bot name (eg. @UniversalAgent1Bot) and it will list it as you type. Then you can just tap on it to add it.
Old answer:
Note that the link you provided does is not an HTML page, but rather a JSON document. The formatting is done by the browser.
You have to decide if:
If you want 1., just tell your application to render a response body with the JSON, set the MIME type (application/json), etc. In this case, formatting is dealt by the browser (and/or browser plugins)
If 2., it's a matter of rendering a simple minimal HTML page with the JSON where you can highlight it in several ways:
If you give more details about your stack, it's easier to provide examples or resources.
EDIT: For client side JS highlighting you can try higlight.js, for instance.
Use the util namespace, you will be able to register the list as a bean in your application context. You can then reuse the list to inject it in other bean definitions.
If you have debug="true"
in web.config and are using Scripts/Styles.Render
to reference the bundles in your pages, that should turn off both bundling and minification. BundleTable.EnableOptimizations = false
will always turn off both bundling and minification as well (irrespective of the debug true/false flag).
Are you perhaps not using the Scripts/Styles.Render
helpers? If you are directly rendering references to the bundle via BundleTable.Bundles.ResolveBundleUrl()
you will always get the minified/bundled content.
This is known as a fork bomb. It keeps splitting itself until there is no option but to restart the system. http://en.wikipedia.org/wiki/Fork_bomb
2016-05-04-03:59A - Windows 7 - Google Chrome [Version 50.0.2661.94]
wanted this done for a 'YouTube Pop-out Player' without Chrome Address / Toolbar or Bookmarks Bar; solution ended up being a small edit of MarkHu's answer (because of new updates, i guess?)
Go to the page you want altered, select Chrome Toolbar's 'Hamburger button' (3 horizontal lines).
From there: More tools > Add to desktop... > Open as window (tick box) > Add (button).
... and, simply open your page from the new desktop shortcut, adjust as needed, and enjoy!
Not sure if this has changed in Laravel 5, but the accepted answer using count($data->$relation)
didn't work for me, as the very act of accessing the relation property caused it to be loaded.
In the end, a straightforward isset($data->$relation)
did the trick for me.
You can assign int
to char
directly.
int a = 65;
char c = a;
printf("%c", c);
In fact this will also work.
printf("%c", a); // assuming a is in valid range
If Ruby is installed, then
ruby yourfile.rb
where yourfile.rb
is the file containing the ruby code.
Or
irb
to start the interactive Ruby environment, where you can type lines of code and see the results immediately.
You need to try one of the following:
They offer many more features and will be easier to get what you are looking for.
Use computeDistanceBetween() Google map API method to calculate near marker between your location and markers list on google map.
Steps:-
Create marker on google map.
function addMarker(location) {
var marker = new google.maps.Marker({
title: 'User added marker',
icon: {
path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,
scale: 5
},
position: location,
map: map
});
}
On Mouse click create event for getting lat, long of your location and pass that to find_closest_marker().
function find_closest_marker(event) {
var distances = [];
var closest = -1;
for (i = 0; i < markers.length; i++) {
var d = google.maps.geometry.spherical.computeDistanceBetween(markers[i].position, event.latLng);
distances[i] = d;
if (closest == -1 || d < distances[closest]) {
closest = i;
}
}
alert('Closest marker is: ' + markers[closest].getTitle());
}
visit this link follow the steps. You will able to get nearer marker to your location.
This is an old question but new info is still worth posting...
Starting with Select2 version 3.4.0 there is an attribute dropdownAutoWidth
which solves the problem and handles all the odd cases. Note it is not on by default. It resizes dynamically as the user makes selections, it adds width for allowClear
if that attribute is used, and it handles placeholder text properly too.
$("#some_select_id").select2({
dropdownAutoWidth : true
});
These days you can just use the file extension
<input type="file" ID="fileSelect" accept=".xlsx, .xls, .csv"/>
Right click the table design and go to Relationships and choose the foreign key on the left-side pane and in the right-side pane, set Enforce foreign key constraint to 'Yes' (to enable foreign key constraints) or 'No' (to disable it).
It is not an import problem. You simply call .dropDuplicates()
on a wrong object. While class of sqlContext.createDataFrame(rdd1, ...)
is pyspark.sql.dataframe.DataFrame
, after you apply .collect()
it is a plain Python list
, and lists don't provide dropDuplicates
method. What you want is something like this:
(df1 = sqlContext
.createDataFrame(rdd1, ['column1', 'column2', 'column3', 'column4'])
.dropDuplicates())
df1.collect()
mysqldump
will backup by default all the triggers but NOT the stored procedures/functions. There are 2 mysqldump parameters that control this behavior:
--routines
– FALSE by default--triggers
– TRUE by defaultso in mysqldump
command , add --routines
like :
mysqldump <other mysqldump options> --routines > outputfile.sql
Git just stores the contents of the link (i.e. the path of the file system object that it links to) in a 'blob' just like it would for a normal file. It then stores the name, mode and type (including the fact that it is a symlink) in the tree object that represents its containing directory.
When you checkout a tree containing the link, it restores the object as a symlink regardless of whether the target file system object exists or not.
If you delete the file that the symlink references it doesn't affect the Git-controlled symlink in any way. You will have a dangling reference. It is up to the user to either remove or change the link to point to something valid if needed.
This is what i've implemented:
$(window).resize(function(){ setTimeout(someFunction, 500); });
we can clear the setTimeout if we expect resize to happen less than 500ms
Good Luck...
Look at these lines:
If yes_ans > no_ans and yes_ans > na_ans
and similar. To what do "yes_ans" etc. refer? You're not using these in the context of a query; the "if exists" condition doesn't extend to the column names you're using inside.
Consider assigning those values to variables you can then use for your conditional flow below. Thus,
if exists (some record)
begin
set @var = column, @var2 = column2, ...
if (@var1 > @var2)
-- do something
end
The return type is also mismatched with the declaration. It would help a lot if you indented, used ANSI-standard punctuation (terminate statements with semicolons), and left out superfluous begin/end - you don't need these for single-statement lines executed as the result of a test.
Color not work, if you use for bootstrap font png image, as i.
[class^="icon-"],
[class*=" icon-"] {
display: inline-block;
width: 14px;
height: 14px;
margin-top: 1px;
*margin-right: .3em;
line-height: 14px;
vertical-align: text-top;
background-image: url("../img/glyphicons-halflings.png");
background-position: 14px 14px;
background-repeat: no-repeat;
}
HTML5 use css filter to colorize image, example
filter: invert(100%) contrast(2) brightness(50%) sepia(40%) saturate(450%) hue-rotate(-50deg);
nosetests is brilliant solution for unit-testing in python. It supports both unittest based testcases and doctests, and gets you started with it with just simple config file.
If you are using maven include the following tag in pom.xml (update versions as needed) inside plugins tag.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
A pretty common use case for getattr
is mapping data to functions.
For instance, in a web framework like Django or Pylons, getattr
makes it straightforward to map a web request's URL to the function that's going to handle it. If you look under the hood of Pylons's routing, for instance, you'll see that (by default, at least) it chops up a request's URL, like:
http://www.example.com/customers/list
into "customers" and "list". Then it searches for a controller class named CustomerController
. Assuming it finds the class, it creates an instance of the class and then uses getattr
to get its list
method. It then calls that method, passing it the request as an argument.
Once you grasp this idea, it becomes really easy to extend the functionality of a web application: just add new methods to the controller classes, and then create links in your pages that use the appropriate URLs for those methods. All of this is made possible by getattr
.
It is an old question but if you need to generalize this to a higher than 2 dimension arrays, here is the solution than can be easily generalized:
np.einsum('ij->ij', a[a[:,1].argsort(),:])
This is an overkill for two dimensions and a[a[:,1].argsort()]
would be enough per @steve's answer, however that answer cannot be generalized to higher dimensions. You can find an example of 3D array in this question.
Output:
[[7 0 5]
[9 2 3]
[4 5 6]]
I find git stash very useful for temporal handling of all 'dirty' states.
Say you have a branch master
with the following commit history:
A -- B -- C -- D
Now, you create a branch test, work on it, and do 4 commits:
E -- F -- G -- H
/
A -- B -- C -- D
master
's head points to D, and test
's head points to H.
The "Already up-to-date" message shows up when the HEAD of the branch you are merging into is a parent of the chain of commits of the branch you want to merge.
That's the case, here: D
is a parent of E
.
There is nothing to merge from test
to master
, since nothing has changed on master
since then.
What you want to do here is literally to tell Git to have master
's head to point to H, so master's branch has the following commits history:
A -- B -- C -- D -- E -- F -- G -- H
This is a job for Git command reset
.
You also want the working directory to reflect this change, so you'll do a hard reset:
git reset --hard H
If you want to retain the exact commit history of the second repository and therefore also retain the ability to easily merge upstream changes in the future then here is the method you want. It results in unmodified history of the subtree being imported into your repo plus one merge commit to move the merged repository to the subdirectory.
git remote add XXX_remote <path-or-url-to-XXX-repo>
git fetch XXX_remote
git merge -s ours --no-commit --allow-unrelated-histories XXX_remote/master
git read-tree --prefix=ZZZ/ -u XXX_remote/master
git commit -m "Imported XXX as a subtree."
You can track upstream changes like so:
git pull -s subtree XXX_remote master
Git figures out on its own where the roots are before doing the merge, so you don't need to specify the prefix on subsequent merges.
The downside is that in the merged history the files are unprefixed (not in a subdirectory). As a result git log ZZZ/a
will show you all the changes (if any) except those in the merged history. You can do:
git log --follow -- a
but that won't show the changes other then in the merged history.
In other words, if you don't change ZZZ
's files in repository XXX
, then you need to specify --follow
and an unprefixed path. If you change them in both repositories, then you have 2 commands, none of which shows all the changes.
Git versions before 2.9: You don’t need to pass the --allow-unrelated-histories
option to git merge
.
The method in the other answer that uses read-tree
and skips the merge -s ours
step is effectively no different than copying the files with cp and committing the result.
Original source was from github's "Subtree Merge" help article. And another useful link.
open your browser,check whether Tomcat homepage is visible by below command.
http://ipaddress:portnumber
also check this
Prints pubkey
and avoid the changed status by adding changed_when: False
to cat
task:
- name: Generate SSH keys for vagrant user
user: name=vagrant generate_ssh_key=yes ssh_key_bits=2048
- name: Check SSH public key
command: /bin/cat $home_directory/.ssh/id_rsa.pub
register: cat
changed_when: False
- name: Print SSH public key
debug: var=cat.stdout
- name: Wait for user to copy SSH public key
pause: prompt="Please add the SSH public key above to your GitHub account"
just try this way
String strFilter = "_id=" + Id;
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
myDB.update("titles", args, strFilter, null);**
For me it was "Prefer 32bit": clearing the checkbox allowed CLR to load Crystal Reports 64bit runtime (the only one installed).
zfill
.This function takes x
and converts it to a string, and adds zeros in the beginning only and only if the length is too short:
def zfill_alternative(x,len=4): return ( (('0'*len)+str(x))[-l:] if len(str(x))<len else str(x) )
To sum it up - build-in: zfill
is good enough, but if someone is curious on how to implement this by hand, here is one more example.
I found the best way to fix this error: Bootstrap’s JavaScript requires jQuery version 1.9.1 or higher
In Wordpress..just ran this plugin and it fixed it. Thought I'd share jQuery Updater
There is no built in construct in C#/.NET, but you can easily add your own extension method for this:
public static class ExtensionsForInt32
{
public static bool IsBetween (this int val, int low, int high)
{
return val > low && val < high;
}
}
Which can be used like:
if (5.IsBetween (0, 10)) { /* Do something */ }
Got into django recently and been looking into a solution to that and found a method that might be useful.
So for example, if using allouth the default redirect is accounts/profile. Make a view that solely redirects to a location of choice using the username field like so:
def profile(request):
name=request.user.username
return redirect('-----choose where-----' + name + '/')
Then create a view that captures it in one of your apps, for example:
def profile(request, name):
user = get_object_or_404(User, username=name)
return render(request, 'myproject/user.html', {'profile': user})
Where the urlpatterns capture would look like this:
url(r'^(?P<name>.+)/$', views.profile, name='user')
Works well for me.
Thanks Ashwin !
In my case I should need wait for a jquery plugin execution in some element.. specifically "qtip"
based in your hint, it worked perfectly for me :
wait.until( new Predicate<WebDriver>() {
public boolean apply(WebDriver driver) {
return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
}
}
);
Note: I'm using Webdriver 2
Your two examples look identical, which makes problems hard to diagnose. Potential problems:
You may need double quotes, as in sed 's/xxx/'"$PWD"'/'
$PWD
may contain a slash, in which case you need to find a character not contained in $PWD
to use as a delimiter.
To nail both issues at once, perhaps
sed 's@xxx@'"$PWD"'@'
You may want to have a look at https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs-memfnptr-types, especially [33.1] Is the type of "pointer-to-member-function" different from "pointer-to-function"?
executes a command and never returns.
It's like a return
statement in a function.
If the command is not found exec
returns false.
It never returns true, because if the command is found it never returns at all.
There is also no point in returning STDOUT
, STDERR
or exit status of the command.
You can find documentation about it in perlfunc
,
because it is a function.
executes a command and your Perl script is continued after the command has finished.
The return value is the exit status of the command.
You can find documentation about it in perlfunc
.
like system
executes a command and your perl script is continued after the command has finished.
In contrary to system
the return value is STDOUT
of the command.
qx//
is equivalent to backticks.
You can find documentation about it in perlop
, because unlike system
and exec
it is an operator.
What is missing from the above is a way to execute a command asynchronously.
That means your perl script and your command run simultaneously.
This can be accomplished with open
.
It allows you to read STDOUT
/STDERR
and write to STDIN
of your command.
It is platform dependent though.
There are also several modules which can ease this tasks.
There is IPC::Open2
and IPC::Open3
and IPC::Run
, as well as
Win32::Process::Create
if you are on windows.
Dynamic Variable Names in Java
There is no such thing.
In your case you can use array:
int[] n = new int[3];
for() {
n[i] = 5;
}
For more general (name, value)
pairs, use Map<>
For anyone that's searching why their chrome debugger is automatically jumping to sources tab on every page load, event though all of the breakpoints/pauses/etc have been disabled.
For me it was the "breakOnLoad": true
line in VS Code launch.json
config.
in Swift 3.0 or Later
passwordTextField.isSecureTextEntry = true
Warning: Note that English is not restricted to just A-Z.
Try this to remove everything except a-z, A-Z and 0-9:
$result = preg_replace("/[^a-zA-Z0-9]+/", "", $s);
If your definition of alphanumeric includes letters in foreign languages and obsolete scripts then you will need to use the Unicode character classes.
Try this to leave only A-Z:
$result = preg_replace("/[^A-Z]+/", "", $s);
The reason for the warning is that words like résumé contains the letter é
that won't be matched by this. If you want to match a specific list of letters adjust the regular expression to include those letters. If you want to match all letters, use the appropriate character classes as mentioned in the comments.
you can render in following way
{{ post.published_at|date("m/d/Y") }}
For more details can visit http://twig.sensiolabs.org/doc/filters/date.html
function hasValue( val ) { // Return true if text input is valid/ not-empty
return val.replace(/\s+/, '').length; // boolean
}
For multiple elements you can pass inside your input elements loop their value into that function argument.
If a user inserted one or more spaces, thanks to the regex s+
the function will return false.
You can still get it, from microsoft servers, see my answer on this question: Where is Visual Studio 2005 Express?
There are two ways to do this, depending on your Bash version.
The classic and portable (Bash pre-4) way is:
cmd >> outfile 2>&1
A nonportable way, starting with Bash 4 is
cmd &>> outfile
(analog to &> outfile
)
For good coding style, you should
If your script already starts with #!/bin/sh
(no matter if intended or not), then the Bash 4 solution, and in general any Bash-specific code, is not the way to go.
Also remember that Bash 4 &>>
is just shorter syntax — it does not introduce any new functionality or anything like that.
The syntax is (beside other redirection syntax) described here: http://bash-hackers.org/wiki/doku.php/syntax/redirection#appending_redirected_output_and_error_output
What is your output when you do java -version
? This will tell you what version the running JVM is.
The Unsupported major.minor version 51.0 error could mean:
Either way, uninstall all JVM runtimes including JDK and download latest and re-install. That should fix any Unsupported major.minor
error as you will have the lastest JRE and JDK (Maybe even newer then the one used to compile the Servlet)
See: http://www.java.com/en/download/manual.jsp (7 Update 25 )
and here: http://www.oracle.com/technetwork/java/javase/downloads/index.html (Java Platform (JDK) 7u25)
for the latest version of the JRE and JDK respectively.
EDIT:
Most likely your code was written in Java7 however maybe it was done using Java7update4 and your system is running Java7update3. Thus they both are effectively the same major version but the minor versions differ. Only the larger minor version is backward compatible with the lower minor version.
Edit 2 : If you have more than one jdk installed on your pc. you should check that Apache Tomcat is using the same one (jre) you are compiling your programs with. If you installed a new jdk after installing apache it normally won't select the new version.
You can use int
and set the base to 2
(for binary):
>>> binary = raw_input('enter a number: ')
enter a number: 11001
>>> int(binary, 2)
25
>>>
However, if you cannot use int
like that, then you could always do this:
binary = raw_input('enter a number: ')
decimal = 0
for digit in binary:
decimal = decimal*2 + int(digit)
print decimal
Below is a demonstration:
>>> binary = raw_input('enter a number: ')
enter a number: 11001
>>> decimal = 0
>>> for digit in binary:
... decimal = decimal*2 + int(digit)
...
>>> print decimal
25
>>>
You can use @Qualifier
along with @Autowired
. In fact spring will ask you explicitly select the bean if ambiguous bean type are found, in which case you should provide the qualifier
For Example in following case it is necessary provide a qualifier
@Component
@Qualifier("staff")
public Staff implements Person {}
@Component
@Qualifier("employee")
public Manager implements Person {}
@Component
public Payroll {
private Person person;
@Autowired
public Payroll(@Qualifier("employee") Person person){
this.person = person;
}
}
EDIT:
In Lombok 1.18.4 it is finally possible to avoid the boilerplate on constructor injection when you have @Qualifier, so now it is possible to do the following:
@Component
@Qualifier("staff")
public Staff implements Person {}
@Component
@Qualifier("employee")
public Manager implements Person {}
@Component
@RequiredArgsConstructor
public Payroll {
@Qualifier("employee") private final Person person;
}
provided you are using the new lombok.config rule copyableAnnotations (by placing the following in lombok.config in the root of your project):
# Copy the Qualifier annotation from the instance variables to the constructor
# see https://github.com/rzwitserloot/lombok/issues/745
lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Qualifier
This was recently introduced in latest lombok 1.18.4.
NOTE
If you are using field or setter injection then you have to place the @Autowired and @Qualifier on top of the field or setter function like below(any one of them will work)
public Payroll {
@Autowired @Qualifier("employee") private final Person person;
}
or
public Payroll {
private final Person person;
@Autowired
@Qualifier("employee")
public void setPerson(Person person) {
this.person = person;
}
}
If you are using constructor injection then the annotations should be placed on constructor, else the code would not work. Use it like below -
public Payroll {
private Person person;
@Autowired
public Payroll(@Qualifier("employee") Person person){
this.person = person;
}
}
You can not ask for instance during configuration phase - you can ask only for providers.
var app = angular.module('modx', []);
// configure stuff
app.config(function($routeProvider, $locationProvider) {
// you can inject any provider here
});
// run blocks
app.run(function($rootScope) {
// you can inject any instance here
});
See http://docs.angularjs.org/guide/module for more info.
There is an important difference between the two.
Everything not allocated with new
behaves much like value types in C# (and people often say that those objects are allocated on the stack, which is probably the most common/obvious case, but not always true. More precisely, objects allocated without using new
have automatic storage duration
Everything allocated with new
is allocated on the heap, and a pointer to it is returned, exactly like reference types in C#.
Anything allocated on the stack has to have a constant size, determined at compile-time (the compiler has to set the stack pointer correctly, or if the object is a member of another class, it has to adjust the size of that other class). That's why arrays in C# are reference types. They have to be, because with reference types, we can decide at runtime how much memory to ask for. And the same applies here. Only arrays with constant size (a size that can be determined at compile-time) can be allocated with automatic storage duration (on the stack). Dynamically sized arrays have to be allocated on the heap, by calling new
.
(And that's where any similarity to C# stops)
Now, anything allocated on the stack has "automatic" storage duration (you can actually declare a variable as auto
, but this is the default if no other storage type is specified so the keyword isn't really used in practice, but this is where it comes from)
Automatic storage duration means exactly what it sounds like, the duration of the variable is handled automatically. By contrast, anything allocated on the heap has to be manually deleted by you. Here's an example:
void foo() {
bar b;
bar* b2 = new bar();
}
This function creates three values worth considering:
On line 1, it declares a variable b
of type bar
on the stack (automatic duration).
On line 2, it declares a bar
pointer b2
on the stack (automatic duration), and calls new, allocating a bar
object on the heap. (dynamic duration)
When the function returns, the following will happen:
First, b2
goes out of scope (order of destruction is always opposite of order of construction). But b2
is just a pointer, so nothing happens, the memory it occupies is simply freed. And importantly, the memory it points to (the bar
instance on the heap) is NOT touched. Only the pointer is freed, because only the pointer had automatic duration.
Second, b
goes out of scope, so since it has automatic duration, its destructor is called, and the memory is freed.
And the bar
instance on the heap? It's probably still there. No one bothered to delete it, so we've leaked memory.
From this example, we can see that anything with automatic duration is guaranteed to have its destructor called when it goes out of scope. That's useful. But anything allocated on the heap lasts as long as we need it to, and can be dynamically sized, as in the case of arrays. That is also useful. We can use that to manage our memory allocations. What if the Foo class allocated some memory on the heap in its constructor, and deleted that memory in its destructor. Then we could get the best of both worlds, safe memory allocations that are guaranteed to be freed again, but without the limitations of forcing everything to be on the stack.
And that is pretty much exactly how most C++ code works.
Look at the standard library's std::vector
for example. That is typically allocated on the stack, but can be dynamically sized and resized. And it does this by internally allocating memory on the heap as necessary. The user of the class never sees this, so there's no chance of leaking memory, or forgetting to clean up what you allocated.
This principle is called RAII (Resource Acquisition is Initialization), and it can be extended to any resource that must be acquired and released. (network sockets, files, database connections, synchronization locks). All of them can be acquired in the constructor, and released in the destructor, so you're guaranteed that all resources you acquire will get freed again.
As a general rule, never use new/delete directly from your high level code. Always wrap it in a class that can manage the memory for you, and which will ensure it gets freed again. (Yes, there may be exceptions to this rule. In particular, smart pointers require you to call new
directly, and pass the pointer to its constructor, which then takes over and ensures delete
is called correctly. But this is still a very important rule of thumb)
For the sake of completeness, there is also a data.table
solution:
library(data.table)
result <- setDT(df)[, paste0(names(df), "_length") := lapply(.SD, stringr::str_length)]
result
# col1 col2 col1_length col2_length
#1: abc adf qqwe 3 8
#2: abcd d 4 1
#3: a e 1 1
#4: abcdefg f 7 1
... right now it happens only to the website I'm testing. I can't post it here because it's confidential.
Then I guess it is one of the sites which is incompatible with TLS1.2. The openssl as used in 12.04 does not use TLS1.2 on the client side while with 14.04 it uses TLS1.2 which might explain the difference. To work around try to explicitly use
--secure-protocol=TLSv1
. If this does not help check if you can access the site with openssl s_client -connect ...
(probably not) and with openssl s_client -tls1 -no_tls1_1, -no_tls1_2 ...
.
Please note that it might be other causes, but this one is the most probable and without getting access to the site everything is just speculation anyway.
The assumed problem in detail: Usually clients use the most compatible handshake to access a server. This is the SSLv23 handshake which is compatible to older SSL versions but announces the best TLS version the client supports, so that the server can pick the best version. In this case wget would announce TLS1.2. But there are some broken servers which never assumed that one day there would be something like TLS1.2 and which refuse the handshake if the client announces support for this hot new version (from 2008!) instead of just responding with the best version the server supports. To access these broken servers the client has to lie and claim that it only supports TLS1.0 as the best version.
Is Ubuntu 14.04 or wget 1.15 not compatible with TLS 1.0 websites? Do I need to install/download any library/software to enable this connection?
The problem is the server, not the client. Most browsers work around these broken servers by retrying with a lower version. Most other applications fail permanently if the first connection attempt fails, i.e. they don't downgrade by itself and one has to enforce another version by some application specific settings.
If you want to only trigger validation when the input looses focus you can use onBlur
Trivia: React <17 listens to blur
event and >=17 listens to focusout
event.
SELECT PersonName, songName, status
FROM table
WHERE name IN ('Holly', 'Ryan')
If you are using parametrized Stored procedure:
INNER JOIN ON t.PersonName = newTable.PersonName
using a table variable which contains passed in namesIf you really need to use sys.path.insert, consider leaving sys.path[0] as it is:
sys.path.insert(1, path_to_dev_pyworkbooks)
This could be important since 3rd party code may rely on sys.path documentation conformance:
As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter.
select t2.*
from t1 join t2 on t2.url='site.com/path/%' + cast(t1.id as varchar) + '%/more'
where t1.id > 9000
Using concat like suggested is even better though
you can insert using loop if you want to insert some random values.
BEGIN
FOR x IN 1 .. 1000 LOOP
INSERT INTO MULTI_INSERT_DEMO (ID, NAME)
SELECT x, 'anyName' FROM dual;
END LOOP;
END;
While the official docs are happy not to provide switch, I have seen a solution using dictionaries.
For example:
# define the function blocks
def zero():
print "You typed zero.\n"
def sqr():
print "n is a perfect square\n"
def even():
print "n is an even number\n"
def prime():
print "n is a prime number\n"
# map the inputs to the function blocks
options = {0 : zero,
1 : sqr,
4 : sqr,
9 : sqr,
2 : even,
3 : prime,
5 : prime,
7 : prime,
}
Then the equivalent switch block is invoked:
options[num]()
This begins to fall apart if you heavily depend on fall through.
A quick search in google provided this:
function mysqlTimeStampToDate(timestamp) {
//function parses mysql datetime string and returns javascript Date object
//input has to be in this format: 2007-06-05 15:26:02
var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
var parts=timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
return new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
}
This should solve your problem:
select replace(to_char(a, '90D90'),'.00','')
from
(
select 50 a from dual
union
select 50.57 from dual
union
select 5.57 from dual
union
select 0.35 from dual
union
select 0.4 from dual
);
Give a look also as this SQL Fiddle for test.
You can write your own WriteLine method-
public static void WriteLine<T>(T obj)
{
var t = typeof(T);
var props = t.GetProperties();
StringBuilder sb = new StringBuilder();
foreach (var item in props)
{
sb.Append($"{item.Name}:{item.GetValue(obj,null)}; ");
}
sb.AppendLine();
Console.WriteLine(sb.ToString());
}
Use it like-
WriteLine(myObject);
To write a collection we can use-
var ifaces = t.GetInterfaces();
if (ifaces.Any(o => o.Name.StartsWith("ICollection")))
{
dynamic lst = t.GetMethod("GetEnumerator").Invoke(obj, null);
while (lst.MoveNext())
{
WriteLine(lst.Current);
}
}
The method may look like-
public static void WriteLine<T>(T obj)
{
var t = typeof(T);
var ifaces = t.GetInterfaces();
if (ifaces.Any(o => o.Name.StartsWith("ICollection")))
{
dynamic lst = t.GetMethod("GetEnumerator").Invoke(obj, null);
while (lst.MoveNext())
{
WriteLine(lst.Current);
}
}
else if (t.GetProperties().Any())
{
var props = t.GetProperties();
StringBuilder sb = new StringBuilder();
foreach (var item in props)
{
sb.Append($"{item.Name}:{item.GetValue(obj, null)}; ");
}
sb.AppendLine();
Console.WriteLine(sb.ToString());
}
}
Using if, else if
and checking interfaces, attributes, base type, etc. and recursion (as this is a recursive method) in this way we may achieve an object dumper, but it is tedious for sure. Using the object dumper from Microsoft's LINQ Sample would save your time.
This will do the trick. Just pass it your select element a la: document.getElementById('lstALL')
when you need your list sorted.
function sortSelect(selElem) {
var tmpAry = new Array();
for (var i=0;i<selElem.options.length;i++) {
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i].text;
tmpAry[i][1] = selElem.options[i].value;
}
tmpAry.sort();
while (selElem.options.length > 0) {
selElem.options[0] = null;
}
for (var i=0;i<tmpAry.length;i++) {
var op = new Option(tmpAry[i][0], tmpAry[i][1]);
selElem.options[i] = op;
}
return;
}
Under system environment variables, make sure "C:\ProgramData\Oracle\Java\javapath" is removed.
Under system environment variables, make sure "C:\Program Files\Java\jdk1.8.0_131\bin" is added.
If the URL that you are trying to remove the query string from is the current URL of the PHP script, you can use one of the previously mentioned methods. If you just have a string variable with a URL in it and you want to strip off everything past the '?' you can do:
$pos = strpos($url, "?");
$url = substr($url, 0, $pos);
nbproject
If I want to edit a specified comment, how to get its content and its question?
You can query by sub-document: db.question.find({'comments.content' : 'xxx'})
.
This will return the whole Question document. To edit the specified comment, you then have to find the comment on the client, make the edit and save that back to the DB.
In general, if your document contains an array of objects, you'll find that those sub-objects will need to be modified client side.
You need to open the file in binary mode i.e. wb
instead of w
. If you don't, the end of line characters are auto-converted to OS specific ones.
Here is an excerpt from Python reference about open()
.
The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading.
In case of HTML5 this will do the trick
window.onpopstate = function() {
alert("clicked back button");
}; history.pushState({}, '');
As abstract methods belong to the class and cannot be overridden by the implementing class.Even if there is a static method with same signature , it hides the method ,does not override it. So it is immaterial to declare the abstract method as static as it will never get the body.Thus, compile time error.
Non programmatically, you can just open the archive using the 7zip UI to add/remove or extract/replace files without the structure changing. I didn't know it was a problem using other things until now :)
Let's say there is an administrator dashboard where users are listed with their id printed as a data attribute so it can be retrieved at some point via JavaScript.
An update could be executed this way …
class UserRepository extends \Doctrine\ORM\EntityRepository
{
public function updateUserStatus($userId, $newStatus)
{
return $this->createQueryBuilder('u')
->update()
->set('u.isActive', '?1')
->setParameter(1, $qb->expr()->literal($newStatus))
->where('u.id = ?2')
->setParameter(2, $qb->expr()->literal($userId))
->getQuery()
->getSingleScalarResult()
;
}
AJAX action handling:
# Post datas may be:
# handled with a specific custom formType — OR — retrieved from request object
$userId = (int)$request->request->get('userId');
$newStatus = (int)$request->request->get('newStatus');
$em = $this->getDoctrine()->getManager();
$r = $em->getRepository('NAMESPACE\User')
->updateUserStatus($userId, $newStatus);
if ( !empty($r) ){
# Row updated
}
Working example using Doctrine 2.5 (on top of Symfony3).
For SQL Server, from http://msdn.microsoft.com/en-us/library/ms179859.aspx :
% Any string of zero or more characters.
WHERE title LIKE '%computer%'
finds all book titles with the word 'computer' anywhere in the book title.
_ Any single character.
WHERE au_fname LIKE '_ean'
finds all four-letter first names that end with ean (Dean, Sean, and so on).
[ ] Any single character within the specified range ([a-f]) or set ([abcdef]).
WHERE au_lname LIKE '[C-P]arsen'
finds author last names ending with arsen and starting with any single character between C and P, for example Carsen, Larsen, Karsen, and so on. In range searches, the characters included in the range may vary depending on the sorting rules of the collation.
[^] Any single character not within the specified range ([^a-f]) or set ([^abcdef]).
WHERE au_lname LIKE 'de[^l]%'
all author last names starting with de and where the following letter is not l.
Here's one way to do it with Awk that's relatively easy to understand:
awk '{print substr($0, index($0, $3))}'
This is a simple awk command with no pattern, so action inside {}
is run for every input line.
The action is to simply prints the substring starting with the position of the 3rd field.
$0
: the whole input line$3
: 3rd fieldindex(in, find)
: returns the position of find
in string in
substr(string, start)
: return a substring starting at index start
If you want to use a different delimiter, such as comma, you can specify it with the -F option:
awk -F"," '{print substr($0, index($0, $3))}'
You can also operate this on a subset of the input lines by specifying a pattern before the action in {}
. Only lines matching the pattern will have the action run.
awk 'pattern{print substr($0, index($0, $3))}'
Where pattern can be something such as:
/abcdef/
: use regular expression, operates on $0 by default.$1 ~ /abcdef/
: operate on a specific field.$1 == blabla
: use string comparisonNR > 1
: use record/line numberNF > 0
: use field/column number$rs = $db->Insert('register',"'$fn','$ln','$email','$pass','$city','$mo','$fil'","'f_name','l_name=','email','password','city','contact','image'");
For anyone like me that was trying to do this via a drush (Drupal shell) command on a remote server, you will not be able to use the solution that requires you to CD into the working directory:
Instead you need to use the solution that breaks up the pull into a fetch & merge:
drush @remote exec git --git-dir=/REPO/PATH --work-tree=/REPO/WORKDIR-PATH fetch origin
drush @remote exec git --git-dir=/REPO/PATH --work-tree=/REPO/WORKDIR-PATH merge origin/branch
You can use mysqlcheck
to do this at the command line.
One database:
mysqlcheck -o <db_schema_name>
All databases:
mysqlcheck -o --all-databases
example : 1 and 2 table is available
1 table delete entry and select nor 2 table records and insert to no 1 table . when delete time no 1 table dont have second table records example emp id not available means this errors appeared
I assume the C string is in a fixed memory, so if you replace spaces you have to shift all characters.
The easiest seems to be to create new string and iterate over the original one and copy only non space characters.
This is really similar to another question. How should I load files into my Java application?
How should I load my files into my Java Application?
You do not want to load your files in by:
C:\your\project\file.txt
this is bad!
You should use getResourceAsStream.
InputStream inputStream = YourClass.class.getResourceAsStream(“file.txt”);
And also you should use File.separator; which is the system-dependent name-separator character, represented as a string for convenience.
Another option you can check the document.readyState like,
var chkReadyState = setInterval(function() {
if (document.readyState == "complete") {
// clear the interval
clearInterval(chkReadyState);
// finally your page is loaded.
}
}, 100);
From the documentation of readyState Page the summary of complete state is
Returns "loading" while the document is loading, "interactive" once it is finished parsing but still loading sub-resources, and "complete" once it has loaded.
if you are using windows , it takes some steps , 1) create a file called package.json
{
"name": "hello"
, "version": "0.0.1"
, "dependencies": {
"express": "*"
}
}
where hello is the name of the package and * means the latest version of your dependency
2) code to you project directory and run the following command
npm install
It installs the dependencies
I have a same problem, with volley, but this is my solution:
In Android Manifiest, in tag application add:
android:usesCleartextTraffic="true"
android:networkSecurityConfig="@xml/network_security_config"
create in folder xml this file network_security_config.xml and write this:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
inside tag application add this tag:
<uses-library android:name="org.apache.http.legacy" android:required="false"/>
Before using foreach
for iteration, reverse the list by the reverse
method:
myList.Reverse();
foreach( List listItem in myList)
{
Console.WriteLine(listItem);
}
I've seen occasional problems with Eclipse forgetting that built-in classes (including Object
and String
) exist. The way I've resolved them is to:
This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.
Attach gdb to one of the httpd child processes and reload or continue working and wait for a crash and then look at the backtrace. Do something like this:
$ ps -ef|grep httpd
0 681 1 0 10:38pm ?? 0:00.45 /Applications/MAMP/Library/bin/httpd -k start
501 690 681 0 10:38pm ?? 0:00.02 /Applications/MAMP/Library/bin/httpd -k start
...
Now attach gdb to one of the child processes, in this case PID 690 (columns are UID, PID, PPID, ...)
$ sudo gdb
(gdb) attach 690
Attaching to process 690.
Reading symbols for shared libraries . done
Reading symbols for shared libraries ....................... done
0x9568ce29 in accept$NOCANCEL$UNIX2003 ()
(gdb) c
Continuing.
Wait for crash... then:
(gdb) backtrace
Or
(gdb) backtrace full
Should give you some clue what's going on. If you file a bug report you should include the backtrace.
If the crash is hard to reproduce it may be a good idea to configure Apache to only use one child processes for handling requests. The config is something like this:
StartServers 1
MinSpareServers 1
MaxSpareServers 1