just call the finish() in the method you would like to end the activity in, for example when you use the onCreate() method, in the end of the method, just add finish() and you will see the activity ends as soon as it is created!
For php, \n should work for you!
If this is a submit button, use <input type="image" src="..." ... />
.
http://www.htmlcodetutorial.com/forms/_INPUT_TYPE_IMAGE.html
If you want to specify the image with CSS, you'll have to use type="submit"
.
You can't do that from the initialization list,
Have a look at this:
http://www.cprogramming.com/tutorial/initialization-lists-c++.html
:)
A simple solution for a simple question:
split -n l/5 your_file.txt
no need for scripting here.
From the man file, CHUNKS may be:
l/N split into N files without splitting lines
Update
Not all unix dist include this flag. For example, it will not work in OSX. To use it, you can consider replacing the Mac OS X utilities with GNU core utilities.
Someone posted this link to the MDN in a comment, and I think it was very helpful. It describes things like ErrorTypes very thoroughly.
EvalError --- Creates an instance representing an error that occurs regarding the global function eval().
InternalError --- Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. "too much recursion".
RangeError --- Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range.
ReferenceError --- Creates an instance representing an error that occurs when de-referencing an invalid reference.
SyntaxError --- Creates an instance representing a syntax error that occurs while parsing code in eval().
TypeError --- Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.
URIError --- Creates an instance representing an error that occurs when encodeURI() or decodeURI() are passed invalid parameters.
In Java
public class Matrix {
/* Author Shrikant Dande */
private static void showMatrix(int[][] arr,int rows,int col){
for(int i =0 ;i<rows;i++){
for(int j =0 ;j<col;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
private static void rotateMatrix(int[][] arr,int rows,int col){
int[][] tempArr = new int[4][4];
for(int i =0 ;i<rows;i++){
for(int j =0 ;j<col;j++){
tempArr[i][j] = arr[rows-1-j][i];
System.out.print(tempArr[i][j]+" ");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] arr = { {1, 2, 3, 4},
{5, 6, 7, 8},
{9, 1, 2, 5},
{7, 4, 8, 9}};
int rows = 4,col = 4;
showMatrix(arr, rows, col);
System.out.println("------------------------------------------------");
rotateMatrix(arr, rows, col);
}
}
SLF4J 1.5.11 and 1.6.0 versions are not compatible (see compatibility report) because the argument list of org.slf4j.spi.LocationAwareLogger.log
method has been changed (added Object[] p5):
SLF4J 1.5.11:
LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
String p4, Throwable p5 )
SLF4J 1.6.0:
LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
String p4, Object[] p5, Throwable p6 )
See compatibility reports for other SLF4J versions on this page.
You can generate such reports by the japi-compliance-checker tool.
After much aggravation, I discovered how to scroll in iframes on my ipad. The secret was to do a vertical finger swipe (single finger was fine) on the LEFT side of the iframe area (and maybe slightly outside of the border). On a laptop or PC, the scroll bar is on the right, so naturally, I spent of lot of time on my ipad experimenting with finger motions on the right side. Only when I tried the left side would the iframe scroll.
You can make a hyperlink in Telegram by writing an URL and send the message. Using Telegram Bot APIs you can send a clickable URL in two ways:
Markdown:
[This is an example](https://example.com)
HTML:
<a href="https://example.com">This is an example</a>
In both cases you will have:
EDIT: In new version of Telegram clients you can do that, see above answers.
Just to update this, the standard now is:
<input type="file" name="image" accept="image/*" capture="environment">
to access the environment-facing (rear) camera, and
<input type="file" name="image" accept="image/*" capture="user">
for user-facing (front) camera. To access video, substitute "video" for "image" in name.
Tested on iPhone 5c, running iOS 10.3.3, firmware 760, works fine.
select ABS(CAST(CAST(NEWID() AS VARBINARY) AS INT)) as [Randomizer]
has always worked for me
As already said, the easiest way is to use querystring.
But if you cannot, because of security reason, you should consider using cookies.
Take a look at anchor tags. You can create an anchor with
<div id="anchor-name">Heading Text</div>
and refer to it later with
<a href="http://server/page.html#anchor-name">Link text</a>
I tried the answer from LBushkin and it worked great, but it won't work for null values and nullable fields. So I've changed it to this:
propertyName= "Latitude";
PropertyInfo propertyInfo = ship.GetType().GetProperty(propertyName);
if (propertyInfo != null)
{
Type t = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
object safeValue = (value == null) ? null : Convert.ChangeType(value, t);
propertyInfo.SetValue(ship, safeValue, null);
}
DECLARE @uuid VARCHAR(50)
SET @uuid = 'a89b1acd95016ae6b9c8aabb07da2010'
SELECT CAST(
SUBSTRING(@uuid, 1, 8) + '-' + SUBSTRING(@uuid, 9, 4) + '-' + SUBSTRING(@uuid, 13, 4) + '-' +
SUBSTRING(@uuid, 17, 4) + '-' + SUBSTRING(@uuid, 21, 12)
AS UNIQUEIDENTIFIER)
It is done to maintain the arrangement of bytes which is sent in the network(Endianness). Depending upon architecture of your device,data can be arranged in the memory either in the big endian format or little endian format. In networking, we call the representation of byte order as network byte order and in our host, it is called host byte order. All network byte order is in big endian format.If your host's memory computer architecture is in little endian format,htons() function become necessity but in case of big endian format memory architecture,it is not necessary.You can find endianness of your computer programmatically too in the following way:->
int x = 1;
if (*(char *)&x){
cout<<"Little Endian"<<endl;
}else{
cout<<"Big Endian"<<endl;
}
and then decide whether to use htons() or not.But in order to avoid the above line,we always write htons() although it does no changes for Big Endian based memory architecture.
Jon has the right answer, but to elaborate a little more with some syntactic sugar..
SET | more
enables you to see the variables one page at a time, rather than the whole lot, or
SET > output.txt
sends the output to a file output.txt which you can open in Notepad or whatever...
If you want to handle your webapp's timeout with an apache load balancer, you first have to understand the different meaning of timeout
.
I try to condense the discussion I found here: http://apache-http-server.18135.x6.nabble.com/mod-proxy-When-does-a-backend-be-considered-as-failed-td5031316.html :
It appears that
mod_proxy
considers a backend as failed only when the transport layer connection to that backend fails. Unlessfailonstatus/failontimeout
is used. ...
So, setting failontimeout
is necessary for apache to consider a timeout of the webapp (e.g. served by tomcat) as a fail (and consecutively switch to the hot spare server). For the proper configuration, note the following misconfiguration:
ProxyPass / balancer://localbalance/ failontimeout=on timeout=10 failonstatus=50
This is a misconfiguration because:
You are defining a
balancer
here, so thetimeout
parameter relates to thebalancer
(like the two others). However for abalancer
, thetimeout
parameter is not a connection timeout (like the one used withBalancerMember
), but the maximum time to wait for a free worker/member (e.g. when all the workers are busy or in error state, the default being to not wait).
So, a proper configuration is done like this
timeout
at the BalanceMember
level: <Proxy balancer://mycluster>
BalancerMember http://member1:8080/svc timeout=6
... more BalanceMembers here
</Proxy>
failontimeout
on the balancer
ProxyPass /svc balancer://mycluster failontimeout=on
Restart apache.
If you are using the two formulas at the same time, it will not work... Here is a simple spreadsheet with it working: https://docs.google.com/spreadsheet/ccc?key=0AiOy0YDBXjt4dDJSQWg1Qlp6TEw5SzNqZENGOWgwbGc If you are still getting problems I would need to know what type of erroneous result you are getting.
Today() returns a numeric integer value: Returns the current computer system date. The value is updated when your document recalculates. TODAY is a function without arguments.
You could try this:
DECLARE @List VARCHAR(MAX)
SELECT @List = '1,2,3,4,5,6,7,8'
EXEC(
'DELETE
FROM TABLE
WHERE ID NOT IN (' + @List + ')'
)
Type SHUTDOWN
in the CLI
or
if your don't care about your data in memory, you may also type SHUTDOWN NOSAVE
to force shutdown the server.
You can instantiate an empty array with a given number of entries if you pass an int
to the Array
constructor and then iterate over it via ngFor
.
In your component code :
export class ForLoop {
fakeArray = new Array(12);
}
In your template :
<ul>
<li *ngFor="let a of fakeArray; let index = index">Something {{ index }}</li>
</ul>
The index properties give you the iteration number.
Other solution can be
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
emailIntent.setType("plain/text");
emailIntent.setClassName("com.google.android.gm", "com.google.android.gm.ComposeActivityGmail");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Yo");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Hi");
startActivity(emailIntent);
Assuming most of the android device has GMail app already installed.
If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user
, picked from your example), then the syntax is quite simple:
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin('a.user', 'u')
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
Since you are applying a condition on the joined result here, using a LEFT JOIN
or simply JOIN
is the same.
If no association is available, then the query looks like following
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin(
'User\Entity\User',
'u',
\Doctrine\ORM\Query\Expr\Join::WITH,
'a.user = u.id'
)
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
This will produce a resultset that looks like following:
array(
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
// ...
)
Yes - it's possible (though not with your method signature) and yes, with your signature the types must be the same.
With the signature you have given, T
must be associated to a single type (e.g. String
or Integer
) at the call-site. You can, however, declare method signatures which take multiple type parameters
public <S, T> void func(Set<S> s, Set<T> t)
Note in the above signature that I have declared the types S
and T
in the signature itself. These are therefore different to and independent of any generic types associated with the class or interface which contains the function.
public class MyClass<S, T> {
public void foo(Set<S> s, Set<T> t); //same type params as on class
public <U, V> void bar(Set<U> s, Set<V> t); //type params independent of class
}
You might like to take a look at some of the method signatures of the collection classes in the java.util
package. Generics is really rather a complicated subject, especially when wildcards (? extends
and ? super
) are considered. For example, it's often the case that a method which might take a Set<Number>
as a parameter should also accept a Set<Integer>
. In which case you'd see a signature like this:
public void baz(Set<? extends T> s);
There are plenty of questions already on SO for you to look at on the subject!
Not sure what the point of returning an int
from the function is, although you could do that if you want!
You need to assign the result back to $content
as preg_replace
does not modify the original string.
$content = preg_replace("/<img[^>]+\>/i", "(image) ", $content);
So, It looks something like this:
git rm --cached /config/deploy.rb
echo /config/deploy.rb >> .gitignore
Remove cache for tracked file from git and add that file to
.gitignore
list
You could use a pre tag instead of a div. This would automatically display your \n's in the correct way.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
var display_txt = "1st line text" +"\n" + "2nd line text";
$('#somediv').html(display_txt).css("color", "green");
});
</script>
</head>
<body>
<pre>
<p id="somediv"></p>
</pre>
</body>
</html>
I recommend you to read the following post: AngularJS: "Controller as" or "$scope"?
It describes very well the advantages of using "Controller as" to expose variables over "$scope".
I know you asked specifically about methods and not variables, but I think that it's better to stick to one technique and be consistent with it.
So for my opinion, because of the variables issue discussed in the post, it's better to just use the "Controller as" technique and also apply it to the methods.
Try the following:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings[key].Value = value;
config.Save();
ConfigurationManager.RefreshSection("appSettings");
If you want to fill NaN for a specific column you can use loc:
d1 = {"Col1" : ['A', 'B', 'C'],
"fruits": ['Avocado', 'Banana', 'NaN']}
d1= pd.DataFrame(d1)
output:
Col1 fruits
0 A Avocado
1 B Banana
2 C NaN
d1.loc[ d1.Col1=='C', 'fruits' ] = 'Carrot'
output:
Col1 fruits
0 A Avocado
1 B Banana
2 C Carrot
def truncate(number: float, digits: int) -> float:
pow10 = 10 ** digits
return number * pow10 // 1 / pow10
f1 = 1.2666666
f2 = truncate(f1, 3)
print(f1, f2)
1.2666666 1.266
It shifts f1
numbers digits
times to the left, then cuts all decimals and finally shifts back the numbers digits
times to the right.
Example in a sequence:
1.2666666 # number
1266.6666 # number * pow10
1266.0 # number * pow10 // 1
1.266 # number * pow10 // 1 / pow10
Go to https://developers.facebook.com/apps and open the app you have created. open setting tab and add platform and insert site url where you want to share facebook button .Its done.
public static void copyFile(File oldLocation, File newLocation) throws IOException {
if ( oldLocation.exists( )) {
BufferedInputStream reader = new BufferedInputStream( new FileInputStream(oldLocation) );
BufferedOutputStream writer = new BufferedOutputStream( new FileOutputStream(newLocation, false));
try {
byte[] buff = new byte[8192];
int numChars;
while ( (numChars = reader.read( buff, 0, buff.length ) ) != -1) {
writer.write( buff, 0, numChars );
}
} catch( IOException ex ) {
throw new IOException("IOException when transferring " + oldLocation.getPath() + " to " + newLocation.getPath());
} finally {
try {
if ( reader != null ){
writer.close();
reader.close();
}
} catch( IOException ex ){
Log.e(TAG, "Error closing files when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
}
}
} else {
throw new IOException("Old location does not exist when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
}
}
encodeURIComponent() : assumes that its argument is a portion (such as the protocol, hostname, path, or query string) of a URI. Therefore it escapes the punctuation characters that are used to separate the portionsof a URI.
encodeURI(): is used for encoding existing url
A cookie is basically just an item in a dictionary. Each item has a key and a value. For authentication, the key could be something like 'username' and the value would be the username. Each time you make a request to a website, your browser will include the cookies in the request, and the host server will check the cookies. So authentication can be done automatically like that.
To set a cookie, you just have to add it to the response the server sends back after requests. The browser will then add the cookie upon receiving the response.
There are different options you can configure for the cookie server side, like expiration times or encryption. An encrypted cookie is often referred to as a signed cookie. Basically the server encrypts the key and value in the dictionary item, so only the server can make use of the information. So then cookie would be secure.
A browser will save the cookies set by the server. In the HTTP header of every request the browser makes to that server, it will add the cookies. It will only add cookies for the domains that set them. Example.com can set a cookie and also add options in the HTTP header for the browsers to send the cookie back to subdomains, like sub.example.com. It would be unacceptable for a browser to ever sends cookies to a different domain.
@fork2x
I have tried like this .Please review and update me whether it is right approach or not.
#/bin/sh
function pause(){
read -p "$*"
}
file="./apptest.properties"
if [ -f "$file" ]
then
echo "$file found."
dbUser=`sed '/^\#/d' $file | grep 'db.uat.user' | tail -n 1 | cut -d "=" -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'`
dbPass=`sed '/^\#/d' $file | grep 'db.uat.passwd' | tail -n 1 | cut -d "=" -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'`
echo database user = $dbUser
echo database pass = $dbPass
else
echo "$file not found."
fi
Select *
FROM test_table
WHERE user_id = value
AND date_added = (select max(date_added)
from test_table
where user_id = value)
True, this is pointless for the most examples. But finally, I came to the following statement and it works fine:
update tablename set column1 = '' where tablename .id = (select id from tablename2 where tablename2.column2 = 'xyz');
And make sure you download the Windows7.1 SDK, not just the Windows 7 one. That caused me a lot of head pounding.
There is just a caveat that I discovered today.
If you have a function that is calling a plot a lot of times you better use plt.close(fig)
instead of fig.clf()
somehow the first does not accumulate in memory. In short if memory is a concern use plt.close(fig) (Although it seems that there are better ways, go to the end of this comment for relevant links).
So the the following script will produce an empty list:
for i in range(5):
fig = plot_figure()
plt.close(fig)
# This returns a list with all figure numbers available
print(plt.get_fignums())
Whereas this one will produce a list with five figures on it.
for i in range(5):
fig = plot_figure()
fig.clf()
# This returns a list with all figure numbers available
print(plt.get_fignums())
From the documentation above is not clear to me what is the difference between closing a figure and closing a window. Maybe that will clarify.
If you want to try a complete script there you have:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1000)
y = np.sin(x)
for i in range(5):
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(x, y)
plt.close(fig)
print(plt.get_fignums())
for i in range(5):
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(x, y)
fig.clf()
print(plt.get_fignums())
If memory is a concern somebody already posted a work-around in SO see: Create a figure that is reference counted
In response to the final part of your question, which is still unanswered... When you write $('#video').duration
, you're asking for the duration
property of the jQuery collection object, which doesn't exist. The native DOM video element does have the duration. You can get that in a few ways.
Here's one:
// get the native element directly
document.getElementById('video').duration
Here's another:
// get it out of the jQuery object
$('#video').get(0).duration
And another:
// use the event object
v.bind('loadeddata', function(e) {
console.log(e.target.duration);
});
Using encodeURIComponent()
:
var url = 'index.php?data='+encodeURIComponent(JSON.stringify({"json":[{"j":"son"}]})),
If you have got your data in a database table, here is a SQL version of a simple z-score algorithm:
with data_with_zscore as (
select
date_time,
value,
value / (avg(value) over ()) as pct_of_mean,
(value - avg(value) over ()) / (stdev(value) over ()) as z_score
from {{tablename}} where datetime > '2018-11-26' and datetime < '2018-12-03'
)
-- select all
select * from data_with_zscore
-- select only points greater than a certain threshold
select * from data_with_zscore where z_score > abs(2)
This is an old question and asks a little bit less than what I needed so this answer actually solves more than this question asks. The answers in this question helped me solve the following:
All this combined with JSON makes for a pretty powerful configuration storage support.
The solution (also on github):
from collections import OrderedDict
from pprint import pprint
class izipDestinationMatching(object):
__slots__ = ("attr", "value", "index")
def __init__(self, attr, value, index):
self.attr, self.value, self.index = attr, value, index
def __repr__(self):
return "izip_destination_matching: found match by '%s' = '%s' @ %d" % (self.attr, self.value, self.index)
def izip_destination(a, b, attrs, addMarker=True):
"""
Returns zipped lists, but final size is equal to b with (if shorter) a padded with nulls
Additionally also tries to find item reallocations by searching child dicts (if they are dicts) for attribute, listed in attrs)
When addMarker == False (patching), final size will be the longer of a, b
"""
for idx, item in enumerate(b):
try:
attr = next((x for x in attrs if x in item), None) # See if the item has any of the ID attributes
match, matchIdx = next(((orgItm, idx) for idx, orgItm in enumerate(a) if attr in orgItm and orgItm[attr] == item[attr]), (None, None)) if attr else (None, None)
if match and matchIdx != idx and addMarker: item[izipDestinationMatching] = izipDestinationMatching(attr, item[attr], matchIdx)
except:
match = None
yield (match if match else a[idx] if len(a) > idx else None), item
if not addMarker and len(a) > len(b):
for item in a[len(b) - len(a):]:
yield item, item
def dictdiff(a, b, searchAttrs=[]):
"""
returns a dictionary which represents difference from a to b
the return dict is as short as possible:
equal items are removed
added / changed items are listed
removed items are listed with value=None
Also processes list values where the resulting list size will match that of b.
It can also search said list items (that are dicts) for identity values to detect changed positions.
In case such identity value is found, it is kept so that it can be re-found during the merge phase
@param a: original dict
@param b: new dict
@param searchAttrs: list of strings (keys to search for in sub-dicts)
@return: dict / list / whatever input is
"""
if not (isinstance(a, dict) and isinstance(b, dict)):
if isinstance(a, list) and isinstance(b, list):
return [dictdiff(v1, v2, searchAttrs) for v1, v2 in izip_destination(a, b, searchAttrs)]
return b
res = OrderedDict()
if izipDestinationMatching in b:
keepKey = b[izipDestinationMatching].attr
del b[izipDestinationMatching]
else:
keepKey = izipDestinationMatching
for key in sorted(set(a.keys() + b.keys())):
v1 = a.get(key, None)
v2 = b.get(key, None)
if keepKey == key or v1 != v2: res[key] = dictdiff(v1, v2, searchAttrs)
if len(res) <= 1: res = dict(res) # This is only here for pretty print (OrderedDict doesn't pprint nicely)
return res
def dictmerge(a, b, searchAttrs=[]):
"""
Returns a dictionary which merges differences recorded in b to base dictionary a
Also processes list values where the resulting list size will match that of a
It can also search said list items (that are dicts) for identity values to detect changed positions
@param a: original dict
@param b: diff dict to patch into a
@param searchAttrs: list of strings (keys to search for in sub-dicts)
@return: dict / list / whatever input is
"""
if not (isinstance(a, dict) and isinstance(b, dict)):
if isinstance(a, list) and isinstance(b, list):
return [dictmerge(v1, v2, searchAttrs) for v1, v2 in izip_destination(a, b, searchAttrs, False)]
return b
res = OrderedDict()
for key in sorted(set(a.keys() + b.keys())):
v1 = a.get(key, None)
v2 = b.get(key, None)
#print "processing", key, v1, v2, key not in b, dictmerge(v1, v2)
if v2 is not None: res[key] = dictmerge(v1, v2, searchAttrs)
elif key not in b: res[key] = v1
if len(res) <= 1: res = dict(res) # This is only here for pretty print (OrderedDict doesn't pprint nicely)
return res
I would like to add to the answers of BalusC and Pascal Thivent another common use of insertable=false, updatable=false
:
Consider a column that is not an id but some kind of sequence number. The responsibility for calculating the sequence number may not necessarily belong to the application.
For example, sequence number starts with 1000 and should increment by one for each new entity. This is easily done, and very appropriately so, in the database, and in such cases these configurations makes sense.
More accurately anything that is not 0
is true.
So 1
is true, but so is 2
, 3
... etc.
It is better if you don't kill a thread. A way could be to introduce a "try" block into the thread's cycle and to throw an exception when you want to stop the thread (for example a break/return/... that stops your for/while/...). I've used this on my app and it works...
System.setProperty("webdriver.gecko.driver", "C:\\gecko\\geckodriver.exe");
System.setProperty("webdriver.firefox.bin","C:\\Program Files\\Mozilla Firefox\\firefox.exe");
WebDriver driver = new FirefoxDriver();
All other answer are correct, but remember that if you cast double to int you will loss decimal value.. so 2.9 double become 2 int.
You can use Math.round(double)
function or simply do :
(int)(yourDoubleValue + 0.5d)
here's my directive:
mainApp.directive('number', function () {
return {
link: function (scope, el, attr) {
el.bind("keydown keypress", function (event) {
//ignore all characters that are not numbers, except backspace, delete, left arrow and right arrow
if ((event.keyCode < 48 || event.keyCode > 57) && event.keyCode != 8 && event.keyCode != 46 && event.keyCode != 37 && event.keyCode != 39) {
event.preventDefault();
}
});
}
};
});
usage:
<input number />
Alternatively if you want to persist in using the DocumentType
class.
Then you could just add the following annotation on top of your DocumentType class.
@XmlRootElement(name="document")
Note: the String value "document"
refers to the name of the root tag of the xml message.
Open up a command prompt then type...
netstat -a
Put the date in single quotes and move the parenthesis (after the 'yes'
) to the end:
INSERT INTO custorder
VALUES ('Kevin', 'yes' , STR_TO_DATE('1-01-2012', '%d-%m-%Y') ) ;
^ ^
---parenthesis removed--| and added here ------|
But you can always use dates without STR_TO_DATE()
function, just use the (Y-m-d) '20120101'
or '2012-01-01'
format. Check the MySQL docs: Date and Time Literals
INSERT INTO custorder
VALUES ('Kevin', 'yes', '2012-01-01') ;
Try using Binding Values. You cannot use variables as you do in T-SQL but you can use "parameters". I hope the following link is usefull.Binding Values
Use nc command,
nc -zv <hostname/ip> <port/port range>
For example,
nc -zv localhost 27017-27019
or
nc -zv localhost 27017
You can also use telnet command
telnet <ip/host> port
In case you are appending to the DOM, make sure the content is compatible:
modal.find ('div.modal-body').append (content) // check content
One way to convert to string is to use astype:
total_rows['ColumnID'] = total_rows['ColumnID'].astype(str)
However, perhaps you are looking for the to_json
function, which will convert keys to valid json (and therefore your keys to strings):
In [11]: df = pd.DataFrame([['A', 2], ['A', 4], ['B', 6]])
In [12]: df.to_json()
Out[12]: '{"0":{"0":"A","1":"A","2":"B"},"1":{"0":2,"1":4,"2":6}}'
In [13]: df[0].to_json()
Out[13]: '{"0":"A","1":"A","2":"B"}'
Note: you can pass in a buffer/file to save this to, along with some other options...
There is a better way that is safer and will not slow down your application. How Excel is set up, a cell can have either a value or a formula; the formula can not refer to its own cell. Otherwise, You end up with an infinite loop, since the new value would cause another calculation... .
Use a helper column to calculate the value based on what you put in the other cell.
For Example:
Column A is a True or False, Column B contains a monetary value, Column C contains the following formula:
=B1
Now, to calculate that column B will be highlighted yellow in a conditional format only if Column A is True and Column B is greater than Zero...
=AND(A1=True,C1>0)
You can then choose to hide column C
There is also this way of specifying the viewmodel:
using Wpf = System.Windows;
public partial class App : Wpf.Application //your skeleton app already has this.
{
protected override void OnStartup( Wpf.StartupEventArgs e ) //you need to add this.
{
base.OnStartup( e );
MainWindow = new MainView();
MainWindow.DataContext = new MainViewModel( e.Args );
MainWindow.Show();
}
}
<Rant>
All of the solutions previously proposed require that MainViewModel
must have a parameterless constructor.
Microsoft is under the impression that systems can be built using parameterless constructors. If you are also under that impression, go ahead and use some of the other solutions.
For those that know that constructors must have parameters, and therefore the instantiation of objects cannot be left in the hands of magic frameworks, the proper way of specifying the viewmodel is the one I showed above.
</Rant>
That is not an error; the make command in unix works based on the timestamps. I.e let's say if you have made certain changes to factorial.cpp
and compile using make
then make shows
the information that only the cc -o factorial.cpp
command is executed. Next time if you execute the same command i.e make
without making any changes to any file with .cpp
extension the compiler says that the output file is up to date. The compiler gives this information until we make certain changes to any file.cpp
.
The advantage of the makefile
is that it reduces the recompiling time by compiling the only files that are modified and by using the object (.o
) files of the unmodified files directly.
CREATE TABLE dbo.OwnerType
(
ID int NOT NULL,
Name varchar(50) NULL
)
insert into OwnerType (Name) values ('User');
insert into OwnerType (Name) values ('Group');
I think that would be the most general way to represent what you want instead of using a flag.
Imports System.Net.NetworkInformation
Public Function PingHost(ByVal nameOrAddress As String) As Boolean
Dim pingable As Boolean = False
Dim pinger As Ping
Dim lPingReply As PingReply
Try
pinger = New Ping()
lPingReply = pinger.Send(nameOrAddress)
MessageBox.Show(lPingReply.Status)
If lPingReply.Status = IPStatus.Success Then
pingable = True
Else
pingable = False
End If
Catch PingException As Exception
pingable = False
End Try
Return pingable
End Function
@SpringBootApplication @ComponentScan(basePackages = {"io.testapi"})
In the main class below springbootapplication annotation i have written componentscan and it worked for me.
=COUNTIFS(1:1,FALSE)=0
This will return TRUE or FALSE (Looks for FALSE, if count isn't 0 (all True) it will be false
How about streams?
public boolean checkFieldsIsNull(Object instance, List<String> fieldNames) {
return fieldNames.stream().allMatch(field -> {
try {
return Objects.isNull(instance.getClass().getDeclaredField(field).get(instance));
} catch (IllegalAccessException | NoSuchFieldException e) {
return true;//You can throw RuntimeException if need.
}
});
}
And answering this seven years after the question was asked, it is possible to do this comparison using built-in methods:
Month.toInt("January") > Month.toInt("May")
becomes
Array.FindIndex( CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,
t => t.Equals("January", StringComparison.CurrentCultureIgnoreCase)) >
Array.FindIndex( CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,
t => t.Equals("May", StringComparison.CurrentCultureIgnoreCase))
Which can be refactored into an extension method for simplicity. The following is a LINQPad example (hence the Dump()
method calls):
void Main()
{
("January".GetMonthIndex() > "May".GetMonthIndex()).Dump();
("January".GetMonthIndex() == "january".GetMonthIndex()).Dump();
("January".GetMonthIndex() < "May".GetMonthIndex()).Dump();
}
public static class Extension {
public static int GetMonthIndex(this string month) {
return Array.FindIndex( CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,
t => t.Equals(month, StringComparison.CurrentCultureIgnoreCase));
}
}
With output:
False
True
True
map.setZoom(zoom:number)
https://developers.google.com/maps/documentation/javascript/reference#Map
RecogniContact is a Windows COM object that parses US and European addresses. You can try it right on http://www.loquisoft.com/index.php?page=8
Both these will give you the first child node:
console.log(parentElement.firstChild); // or
console.log(parentElement.childNodes[0]);
If you need the first child that is an element node then use:
console.log(parentElement.children[0]);
Edit
Ah, I see your problem now; parentElement
is an array.
If you know that getElementsByClassName will only return one result, which it seems you do, you should use [0]
to dearray (yes, I made that word up) the element:
var parentElement = document.getElementsByClassName("uniqueClassName")[0];
Since this is a fatal error and also quite difficult to debug, maybe the fix could be put somewhere (in the provided command line?):
export GPG_TTY=$(tty)
Here is another way to format the query:
return $repository->createQueryBuilder('u')
->select('count(u.id)')
->getQuery()
->getSingleScalarResult();
MySQL 8.0.16 is the first version that supports CHECK constraints.
Read https://dev.mysql.com/doc/refman/8.0/en/create-table-check-constraints.html
If you use MySQL 8.0.15 or earlier, the MySQL Reference Manual says:
The
CHECK
clause is parsed but ignored by all storage engines.
Try a trigger...
mysql> delimiter //
mysql> CREATE TRIGGER trig_sd_check BEFORE INSERT ON Customer
-> FOR EACH ROW
-> BEGIN
-> IF NEW.SD<0 THEN
-> SET NEW.SD=0;
-> END IF;
-> END
-> //
mysql> delimiter ;
Hope that helps.
My solution with Angular 4.0.1: Just showing the UI for required CVC input - where the CVC must be exactly 3 digits:
<form #paymentCardForm="ngForm">
...
<md-input-container align="start">
<input #cvc2="ngModel" mdInput type="text" id="cvc2" name="cvc2" minlength="3" maxlength="3" placeholder="CVC" [(ngModel)]="paymentCard.cvc2" [disabled]="isBusy" pattern="\d{3}" required />
<md-hint *ngIf="cvc2.errors && (cvc2.touched || submitted)" class="validation-result">
<span [hidden]="!cvc2.errors.required && cvc2.dirty">
CVC is required.
</span>
<span [hidden]="!cvc2.errors.minlength && !cvc2.errors.maxlength && !cvc2.errors.pattern">
CVC must be 3 numbers.
</span>
</md-hint>
</md-input-container>
...
<button type="submit" md-raised-button color="primary" (click)="confirm($event, paymentCardForm.value)" [disabled]="isBusy || !paymentCardForm.valid">Confirm</button>
</form>
From experience I'll just note that while it is the C++ way to put formerly-static functions into the anonymous namespace, older compilers can sometimes have problems with this. I currently work with a few compilers for our target platforms, and the more modern Linux compiler is fine with placing functions into the anonymous namespace.
But an older compiler running on Solaris, which we are wed to until an unspecified future release, will sometimes accept it, and other times flag it as an error. The error is not what worries me, it's what it might be doing when it accepts it. So until we go modern across the board, we are still using static (usually class-scoped) functions where we'd prefer the anonymous namespace.
There is a slight effect, since you're doing the same check twice, at least in your example:
IF EXISTS(SELECT 1 FROM Contacs WHERE [Type] = 1)
Has to query, see if there are any, if true then:
UPDATE Contacs SET [Deleted] = 1 WHERE [Type] = 1
Has to query, see which ones...same check twice for no reason. Now if the condition you're looking for is indexed it ought to be quick, but for large tables you could see some delay just because you're running the select.
If you know what the sections are, you can do:
select top 10 * from table where section=1
union
select top 10 * from table where section=2
union
select top 10 * from table where section=3
You can use pandas
, by transforming the list
to a pd.Series
then simply use .value_counts()
import pandas as pd
a = ['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
a_cnts = pd.Series(a).value_counts().to_dict()
Input >> a_cnts["1"], a_cnts["10"]
Output >> (6, 2)
This matches 1.2.3.* too
^(*|\d+(.\d+){0,2}(.*)?)$
I would propose the less elegant:
(*|\d+(.\d+)?(.*)?)|\d+.\d+.\d+)
Here's an adaptation of the accepted answer for performing a simple GET request.
One thing to note if the server does any url rewriting, this will not work. You'll need to use a more full featured http client.
/**
* Performs an async get request (doesn't wait for response)
* Note: One limitation of this approach is it will not work if server does any URL rewriting
*/
function async_get($url)
{
$parts=parse_url($url);
$fp = fsockopen($parts['host'],
isset($parts['port'])?$parts['port']:80,
$errno, $errstr, 30);
$out = "GET ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
fclose($fp);
}
What no-one seems to realize is that none of the System.Uri
constructors correctly handles certain paths with percent signs in them.
new Uri(@"C:\%51.txt").AbsoluteUri;
This gives you "file:///C:/Q.txt"
instead of "file:///C:/%2551.txt"
.
Neither values of the deprecated dontEscape argument makes any difference, and specifying the UriKind gives the same result too. Trying with the UriBuilder doesn't help either:
new UriBuilder() { Scheme = Uri.UriSchemeFile, Host = "", Path = @"C:\%51.txt" }.Uri.AbsoluteUri
This returns "file:///C:/Q.txt"
as well.
As far as I can tell the framework is actually lacking any way of doing this correctly.
We can try to it by replacing the backslashes with forward slashes and feed the path to Uri.EscapeUriString
- i.e.
new Uri(Uri.EscapeUriString(filePath.Replace(Path.DirectorySeparatorChar, '/'))).AbsoluteUri
This seems to work at first, but if you give it the path C:\a b.txt
then you end up with file:///C:/a%2520b.txt
instead of file:///C:/a%20b.txt
- somehow it decides that some sequences should be decoded but not others. Now we could just prefix with "file:///"
ourselves, however this fails to take UNC paths like \\remote\share\foo.txt
into account - what seems to be generally accepted on Windows is to turn them into pseudo-urls of the form file://remote/share/foo.txt
, so we should take that into account as well.
EscapeUriString
also has the problem that it does not escape the '#'
character. It would seem at this point that we have no other choice but making our own method from scratch. So this is what I suggest:
public static string FilePathToFileUrl(string filePath)
{
StringBuilder uri = new StringBuilder();
foreach (char v in filePath)
{
if ((v >= 'a' && v <= 'z') || (v >= 'A' && v <= 'Z') || (v >= '0' && v <= '9') ||
v == '+' || v == '/' || v == ':' || v == '.' || v == '-' || v == '_' || v == '~' ||
v > '\xFF')
{
uri.Append(v);
}
else if (v == Path.DirectorySeparatorChar || v == Path.AltDirectorySeparatorChar)
{
uri.Append('/');
}
else
{
uri.Append(String.Format("%{0:X2}", (int)v));
}
}
if (uri.Length >= 2 && uri[0] == '/' && uri[1] == '/') // UNC path
uri.Insert(0, "file:");
else
uri.Insert(0, "file:///");
return uri.ToString();
}
This intentionally leaves + and : unencoded as that seems to be how it's usually done on Windows. It also only encodes latin1 as Internet Explorer can't understand unicode characters in file urls if they are encoded.
If you want to use it on XML content then add the below line in your Gradle file:
applicationVariants.all { variant ->
variant.resValue "string", "versionName", variant.versionName
}
And then use it on your XML content like this:
<TextView
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/versionName" />
None of those worked for me. I was trying to clone a directory from a private git server and entered my credentials false and then it wouldn't let me try different credentials on subsequent tries, it just errored out immediately with an authentication error.
What did work was specifying the user name (mike-wise
)in the url like this:
git clone https://[email protected]/someuser/somerepo.git
Two issues:
You're passing the jQuery wrapper of the element into parseInt
, which isn't what you want, as parseInt
will call toString
on it and get back "[object Object]"
. You need to use val
or text
or something (depending on what the element is) to get the string you want.
You're not telling parseInt
what radix (number base) it should use, which puts you at risk of odd input giving you odd results when parseInt
guesses which radix to use.
Fix if the element is a form field:
// vvvvv-- use val to get the value
var test = parseInt($("#testid").val(), 10);
// ^^^^-- tell parseInt to use decimal (base 10)
Fix if the element is something else and you want to use the text within it:
// vvvvvv-- use text to get the text
var test = parseInt($("#testid").text(), 10);
// ^^^^-- tell parseInt to use decimal (base 10)
There is only one PNG format, but it supports 5 color types.
PNG-8 refers to palette variant, which supports only 256 colors, but is usually smaller in size. PNG-8 can be a GIF substitute.
PNG-24 refers to true color variant, which supports more colors, but might be bigger. PNG-24 can be used instead of JPEG, if lossless image format is needed.
Any modern web browser will support both variants.
With the Entity Framework most of the time SaveChanges()
is sufficient. This creates a transaction, or enlists in any ambient transaction, and does all the necessary work in that transaction.
Sometimes though the SaveChanges(false) + AcceptAllChanges()
pairing is useful.
The most useful place for this is in situations where you want to do a distributed transaction across two different Contexts.
I.e. something like this (bad):
using (TransactionScope scope = new TransactionScope())
{
//Do something with context1
//Do something with context2
//Save and discard changes
context1.SaveChanges();
//Save and discard changes
context2.SaveChanges();
//if we get here things are looking good.
scope.Complete();
}
If context1.SaveChanges()
succeeds but context2.SaveChanges()
fails the whole distributed transaction is aborted. But unfortunately the Entity Framework has already discarded the changes on context1
, so you can't replay or effectively log the failure.
But if you change your code to look like this:
using (TransactionScope scope = new TransactionScope())
{
//Do something with context1
//Do something with context2
//Save Changes but don't discard yet
context1.SaveChanges(false);
//Save Changes but don't discard yet
context2.SaveChanges(false);
//if we get here things are looking good.
scope.Complete();
context1.AcceptAllChanges();
context2.AcceptAllChanges();
}
While the call to SaveChanges(false)
sends the necessary commands to the database, the context itself is not changed, so you can do it again if necessary, or you can interrogate the ObjectStateManager
if you want.
This means if the transaction actually throws an exception you can compensate, by either re-trying or logging state of each contexts ObjectStateManager
somewhere.
I had a similar problem and had to convert the URL from string to Uri object using:
Uri myUri = new Uri(URLInStringFormat, UriKind.Absolute);
(URLInStringFormat is your URL) Try to connect using the Uri instead of the string as:
WebClient client = new WebClient();
client.OpenRead(myUri);
On localhost you should consider context path.
function wsURL(path) {
var protocol = (location.protocol === 'https:') ? 'wss://' : 'ws://';
var url = protocol + location.host;
if(location.hostname === 'localhost') {
url += '/' + location.pathname.split('/')[1]; // add context path
}
return url + path;
}
I have written a quick guide on how to install the latest versions of Python 2 and Python 3 on CentOS 6 and CentOS 7. It currently covers Python 2.7.13 and Python 3.6.0:
# Start by making sure your system is up-to-date:
yum update
# Compilers and related tools:
yum groupinstall -y "development tools"
# Libraries needed during compilation to enable all features of Python:
yum install -y zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel expat-devel
# If you are on a clean "minimal" install of CentOS you also need the wget tool:
yum install -y wget
The next steps depend on the version of Python you're installing.
For Python 2.7.14:
wget http://python.org/ftp/python/2.7.14/Python-2.7.14.tar.xz
tar xf Python-2.7.14.tar.xz
cd Python-2.7.14
./configure --prefix=/usr/local --enable-unicode=ucs4 --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"
make && make altinstall
# Strip the Python 2.7 binary:
strip /usr/local/lib/libpython2.7.so.1.0
For Python 3.6.3:
wget http://python.org/ftp/python/3.6.3/Python-3.6.3.tar.xz
tar xf Python-3.6.3.tar.xz
cd Python-3.6.3
./configure --prefix=/usr/local --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"
make && make altinstall
# Strip the Python 3.6 binary:
strip /usr/local/lib/libpython3.6m.so.1.0
To install Pip:
# First get the script:
wget https://bootstrap.pypa.io/get-pip.py
# Then execute it using Python 2.7 and/or Python 3.6:
python2.7 get-pip.py
python3.6 get-pip.py
# With pip installed you can now do things like this:
pip2.7 install [packagename]
pip2.7 install --upgrade [packagename]
pip2.7 uninstall [packagename]
You are not supposed to change the system version of Python because it will break the system (as you found out). Installing other versions works fine as long as you leave the original system version alone. This can be accomplished by using a custom prefix (for example /usr/local
) when running configure, and using make altinstall
(instead of the normal make install
) when installing your build of Python.
Having multiple versions of Python available is usually not a big problem as long as you remember to type the full name including the version number (for example "python2.7" or "pip2.7"). If you do all your Python work from a virtualenv the versioning is handled for you, so make sure you install and use virtualenv!
xcopy "C:\Documents and Settings\user\Desktop\?????????" "D:\Backup" /s /e /y /i
Probably the problem is the space.Try with quotes.
Here is a JS fiddle http://jsfiddle.net/ke9kW/1/
As the others say, set the header to fixed, and start it with display: none
then jQuery
$(window).scroll(function () {
if ( $(this).scrollTop() > 200 && !$('header').hasClass('open') ) {
$('header').addClass('open');
$('header').slideDown();
} else if ( $(this).scrollTop() <= 200 ) {
$('header').removeClass('open');
$('header').slideUp();
}
});
where 200 is the height in pixels you'd like it to move down at. The addition of the open class is to allow us to run an elseif instead of just else, so some of the code doesn't unnecessarily run on every scrollevent, save a lil bit of memory
Select CONVERT(VARCHAR(8), GETDATE(), 112)
Tested in SQL Server 2012
If you're just looking for a syntactically simple way to assign/return a string or numeric based on a boolean condition, you can use the multiplication operator like this:
"Condition is "+("true"*$condition)+("false"*!$condition)
(12.34*$condition)+(56.78*!$condition)
If you're only ever interested in the result when something is true, you can just omit the false part entirely (or vice versa), e.g. a simple scoring system:
$isTall = $true
$isDark = $false
$isHandsome = $true
$score = (2*$isTall)+(4*$isDark)+(10*$isHandsome)
"Score = $score"
# or
# "Score = $((2*$isTall)+(4*$isDark)+(10*$isHandsome))"
Note that the boolean value should not be the leading term in the multiplication, i.e. $condition*"true" etc. won't work.
function listCookies() {
let cookies = document.cookie.split(';')
cookies.map((cookie, n) => console.log(`${n}:`, decodeURIComponent(cookie)))
}
function findCookie(e) {
let cookies = document.cookie.split(';')
cookies.map((cookie, n) => cookie.includes(e) && console.log(decodeURIComponent(cookie), n))
}
This is specifically for the window you're in. Tried to keep it clean and concise.
Somehow if you want to check if the ethernet cable plugged in linux after the commend:" ifconfig eth0 down". I find a solution: use the ethtool tool.
#ethtool -t eth0
The test result is PASS
The test extra info:
Register test (offline) 0
Eeprom test (offline) 0
Interrupt test (offline) 0
Loopback test (offline) 0
Link test (on/offline) 0
if cable is connected,link test is 0,otherwise is 1.
Here is a reliable solution that works with both 32bit and 64bit applications.
Add these references:
using System.Diagnostics;
using System.Management;
Add this method to your project:
public static string GetProcessPath(int processId)
{
string MethodResult = "";
try
{
string Query = "SELECT ExecutablePath FROM Win32_Process WHERE ProcessId = " + processId;
using (ManagementObjectSearcher mos = new ManagementObjectSearcher(Query))
{
using (ManagementObjectCollection moc = mos.Get())
{
string ExecutablePath = (from mo in moc.Cast<ManagementObject>() select mo["ExecutablePath"]).First().ToString();
MethodResult = ExecutablePath;
}
}
}
catch //(Exception ex)
{
//ex.HandleException();
}
return MethodResult;
}
Now use it like so:
int RootProcessId = Process.GetCurrentProcess().Id;
GetProcessPath(RootProcessId);
Notice that if you know the id of the process, then this method will return the corresponding ExecutePath.
Extra, for those interested:
Process.GetProcesses()
...will give you an array of all the currently running processes, and...
Process.GetCurrentProcess()
...will give you the current process, along with their information e.g. Id, etc. and also limited control e.g. Kill, etc.*
.NET DDD Sample from Domain-Driven Design Book by Eric Evans can be found here: http://dddsamplenet.codeplex.com
Cheers,
Jakub G
One gotcha to do with converting Base64 from a string is that some conversion functions use the preceding "data:image/jpg;base64," and others only accept the actual data.
What is currently happening is, that you have a certain set of files, which you have tried merging earlier, but they threw up merge conflicts.
Ideally, if one gets a merge conflict, he should resolve them manually, and commit the changes using git add file.name && git commit -m "removed merge conflicts"
.
Now, another user has updated the files in question on his repository, and has pushed his changes to the common upstream repo.
It so happens, that your merge conflicts from (probably) the last commit were not not resolved, so your files are not merged all right, and hence the U
(unmerged
) flag for the files.
So now, when you do a git pull
, git is throwing up the error, because you have some version of the file, which is not correctly resolved.
To resolve this, you will have to resolve the merge conflicts in question, and add and commit the changes, before you can do a git pull
.
# Note: commands below in format `CUURENT_WORKING_DIRECTORY $ command params`
Desktop $ cd test
First, let us create the repository structure
test $ mkdir repo && cd repo && git init && touch file && git add file && git commit -m "msg"
repo $ cd .. && git clone repo repo_clone && cd repo_clone
repo_clone $ echo "text2" >> file && git add file && git commit -m "msg" && cd ../repo
repo $ echo "text1" >> file && git add file && git commit -m "msg" && cd ../repo_clone
Now we are in repo_clone, and if you do a git pull
, it will throw up conflicts
repo_clone $ git pull origin master
remote: Counting objects: 5, done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (3/3), done.
From /home/anshulgoyal/Desktop/test/test/repo
* branch master -> FETCH_HEAD
24d5b2e..1a1aa70 master -> origin/master
Auto-merging file
CONFLICT (content): Merge conflict in file
Automatic merge failed; fix conflicts and then commit the result.
If we ignore the conflicts in the clone, and make more commits in the original repo now,
repo_clone $ cd ../repo
repo $ echo "text1" >> file && git add file && git commit -m "msg" && cd ../repo_clone
And then we do a git pull
, we get
repo_clone $ git pull
U file
Pull is not possible because you have unmerged files.
Please, fix them up in the work tree, and then use 'git add/rm <file>'
as appropriate to mark resolution, or use 'git commit -a'.
Note that the file
now is in an unmerged state and if we do a git status
, we can clearly see the same:
repo_clone $ git status
On branch master
Your branch and 'origin/master' have diverged,
and have 1 and 1 different commit each, respectively.
(use "git pull" to merge the remote branch into yours)
You have unmerged paths.
(fix conflicts and run "git commit")
Unmerged paths:
(use "git add <file>..." to mark resolution)
both modified: file
So, to resolve this, we first need to resolve the merge conflict we ignored earlier
repo_clone $ vi file
and set its contents to
text2
text1
text1
and then add it and commit the changes
repo_clone $ git add file && git commit -m "resolved merge conflicts"
[master 39c3ba1] resolved merge conflicts
There's also Array.find()
in ES6 which returns the first matching element it finds.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
const myArray = [1, 2, 3]
const myElement = myArray.find((element) => element === 2)
console.log(myElement)
// => 2
What you posted has a syntax error, but it makes no difference as you cannot pass HTTP headers via $.post()
.
Provided you're on jQuery version >= 1.5, switch to $.ajax()
and pass the headers
(docs) option. (If you're on an older version of jQuery, I will show you how to do it via the beforeSend
option.)
$.ajax({
url: 'https://url.com',
type: 'post',
data: {
access_token: 'XXXXXXXXXXXXXXXXXXX'
},
headers: {
Header_Name_One: 'Header Value One', //If your header name has spaces or any other char not appropriate
"Header Name Two": 'Header Value Two' //for object property name, use quoted notation shown in second
},
dataType: 'json',
success: function (data) {
console.info(data);
}
});
I'm not sure how efficient it is memory-wise, but my first approach would be using a Scanner as it is incredibly easy to use:
File file = new File("/path/to/my/file.txt");
Scanner input = new Scanner(file);
while(input.hasNext()) {
String nextToken = input.next();
//or to process line by line
String nextLine = input.nextLine();
}
input.close();
Check the API for how to alter the delimiter it uses to split tokens.
a bit late to the game, but I found a way to make the original syntax in this question work (I'm on Oracle 11g)
** first switch to schema of your MV **
EXECUTE DBMS_MVIEW.REFRESH(LIST=>'MV_MY_VIEW');
alternatively you can add some options:
EXECUTE DBMS_MVIEW.REFRESH(LIST=>'MV_MY_VIEW',PARALLELISM=>4);
this actually works for me, and adding parallelism option sped my execution about 2.5 times.
More info here: How to Refresh a Materialized View in Parallel
I have tried pm2 : installation is easy and easy to use too; the result is satisfying. However, we have to take care of which edition of pm2 that we want. pm 2 runtime is the free edition, whereas pm2 plus and pm2 enterprise are not free.
As for Strongloop, my installation failed or was not complete, so I couldn't use it.
Why don't you just cast the value to INTEGER
and then back to VARCHAR
?
SELECT CAST(CAST('000000000' AS INTEGER) AS VARCHAR)
--------
0
On Unix:
usually you start cpan in your shell:
$ cpan
and type
install Chocolate::Belgian
or in short form:
cpan Chocolate::Belgian
On Windows:
If you're using ActivePerl on Windows, the PPM (Perl Package Manager) has much of the same functionality as CPAN.pm.
Example:
$ ppm
ppm> search net-smtp
ppm> install Net-SMTP-Multipart
see How do I install Perl modules? in the CPAN FAQ
Many distributions ship a lot of perl modules as packages.
apt-cache search 'perl$'
pacman -Ss '^perl-'
dev-perl
You should always prefer them as you benefit from automatic (security) updates and the ease of removal. This can be pretty tricky with the cpan tool itself.
For Gentoo there's a nice tool called g-cpan which builds/installs the module from CPAN and creates a Gentoo package (ebuild) for you.
This might not be the best way to do it. But it somehow worked for me, so i'm going to run with it.
In my php function that returns the data, one line before the return line, I add an echo statement, echoing the data I want to send.
Now sure why it worked, but it did.
You need to recompile ffmpeg (from source) so that it supports x264. If you follow the instructions in this page, then you will be able to peform any kind of conversion you want.
var jsonData = { Name: "Ricardo Vasquez", age: "46", Email: "[email protected]" };
for (x in jsonData) {
console.log(x +" => "+ jsonData[x]);
alert(x +" => "+ jsonData[x]);
}
Here's what I use to do this:
Manifest:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
<!--This part is inside the application-->
<receiver android:name=".CallReceiver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
My base reusable call detector
package com.gabesechan.android.reusable.receivers;
import java.util.Date;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
public abstract class PhonecallReceiver extends BroadcastReceiver {
//The receiver will be recreated whenever android feels like it. We need a static variable to remember data between instantiations
private static int lastState = TelephonyManager.CALL_STATE_IDLE;
private static Date callStartTime;
private static boolean isIncoming;
private static String savedNumber; //because the passed incoming is only valid in ringing
@Override
public void onReceive(Context context, Intent intent) {
//We listen to two intents. The new outgoing call only tells us of an outgoing call. We use it to get the number.
if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
savedNumber = intent.getExtras().getString("android.intent.extra.PHONE_NUMBER");
}
else{
String stateStr = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
String number = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
int state = 0;
if(stateStr.equals(TelephonyManager.EXTRA_STATE_IDLE)){
state = TelephonyManager.CALL_STATE_IDLE;
}
else if(stateStr.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
state = TelephonyManager.CALL_STATE_OFFHOOK;
}
else if(stateStr.equals(TelephonyManager.EXTRA_STATE_RINGING)){
state = TelephonyManager.CALL_STATE_RINGING;
}
onCallStateChanged(context, state, number);
}
}
//Derived classes should override these to respond to specific events of interest
protected abstract void onIncomingCallReceived(Context ctx, String number, Date start);
protected abstract void onIncomingCallAnswered(Context ctx, String number, Date start);
protected abstract void onIncomingCallEnded(Context ctx, String number, Date start, Date end);
protected abstract void onOutgoingCallStarted(Context ctx, String number, Date start);
protected abstract void onOutgoingCallEnded(Context ctx, String number, Date start, Date end);
protected abstract void onMissedCall(Context ctx, String number, Date start);
//Deals with actual events
//Incoming call- goes from IDLE to RINGING when it rings, to OFFHOOK when it's answered, to IDLE when its hung up
//Outgoing call- goes from IDLE to OFFHOOK when it dials out, to IDLE when hung up
public void onCallStateChanged(Context context, int state, String number) {
if(lastState == state){
//No change, debounce extras
return;
}
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
isIncoming = true;
callStartTime = new Date();
savedNumber = number;
onIncomingCallReceived(context, number, callStartTime);
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
//Transition of ringing->offhook are pickups of incoming calls. Nothing done on them
if(lastState != TelephonyManager.CALL_STATE_RINGING){
isIncoming = false;
callStartTime = new Date();
onOutgoingCallStarted(context, savedNumber, callStartTime);
}
else
{
isIncoming = true;
callStartTime = new Date();
onIncomingCallAnswered(context, savedNumber, callStartTime);
}
break;
case TelephonyManager.CALL_STATE_IDLE:
//Went to idle- this is the end of a call. What type depends on previous state(s)
if(lastState == TelephonyManager.CALL_STATE_RINGING){
//Ring but no pickup- a miss
onMissedCall(context, savedNumber, callStartTime);
}
else if(isIncoming){
onIncomingCallEnded(context, savedNumber, callStartTime, new Date());
}
else{
onOutgoingCallEnded(context, savedNumber, callStartTime, new Date());
}
break;
}
lastState = state;
}
}
Then to use it, simply derive a class from it and implement a few easy functions, whichever call types you care about:
public class CallReceiver extends PhonecallReceiver {
@Override
protected void onIncomingCallReceived(Context ctx, String number, Date start)
{
//
}
@Override
protected void onIncomingCallAnswered(Context ctx, String number, Date start)
{
//
}
@Override
protected void onIncomingCallEnded(Context ctx, String number, Date start, Date end)
{
//
}
@Override
protected void onOutgoingCallStarted(Context ctx, String number, Date start)
{
//
}
@Override
protected void onOutgoingCallEnded(Context ctx, String number, Date start, Date end)
{
//
}
@Override
protected void onMissedCall(Context ctx, String number, Date start)
{
//
}
}
In addition you can see a writeup I did on why the code is like it is on my blog. Gist link: https://gist.github.com/ftvs/e61ccb039f511eb288ee
EDIT: Updated to simpler code, as I've reworked the class for my own use
To answer the original question "Why is php not running?" The file your browser is asking for must have the .php extension. If the file has the .html extension, php will not be executed.
The simplest that helped me:
rm -rf _dir_in_question_
svn up
If you have changes in the problematic dir, then this is not a good solution for you.
chsh -s $(which zsh)
You'll be prompted for your password, but once you update your settings any new iTerm/Terminal sessions you start on that machine will default to zsh.
No, that's not really possible, as
The goal of the MD5 and its family of hashing functions is
Think that you can get the MD5 of any string, even very long. And the MD5 is only 16 bytes long (32 if you write it in hexa to store or distribute it more easily). If you could reverse them, you'd have a magical compacting scheme.
This being said, as there aren't so many short strings (passwords...) used in the world, you can test them from a dictionary (that's called "brute force attack") or even google for your MD5. If the word is common and wasn't salted, you have a reasonable chance to succeed...
You can use reduce method:
long sum = result.stream().map(e -> e.getCreditAmount()).reduce(0L, (x, y) -> x + y);
or
long sum = result.stream().map(e -> e.getCreditAmount()).reduce(0L, Integer::sum);
1 = 1 expression is commonly used in generated sql code. This expression can simplify sql generating code reducing number of conditional statements.
One thing we should note: the jdk
should be installed on C:
drive.
I had JDK installed on my D:
drive like this:
D:\Program Files\Java\jdk1.8.0_101
And it would still give me the same error. For some reason Java should be installed on C: drive.
// 24-hour time to 12-hour time
$time_in_12_hour_format = date("g:i a", strtotime("13:30"));
// 12-hour time to 24-hour time
$time_in_24_hour_format = date("H:i", strtotime("1:30 PM"));
<script type="text/javascript">
$(document).ready(function () {
$('#btnadd').on('click', function () {
var n1 = parseInt($('#txtn1').val());
var n2 = parseInt($('#txtn2').val());
var r = n1 + n2;
alert("sum of 2 No= " + r);
return false;
});
$('#btnclear').on('click', function () {
$('#txtn1').val('');
$('#txtn2').val('');
$('#txtn1').focus();
return false;
});
});
</script>
In High Sierra, the cacerts is located at : /Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/jre/lib/security/cacerts
I came up with this simple and elegant solution. It assumes that the activity is responsible for creating the Fragments, and the Adapter just serves them.
This is the adapter's code (nothing weird here, except for the fact that mFragments
is a list of fragments maintained by the Activity)
class MyFragmentPagerAdapter extends FragmentStatePagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
@Override
public int getCount() {
return mFragments.size();
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
@Override
public CharSequence getPageTitle(int position) {
TabFragment fragment = (TabFragment)mFragments.get(position);
return fragment.getTitle();
}
}
The whole problem of this thread is getting a reference of the "old" fragments, so I use this code in the Activity's onCreate.
if (savedInstanceState!=null) {
if (getSupportFragmentManager().getFragments()!=null) {
for (Fragment fragment : getSupportFragmentManager().getFragments()) {
mFragments.add(fragment);
}
}
}
Of course you can further fine tune this code if needed, for example making sure the fragments are instances of a particular class.
It is illegal to nest EL expressions: you should inline them. Using JSTL is perfectly valid in your situation. Correcting the mistake, you'll make the code working:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:c="http://java.sun.com/jstl/core">
<c:if test="#{not empty user or user.userId eq 0}">
<a href="Images/thumb_02.jpg" target="_blank" ></a>
<img src="Images/thumb_02.jpg" />
</c:if>
<c:if test="#{empty user or user.userId eq 0}">
<a href="/DisplayBlobExample?userId=#{user.userId}" target="_blank"></a>
<img src="/DisplayBlobExample?userId=#{user.userId}" />
</c:if>
</html>
Another solution is to specify all the conditions you want inside an EL of one element. Though it could be heavier and less readable, here it is:
<a href="#{not empty user or user.userId eq 0 ? '/Images/thumb_02.jpg' : '/DisplayBlobExample?userId='}#{not empty user or user.userId eq 0 ? '' : user.userId}" target="_blank"></a>
<img src="#{not empty user or user.userId eq 0 ? '/Images/thumb_02.jpg' : '/DisplayBlobExample?userId='}#{not empty user or user.userId eq 0 ? '' : user.userId}" target="_blank"></img>
My case was different from the accepted answer. I was trying to mock a package-private method for an instance that did not live in that package
package common;
public class Animal {
void packageProtected();
}
package instances;
class Dog extends Animal { }
and the test classes
package common;
public abstract class AnimalTest<T extends Animal> {
@Before
setup(){
doNothing().when(getInstance()).packageProtected();
}
abstract T getInstance();
}
package instances;
class DogTest extends AnimalTest<Dog> {
Dog getInstance(){
return spy(new Dog());
}
@Test
public void myTest(){}
}
The compilation is correct, but when it tries to setup the test, it invokes the real method instead.
Declaring the method protected or public fixes the issue, tho it's not a clean solution.
The curly braces are inside the string, so it is being evaluated as string. They need to be outside, so this should work:
<div className={"btn-group pull-right " + (this.props.showBulkActions ? 'show' : 'hidden')}>
Note the space after "pull-right". You don't want to accidentally provide the class "pull-rightshow" instead of "pull-right show". Also the parentheses needs to be there.
Many good answers here, but I use a simple one using Exists, as below:
foreach (var setting in FullList)
{
if(cleanList.Exists(x => x.ProcedureName == setting.ProcedureName))
setting.IsActive = true; // do you business logic here
else
setting.IsActive = false;
updateList.Add(setting);
}
make sure to include __init__.py
, which makes Python know that those directories containpackages
Another possibile solution is,maybe your file is ASCII type file,just change the type of your files.
java.lang.UnsupportedClassVersionError
happens because of a higher JDK during compile time and lower JDK during runtime.
Here's the list of versions:
Java SE 9 = 53,
Java SE 8 = 52,
Java SE 7 = 51,
Java SE 6.0 = 50,
Java SE 5.0 = 49,
JDK 1.4 = 48,
JDK 1.3 = 47,
JDK 1.2 = 46,
JDK 1.1 = 45
If you don't want to use a List
, ArrayList
, or other dynamically-sized collection and then convert to an array (that's the method I'd recommend, by the way), then you'll have to allocate the array to its maximum possible size, keep track of how many items you put in it, and then create a new array with just those items in it:
private Update BuildMetaData(MetaData[] nvPairs)
{
Update update = new Update();
InputProperty[] ip = new InputProperty[20]; // how to make this "dynamic"
int i;
for (i = 0; i < nvPairs.Length; i++)
{
if (nvPairs[i] == null) break;
ip[i] = new InputProperty();
ip[i].Name = "udf:" + nvPairs[i].Name;
ip[i].Val = nvPairs[i].Value;
}
if (i < nvPairs.Length)
{
// Create new, smaller, array to hold the items we processed.
update.Items = new InputProperty[i];
Array.Copy(ip, update.Items, i);
}
else
{
update.Items = ip;
}
return update;
}
An alternate method would be to always assign update.Items = ip;
and then resize if necessary:
update.Items = ip;
if (i < nvPairs.Length)
{
Array.Resize(update.Items, i);
}
It's less code, but will likely end up doing the same amount of work (i.e. creating a new array and copying the old items).
Having the same error trying to install matplotlib for Python 3, those solutions didn't work for me. It was just a matter of dependencies, though it wasn't clear in the error message.
I used sudo apt-get build-dep python3-matplotlib
then sudo pip3 install matplotlib
and it worked.
Hope it'll help !
Well one way to do it would be saving the base method and then calling it from the overriden method, like so
MyClass.prototype._do_base = MyClass.prototype.do;
MyClass.prototype.do = function(){
if (this.name === 'something'){
//do something new
}else{
return this._do_base();
}
};
I've tried with
let UUID = UIDevice.currentDevice().identifierForVendor?.UUIDString
instead
let UUID = NSUUID().UUIDString
and it works.
Try Bootstrap’s .table-hover
class to implement hoverable rows, for example
<table class="table table-hover">
...
</table>
Actually I cannot agree to each statement.
"COALESCE expects all arguments to be of same datatype."
This is wrong, see below. Arguments can be different data types, that is also documented: If all occurrences of expr are numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type, then Oracle Database determines the argument with the highest numeric precedence, implicitly converts the remaining arguments to that data type, and returns that data type.. Actually this is even in contradiction to common expression "COALESCE stops at first occurrence of a non-Null value", otherwise test case No. 4 should not raise an error.
Also according to test case No. 5 COALESCE
does an implicit conversion of arguments.
DECLARE
int_val INTEGER := 1;
string_val VARCHAR2(10) := 'foo';
BEGIN
BEGIN
DBMS_OUTPUT.PUT_LINE( '1. NVL(int_val,string_val) -> '|| NVL(int_val,string_val) );
EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('1. NVL(int_val,string_val) -> '||SQLERRM );
END;
BEGIN
DBMS_OUTPUT.PUT_LINE( '2. NVL(string_val, int_val) -> '|| NVL(string_val, int_val) );
EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('2. NVL(string_val, int_val) -> '||SQLERRM );
END;
BEGIN
DBMS_OUTPUT.PUT_LINE( '3. COALESCE(int_val,string_val) -> '|| COALESCE(int_val,string_val) );
EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('3. COALESCE(int_val,string_val) -> '||SQLERRM );
END;
BEGIN
DBMS_OUTPUT.PUT_LINE( '4. COALESCE(string_val, int_val) -> '|| COALESCE(string_val, int_val) );
EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('4. COALESCE(string_val, int_val) -> '||SQLERRM );
END;
DBMS_OUTPUT.PUT_LINE( '5. COALESCE(SYSDATE,SYSTIMESTAMP) -> '|| COALESCE(SYSDATE,SYSTIMESTAMP) );
END;
Output:
1. NVL(int_val,string_val) -> ORA-06502: PL/SQL: numeric or value error: character to number conversion error
2. NVL(string_val, int_val) -> foo
3. COALESCE(int_val,string_val) -> 1
4. COALESCE(string_val, int_val) -> ORA-06502: PL/SQL: numeric or value error: character to number conversion error
5. COALESCE(SYSDATE,SYSTIMESTAMP) -> 2016-11-30 09:55:55.000000 +1:0 --> This is a TIMESTAMP value, not a DATE value!
Yet another take at this is to forgo all the character mapping altogether and to instead convert all unwanted characters into their respective numeric character references, e.g.:
function escapeHtml(raw) {
return raw.replace(/[&<>"']/g, function onReplace(match) {
return '&#' + match.charCodeAt(0) + ';';
});
}
Note that the specified RegEx only handles the specific characters that the OP wanted to escape but, depending on the context that the escaped HTML is going to be used, these characters may not be sufficient. Ryan Grove’s article There's more to HTML escaping than &, <, >, and " is a good read on the topic. And depending on your context, the following RegEx may very well be needed in order to avoid XSS injection:
var regex = /[&<>"'` !@$%()=+{}[\]]/g
Copying from another answer, the above methods work but gmail always replaces the "from" and "reply to" email with the actual sending gmail account. apparently there is a work around however:
http://karmic-development.blogspot.in/2013/10/send-email-from-aspnet-using-gmail-as.html
"3. In the Accounts Tab, Click on the link "Add another email address you own" then verify it"
Or possibly this
Update 3: Reader Derek Bennett says, "The solution is to go into your gmail Settings:Accounts and "Make default" an account other than your gmail account. This will cause gmail to re-write the From field with whatever the default account's email address is."
$request = Request::createFromGlobals();
$getParameter = $request->get('getParameter');
I would keep an extra column in the middle for larger displays and reset to default when the columns collapse on smaller displays. Something like this:
<div class="row">
<div class="text-center col-md-5 col-sm-6">
Widget 1
</div>
<div class="col-md-2">
<!-- Gap between columns -->
</div>
<div class="text-center col-md-5 col-sm-6">
Widget 2
</div>
</div>
you could just set outline: none;
and border to a different color on focus.
As the more recent MySQL documentation on view restrictions says:
Before MySQL 5.7.7, subqueries cannot be used in the FROM clause of a view.
This means, that choosing a MySQL v5.7.7 or newer or upgrading the existing MySQL instance to such a version, would remove this restriction on views completely.
However, if you have a current production MySQL version that is earlier than v5.7.7, then the removal of this restriction on views should only be one of the criteria being assessed while making a decision as to upgrade or not. Using the workaround techniques described in the other answers may be a more viable solution - at least on the shorter run.
Thanks All, I found how to do it, which is the same as Dave and Sergey:
I am using QT Creator:
In the main GUI window create using the drag drop GUI and create label (e.g. "myLabel")
In the callback of the button (clicked) do the following using the (*ui) pointer to the user interface window:
void MainWindow::on_pushButton_clicked()
{
QImage imageObject;
imageObject.load(imagePath);
ui->myLabel->setPixmap(QPixmap::fromImage(imageObject));
//OR use the other way by setting the Pixmap directly
QPixmap pixmapObject(imagePath");
ui->myLabel2->setPixmap(pixmapObject);
}
It seems the button you are invoking is not in the layout you are using in setContentView(R.layout.your_layout)
Check it.
Use the %
wildcard, which matches any number of characters.
SELECT * FROM Accounts WHERE Username LIKE '%query%'
You can't get the C++ source from an exe, and you can only get some version of the C# source via reflection.
In standard C lua, no. You will have to settle for seconds, unless you are willing to modify the lua interpreter yourself to have os.time use the resolution you want. That may be unacceptable, however, if you are writing code for other people to run on their own and not something like a web application where you have full control of the environment.
Edit: another option is to write your own small DLL in C that extends lua with a new function that would give you the values you want, and require that dll be distributed with your code to whomever is going to be using it.
Probably you need to set library reference as "Copy Local = True" on properties dialog. On visual studio click on "references" then right-click on the missing reference, from the context menu click properties, you should see copy local setting.
you could enter this code form for (today date & Names of the Day & hour) :
datetime.datetime.now().strftime('%y-%m-%d %a %H:%M:%S')
'19-09-09 Mon 17:37:56'
and enter this code for (today date simply):
datetime.date.today().strftime('%y-%m-%d')
'19-09-10'
for object :
datetime.datetime.now().date()
datetime.datetime.today().date()
datetime.datetime.utcnow().date()
datetime.datetime.today().time()
datetime.datetime.utcnow().date()
datetime.datetime.utcnow().time()
Including the fb:app_id
tag in your HTML HEAD will allow the Facebook scraper to associate the Open Graph entity for that URL with an application. This will allow any admins of that app to view Insights about that URL and any social plugins connected with it.
The fb:admins
tag is similar, but allows you to just specify each user ID that you would like to give the permission to do the above.
You can include either of these tags or both, depending on how many people you want to admin the Insights, etc. A single as fb:admins
is pretty much a minimum requirement. The rest of the Open Graph tags will still be picked up when people share and like your URL, however it may cause problems in the future, so please include one of the above.
fb:admins is specified like this:
<meta property="fb:admins" content="USER_ID"/>
OR
<meta property="fb:admins" content="USER_ID,USER_ID2,USER_ID3"/>
and fb:app_id like this:
<meta property="fb:app_id" content="APPID"/>
$myVar = $someVar ?? 42;
Is equivalent to :
$myVar = isset($someVar) ? $someVar : 42;
For constants, the behaviour is the same when using a constant that already exists :
define("FOO", "bar");
define("BAR", null);
$MyVar = FOO ?? "42";
$MyVar2 = BAR ?? "42";
echo $MyVar . PHP_EOL; // bar
echo $MyVar2 . PHP_EOL; // 42
However, for constants that don't exist, this is different :
$MyVar3 = IDONTEXIST ?? "42"; // Raises a warning
echo $MyVar3 . PHP_EOL; // IDONTEXIST
Warning: Use of undefined constant IDONTEXIST - assumed 'IDONTEXIST' (this will throw an Error in a future version of PHP)
Php will convert the non-existing constant to a string.
You can use constant("ConstantName")
that returns the value of the constant or null if the constant doesn't exist, but it will still raise a warning. You can prepended the function with the error control operator @
to ignore the warning message :
$myVar = @constant("IDONTEXIST") ?? "42"; // No warning displayed anymore
echo $myVar . PHP_EOL; // 42
<a href="#"><i class="fab fa-facebook-square"></i></a>
<a href="#"><i class="fab fa-twitter-square"></i></a>
<a href="#"><i class="fas fa-basketball-ball"></i></a>
<a href="#"><i class="fab fa-google-plus-square"></i></a>
All you have to do is wrap your font-awesome icon link in your HTML
with an anchor tag.
Following this format:
<a href="Link here"> <font-awesome icon code> </a>
This answer is good for typescript / Angular 2, 4, 5+
I got this answer with the help of @rujmah answer above. His answer brings in the array count... and then find's the value and replaces it with another value...
What this answer does is simply grabs the array name that might be set in another variable via another module / component... in this case the array I build had a css name of stay-dates. So what this does is extract that name and then allows me to set it to another variable and use it like so. In my case it was an html css class.
let obj = this.highlightDays.find(x => x.css);
let index = this.highlightDays.indexOf(obj);
console.log('here we see what hightlightdays is ', obj.css);
let dayCss = obj.css;
None of the above answers worked for me using Hibernate 5.2.10, Jersey 2.25.1 and Jackson 2.8.9. I finally found the answer (sort of, they reference hibernate4module but it works for 5 too) here. None of the Json annotations worked at all with @Transient
. Apparently Jackson2 is 'smart' enough to kindly ignore stuff marked with @Transient
unless you explicitly tell it not to. The key was to add the hibernate5 module (which I was using to deal with other Hibernate annotations) and disable the USE_TRANSIENT_ANNOTATION
feature in my Jersey Application:
ObjectMapper jacksonObjectMapper = new ObjectMapper();
Hibernate5Module jacksonHibernateModule = new Hibernate5Module();
jacksonHibernateModule.disable(Hibernate5Module.Feature.USE_TRANSIENT_ANNOTATION);
jacksonObjectMapper.registerModule(jacksonHibernateModule);
Here is the dependency for the Hibernate5Module:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate5</artifactId>
<version>2.8.9</version>
</dependency>
A SELECT INTO
statement creates the table for you. There is no need for the CREATE TABLE
statement before hand.
What is happening is that you create #ivmy_cash_temp1
in your CREATE
statement, then the DB tries to create it for you when you do a SELECT INTO
. This causes an error as it is trying to create a table that you have already created.
Either eliminate the CREATE TABLE
statement or alter your query that fills it to use INSERT INTO SELECT
format.
If you need a unique ID added to your new row then it's best to use SELECT INTO
... since IDENTITY()
only works with this syntax.
for color in ['r', 'b', 'g', 'k', 'm']:
plot(x, y, color=color)
Your keystore is broken, and you will have to restore or regenerate it.
This is a later answer that works for me, if it may be of use to anyone in the future. I wanted a simple border around all four sides of the grid and I achieved it like so...
<DataGrid x:Name="dgDisplay" Margin="5" BorderBrush="#1266a7" BorderThickness="1"...
Working for me only after installing Python 2.7.x (not 3.x) and then npm uninstall node-sass && npm install node-sass
like @Quinn Comendant said.
Here is a snippet I wrote; to ask for users' password and set it in /etc/passwd. You can manipulate it a little probably to get what you need:
echo -n " Please enter the password for the given user: "
read userPass
useradd $userAcct && echo -e "$userPass\n$userPass\n" | passwd $userAcct > /dev/null 2>&1 && echo " User account has been created." || echo " ERR -- User account creation failed!"
I put this in the head of my _Layout.cshtml
<base href="~/" />
we can write the UTF-8 encoded file with java using use PrintWriter to write UTF-8 encoded xml
Or Click here
PrintWriter out1 = new PrintWriter(new File("C:\\abc.xml"), "UTF-8");
other way is to use different third party software. This link shows more third party software to view chm files...
I tried with SumatraPDF and it work fine.
Make sure you declare the bean associated with the form in GET method of the associated controller and also add it in the model model.addAttribute("uploadItem", uploadItem);
which contains @RequestMapping(method = RequestMethod.GET)
annotation.
For example UploadItem.java is associated with myform.jsp and controller is SecureAreaController.java
myform.jsp contains
<form:form action="/securedArea" commandName="uploadItem" enctype="multipart/form-data"></form:form>
@RequestMapping("/securedArea")
@Controller
public class SecureAreaController {
@RequestMapping(method = RequestMethod.GET)
public String showForm(Model model) {
UploadItem uploadItem = new UploadItem(); // declareing
model.addAttribute("uploadItem", uploadItem); // adding in model
return "securedArea/upload";
}
}
As you can see I am declaring UploadItem.java in controller GET method.
I have now come up with an own solution to this:
1. Created a general function to extract specific attributes from arrays
The function below extract only specific attributes from an associative array, or an array of associative arrays (the last is what you get when doing $collection->toArray() in Laravel).
It can be used like this:
$data = array_extract( $collection->toArray(), ['id','url'] );
I am using the following functions:
function array_is_assoc( $array )
{
return is_array( $array ) && array_diff_key( $array, array_keys(array_keys($array)) );
}
function array_extract( $array, $attributes )
{
$data = [];
if ( array_is_assoc( $array ) )
{
foreach ( $attributes as $attribute )
{
$data[ $attribute ] = $array[ $attribute ];
}
}
else
{
foreach ( $array as $key => $values )
{
$data[ $key ] = [];
foreach ( $attributes as $attribute )
{
$data[ $key ][ $attribute ] = $values[ $attribute ];
}
}
}
return $data;
}
This solution does not focus on performance implications on looping through the collections in large datasets.
2. Implement the above via a custom collection i Laravel
Since I would like to be able to simply do $collection->extract('id','url');
on any collection object, I have implemented a custom collection class.
First I created a general Model, which extends the Eloquent model, but uses a different collection class. All you models need to extend this custom model, and not the Eloquent Model then.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use Lib\Collection;
class Model extends EloquentModel
{
public function newCollection(array $models = [])
{
return new Collection( $models );
}
}
?>
Secondly I created the following custom collection class:
<?php
namespace Lib;
use Illuminate\Support\Collection as EloquentCollection;
class Collection extends EloquentCollection
{
public function extract()
{
$attributes = func_get_args();
return array_extract( $this->toArray(), $attributes );
}
}
?>
Lastly, all models should then extend your custom model instead, like such:
<?php
namespace App\Models;
class Article extends Model
{
...
Now the functions from no. 1 above are neatly used by the collection to make the $collection->extract()
method available.
The accepted answer does not tell the entire story.
Yes, whenever you see zeros, a NULL
pointer is involved. That is because NULL
is by definition zero. So calling zero NULL
may not be saying much.
What is interesting about the message you get is the fact that NULL
is mentioned twice. In fact, the message you report looks a little bit like the messages Windows-brand operating systems show the user.
The message says the address NULL
tried to read NULL
. So what does that mean? Specifically, how does an address read itself?
We typically think of the instructions at an address reading and writing from memory at certain addresses. Knowing that allows us to parse the error message. The message is trying to articulate that the instruction at address NULL
tried to read NULL
.
Of course, there is no instruction at address NULL
, that is why we think of NULL
as special in our code. But every instruction can be thought of as commencing with the attempt to read itself. If the CPUs EIP
register is at address NULL
, then the CPU will attempt to read the opcode for an instruction from address 0x00000000 (NULL
). This attempt to read NULL
will fail, and generate the message you have received.
In the debugger, notice that EIP
equals 0x00000000 when you receive this message. This confirms the description I have given you.
The question then becomes, "why does my program attempt to execute the NULL
address." There are three possibilities which spring to mind:
NULL
, never initialized otherwise, and are dereferencing.NULL
entry in the object's vtable. These are created in your code with the syntax virtual function_name()=0
.ret
instruction, the value 0x00000000 (NULL
) is loaded from the overwritten memory spot. This type of error, stack overflow, is the eponym of our forum.Since you mention that you are calling a third-party library, I will point out that it may be a situation of the library expecting you to provide a non-NULL
function pointer as input to some API. These are sometimes known as "call back" functions.
You will have to use the debugger to narrow down the cause of your problem further, but the above possiblities should help you solve the riddle.
Thanks to user1354692 I could made it more easy, with only one line! the one he has commented:
try {
File file = new File(Environment.getExternalStorageDirectory(), String.valueOf(System.currentTimeMillis()));
Runtime.getRuntime().exec("logcat -d -v time -f " + file.getAbsolutePath());}catch (IOException e){}
Although many answers have been given, the problem I encountered was not yet mentioned.
Installation of the 32-Bit Installer AccessDatabaseEngine.exe as downloaded from MS reports success, but is NOT installed, as verified with the Powershell Script of one of the postings above here.
Installation of the 64-Bit installer AccessDatabaseEngine_X64.exe reported a shocking error message:
The very simple solution has been found here on an Autodesk site. Just add the parameter /passive to the commandline string, like this:
AccessDatabaseEngine_X64.exe /passive
Installation successful, the OleDb driver worked.
The Excel files I am processing with OleDb are of xlsx type, produced with EPPlus 4.5 and modified with Excel 2007.
Finally got working :)
using System.Net.Mail;
using System.Text;
...
// Command line argument must the the SMTP host.
SmtpClient client = new SmtpClient();
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("[email protected]","password");
MailMessage mm = new MailMessage("[email protected]", "[email protected]", "test", "test");
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
client.Send(mm);
sorry about poor spelling before
Not being at work, I don't have Oracle to hand, but I seem to recall that Oracle allows multiple columns to be matched in an IN clause, which should at least avoid the options that use a correlated subquery, which is seldom a good idea.
Something like this, perhaps (can't remember if the column list should be parenthesised or not):
SELECT *
FROM MyTable
WHERE (User, Date) IN
( SELECT User, MAX(Date) FROM MyTable GROUP BY User)
EDIT: Just tried it for real:
SQL> create table MyTable (usr char(1), dt date);
SQL> insert into mytable values ('A','01-JAN-2009');
SQL> insert into mytable values ('B','01-JAN-2009');
SQL> insert into mytable values ('A', '31-DEC-2008');
SQL> insert into mytable values ('B', '31-DEC-2008');
SQL> select usr, dt from mytable
2 where (usr, dt) in
3 ( select usr, max(dt) from mytable group by usr)
4 /
U DT
- ---------
A 01-JAN-09
B 01-JAN-09
So it works, although some of the new-fangly stuff mentioned elsewhere may be more performant.
<?php
function download_page($path){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$path);
curl_setopt($ch, CURLOPT_FAILONERROR,1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$retValue = curl_exec($ch);
curl_close($ch);
return $retValue;
}
$sXML = download_page('http://alanstorm.com/atom');
$oXML = new SimpleXMLElement($sXML);
foreach($oXML->entry as $oEntry){
echo $oEntry->title . "\n";
}
It's not possible to do that using JPA annotation. And this make sense: where a UniqueConstraint clearly define a business rules, an index is just a way to make search faster. So this should really be done by a DBA.
You can also use UNION like
SELECT user_fname ,
user_lname
FROM users
WHERE user_id = $_GET[id]
UNION
SELECT user_fname ,
user_lname
FROM users
WHERE user_parent_id = $_GET[id]
Use this batch script made by me:
@echo off
title Folder Creator
color b
setlocal enabledelayedexpansion
echo Enter the folder name, you can use these codes:
echo /t - Time (eg. 16:29)
echo /d - Date (eg. 17-02-19)
echo /a - Day (eg. 17)
echo /m - Month (eg. 02)
echo /y - Year (eg. 19)
echo /f - Full Year (eg. 2019)
echo.
set /p foldername=Folder Name:
set foldername=%foldername:/t=!time:~0,5!%
set foldername=%foldername:/d=!date:~0,2!-!date:~3,2!-!date:~8,2!%
set foldername=%foldername:/a=!date:~0,2!%
set foldername=%foldername:/m=!date:~3,2!%
set foldername=%foldername:/y=!date:~8,2!%
set foldername=%foldername:/f=!date:~6,4!%
md %foldername%
For example if you wanted to make a folder named the date in the DD-MM-YY format you would type "/d" but if you wanted to do that in the DD-MM-YYYY format you would type "/a-/m-/f".
you can use distutils.util.strtobool
>>> from distutils.util import strtobool
>>> strtobool('True')
1
>>> strtobool('False')
0
True
values are y
, yes
, t
, true
, on
and 1
; False
values are n
, no
, f
, false
, off
and 0
. Raises ValueError
if val is anything else.
Maybe a little late, but here's a link to the actual specification. http://tools.ietf.org/html/rfc55451
You could make your own constructor for JSON parsing:
var JSONObj = function(obj) { $.extend(this, JSON.parse(obj)); }
var test = new JSONObj('{"a": "apple"}');
//{a: "apple"}
Then check instanceof to see if it needed parsing originally
test instanceof JSONObj
Subscribing to the IUS Community Project Repository
cd ~
curl 'https://setup.ius.io/' -o setup-ius.sh
Run the script:
sudo bash setup-ius.sh
Upgrading mod_php with Apache
This section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section.
Begin by removing existing PHP packages. Press y and hit Enter to continue when prompted.
sudo yum remove php-cli mod_php php-common
Install the new PHP 7 packages from IUS. Again, press y and Enter when prompted.
sudo yum install mod_php70u php70u-cli php70u-mysqlnd
Finally, restart Apache to load the new version of mod_php:
sudo apachectl restart
You can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl:
systemctl status httpd
you must use [ngModel] instead of two way model binding with [(ngModel)]. then use manual change event with (ngModelChange). this is public rule for all two way input in components.
because pipe on event emitter is wrong.
You can't do this reliably across all browsers. Microsoft no longer supports DX filters as of IE10+, so none of the solutions here work fully:
https://msdn.microsoft.com/en-us/library/hh801215(v=vs.85).aspx
The only property that works reliably across all browsers is box-shadow
, and this just puts the border on your element (e.g. a div), resulting in a square border:
box-shadow: horizontalOffset verticalOffset blurDistance spreadDistance color inset;
e.g.
box-shadow: -2px 6px 12px 6px #CCCED0;
If you happen to have an image that is 'square' but with uniform rounded corners, the drop shadow works with border-radius
, so you could always emulate the rounded corners of your image in your div.
Here's the Microsoft documentation for box-shadow
:
https://msdn.microsoft.com/en-us/library/gg589484(v=vs.85).aspx
No way to do this that I know of, although I'm very curious to read if anyone has a good answer. I have been thinking about adding something like this to one of the apps my company builds, but have found no good way to do it.
The one thing I can think of (although not directly on point) is that I believe you can limit the total memory usage for a COM+ application in Windows. It would require the app to be written to run in COM+, of course, but it's the closest way I know of.
The working set stuff is good (Job Objects also control working sets), but that's not total memory usage, only real memory usage (paged in) at any one time. It may work for what you want, but afaik it doesn't limit total allocated memory.
So, as was mentioned in a couple comments containing the data in an array is simpler but the solution does not scale well in terms of efficiency as the data set size increases. You really should only use an iterator when you want to access a random object in the array, otherwise, generators are the way to go. Below I have prototyped a reader function which reads each json object individually and returns a generator.
The basic idea is to signal the reader to split on the carriage character "\n"
(or "\r\n"
for Windows). Python can do this with the file.readline()
function.
import json
def json_reader(filename):
with open(filename) as f:
for line in f:
yield json.loads(line)
However, this method only really works when the file is written as you have it -- with each object separated by a newline character. Below I wrote an example of a writer that separates an array of json objects and saves each one on a new line.
def json_writer(file, json_objects):
with open(file, "w") as f:
for jsonobj in json_objects:
jsonstr = json.dumps(jsonobj)
f.write(jsonstr + "\n")
You could also do the same operation with file.writelines()
and a list comprehension:
...
json_strs = [json.dumps(j) + "\n" for j in json_objects]
f.writelines(json_strs)
...
And if you wanted to append the data instead of writing a new file just change open(file, "w")
to open(file, "a")
.
In the end I find this helps a great deal not only with readability when I try and open json files in a text editor but also in terms of using memory more efficiently.
On that note if you change your mind at some point and you want a list out of the reader, Python allows you to put a generator function inside of a list and populate the list automatically. In other words, just write
lst = list(json_reader(file))
When an element, such as a div
is floated
, its parent container no longer considers its height, i.e.
<div id="main">
<div id="child" style="float:left;height:40px;"> Hi</div>
</div>
The parent container will not be be 40 pixels tall by default. This causes a lot of weird little quirks if you're using these containers to structure layout.
So the clearfix
class that various frameworks use fixes this problem by making the parent container "acknowledge" the contained elements.
Day to day, I normally just use frameworks such as 960gs, Twitter Bootstrap for laying out and not bothering with the exact mechanics.
Can read more here
find my_directory/ -maxdepth 1 -printf "%P\n" | tar -cvf my_archive.tar -C my_directory/ -T -
This creates a standard archive file. Standard in a way that files and dirs you want to pack are in the root of the archive. There are no extra special files as '.' and dirs as ./
before each './file'.
Trying so many solutions which are already here with only one successfully, seems to me that using find
or possibly other commands like ls -A -1
on the left side of the pipe (-1 as 'one', not -l as 'L') is the only way to achieve above goal.
If tar file is further processed, or delivered to someone as a product of my work, then I don't want to have some weirdness there.
-maxdepth 1
Descend at most 1 level - No recursing.
-printf
print format on the standard output
%P
File's name with the name of the starting-point under which it was found removed.
\n
Newline
printf does not add a newline at the end of the string. It must be added here
tar:
-C DIR
, --directory=DIR
change to directory DIR
-T FILE
, --files-from=FILE
get names to extract or create from FILE
-
that FILE from above is the standard input, from the pipe
The same result might be achieved using solution described by @aross.
The difference with the solution here is in that which tool is doing the recursing. If you leave the job to find
, every filepath name, goes through the pipe. It also sends all directory names, which tar with --no-recursion ignores or adds as empty ones followed by all files in each directory. If there was unexpected output as errors in file read from find
, tar would not know or care what's going on.
But with further checks, like processing error stream from find, it might be a good solution where many options and filters on files are required.
I prefer to leave the recursing on tar, it does seem simpler and as such more stable solution.
With my complicated directory structure, I feel more confident the archive is complete when tar will not report an error.
Another solution using find
proposed by @serendrewpity seems to be fine, but it fails on filenames with spaces. Difference is that output from find
supplied by $() sub-shell is space-divided. It might be possible to add quotes using printf, but it would further complicate the statement.
There is no reason to cd into the my_directory and then back, while using ../my_archive.tar for tar path, because TAR has -C DIR
, --directory=DIR
command which is there just for this purpose.
Using .
(dot) will include dots
Using * will let shell supply the input file list. It might be possible using shell options to include dot files. But it's complicated. The command must be executed in shell which allows that. Enabling and disabling must be done before and after tar command. And it will fail if root dir of future archive contains too many files.
That last point also applies to all those solutions which are not using pipe.
Most of solutions are creating a dir inside which are the files and dirs. That is barely ever desired.
You could do something like this if you wanted
package main
import "fmt"
type Pair struct {
a, b interface{}
}
func main() {
p1 := Pair{"finished", 42}
p2 := Pair{6.1, "hello"}
fmt.Println("p1=", p1, "p2=", p2)
fmt.Println("p1.b", p1.b)
// But to use the values you'll need a type assertion
s := p1.a.(string) + " now"
fmt.Println("p1.a", s)
}
However I think what you have already is perfectly idiomatic and the struct describes your data perfectly which is a big advantage over using plain tuples.
you can have the return as an object. You create that object 'on fly' in your
function: if(int)
return new object(){
int nr=..
}
same for string. But I am concerned that is an expensive solution...
VirtualBox version has many uncompatibilities with Linux version, so it's hard to install by using "Guest Addition CD image". For linux distributions it's frequently have a good companion Guest Addition package(equivalent functions to the CD image) which can be installed by:
sudo apt-get install virtualbox-guest-dkms
After that, on the window menu of the Guest, go to Devices->Shared Folders Settings->Shared Folders and add a host window folder to Machine Folders(Mark Auto-mount option) then you can see the shared folder in the Files of Guest Linux.
Here is a pure JavaScript solution (without jQuery)
var _Utils = function ()
{
this.findChildById = function (element, childID, isSearchInnerDescendant) // isSearchInnerDescendant <= true for search in inner childern
{
var retElement = null;
var lstChildren = isSearchInnerDescendant ? Utils.getAllDescendant(element) : element.childNodes;
for (var i = 0; i < lstChildren.length; i++)
{
if (lstChildren[i].id == childID)
{
retElement = lstChildren[i];
break;
}
}
return retElement;
}
this.getAllDescendant = function (element, lstChildrenNodes)
{
lstChildrenNodes = lstChildrenNodes ? lstChildrenNodes : [];
var lstChildren = element.childNodes;
for (var i = 0; i < lstChildren.length; i++)
{
if (lstChildren[i].nodeType == 1) // 1 is 'ELEMENT_NODE'
{
lstChildrenNodes.push(lstChildren[i]);
lstChildrenNodes = Utils.getAllDescendant(lstChildren[i], lstChildrenNodes);
}
}
return lstChildrenNodes;
}
}
var Utils = new _Utils;
Example of use:
var myDiv = document.createElement("div");
myDiv.innerHTML = "<table id='tableToolbar'>" +
"<tr>" +
"<td>" +
"<div id='divIdToSearch'>" +
"</div>" +
"</td>" +
"</tr>" +
"</table>";
var divToSearch = Utils.findChildById(myDiv, "divIdToSearch", true);
The problems were:
The solution based on omerkirk's answer involves:
autoOpen: false, width: "auto", height: "auto"
Here is a rough outline of code:
<div class="thumb">
<a href="http://jsfiddle.net/yBNVr/show/" data-title="Std 4:3 ratio video" data-width="512" data-height="384"><img src="http://dummyimage.com/120x90/000/f00&text=Std+4-3+ratio+video" /></a></li>
<a href="http://jsfiddle.net/yBNVr/1/show/" data-title="HD 16:9 ratio video" data-width="512" data-height="288"><img src="http://dummyimage.com/120x90/000/f00&text=HD+16-9+ratio+video" /></a></li>
</div>
$(function () {
var iframe = $('<iframe frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>');
var dialog = $("<div></div>").append(iframe).appendTo("body").dialog({
autoOpen: false,
modal: true,
resizable: false,
width: "auto",
height: "auto",
close: function () {
iframe.attr("src", "");
}
});
$(".thumb a").on("click", function (e) {
e.preventDefault();
var src = $(this).attr("href");
var title = $(this).attr("data-title");
var width = $(this).attr("data-width");
var height = $(this).attr("data-height");
iframe.attr({
width: +width,
height: +height,
src: src
});
dialog.dialog("option", "title", title).dialog("open");
});
});
Demo here and code here. And another example along similar lines
I guess you can use @CollectionOfElements
(for hibernate/jpa 1) / @ElementCollection
(jpa 2) to map a collection of "entity properties" to a List
in entity
.
You can create the EntityProperty
type and annotate it with @Embeddable
In order to simplify your life you can extend the HTMLElement
object. It might not work for older browsers, but definitely makes your life easier:
HTMLElement = typeof(HTMLElement) != 'undefined' ? HTMLElement : Element;
HTMLElement.prototype.prepend = function(element) {
if (this.firstChild) {
return this.insertBefore(element, this.firstChild);
} else {
return this.appendChild(element);
}
};
So next time you can do this:
document.getElementById('container').prepend(document.getElementById('block'));
// or
var element = document.getElementById('anotherElement');
document.body.prepend(div);
'In Visual Basic
Dim FileName = "newfile.xml" ' The Name of file with its Extension Example A.txt or A.xml
Dim FilePath ="C:\MyFolderName" & "\" & FileName 'First Name of Directory and Then Name of Folder if it exists and then attach the name of file you want to search.
If System.IO.File.Exists(FilePath) Then
MsgBox("The file exists")
Else
MsgBox("the file doesn't exist")
End If
The solution is to put an N in front of both the type and the SQL string to indicate it is a double-byte character string:
DECLARE @SQL NVARCHAR(100)
SET @SQL = N'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL
If you like an ugly hacks which you should never do in real worlds systems; you could strip all :hover style rules from document.styleSheets.
Just go through all CSS styles with JavaScript and remove all rules, which contain ":hover" in their selector. I use this method when I need to remove :hover styles from bootstrap 2.
_.each(document.styleSheets, function (sheet) {
var rulesToLoose = [];
_.each(sheet.cssRules, function (rule, index) {
if (rule.selectorText && rule.selectorText.indexOf(':hover') > 0) {
rulesToLoose.push(index);
}
});
_.each(rulesToLoose.reverse(), function (index) {
if (sheet.deleteRule) {
sheet.deleteRule(index);
} else if (sheet.removeRule) {
sheet.removeRule(index);
}
});
});
I did use underscore for iterating arrays, but one could write those with pure js loop as well:
for (var i = 0; i < document.styleSheets.length; i++) {}
A SurfaceView
is a custom view in Android that can be used to drawn inside it.
The main difference between a View
and a SurfaceView
is that a View is drawn in the
UI Thread
, which is used for all the user interaction.
If you want to update the UI rapidly enough and render a good amount of information in
it, a SurfaceView is a better choice.
But there are a few technical insides to the SurfaceView
:
1. They are not hardware accelerated.
2. Normal views are rendered when you call the methods invalidate
or postInvalidate()
, but this does not mean the view will be
immediately updated (A VSYNC
will be sent, and the OS decides when
it gets updated. The SurfaceView
can be immediately updated.
3. A SurfaceView has an allocated surface buffer
, so it is more costly
You have to use style="width:value" with center block class
I also faced the same issue. After lot of hard work, I found what was wrong in my case. My device was connected to computer via USB cable. There are types for USB connections like Mass Storage, Media Device(MTP), Camera(PTP) etc. My connection type was - 'Mass Storage', and this was causing the problems. When I changed the connection type, the issue was solved.
Always remember while accessing filesystem on android device :-
DON'T CONNECT AS MASS STORAGE to the computer/pc.
here is my initial git commands (possibly, this action takes place in C:/Documents and Settings/your_username/
):
mkdir ~/Hello-World
# Creates a directory for your project called "Hello-World" in your user directory
cd ~/Hello-World
# Changes the current working directory to your newly created directory
touch blabla.html
# create a file, named blabla.html
git init
# Sets up the necessary Git files
git add blabla.html
# Stages your blabla.html file, adding it to the list of files to be committed
git commit -m 'first committttt'
# Commits your files, adding the message
git remote add origin https://github.com/username/Hello-World.git
# Creates a remote named "origin" pointing at your GitHub repository
git push -u origin master
# Sends your commits in the "master" branch to GitHub
I did what FD_ said and it crashed with errors as it was looking for "Landroid/support/v7/cardview/R$styleable;", which was not compiled with it
If you really want to use CardView before in eclipse before it gets its own library, you can extract the classes from the classes.jar, copy and paste them into your project, with the values.xml from above from Android Studio and change all the references to android.support.v7.R to yourpackagename.R in the copied classes. This worked and ran for me
You can also clear the packages directory and allow NuGet to re-download missing packages
it solved the issue for me