In .Net Core (as of v2.2) it should be:
new Process
{
StartInfo = new ProcessStartInfo(@"file path")
{
UseShellExecute = true
}
}.Start();
Related github issue can be found here
You can use the following command to revert all local changes:
svn st -q | awk '{print $2;}' | xargs svn revert
Check Following Things
Here is a component that incorporates much of this by lovasoa: https://github.com/lovasoa/react-contenteditable/blob/master/index.js
He shims the event in the emitChange
emitChange: function(evt){
var html = this.getDOMNode().innerHTML;
if (this.props.onChange && html !== this.lastHtml) {
evt.target = { value: html };
this.props.onChange(evt);
}
this.lastHtml = html;
}
I'm using a similar approach successfully
Old thread I know.......
Problem with the answer of @ryuutatsuo is that it blocks also any input or other element that has to react on 'clicks' (for example inputs), so i wrote this solution. This solution made it possible to use any existing drag and drop library that is based upon mousedown, mousemove and mouseup events on any touch device (or cumputer). This is also a cross-browser solution.
I have tested in on several devices and it works fast (in combination with the drag and drop feature of ThreeDubMedia (see also http://threedubmedia.com/code/event/drag)). It is a jQuery solution so you can use it only with jQuery libs. I have used jQuery 1.5.1 for it because some newer functions don't work properly with IE9 and above (not tested with newer versions of jQuery).
Before you add any drag or drop operation to an event you have to call this function first:
simulateTouchEvents(<object>);
You can also block all components/children for input or to speed up event handling by using the following syntax:
simulateTouchEvents(<object>, true); // ignore events on childs
Here is the code i wrote. I used some nice tricks to speed up evaluating things (see code).
function simulateTouchEvents(oo,bIgnoreChilds)
{
if( !$(oo)[0] )
{ return false; }
if( !window.__touchTypes )
{
window.__touchTypes = {touchstart:'mousedown',touchmove:'mousemove',touchend:'mouseup'};
window.__touchInputs = {INPUT:1,TEXTAREA:1,SELECT:1,OPTION:1,'input':1,'textarea':1,'select':1,'option':1};
}
$(oo).bind('touchstart touchmove touchend', function(ev)
{
var bSame = (ev.target == this);
if( bIgnoreChilds && !bSame )
{ return; }
var b = (!bSame && ev.target.__ajqmeclk), // Get if object is already tested or input type
e = ev.originalEvent;
if( b === true || !e.touches || e.touches.length > 1 || !window.__touchTypes[e.type] )
{ return; } //allow multi-touch gestures to work
var oEv = ( !bSame && typeof b != 'boolean')?$(ev.target).data('events'):false,
b = (!bSame)?(ev.target.__ajqmeclk = oEv?(oEv['click'] || oEv['mousedown'] || oEv['mouseup'] || oEv['mousemove']):false ):false;
if( b || window.__touchInputs[ev.target.tagName] )
{ return; } //allow default clicks to work (and on inputs)
// https://developer.mozilla.org/en/DOM/event.initMouseEvent for API
var touch = e.changedTouches[0], newEvent = document.createEvent("MouseEvent");
newEvent.initMouseEvent(window.__touchTypes[e.type], true, true, window, 1,
touch.screenX, touch.screenY,
touch.clientX, touch.clientY, false,
false, false, false, 0, null);
touch.target.dispatchEvent(newEvent);
e.preventDefault();
ev.stopImmediatePropagation();
ev.stopPropagation();
ev.preventDefault();
});
return true;
};
What it does: At first, it translates single touch events into mouse events. It checks if an event is caused by an element on/in the element that must be dragged around. If it is an input element like input, textarea etc, it skips the translation, or if a standard mouse event is attached to it it will also skip a translation.
Result: Every element on a draggable element is still working.
Happy coding, greetz, Erwin Haantjes
Other option is to use ArrayUtils.toArray in org.apache.commons.lang3
ArrayUtils.toArray("elem1","elem2")
String concatenation, str.join
, can be used to build the string.
d = datetime.now()
'/'.join(str(x) for x in (d.month, d.day, d.year))
'3/7/2016'
If you can use jquery then its simple
$("#txt").text()
Just want to complete the answer (as I struggled with it for a while), want to show how to access the json information, this example shows accessing Json Array:
var request = require('request');_x000D_
request('https://server/run?oper=get_groups_joined_by_user_id&user_id=5111298845048832', function (error, response, body) {_x000D_
if (!error && response.statusCode == 200) {_x000D_
var jsonArr = JSON.parse(body);_x000D_
console.log(jsonArr);_x000D_
console.log("group id:" + jsonArr[0].id);_x000D_
}_x000D_
})
_x000D_
The @Devart's version is correct, but here are some improvements to avoid having error. I've edited the @Devart's answer, but it was not accepted.
SET FOREIGN_KEY_CHECKS = 0;
SET GROUP_CONCAT_MAX_LEN=32768;
SET @tables = NULL;
SELECT GROUP_CONCAT('`', table_name, '`') INTO @tables
FROM information_schema.tables
WHERE table_schema = (SELECT DATABASE());
SELECT IFNULL(@tables,'dummy') INTO @tables;
SET @tables = CONCAT('DROP TABLE IF EXISTS ', @tables);
PREPARE stmt FROM @tables;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET FOREIGN_KEY_CHECKS = 1;
This script will not raise error with NULL result in case when you already deleted all tables in the database by adding at least one nonexistent - "dummy" table.
And it fixed in case when you have many tables.
And This small change to drop all view exist in the Database
SET FOREIGN_KEY_CHECKS = 0;
SET GROUP_CONCAT_MAX_LEN=32768;
SET @views = NULL;
SELECT GROUP_CONCAT('`', TABLE_NAME, '`') INTO @views
FROM information_schema.views
WHERE table_schema = (SELECT DATABASE());
SELECT IFNULL(@views,'dummy') INTO @views;
SET @views = CONCAT('DROP VIEW IF EXISTS ', @views);
PREPARE stmt FROM @views;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET FOREIGN_KEY_CHECKS = 1;
It assumes that you run the script from Database you want to delete. Or run this before:
USE REPLACE_WITH_DATABASE_NAME_YOU_WANT_TO_DELETE;
Thank you to Steve Horvath to discover the issue with backticks.
you must create a background.xml in res/drawable this code
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF" />
<corners android:radius="6dp" />
<stroke
android:width="6dp"
android:color="@android:color/white" />
<padding
android:bottom="6dp"
android:left="6dp"
android:right="6dp"
android:top="6dp" />
</shape>
// Excuse my beginner's english
There is msgHTML() method, which, also, call IsHTML().
Hrm... name IsHTML
is confusing...
/**
* Create a message from an HTML string.
* Automatically makes modifications for inline images and backgrounds
* and creates a plain-text version by converting the HTML.
* Overwrites any existing values in $this->Body and $this->AltBody
* @access public
* @param string $message HTML message string
* @param string $basedir baseline directory for path
* @param bool $advanced Whether to use the advanced HTML to text converter
* @return string $message
*/
public function msgHTML($message, $basedir = '', $advanced = false)
You can use ObjectMapper.convertValue()
, either value by value or even for the whole list. But you need to know the type to convert to:
POJO pojo = mapper.convertValue(singleObject, POJO.class);
// or:
List<POJO> pojos = mapper.convertValue(listOfObjects, new TypeReference<List<POJO>>() { });
this is functionally same as if you did:
byte[] json = mapper.writeValueAsBytes(singleObject);
POJO pojo = mapper.readValue(json, POJO.class);
but avoids actual serialization of data as JSON, instead using an in-memory event sequence as the intermediate step.
I encourage you to read the Maven Book about multi-module (reactor) builds.
I meant in particular the following:
<parent>
<artifactId>xyz-application</artifactId>
<groupId>com.xyz</groupId>
<version>2.50.0.g</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.xyz</groupId>
<artifactId>xyz-Library</artifactId>
<version>2.50.0.g</version>
should be changed into. Here take care about the not defined version only in parent part it is defined.
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>xyz-application</artifactId>
<groupId>com.xyz</groupId>
<version>2.50.0.g</version>
</parent>
<groupId>com.xyz</groupId>
<artifactId>xyz-Library</artifactId>
This is a better link.
Ed McManus has certainly provided a key to getting this to work. I found a case that does not work
UIFont *font = ...
UIColor *color = ...
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
font, NSFontAttributeName,
color, NSForegroundColorAttributeName,
nil];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString: someString attributes:attributesDictionary];
[string appendAttributedString: [[NSAttributedString alloc] initWithString: anotherString];
CGRect rect = [string boundingRectWithSize:constraint options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) context:nil];
rect will not have the correct height. Notice that anotherString (which is appended to string) was initialized without an attribute dictionary. This is a legitimate initializer for anotherString but boundingRectWithSize: does not give an accurate size in this case.
In Linux, adding a symbolic link in the directory your python script is located works.
ie:
ln -s /absolute/path/to/module/module.py /absolute/path/to/script/module.py
python will create /absolute/path/to/script/module.pyc
and will update it if you change the contents of /absolute/path/to/module/module.py
then include the following in mypythonscript.py
from module import *
If you don't want to add a wrapper, you could just add the code manually, since you know the ID you are targeting:
var myID = "xxx";
var newCode = "<div id='"+myID+"'>"+$("#"+myID).html()+"</div>";
Interestingly enough I tried both of these in LinqPad and the variant using group from Dmitry Gribkov by appears to be quicker. (also the final distinct is not required as the result is already distinct.
My (somewhat simple) code was:
public class Pair
{
public int id {get;set;}
public string Arb {get;set;}
}
void Main()
{
var theList = new List<Pair>();
var randomiser = new Random();
for (int count = 1; count < 10000; count++)
{
theList.Add(new Pair
{
id = randomiser.Next(1, 50),
Arb = "not used"
});
}
var timer = new Stopwatch();
timer.Start();
var distinct = theList.GroupBy(c => c.id).Select(p => p.First().id);
timer.Stop();
Debug.WriteLine(timer.Elapsed);
timer.Start();
var otherDistinct = theList.Select(p => p.id).Distinct();
timer.Stop();
Debug.WriteLine(timer.Elapsed);
}
I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.
Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled
Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is
Here is the xmlns reference:
xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI"
Then the ad itself:
<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480" AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/>
I was having a heck of a time trying to accomplish this. I didn't want to use a Flash solution, and none of the jQuery libraries I looked at were reliable across all browsers.
I came up with my own solution, which is implemented completely in CSS (except for the onclick style change to make the button appear 'clicked').
You can try a working example here: http://jsfiddle.net/VQJ9V/307/ (Tested in FF 7, IE 9, Safari 5, Opera 11 and Chrome 14)
It works by creating a big file input (with font-size:50px), then wrapping it in a div that has a fixed size and overflow:hidden. The input is then only visible through this "window" div. The div can be given a background image or color, text can be added, and the input can be made transparent to reveal the div background:
HTML:
<div class="inputWrapper">
<input class="fileInput" type="file" name="file1"/>
</div>
CSS:
.inputWrapper {
height: 32px;
width: 64px;
overflow: hidden;
position: relative;
cursor: pointer;
/*Using a background color, but you can use a background image to represent a button*/
background-color: #DDF;
}
.fileInput {
cursor: pointer;
height: 100%;
position:absolute;
top: 0;
right: 0;
z-index: 99;
/*This makes the button huge. If you want a bigger button, increase the font size*/
font-size:50px;
/*Opacity settings for all browsers*/
opacity: 0;
-moz-opacity: 0;
filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0)
}
Let me know if there are any problems with it and I'll try to fix them.
Well, you could look it up in Wikipedia... But since you want an explanation, I'll do my best here:
They provide a mapping between an arbitrary length input, and a (usually) fixed length (or smaller length) output. It can be anything from a simple crc32, to a full blown cryptographic hash function such as MD5 or SHA1/2/256/512. The point is that there's a one-way mapping going on. It's always a many:1 mapping (meaning there will always be collisions) since every function produces a smaller output than it's capable of inputting (If you feed every possible 1mb file into MD5, you'll get a ton of collisions).
The reason they are hard (or impossible in practicality) to reverse is because of how they work internally. Most cryptographic hash functions iterate over the input set many times to produce the output. So if we look at each fixed length chunk of input (which is algorithm dependent), the hash function will call that the current state. It will then iterate over the state and change it to a new one and use that as feedback into itself (MD5 does this 64 times for each 512bit chunk of data). It then somehow combines the resultant states from all these iterations back together to form the resultant hash.
Now, if you wanted to decode the hash, you'd first need to figure out how to split the given hash into its iterated states (1 possibility for inputs smaller than the size of a chunk of data, many for larger inputs). Then you'd need to reverse the iteration for each state. Now, to explain why this is VERY hard, imagine trying to deduce a
and b
from the following formula: 10 = a + b
. There are 10 positive combinations of a
and b
that can work. Now loop over that a bunch of times: tmp = a + b; a = b; b = tmp
. For 64 iterations, you'd have over 10^64 possibilities to try. And that's just a simple addition where some state is preserved from iteration to iteration. Real hash functions do a lot more than 1 operation (MD5 does about 15 operations on 4 state variables). And since the next iteration depends on the state of the previous and the previous is destroyed in creating the current state, it's all but impossible to determine the input state that led to a given output state (for each iteration no less). Combine that, with the large number of possibilities involved, and decoding even an MD5 will take a near infinite (but not infinite) amount of resources. So many resources that it's actually significantly cheaper to brute-force the hash if you have an idea of the size of the input (for smaller inputs) than it is to even try to decode the hash.
They provide a 1:1 mapping between an arbitrary length input and output. And they are always reversible. The important thing to note is that it's reversible using some method. And it's always 1:1 for a given key. Now, there are multiple input:key pairs that might generate the same output (in fact there usually are, depending on the encryption function). Good encrypted data is indistinguishable from random noise. This is different from a good hash output which is always of a consistent format.
Use a hash function when you want to compare a value but can't store the plain representation (for any number of reasons). Passwords should fit this use-case very well since you don't want to store them plain-text for security reasons (and shouldn't). But what if you wanted to check a filesystem for pirated music files? It would be impractical to store 3 mb per music file. So instead, take the hash of the file, and store that (md5 would store 16 bytes instead of 3mb). That way, you just hash each file and compare to the stored database of hashes (This doesn't work as well in practice because of re-encoding, changing file headers, etc, but it's an example use-case).
Use a hash function when you're checking validity of input data. That's what they are designed for. If you have 2 pieces of input, and want to check to see if they are the same, run both through a hash function. The probability of a collision is astronomically low for small input sizes (assuming a good hash function). That's why it's recommended for passwords. For passwords up to 32 characters, md5 has 4 times the output space. SHA1 has 6 times the output space (approximately). SHA512 has about 16 times the output space. You don't really care what the password was, you care if it's the same as the one that was stored. That's why you should use hashes for passwords.
Use encryption whenever you need to get the input data back out. Notice the word need. If you're storing credit card numbers, you need to get them back out at some point, but don't want to store them plain text. So instead, store the encrypted version and keep the key as safe as possible.
Hash functions are also great for signing data. For example, if you're using HMAC, you sign a piece of data by taking a hash of the data concatenated with a known but not transmitted value (a secret value). So, you send the plain-text and the HMAC hash. Then, the receiver simply hashes the submitted data with the known value and checks to see if it matches the transmitted HMAC. If it's the same, you know it wasn't tampered with by a party without the secret value. This is commonly used in secure cookie systems by HTTP frameworks, as well as in message transmission of data over HTTP where you want some assurance of integrity in the data.
A key feature of cryptographic hash functions is that they should be very fast to create, and very difficult/slow to reverse (so much so that it's practically impossible). This poses a problem with passwords. If you store sha512(password)
, you're not doing a thing to guard against rainbow tables or brute force attacks. Remember, the hash function was designed for speed. So it's trivial for an attacker to just run a dictionary through the hash function and test each result.
Adding a salt helps matters since it adds a bit of unknown data to the hash. So instead of finding anything that matches md5(foo)
, they need to find something that when added to the known salt produces md5(foo.salt)
(which is very much harder to do). But it still doesn't solve the speed problem since if they know the salt it's just a matter of running the dictionary through.
So, there are ways of dealing with this. One popular method is called key strengthening (or key stretching). Basically, you iterate over a hash many times (thousands usually). This does two things. First, it slows down the runtime of the hashing algorithm significantly. Second, if implemented right (passing the input and salt back in on each iteration) actually increases the entropy (available space) for the output, reducing the chances of collisions. A trivial implementation is:
var hash = password + salt;
for (var i = 0; i < 5000; i++) {
hash = sha512(hash + password + salt);
}
There are other, more standard implementations such as PBKDF2, BCrypt. But this technique is used by quite a few security related systems (such as PGP, WPA, Apache and OpenSSL).
The bottom line, hash(password)
is not good enough. hash(password + salt)
is better, but still not good enough... Use a stretched hash mechanism to produce your password hashes...
Do not under any circumstances feed the output of one hash directly back into the hash function:
hash = sha512(password + salt);
for (i = 0; i < 1000; i++) {
hash = sha512(hash); // <-- Do NOT do this!
}
The reason for this has to do with collisions. Remember that all hash functions have collisions because the possible output space (the number of possible outputs) is smaller than then input space. To see why, let's look at what happens. To preface this, let's make the assumption that there's a 0.001% chance of collision from sha1()
(it's much lower in reality, but for demonstration purposes).
hash1 = sha1(password + salt);
Now, hash1
has a probability of collision of 0.001%. But when we do the next hash2 = sha1(hash1);
, all collisions of hash1
automatically become collisions of hash2
. So now, we have hash1's rate at 0.001%, and the 2nd sha1()
call adds to that. So now, hash2
has a probability of collision of 0.002%. That's twice as many chances! Each iteration will add another 0.001%
chance of collision to the result. So, with 1000 iterations, the chance of collision jumped from a trivial 0.001% to 1%. Now, the degradation is linear, and the real probabilities are far smaller, but the effect is the same (an estimation of the chance of a single collision with md5
is about 1/(2128) or 1/(3x1038). While that seems small, thanks to the birthday attack it's not really as small as it seems).
Instead, by re-appending the salt and password each time, you're re-introducing data back into the hash function. So any collisions of any particular round are no longer collisions of the next round. So:
hash = sha512(password + salt);
for (i = 0; i < 1000; i++) {
hash = sha512(hash + password + salt);
}
Has the same chance of collision as the native sha512
function. Which is what you want. Use that instead.
To find the name of the current user within an Oracle session, use the USER
function.
Note that the owner of the constraint, the owner of the table containing the foreign key, and the owner of the referenced table may all be different. It sounds like it’s the table owner you’re interested in, in which case this should be close to what you want:
select Constraint_Name
from All_Constraints
where Table_Name = 'WHICHEVER_TABLE'
and Constraint_Type = 'R' and Owner = User;
[update for 0.17]
See the docs of sklearn.model_selection.train_test_split
:
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y,
stratify=y,
test_size=0.25)
[/update for 0.17]
There is a pull request here.
But you can simply do train, test = next(iter(StratifiedKFold(...)))
and use the train and test indices if you want.
I'm adding my answer because the thing that solved it for me isn't clearly mentioned yet. Actually what helped me was this article:
and here is a short description of the solution:
Note how counter-intuitive this is: I had to disable (uncheck) "Enable Edit and Continue".
This will then allow you to change code in your editor without getting that message "Changes are not allowed while code is running".
Note however that the code changes you make will NOT be reflected in your running program - for that you need to stop and restart your program (off the top of my head I think that template/ASPX changes do get reflected, but not VB/C# changes, i.e. "code behind" code).
If you're willing to consider a different approach altogether to detecting illegal copies of your images, you could consider watermarking. (from 1.4)
...inserts copyright information into the digital object without the loss of quality. Whenever the copyright of a digital object is in question, this information is extracted to identify the rightful owner. It is also possible to encode the identity of the original buyer along with the identity of the copyright holder, which allows tracing of any unauthorized copies.
While it's also a complex field, there are techniques that allow the watermark information to persist through gross image alteration: (from 1.9)
... any signal transform of reasonable strength cannot remove the watermark. Hence a pirate willing to remove the watermark will not succeed unless they debase the document too much to be of commercial interest.
of course, the faq calls implementing this approach: "...very challenging" but if you succeed with it, you get a high confidence of whether the image is a copy or not, rather than a percentage likelihood.
I was following the replies, When editing /etc/group I also deleted this line:
ssl-cert:x:112:postgres
then, when trying to install postgresql, I got this error
Preconfiguring packages ...
dpkg: unrecoverable fatal error, aborting:
syntax error: unknown group 'ssl-cert' in statoverride file
E: Sub-process /usr/bin/dpkg returned an error code (2)
Putting the "ssl-cert:x:112:postgres" line back in /etc/group seems to fix it (so I was able to install postgresql)
You can make this bit more cleaner by using:
$http.get(url)
.then(function (response) {
console.log('get',response)
})
.catch(function (data) {
// Handle error here
});
Similar to @this.lau_ answer, different approach.
It is enough to close just Statement
and Connection
. There is no need to explicitly close the ResultSet
object.
Java documentation says about java.sql.ResultSet
:
A ResultSet object is automatically closed by the Statement object that generated it when that Statement object is closed, re-executed, or is used to retrieve the next result from a sequence of multiple results.
Thanks BalusC for comments: "I wouldn't rely on that. Some JDBC drivers fail on that."
useEffect are isolated within its own scope and gets rendered accordingly. Image from https://reactjs.org/docs/hooks-custom.html
I had a similar problem when trying to operate on a rooted Samsung Galaxy S. Issuing a command from the computer shell
> adb root
fails with a message "cannot run as root in production builds". Here is a simple method that allows to become root.
Instead of the previous, issue the following two commands one after the other
> adb shell
$ su
After the first command, if the prompt has changed from '>' to '$' as shown above, it means that you have entered the adb shell environment. If subsequently the prompt has changed to '#' after issuing the second command, that means that you are now root. Now, as root, you can do anything you want with your device.
To switch back to 'safe' shell, issue
# exit
You will see that the prompt '$' reappears which means you are in the adb shell as a user and not as root.
I assume this is *nix?
Use "here document":
sqlplus -s user/pass <<+EOF
select 1 from dual;
+EOF
EDIT: I should have tried your second example. It works, too (even in Windows, sans ticks):
$ echo 'select 1 from dual;'|sqlplus -s user/pw
1
----------
1
$
I also found another way of doing this that gives proper 'x10(superscript)5' notation on the axes. I'm posting it here in the hope it might be useful to some. I got the code from here so I claim no credit for it, that rightly goes to Brian Diggs.
fancy_scientific <- function(l) {
# turn in to character string in scientific notation
l <- format(l, scientific = TRUE)
# quote the part before the exponent to keep all the digits
l <- gsub("^(.*)e", "'\\1'e", l)
# turn the 'e+' into plotmath format
l <- gsub("e", "%*%10^", l)
# return this as an expression
parse(text=l)
}
Which you can then use as
ggplot(data=df, aes(x=x, y=y)) +
geom_point() +
scale_y_continuous(labels=fancy_scientific)
So you have committed your local changes to your local repository. Then in order to get remote changes to your local repository without making changes to your local files, you can use git fetch
. Actually git pull
is a two step operation: a non-destructive git fetch
followed by a git merge
. See What is the difference between 'git pull' and 'git fetch'? for more discussion.
Detailed example:
Suppose your repository is like this (you've made changes test2
:
* ed0bcb2 - (HEAD, master) test2
* 4942854 - (origin/master, origin/HEAD) first
And the origin
repository is like this (someone else has committed test1
):
* 5437ca5 - (HEAD, master) test1
* 4942854 - first
At this point of time, git will complain and ask you to pull first if you try to push your test2
to remote repository. If you want to see what test1 is without modifying your local repository, run this:
$ git fetch
Your result local repository would be like this:
* ed0bcb2 - (HEAD, master) test2
| * 5437ca5 - (origin/master, origin/HEAD) test1
|/
* 4942854 - first
Now you have the remote changes in another branch, and you keep your local files intact.
Then what's next? You can do a git merge
, which will be the same effect as git pull
(when combined with the previous git fetch
), or, as I would prefer, do a git rebase origin/master
to apply your change on top of origin/master
, which gives you a cleaner history.
Just wanted to re-emphasize that ++x is expected to be faster than x++, (especially if x is an object of some arbitrary type), so unless required for logical reasons, ++x should be used.
As I found the best way is doing is preloading a stylesheet that contains the font face, and then let browser to load it automatically. I used the font-face in other locations (in the html page), but then I could observe the font changing effect briefly.
<link href="fonts.css?family=Open+Sans" rel="preload stylesheet" as="style">
then in the font.css file, specify as following.
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans Regular'), local('OpenSans-Regular'),
url('open-sans-v16-latin-regular.woff2') format('woff2'); /* Super Modern Browsers */
}
You can't assign a name to fonts when it's preloaded through link tag (correct me if I was wrong I couldn't find a way yet), and thus you have to use font-face to assign the name to the font. Even though it's possible to load a font through link tag, it's not recommended as you can't assign a name to the font with it. Without a name as with font-face, you won't be able to use it anywhere in the web page. According to gtmetrix, style sheet loads at the beginning, then rest of the scripts/style by order, then the font before dom is loaded, and therefore you don't see font changing effect.
The problem with :scriptnames
, :commands
, :functions
, and similar Vim commands, is that they display information in a large slab of text, which is very hard to visually parse.
To get around this, I wrote Headlights, a plugin that adds a menu to Vim showing all loaded plugins, TextMate style. The added benefit is that it shows plugin commands, mappings, files, and other bits and pieces.
Consistency is the key to any naming standard. As long as it's logical and consistent, you're 99% there.
The standard itself is very much personal preference - so if you like your standard, then run with it.
To answer your question outright - no, MySQL doesn't have a preferred naming convention/standard, so rolling your own is fine (and yours seems logical).
same issue...resolved by dong the following
1.) close pm manager 2.) close Visual Studio 3.) Open Visual Studio 4.) Open pm manager
seems the trick is to close PM Manager before closing VS
you can use RETURNING clause in INSERT statement,just like the following
wgzhao=# create table foo(id int,name text);
CREATE TABLE
wgzhao=# insert into foo values(1,'wgzhao') returning id;
id
----
1
(1 row)
INSERT 0 1
wgzhao=# insert into foo values(3,'wgzhao') returning id;
id
----
3
(1 row)
INSERT 0 1
wgzhao=# create table bar(id serial,name text);
CREATE TABLE
wgzhao=# insert into bar(name) values('wgzhao') returning id;
id
----
1
(1 row)
INSERT 0 1
wgzhao=# insert into bar(name) values('wgzhao') returning id;
id
----
2
(1 row)
INSERT 0
I had the same problem, but I didnt find export command in line 70 in gradle file for the latest version 2.13, but I understand a silly mistake there, that is following,
If you don't find line 70 with export command in gradle file in your gradle folder/bin/ , then check your ~/.bashrc, if you find export JAVA_HOME==/usr/lib/jvm/java-7-openjdk-amd64/bin/java
, then remove /bin/java
from this line, like JAVA_HOME==/usr/lib/jvm/java-7-openjdk-amd64
, and it in path>>> instead of this export PATH=$PATH:$HOME/bin:JAVA_HOME/
, it will be export PATH=$PATH:$HOME/bin:JAVA_HOME/bin/java
. Then run source ~/.bashrc
.
The reason is, if you check your gradle file, you will find in line 70 (if there's no export command) or in line 75,
JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
That means
/bin/java
is already there, so it needs to be substracted fromJAVA_HOME
path.
That happened in my case.
I have met the same 404.14 problem suddenly. Finally the problem had been fixed by unchecking "precompile while publishing" in the publish profile settings.
Using http://phrogz.net/JS/ArraySetMath.js you can:
var array1 = ["test1", "test2","test3", "test4"];
var array2 = ["test1", "test2","test3","test4", "test5", "test6"];
var array3 = array2.subtract( array1 );
// ["test5", "test6"]
var array4 = array1.exclusion( array2 );
// ["test5", "test6"]
Since nobody bothered to post the 'Reflection' answer (which I personally think is the best answer), here goes:
public static string GetAllItems<T>(...) where T : new()
{
...
List<T> tabListItems = new List<T>();
foreach (ListItem listItem in listCollection)
{
Type classType = typeof(T);
ConstructorInfo classConstructor = classType.GetConstructor(new Type[] { listItem.GetType() });
T classInstance = (T)classConstructor.Invoke(new object[] { listItem });
tabListItems.Add(classInstance);
}
...
}
Edit: This answer is deprecated due to .NET 3.5's Activator.CreateInstance, however it is still useful in older .NET versions.
In windows, type rmdir .git
or rmdir /s .git
if the .git folder has subfolders.
If your git shell isn't setup with proper administrative rights (i.e. it denies you when you try to rmdir
), you can open a command prompt (possibly as administrator--hit the windows key, type 'cmd', right click 'command prompt' and select 'run as administrator) and try the same commands.
rd
is an alternative form of the rmdir
command. http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/rmdir.mspx?mfr=true
Another way to do this in PHP 5.6+ would be to use the ...
token
$a = array('a', 'b');
$b = array('c', 'd');
array_push($a, ...$b);
// $a is now equals to array('a','b','c','d');
This will also work with any Traversable
$a = array('a', 'b');
$b = new ArrayIterator(array('c', 'd'));
array_push($a, ...$b);
// $a is now equals to array('a','b','c','d');
A warning though:
$b
is an empty array or not traversable e.g. not an array$b
is not traversable Normally it is quite good to do:
echo isset($_GET['id']) ? $_GET['id'] : 'wtf';
This is so when assigning the var to other variables you can do defaults all in one breath instead of constantly using if
statements to just give them a default value if they are not set.
Global variables that are defined outside of any method or closure can be scope restricted by using the private keyword.
import UIKit
// MARK: Local Constants
private let changeSegueId = "MasterToChange"
private let bookSegueId = "MasterToBook"
Within the same folder, just use the file name:
<a href="thefile.html">my link</a>
Within the parent folder's directory:
<a href="../thefile.html">my link</a>
Within a sub-directory:
<a href="subdir/thefile.html">my link</a>
Based on your edit and comments.. would this be what you're after?
byte[] newByteArray = UTF8Encoding.UTF8.GetBytes(Convert.ToBase64String(currentByteArray));
If you have a hard time remembering the default values (I know I have...) here's a short extract from BalusC's answer:
Component | Submit | Refresh ------------ | --------------- | -------------- f:ajax | execute="@this" | render="@none" p:ajax | process="@this" | update="@none" p:commandXXX | process="@form" | update="@none"
I know this is an old question and was already answered, but for some reason, I still wanna post this alternative solution. I know it's easy to just find out which built-in function does the "magic" you need, but it doesn't hurt to know you can do it by yourself.
>>> list_1 = ['Ace', 'King']
>>> list_2 = ['Spades', 'Clubs', 'Diamonds']
>>> deck = []
>>> for i in range(max((len(list_1),len(list_2)))):
while True:
try:
card = (list_1[i],list_2[i])
except IndexError:
if len(list_1)>len(list_2):
list_2.append('')
card = (list_1[i],list_2[i])
elif len(list_1)<len(list_2):
list_1.append('')
card = (list_1[i], list_2[i])
continue
deck.append(card)
break
>>>
>>> #and the result should be:
>>> print deck
>>> [('Ace', 'Spades'), ('King', 'Clubs'), ('', 'Diamonds')]
You cannot do file i/o on the client side using javascript as that would be a security risk. You'd either have to get them to download and run an exe, or if the file is on your server, use AJAX and a server-side language such as PHP to do the i/o on serverside
Cookies.set("example", "foo"); // Sample 1
Cookies.set("example", "foo", { expires: 7 }); // Sample 2
Cookies.set("example", "foo", { path: '/admin', expires: 7 }); // Sample 3
alert( Cookies.get("example") );
Cookies.remove("example");
Cookies.remove('example', { path: '/admin' }) // Must specify path if used when setting.
Recommendation. Do not use user-added REM statements to block batch steps. Use conditional GOTO instead. That way you can predefine and test the steps and options. The users also get much simpler changes and better confidence.
@Echo on
rem Using flags to control command execution
SET ExecuteSection1=0
SET ExecuteSection2=1
@echo off
IF %ExecuteSection1%==0 GOTO EndSection1
ECHO Section 1 Here
:EndSection1
IF %ExecuteSection2%==0 GOTO EndSection2
ECHO Section 2 Here
:EndSection2
You can also sort the column by importing the spark sql functions
import org.apache.spark.sql.functions._
df.orderBy(asc("col1"))
Or
import org.apache.spark.sql.functions._
df.sort(desc("col1"))
importing sqlContext.implicits._
import sqlContext.implicits._
df.orderBy($"col1".desc)
Or
import sqlContext.implicits._
df.sort($"col1".desc)
The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.
You can create TIMESTAMP field in table on the SQLite, see this:
CREATE TABLE my_table (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
name VARCHAR(64),
sqltime TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
);
INSERT INTO my_table(name, sqltime) VALUES('test1', '2010-05-28T15:36:56.200');
INSERT INTO my_table(name, sqltime) VALUES('test2', '2010-08-28T13:40:02.200');
INSERT INTO my_table(name) VALUES('test3');
This is the result:
SELECT * FROM my_table;
Take a look at the table TABLES
in the database information_schema
. It contains information about the tables in your other databases. But if you're on shared hosting, you probably don't have access to it.
I use the str_count
function from the stringr
library with the escape sequence \w
that represents:
any ‘word’ character (letter, digit or underscore in the current locale: in UTF-8 mode only ASCII letters and digits are considered)
Example:
> str_count("How many words are in this sentence", '\\w+')
[1] 7
Of all other 9 answers that I was able to test, only two (by Vincent Zoonekynd, and by petermeissner) worked for all inputs presented here so far, but they also require stringr
.
But only this solution works with all inputs presented so far, plus inputs such as "foo+bar+baz~spam+eggs"
or "Combien de mots sont dans cette phrase ?"
.
Benchmark:
library(stringr)
questions <-
c(
"", "x", "x y", "x y!", "x y! z",
"foo+bar+baz~spam+eggs",
"one, two three 4,,,, 5 6",
"How many words are in this sentence",
"How many words are in this sentence",
"Combien de mots sont dans cette phrase ?",
"
Day after day, day after day,
We stuck, nor breath nor motion;
"
)
answers <- c(0, 1, 2, 2, 3, 5, 6, 7, 7, 7, 12)
score <- function(f) sum(unlist(lapply(questions, f)) == answers)
funs <-
c(
function(s) sapply(gregexpr("\\W+", s), length) + 1,
function(s) sapply(gregexpr("[[:alpha:]]+", s), function(x) sum(x > 0)),
function(s) vapply(strsplit(s, "\\W+"), length, integer(1)),
function(s) length(strsplit(gsub(' {2,}', ' ', s), ' ')[[1]]),
function(s) length(str_match_all(s, "\\S+")[[1]]),
function(s) str_count(s, "\\S+"),
function(s) sapply(gregexpr("\\W+", s), function(x) sum(x > 0)) + 1,
function(s) length(unlist(strsplit(s," "))),
function(s) sapply(strsplit(s, " "), length),
function(s) str_count(s, '\\w+')
)
unlist(lapply(funs, score))
Output:
6 10 10 8 9 9 7 6 6 11
The latest release of Requests will build CookieJars for you from simple dictionaries.
import requests
cookies = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918558'}
r = requests.post('http://wikipedia.org', cookies=cookies)
Enjoy :)
My suggestion is a variation on Kiran's answer above. I used this in a project.
Swift 5
// convenience property API on my class object to provide access to the my WindowController (MyController).
var myXWindowController: MyController? {
var myWC: MyController?
for viewController in self.windowControllers {
if ((viewController as? MyController) != nil) {
myWC = viewController as? MyController
break
}
}
return myWC
}
// example of use
guard let myController = myXWindowController else {
reportAssertionFailure("Failed to get MyXController from WindowController.")
return
}
For EditText in image above, You have to create two xml files in res-->drawable folder. First will be "bg_edittext_focused.xml" paste the lines of code in it
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#FFFFFF" />
<stroke
android:width="2dip"
android:color="#F6F6F6" />
<corners android:radius="2dip" />
<padding
android:bottom="7dip"
android:left="7dip"
android:right="7dip"
android:top="7dip" />
</shape>
Second file will be "bg_edittext_normal.xml" paste the lines of code in it
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#F6F6F6" />
<stroke
android:width="2dip"
android:color="#F6F6F6" />
<corners android:radius="2dip" />
<padding
android:bottom="7dip"
android:left="7dip"
android:right="7dip"
android:top="7dip" />
</shape>
In res-->drawable folder create another xml file with name "bg_edittext.xml" that will call above mentioned code. paste the following lines of code below in bg_edittext.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/bg_edittext_focused" android:state_focused="true"/>
<item android:drawable="@drawable/bg_edittext_normal"/>
</selector>
Finally in res-->layout-->example.xml file in your case wherever you created your editText you'll call bg_edittext.xml as background
<EditText
:::::
:::::
android:background="@drawable/bg_edittext"
:::::
:::::
/>
random.sample()
also works on text
example:
> text = open("textfile.txt").read()
> random.sample(text, 5)
> ['f', 's', 'y', 'v', '\n']
\n is also seen as a character so that can also be returned
you could use random.sample()
to return random words from a text file if you first use the split method
example:
> words = text.split()
> random.sample(words, 5)
> ['the', 'and', 'a', 'her', 'of']
package in.co.largestinarraylist;
import java.util.ArrayList;
import java.util.Scanner;
public class LargestInArrayList {
public static void main(String[] args) {
int n;
ArrayList<Integer> L = new ArrayList<Integer>();
int max;
Scanner in = new Scanner(System.in);
System.out.println("Enter Size of Array List");
n = in.nextInt();
System.out.println("Enter elements in Array List");
for (int i = 0; i < n; i++) {
L.add(in.nextInt());
}
max = L.get(0);
for (int i = 0; i < L.size(); i++) {
if (L.get(i) > max) {
max = L.get(i);
}
}
System.out.println("Max Element: " + max);
in.close();
}
}
Answer below the dotted line below is the original that's now outdated.
Here is the latest information ( Thank you @deadfish ):
add &hl=<language>
like &hl=pl
or &hl=en
example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl
All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en
......................................................................
To change the actual local market:
Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html
To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720
I don't think this question has been completely answered yet because all of the answers only give single match examples. The OP's question demonstrates the nuances of having 2 matches as well as a substring match which should not be reported because it is not a word/token.
To match multiple occurrences, one might do something like this:
iter = re.finditer(r"\bis\b", String)
indices = [m.start(0) for m in iter]
This would return a list of the two indices for the original string.
Since this came up on a Google search for "javascript get number of digits", I wanted to throw it out there that there is a shorter alternative to this that relies on internal casting to be done for you:
var int_number = 254;
var int_length = (''+int_number).length;
var dec_number = 2.12;
var dec_length = (''+dec_number).length;
console.log(int_length, dec_length);
Yields
3 4
If this doesn't work I'm out of ideas. This way you get the 4 columns in both tables (as Bar
owns them and Foo
uses them to reference Bar
) and the generated IDs in both entities. The set of 4 columns has to be unique in Bar
so the many-to-one relation doesn't become a many-to-many.
@Embeddable
public class AnEmbeddedObject
{
@Column(name = "column_1")
private Long column1;
@Column(name = "column_2")
private Long column2;
@Column(name = "column_3")
private Long column3;
@Column(name = "column_4")
private Long column4;
}
@Entity
public class Foo
{
@Id
@Column(name = "id")
@GeneratedValue(generator = "seqGen")
@SequenceGenerator(name = "seqGen", sequenceName = "FOO_ID_SEQ", allocationSize = 1)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumns({
@JoinColumn(name = "column_1", referencedColumnName = "column_1"),
@JoinColumn(name = "column_2", referencedColumnName = "column_2"),
@JoinColumn(name = "column_3", referencedColumnName = "column_3"),
@JoinColumn(name = "column_4", referencedColumnName = "column_4")
})
private Bar bar;
}
@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = {
"column_1",
"column_2",
"column_3",
"column_4"
}))
public class Bar
{
@Id
@Column(name = "id")
@GeneratedValue(generator = "seqGen")
@SequenceGenerator(name = "seqGen", sequenceName = "BAR_ID_SEQ", allocationSize = 1)
private Long id;
@Embedded
private AnEmbeddedObject anEmbeddedObject;
}
You can use like bellow:
(( var0 = var1<98?9:21 ))
the same as
if [ "$var1" -lt 98 ]; then
var0=9
else
var0=21
fi
extends
condition?result-if-true:result-if-false
I found the interested thing on the book "Advanced Bash-Scripting Guide"
If this is nullable int field then yes.
update TableName
set FiledName = null
where Id = SomeId
Max. capacity is 2 gigabytes of space - so you're looking at just over 1 billion 2-byte characters that will fit into a NVARCHAR(MAX)
field.
Using the other answer's more detailed numbers, you should be able to store
(2 ^ 31 - 1 - 2) / 2 = 1'073'741'822 double-byte characters
1 billion, 73 million, 741 thousand and 822 characters to be precise
in your NVARCHAR(MAX)
column (unfortunately, that last half character is wasted...)
Update: as @MartinMulder pointed out: any variable length character column also has a 2 byte overhead for storing the actual length - so I needed to subtract two more bytes from the 2 ^ 31 - 1
length I had previously stipulated - thus you can store 1 Unicode character less than I had claimed before.
If you want something beyond the ID column that's there in all lists, you're probably going to have to resort to an Event Receiver on the list that "calculates" what the value of your unique identified should be or using a custom field type that has the required logic embedded in this. Unfortunately, both of these options will require writing and deploying custom code to the server and deploying assemblies to the GAC, which can be frowned upon in environments where you don't have complete control over the servers.
If you don't need the unique identifier to show up immediately, you could probably generate it via a workflow (either with SharePoint Designer or a custom WF workflow built in Visual Studio).
Unfortunately, calculated columns, which seem like an obvious solution, won't work for this purpose because the ID is not yet assigned when the calculation is attempted. If you go in after the fact and edit the item, the calculation may achieve what you want, but on initial creation of a new item it will not be calculated correctly.
SOAP Web services:
RestWeb services:
In javascript you can do something like this
<input
ref="fileInput"
multiple
type="file"
style="display: none"
@change="trySubmitFile"
>
and the function can be something like this.
trySubmitFile(e) {
if (this.disabled) return;
const files = e.target.files || e.dataTransfer.files;
if (files.length > 5) {
alert('You are only allowed to upload a maximum of 2 files at a time');
}
if (!files.length) return;
for (let i = 0; i < Math.min(files.length, 2); i++) {
this.fileCallback(files[i]);
}
}
I am also searching for a solution where this can be limited at the time of selecting files but until now I could not find anything like that.
You probably have a forward declaration of the class, but haven't included the header:
#include <sstream>
//...
QString Stats_Manager::convertInt(int num)
{
std::stringstream ss; // <-- also note namespace qualification
ss << num;
return ss.str();
}
You can try to re-set your Jenkins security:
config.xml
with a text editor (i.e notepad++), maybe be in C:\jenkins\config.xml
(could backup it also).<useSecurity>true</useSecurity>
and change it to <useSecurity>false</useSecurity>
You might create an admin user and enable security again.
If you need a quick work around in Chrome for ajax requests, this chrome plugin automatically allows you to access any site from any source by adding the proper response header
Well, after looking around the best comparison I've found so far is:
http://www.sturmnet.org/blog/2010/03/04/poll-ioc-containers-for-net
http://www.sturmnet.org/blog/2010/03/04/poll-results-ioc-containers-for-net
It was a poll taken in March 2010.
One point of interest to me is that people who've used a DI/IoC Framework and liked/disliked it, StructureMap appears to come out on top.
Also from the poll, it seems that Castle.Windsor and StructureMap seem to be most highly favoured.
Interestingly, Unity and Spring.Net seem to be the popular options which are most generally disliked. (I was considering Unity out of laziness (and Microsoft badge/support), but I'll be looking more closely at Castle Windsor and StructureMap now.)
Of course this probably (?) doesn't apply to Unity 2.0 which was released in May 2010.
Hopefully someone else can provide a comparison based on direct experience.
public static T Runner<T>(Func<T> funcToRun)
{
//Do stuff before running function as normal
return funcToRun();
}
Usage:
var ReturnValue = Runner(() => GetUser(99));
OR... to place 20 points, compute the centers of the icosahedronal faces. For 12 points, find the vertices of the icosahedron. For 30 points, the mid point of the edges of the icosahedron. you can do the same thing with the tetrahedron, cube, dodecahedron and octahedrons: one set of points is on the vertices, another on the center of the face and another on the center of the edges. They cannot be mixed, however.
By 'return non-false', they mean to return any value which would not work out to boolean false. So you could return true
, 1
, 'non-false'
, or whatever else you can think up.
this worked for me:
ProxyRequests Off
ProxyPreserveHost On
RewriteEngine On
<Proxy http://localhost:8123>
Order deny,allow
Allow from all
</Proxy>
ProxyPass /node http://localhost:8123
ProxyPassReverse /node http://localhost:8123
I'd suggest using wasabi then you can either use the markdown-ish feel like this
root/ # entry comments can be inline after a '#'
# or on their own line, also after a '#'
readme.md # a child of, 'root/', it's indented
# under its parent.
usage.md # indented syntax is nice for small projects
# and short comments.
src/ # directories MUST be identified with a '/'
fileOne.txt # files don't need any notation
fileTwo* # '*' can identify executables
fileThree@ # '@' can identify symlinks
and throw that exact syntax at the js library for this
Add this line at the top:
"xmlns:app="http://schemas.android.com/apk/res-auto"
and then use:
app:showasaction="ifroom"
ORDER BY column1 DESC, column2
This sorts everything by column1
(descending) first, and then by column2
(ascending, which is the default) whenever the column1
fields for two or more rows are equal.
For local time in ISO8601
for SQL TIMESTAMP
you could try:
var tzoffset = (new Date()).getTimezoneOffset() * 60000;
var localISOTime = (new Date(Date.now() - tzoffset))
.toISOString()
.slice(0, 19)
.replace('T', ' ');
$('#mydatediv').val(localISOTime);
Use pyenv instead to install and switch between versions of Python. I've been using rbenv for years which does the same thing, but for Ruby. Before that it was hell managing versions.
Consult pyenv's github page for installation instructions. Basically it goes like this:
- Install pyenv using homebrew. brew install pyenv
- Add a function to the end of your shell startup script so pyenv can do it's magic. echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n eval "$(pyenv init -)"\nfi' >> ~/.bash_profile
pyenv install 3.7.7
.pyenv global 3.7.7
.pyevn local
. This creates a file in your project's folder that specifies the python version. Pyenv will look override the global python version with the version in that file. Consider using matplotlib.cbook pieces
for example:
import matplotlib.cbook as cbook
segments = cbook.pieces(np.arange(20), 3)
for s in segments:
print s
Maybe I'm missing something, but a lot of these answers seem overly complicated. You should be able to just set the columns within a single list:
Column to the front:
df = df[ ['Mid'] + [ col for col in df.columns if col != 'Mid' ] ]
Or if instead, you want to move it to the back:
df = df[ [ col for col in df.columns if col != 'Mid' ] + ['Mid'] ]
Or if you wanted to move more than one column:
cols_to_move = ['Mid', 'Zsore']
df = df[ cols_to_move + [ col for col in df.columns if col not in cols_to_move ] ]
You've almost done it. However setting flex: 0 0 <basis>
declaration to the columns would prevent them from growing/shrinking; And the <basis>
parameter would define the width of columns.
In addition, you could use CSS3 calc()
expression to specify the height
of columns with the respect to the height of the header.
#productShowcaseTitle {
flex: 0 0 100%; /* Let it fill the entire space horizontally */
height: 100px;
}
#productShowcaseDetail,
#productShowcaseThumbnailContainer {
height: calc(100% - 100px); /* excluding the height of the header */
}
#productShowcaseContainer {_x000D_
display: flex;_x000D_
flex-flow: row wrap;_x000D_
_x000D_
height: 600px;_x000D_
width: 580px;_x000D_
}_x000D_
_x000D_
#productShowcaseTitle {_x000D_
flex: 0 0 100%; /* Let it fill the entire space horizontally */_x000D_
height: 100px;_x000D_
background-color: silver;_x000D_
}_x000D_
_x000D_
#productShowcaseDetail {_x000D_
flex: 0 0 66%; /* ~ 2 * 33.33% */_x000D_
height: calc(100% - 100px); /* excluding the height of the header */_x000D_
background-color: lightgray;_x000D_
}_x000D_
_x000D_
#productShowcaseThumbnailContainer {_x000D_
flex: 0 0 34%; /* ~ 33.33% */_x000D_
height: calc(100% - 100px); /* excluding the height of the header */_x000D_
background-color: black;_x000D_
}
_x000D_
<div id="productShowcaseContainer">_x000D_
<div id="productShowcaseTitle"></div>_x000D_
<div id="productShowcaseDetail"></div>_x000D_
<div id="productShowcaseThumbnailContainer"></div>_x000D_
</div>
_x000D_
(Vendor prefixes omitted due to brevity)
Alternatively, if you could change your markup e.g. wrapping the columns by an additional <div>
element, it would be achieved without using calc()
as follows:
<div class="contentContainer"> <!-- Added wrapper -->
<div id="productShowcaseDetail"></div>
<div id="productShowcaseThumbnailContainer"></div>
</div>
#productShowcaseContainer {
display: flex;
flex-direction: column;
height: 600px; width: 580px;
}
.contentContainer { display: flex; flex: 1; }
#productShowcaseDetail { flex: 3; }
#productShowcaseThumbnailContainer { flex: 2; }
#productShowcaseContainer {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
_x000D_
height: 600px;_x000D_
width: 580px;_x000D_
}_x000D_
_x000D_
.contentContainer {_x000D_
display: flex;_x000D_
flex: 1;_x000D_
}_x000D_
_x000D_
#productShowcaseTitle {_x000D_
height: 100px;_x000D_
background-color: silver;_x000D_
}_x000D_
_x000D_
#productShowcaseDetail {_x000D_
flex: 3;_x000D_
background-color: lightgray;_x000D_
}_x000D_
_x000D_
#productShowcaseThumbnailContainer {_x000D_
flex: 2;_x000D_
background-color: black;_x000D_
}
_x000D_
<div id="productShowcaseContainer">_x000D_
<div id="productShowcaseTitle"></div>_x000D_
_x000D_
<div class="contentContainer"> <!-- Added wrapper -->_x000D_
<div id="productShowcaseDetail"></div>_x000D_
<div id="productShowcaseThumbnailContainer"></div>_x000D_
</div>_x000D_
</div>
_x000D_
(Vendor prefixes omitted due to brevity)
With Spring's JavaConfig mechanism, you can do it like so:
@Configuration
public class MainConfig {
...
@Bean
DataSource dataSource() {
DataSource dataSource = null;
JndiTemplate jndi = new JndiTemplate();
try {
dataSource = jndi.lookup("java:comp/env/jdbc/yourname", DataSource.class);
} catch (NamingException e) {
logger.error("NamingException for java:comp/env/jdbc/yourname", e);
}
return dataSource;
}
}
Your Win32 project is likely a GUI project, not a console project. This causes a difference in the executable header. As a result, your GUI project will be responsible for opening its own window. That may be a console window, though. Call AllocConsole()
to create it, and use the Win32 console functions to write to it.
Starting Python 3.8
, the standard library provides the NormalDist
object as part of the statistics
module.
It can be used to get the probability density function (pdf
- likelihood that a random sample X will be near the given value x) for a given mean (mu
) and standard deviation (sigma
):
from statistics import NormalDist
NormalDist(mu=100, sigma=12).pdf(98)
# 0.032786643008494994
Also note that the NormalDist
object also provides the cumulative distribution function (cdf
- probability that a random sample X will be less than or equal to x):
NormalDist(mu=100, sigma=12).cdf(98)
# 0.43381616738909634
You could add flex-basis: 100%
to achieve this.
.header {
display: flex;
}
.item {
flex-basis: 100%;
text-align: center;
border: 1px solid black;
}
For what it's worth, you could also use flex: 1
for the same results as well.
The shorthand of flex: 1
is the same as flex: 1 1 0
, which is equivalent to:
.item {
flex-grow: 1;
flex-shrink: 1;
flex-basis: 0;
text-align: center;
border: 1px solid black;
}
All nice solutions, borrowing and improvising for special case -> If you want to add a label near the arrowhead:
arr = [2,3]
txt = “Vector X”
ax.annotate(txt, arr)
ax.arrow(0, 0, *arr, head_width=0.05, head_length=0.1)
Recursion is more costly in memory, as each recursive call generally requires a memory address to be pushed to the stack - so that later the program could return to that point.
Still, there are many cases in which recursion is a lot more natural and readable than loops - like when working with trees. In these cases I would recommend sticking to recursion.
This worked for me - ( from mongo shell )
var file = cat('./new.json'); # file name
use testdb # db name
var o = JSON.parse(file); # convert string to JSON
db.forms.insert(o) # collection name
Here is a simple answer. Hope it helps someone.
import org.springframework.boot.devtools.remote.client.HttpHeaderInterceptor;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;
public String post(SomeRequest someRequest) {
// create a list the headers
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new HttpHeaderInterceptor("Accept", MediaType.APPLICATION_JSON_VALUE));
interceptors.add(new HttpHeaderInterceptor("ContentType", MediaType.APPLICATION_JSON_VALUE));
interceptors.add(new HttpHeaderInterceptor("username", "user123"));
interceptors.add(new HttpHeaderInterceptor("customHeader1", "c1"));
interceptors.add(new HttpHeaderInterceptor("customHeader2", "c2"));
// initialize RestTemplate
RestTemplate restTemplate = new RestTemplate();
// set header interceptors here
restTemplate.setInterceptors(interceptors);
// post the request. The response should be JSON string
String response = restTemplate.postForObject(Url, someRequest, String.class);
return response;
}
The app that contains the custom tags must be in INSTALLED_APPS
. So Are you sure that your directory is in INSTALLED_APPS
?
From the documentation:
The app that contains the custom tags must be in
INSTALLED_APPS
in order for the{% load %}
tag to work. This is a security feature: It allows you to host Python code for many template libraries on a single host machine without enabling access to all of them for every Django installation.
Component 2, the directive component can define a input property (@input
annotation in Typescript). And Component 1 can pass that property to the directive component from template.
See this SO answer How to do inter communication between a master and detail component in Angular2?
and how input is being passed to child components. In your case it is directive.
Is there any specific reason you would want your buttons in an item template.You can alternatively do it the following way , there by giving you the full power of the grid row editing event.You are also given a bonus of wiring easily the cancel and delete functionality.
Mark up
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:ImageButton ID="EditImageButton" runat="server" CommandName="Edit"
ImageUrl="~/images/Edit.png" Style="height: 16px" ToolTip="Edit"
CausesValidation="False" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" runat="server" CommandName="Update"
Text="Update" Visible="true" ImageUrl="~/images/saveHS.png"
/>
<asp:LinkButton ID="btnCancel" runat="server" CommandName="Cancel"
ImageUrl="~/images/Edit_UndoHS.png" />
<asp:LinkButton ID="btnDelete" runat="server" CommandName="Delete"
ImageUrl="~/images/delete.png" />
</EditItemTemplate>
<ControlStyle BackColor="Transparent" BorderStyle="None" />
<FooterStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
Code behind
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
TextBox txtledName = (TextBox) GridView1.Rows[e.NewEditIndex].FindControl("txtAccountName");
//then do something with the retrieved textbox's text.
}
A parent ViewGroup into which the fragment's View is to be inserted,
A third boolean telling whether the fragment's View as inflated from the layout XML file should be inserted into the parent ViewGroup.
In this case we pass false because the View will be attached to the parent ViewGroup elsewhere, by some of the Android code we call (in other words, behind our backs). When you pass false as last parameter to inflate(), the parent ViewGroup is still used for layout calculations of the inflated View, so you cannot pass null as parent ViewGroup .
View rootView = inflater.inflate(R.layout.fragment_photos, container, false);
So, You need to call rootView
in here
ListView lv = (ListView)rootView.findViewById(R.id.lv_contact);
I found an app for Mac OSX called ICOBundle that allows you to easily drop a selection of ico files in different sizes onto the ICOBundle.app, prompts you for a folder destination and file name, and it creates the multi-icon .ico file.
Now if it were only possible to mix-in an animated gif version into that one file it'd be a complete icon set, sadly not possible and requires a separate file and code snippet.
I am getting the error (...) javax.naming.NameNotFoundException: greetJndi not bound
This means that nothing is bound to the jndi name greetJndi
, very likely because of a deployment problem given the incredibly low quality of this tutorial (check the server logs). I'll come back on this.
Is there any specific directory structure to deploy in JBoss?
The internal structure of the ejb-jar
is supposed to be like this (using the poor naming conventions and the default package as in the mentioned link):
. +-- greetBean.java +-- greetHome.java +-- greetRemote.java +-- META-INF +-- ejb-jar.xml +-- jboss.xml
But as already mentioned, this tutorial is full of mistakes:
<enterprise-beans>]
<-- HERE) in the ejb-jar.xml
(!)PUBLIC
in the ejb-jar.xml
and jboss.xml
(!!)jboss.xml
is incorrect, it should contain a session
element instead of entity
(!!!)Here is a "fixed" version of the ejb-jar.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
<ejb-jar>
<enterprise-beans>
<session>
<ejb-name>greetBean</ejb-name>
<home>greetHome</home>
<remote>greetRemote</remote>
<ejb-class>greetBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>
</ejb-jar>
And of the jboss.xml
:
<?xml version="1.0"?>
<!DOCTYPE jboss PUBLIC "-//JBoss//DTD JBOSS 3.2//EN" "http://www.jboss.org/j2ee/dtd/jboss_3_2.dtd">
<jboss>
<enterprise-beans>
<session>
<ejb-name>greetBean</ejb-name>
<jndi-name>greetJndi</jndi-name>
</session>
</enterprise-beans>
</jboss>
After doing these changes and repackaging the ejb-jar, I was able to successfully deploy it:
21:48:06,512 INFO [Ejb3DependenciesDeployer] Encountered deployment AbstractVFSDeploymentContext@5060868{vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/} 21:48:06,534 INFO [EjbDeployer] installing bean: ejb/#greetBean,uid19981448 21:48:06,534 INFO [EjbDeployer] with dependencies: 21:48:06,534 INFO [EjbDeployer] and supplies: 21:48:06,534 INFO [EjbDeployer] jndi:greetJndi 21:48:06,624 INFO [EjbModule] Deploying greetBean 21:48:06,661 WARN [EjbModule] EJB configured to bypass security. Please verify if this is intended. Bean=greetBean Deployment=vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/ 21:48:06,805 INFO [ProxyFactory] Bound EJB Home 'greetBean' to jndi 'greetJndi'
That tutorial needs significant improvement; I'd advise from staying away from roseindia.net.
You could also try the dateparser module, which may be slower than datefinder on free text but which should cover more potential cases and date formats, as well as a significant number of languages.
When I faced this problem I was on Android Studio 3.1 version. I tried a lot of approach above, nothing worked for me ( Don't know why :/ ). Finally I tried something different by my own. My approach was:
Before going to bellow steps make sure
*Your "Google USB Driver" package is installed ("Tools" -> "SDK Manager" -> Check "Google USB Driver" -> "Apply" -> "Ok").
*If you are trying to access with emulator then check "Intel x86 Emulator Accelarator(HAXM installer)" is instaled. ("Tools" -> "SDK Manager" -> Check "Intel x86 Emulator Accelarator(HAXM installer)"" -> "Apply" -> "Ok")
Hope this will help somebody like me.
#register a:link
{
color:#fffff;
}
Solution : SpreadsheetApp.getActiveSheet().getRange('F2').setValue('hello')
Explanation :
Setting value in a cell in spreadsheet to which script is attached
SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_NAME).getRange(RANGE).setValue(VALUE);
Setting value in a cell in sheet which is open currently and to which script is attached
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(RANGE).setValue(VALUE);
Setting value in a cell in some spreadsheet to which script is NOT attached (Destination sheet name known)
SpreadsheetApp.openById(SHEET_ID).getSheetByName(SHEET_NAME).getRange(RANGE).setValue(VALUE);
Setting value in a cell in some spreadsheet to which script is NOT attached (Destination sheet position known)
SpreadsheetApp.openById(SHEET_ID).getSheets()[POSITION].getRange(RANGE).setValue(VALUE);
These are constants, you must define them yourself
SHEET_ID
SHEET_NAME
POSITION
VALUE
RANGE
By script attached to a sheet I mean that script is residing in the script editor of that sheet. Not attached means not residing in the script editor of that sheet. It can be in any other place.
For any case set overflow-x
to hidden
and I prefer to set max-height
in order to limit the expansion of the height of the div. Your code should looks like this:
overflow-y: scroll;
overflow-x: hidden;
max-height: 450px;
Use clearAllTables() with RXJava like below inorder to avoid java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
Completable.fromAction(new Action() {
@Override
public void run() throws Exception {
getRoomDatabase().clearAllTables();
}
}).subscribeOn(getSchedulerProvider().io())
.observeOn(getSchedulerProvider().ui())
.subscribe(new Action() {
@Override
public void run() throws Exception {
Log.d(TAG, "--- clearAllTables(): run() ---");
getInteractor().setUserAsLoggedOut();
getMvpView().openLoginActivity();
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
Log.d(TAG, "--- clearAllTables(): accept(Throwable throwable) ----");
Log.d(TAG, "throwable.getMessage(): "+throwable.getMessage());
}
});
Workaround:
t = time()
t2 = time(t.hour+1, t.minute, t.second, t.microsecond)
You can also omit the microseconds, if you don't need that much precision.
Copy a value from one row to any other qualified rows within the same table (or different tables):
UPDATE `your_table` t1, `your_table` t2
SET t1.your_field = t2.your_field
WHERE t1.other_field = some_condition
AND t1.another_field = another_condition
AND t2.source_id = 'explicit_value'
Start off by aliasing the table into 2 unique references so the SQL server can tell them apart
Next, specify the field(s) to copy.
Last, specify the conditions governing the selection of the rows
Depending on the conditions you may copy from a single row to a series, or you may copy a series to a series. You may also specify different tables, and you can even use sub-selects or joins to allow using other tables to control the relationships.
I have managed to do it with the following css combination:
text-align: justify;
text-align-last: justify;
text-justify: inter-word;
Solved this by adding following
RewriteCond %{ENV:REDIRECT_STATUS} 200 [OR]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
I was dealing with CRLF
issues so I decided to build really simple tool for conversion (in NodeJS):
So if you have NodeJS with npm installed you can try it:
npm i -g eol-converter-cli
eolConverter crlf "**/*.{txt,js,java,etc}"
Path might be configured dynamically by using Glob regex (same regex as in shell).
So if you can use NodeJS, it's really simple and you can integrate this command to convert whole workspace to desired line endings.
You don't see any output from the print
statements because FileInput
redirects stdout
to the input file when the keyword argument inplace=1
is given. This causes the input file to effectively be rewritten and if you look at it afterwards the lines in it will indeed have no trailing or leading whitespace in them (except for the newline at the end of each which the print
statement adds back).
If you only want to remove trailing whitespace, you should use rstrip()
instead of strip()
. Also note that the if lines == '': continue
is causing blank lines to be completely removed (regardless of whether strip
or rstrip
gets used).
Unless your intent is to rewrite the input file, you should probably just use for line in open(filename):
. Otherwise you can see what's being written to the file by simultaneously echoing the output to sys.stderr
using something like the following:
import fileinput
import sys
for line in (line.rstrip() for line in
fileinput.FileInput("test.txt", inplace=1)):
if line:
print line
print >>sys.stderr, line
Take a look at this Github issue:
https://github.com/facebook/react-native/issues/231
They are trying to require
non-JSON files, in particular JSON. There is no method of doing this right now, so you either have to use AsyncStorage as @CocoOS mentioned, or you could write a small native module to do what you need to do.
This will definitely work for you...
ArrayList<String> list = new ArrayList<String>();
list.add(textview.getText().toString());
list.add("B");
list.add("C");
Also if you're retrieving something from intent
of another activity using getIntent
in the current activity and setting those retrieved data before/above onCreate
then this exception is thrown.
For eg. if i retrieve a string like this
final String slot1 = getIntent().getExtras().getString("Slot1");
and put this line of code before/above onCreate
then this exception is thrown.
I wasn't able to ever accomplish this but rather used view html source apps available on the Play Store to simply look for the element.
following code is working fine for me:
import smtplib
to = '[email protected]'
gmail_user = '[email protected]'
gmail_pwd = 'yourpassword'
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo() # extra characters to permit edit
smtpserver.login(gmail_user, gmail_pwd)
header = 'To:' + to + '\n' + 'From: ' + gmail_user + '\n' + 'Subject:testing \n'
print header
msg = header + '\n this is test msg from mkyong.com \n\n'
smtpserver.sendmail(gmail_user, to, msg)
print 'done!'
smtpserver.quit()
Ref: http://www.mkyong.com/python/how-do-send-email-in-python-via-smtplib/
As simply as:
if (numbers.isEmpty()) {...}
Note that a quick look at the documentation would have given you that information.
You can't have an hash map with multiple keys, but you can have an object that takes multiple parameters as the key.
Create an object called Index that takes an x and y value.
public class Index {
private int x;
private int y;
public Index(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int hashCode() {
return this.x ^ this.y;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Index other = (Index) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}
Then have your HashMap<Index, Value>
to get your result. :)
Here is an example of some boolean functions written in Python that return True
if the card is detected as per the function name.
def is_american_express(cc_number):
"""Checks if the card is an american express. If us billing address country code, & is_amex, use vpos
https://en.wikipedia.org/wiki/Bank_card_number#cite_note-GenCardFeatures-3
:param cc_number: unicode card number
"""
return bool(re.match(r'^3[47][0-9]{13}$', cc_number))
def is_visa(cc_number):
"""Checks if the card is a visa, begins with 4 and 12 or 15 additional digits.
:param cc_number: unicode card number
"""
# Standard Visa is 13 or 16, debit can be 19
if bool(re.match(r'^4', cc_number)) and len(cc_number) in [13, 16, 19]:
return True
return False
def is_mastercard(cc_number):
"""Checks if the card is a mastercard. Begins with 51-55 or 2221-2720 and 16 in length.
:param cc_number: unicode card number
"""
if len(cc_number) == 16 and cc_number.isdigit(): # Check digit, before cast to int
return bool(re.match(r'^5[1-5]', cc_number)) or int(cc_number[:4]) in range(2221, 2721)
return False
def is_discover(cc_number):
"""Checks if the card is discover, re would be too hard to maintain. Not a supported card.
:param cc_number: unicode card number
"""
if len(cc_number) == 16:
try:
# return bool(cc_number[:4] == '6011' or cc_number[:2] == '65' or cc_number[:6] in range(622126, 622926))
return bool(cc_number[:4] == '6011' or cc_number[:2] == '65' or 622126 <= int(cc_number[:6]) <= 622925)
except ValueError:
return False
return False
def is_jcb(cc_number):
"""Checks if the card is a jcb. Not a supported card.
:param cc_number: unicode card number
"""
# return bool(re.match(r'^(?:2131|1800|35\d{3})\d{11}$', cc_number)) # wikipedia
return bool(re.match(r'^35(2[89]|[3-8][0-9])[0-9]{12}$', cc_number)) # PawelDecowski
def is_diners_club(cc_number):
"""Checks if the card is a diners club. Not a supported card.
:param cc_number: unicode card number
"""
return bool(re.match(r'^3(?:0[0-6]|[68][0-9])[0-9]{11}$', cc_number)) # 0-5 = carte blance, 6 = international
def is_laser(cc_number):
"""Checks if the card is laser. Not a supported card.
:param cc_number: unicode card number
"""
return bool(re.match(r'^(6304|670[69]|6771)', cc_number))
def is_maestro(cc_number):
"""Checks if the card is maestro. Not a supported card.
:param cc_number: unicode card number
"""
possible_lengths = [12, 13, 14, 15, 16, 17, 18, 19]
return bool(re.match(r'^(50|5[6-9]|6[0-9])', cc_number)) and len(cc_number) in possible_lengths
# Child cards
def is_visa_electron(cc_number):
"""Child of visa. Checks if the card is a visa electron. Not a supported card.
:param cc_number: unicode card number
"""
return bool(re.match(r'^(4026|417500|4508|4844|491(3|7))', cc_number)) and len(cc_number) == 16
def is_total_rewards_visa(cc_number):
"""Child of visa. Checks if the card is a Total Rewards Visa. Not a supported card.
:param cc_number: unicode card number
"""
return bool(re.match(r'^41277777[0-9]{8}$', cc_number))
def is_diners_club_carte_blanche(cc_number):
"""Child card of diners. Checks if the card is a diners club carte blance. Not a supported card.
:param cc_number: unicode card number
"""
return bool(re.match(r'^30[0-5][0-9]{11}$', cc_number)) # github PawelDecowski, jquery-creditcardvalidator
def is_diners_club_carte_international(cc_number):
"""Child card of diners. Checks if the card is a diners club international. Not a supported card.
:param cc_number: unicode card number
"""
return bool(re.match(r'^36[0-9]{12}$', cc_number)) # jquery-creditcardvalidator
I believe IE requires the H.264 or MPEG-4 codec, which it seems like you don't specify/include. You can always check for browser support by using HTML5Please and Can I use.... Both sites usually have very up-to-date information about support, polyfills, and advice on how to take advantage of new technology.
Strictly stated you must check all of the following: defined, not empty AND not None.
For "normal" variables it makes a difference if defined and set or not set. See foo
and bar
in the example below. Both are defined but only foo
is set.
On the other side registered variables are set to the result of the running command and vary from module to module. They are mostly json structures. You probably must check the subelement you're interested in. See xyz
and xyz.msg
in the example below:
cat > test.yml <<EOF
- hosts: 127.0.0.1
vars:
foo: "" # foo is defined and foo == '' and foo != None
bar: # bar is defined and bar != '' and bar == None
tasks:
- debug:
msg : ""
register: xyz # xyz is defined and xyz != '' and xyz != None
# xyz.msg is defined and xyz.msg == '' and xyz.msg != None
- debug:
msg: "foo is defined and foo == '' and foo != None"
when: foo is defined and foo == '' and foo != None
- debug:
msg: "bar is defined and bar != '' and bar == None"
when: bar is defined and bar != '' and bar == None
- debug:
msg: "xyz is defined and xyz != '' and xyz != None"
when: xyz is defined and xyz != '' and xyz != None
- debug:
msg: "{{ xyz }}"
- debug:
msg: "xyz.msg is defined and xyz.msg == '' and xyz.msg != None"
when: xyz.msg is defined and xyz.msg == '' and xyz.msg != None
- debug:
msg: "{{ xyz.msg }}"
EOF
ansible-playbook -v test.yml
The general pattern for search and replace is:
:s/search/replace/
Replaces the first occurrence of 'search' with 'replace' for current line
:s/search/replace/g
Replaces all occurrences of 'search' with 'replace' for current line, 'g' is short for 'global'
This command will replace each occurrence of 'search' with 'replace' for the current line only. The % is used to search over the whole file. To confirm each replacement interactively append a 'c' for confirm:
:%s/search/replace/c
Interactive confirm replacing 'search' with 'replace' for the entire file
Instead of the % character you can use a line number range (note that the '^' character is a special search character for the start of line):
:14,20s/^/#/
Inserts a '#' character at the start of lines 14-20
If you want to use another comment character (like //) then change your command delimiter:
:14,20s!^!//!
Inserts a '//' character sequence at the start of lines 14-20
Or you can always just escape the // characters like:
:14,20s/^/\/\//
Inserts a '//' character sequence at the start of lines 14-20
If you are not seeing line numbers in your editor, simply type the following
:set nu
This often occurs when you build software in RHEL 7 and try to run on RHEL 6.
To update GLIBC to any version, simply download the package from
For example glibc-2.14.tar.gz in your case.
1. tar xvfz glibc-2.14.tar.gz
2. cd glibc-2.14
3. mkdir build
4. cd build
5. ../configure --prefix=/opt/glibc-2.14
6. make
7. sudo make install
8. export LD_LIBRARY_PATH=/opt/glibc-2.14/lib:$LD_LIBRARY_PATH
Then try to run your software, glibc-2.14 should be linked.
Update 2020 with Visual Studio Community 2019 and Unity 2019.3:
Open Visual Studio Installer as Administrator, select to modify your current installation and add "Game development for Unity"
If you add a new c# script in Unity now, and open it (automatically) with Visual Studio, it is not described as "Miscellaneous" at the top of the window but with "Assembly-CSharp", and the autocomplete works.
you can disable security check. go to
Project -> Properties -> Configuration properties -> C/C++ -> Code Generation -> Security Check
and select Disable Security Check (/GS-)
I used the properties plugin to solve this.
Properties are defined in the pom, and written out to a my.properties file, where they can then be accessed from your Java code.
In my case it is test code that needs to access this properties file, so in the pom the properties file is written to maven's testOutputDirectory:
<configuration>
<outputFile>${project.build.testOutputDirectory}/my.properties</outputFile>
</configuration>
Use outputDirectory if you want properties to be accessible by your app code:
<configuration>
<outputFile>${project.build.outputDirectory}/my.properties</outputFile>
</configuration>
For those looking for a fuller example (it took me a bit of fiddling to get this working as I didn't understand how naming of properties tags affects ability to retrieve them elsewhere in the pom file), my pom looks as follows:
<dependencies>
<dependency>
...
</dependency>
</dependencies>
<properties>
<app.env>${app.env}</app.env>
<app.port>${app.port}</app.port>
<app.domain>${app.domain}</app.domain>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0.0</version>
<executions>
<execution>
<phase>generate-resources</phase>
<goals>
<goal>write-project-properties</goal>
</goals>
<configuration>
<outputFile>${project.build.testOutputDirectory}/my.properties</outputFile>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
And on the command line:
mvn clean test -Dapp.env=LOCAL -Dapp.domain=localhost -Dapp.port=9901
So these properties can be accessed from the Java code:
java.io.InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("my.properties");
java.util.Properties properties = new Properties();
properties.load(inputStream);
appPort = properties.getProperty("app.port");
appDomain = properties.getProperty("app.domain");
in my case it also need to install it's npm package
so
npm install react-native-debugger -g
Unless you write your own Homescreen launcher or use an existing one from Goolge Play, there's "no way" to resize icons.
Well, "no way" does not mean its impossible:
Goto my blog : retrofit with kotlin
the link below explains everything step by step.
http://loopj.com/android-async-http/
Here are sample apps:
Create a class :
public class HttpUtils {
private static final String BASE_URL = "http://api.twitter.com/1/";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(url, params, responseHandler);
}
public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(url, params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}
Call Method :
RequestParams rp = new RequestParams();
rp.add("username", "aaa"); rp.add("password", "aaa@123");
HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// If the response is JSONObject instead of expected JSONArray
Log.d("asd", "---------------- this is response : " + response);
try {
JSONObject serverResp = new JSONObject(response.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
// Pull out the first event on the public timeline
}
});
Please grant internet permission in your manifest file.
<uses-permission android:name="android.permission.INTERNET" />
you can add compile 'com.loopj.android:android-async-http:1.4.9'
for Header[]
and compile 'org.json:json:20160212'
for JSONObject
in build.gradle file if required.
"most convenient block of data" probably refers to the width (in bits) of the WORD, in correspondance to the system bus width, or whatever underlying "bandwidth" is available. On a 16 bit system, with WORD being defined as 16 bits wide, moving data around in chunks the size of a WORD will be the most efficient way. (On hardware or "system" level.)
With Java being more or less platform independant, it just defines a "WORD" as the next size from a "BYTE", meaning "full bandwidth". I guess any platform that's able to run Java will use 32 bits for a WORD.
All the responses above work okay, but you'll still probably get a CORS error, if the application throws an error you are not handling, like a key-error, if you aren't doing input validation properly, for example. You could add an error handler to catch all instances of exceptions and add CORS response headers in the server response
So define an error handler - errors.py:
from flask import json, make_response, jsonify
from werkzeug.exceptions import HTTPException
# define an error handling function
def init_handler(app):
# catch every type of exception
@app.errorhandler(Exception)
def handle_exception(e):
#loggit()!
# return json response of error
if isinstance(e, HTTPException):
response = e.get_response()
# replace the body with JSON
response.data = json.dumps({
"code": e.code,
"name": e.name,
"description": e.description,
})
else:
# build response
response = make_response(jsonify({"message": 'Something went wrong'}), 500)
# add the CORS header
response.headers['Access-Control-Allow-Origin'] = '*'
response.content_type = "application/json"
return response
then using Billal's answer:
from flask import Flask
from flask_cors import CORS
# import error handling file from where you have defined it
from . import errors
app = Flask(__name__)
CORS(app) # This will enable CORS for all routes
errors.init_handler(app) # initialise error handling
If someone has installed LAMP in the /opt
folder, then the /etc/apache2
folder is not what you are looking for.
Look for httpd.conf
file in folder /opt/lampp/etc
.
Change the line in this folder and save it from the terminal.
In my case the binding name in under protocol mapping did not match the binding name on the endpoint. They match in the example below.
<endpoint address="" binding="basicHttpsBinding" contract="serviceName" />
and
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
I think that the the align="center"
aligns the content, so if you wanted to use that method, you would need to use it in a 'wraper' div - a div that just wraps the rest.
text-align
is doing a similar sort of thing.
left:50%
is ignored unless you set the div's position to be something like relative or absolute.
The generally accepted methods is to use the following properties
width:500px; // this can be what ever unit you want, you just have to define it
margin-left:auto;
margin-right:auto;
the margins being auto means they grow/shrink to match the browser window (or parent div)
UPDATE
Thanks to Meo for poiting this out, if you wanted to you could save time and use the short hand propery for the margin.
margin:0 auto;
this defines the top and bottom as 0 (as it is zero it does not matter about lack of units) and the left and right get defined as 'auto' You can then, if you wan't override say the top margin as you would with any other CSS rules.
toString()
valueOf()
handles primitive types as well as object types.
Integer a = null;
System.out.println(Integer.toString()) ; NUll pointer exception
System.out.println(String.valueOf() ; give NULL as value
check this link its very good. http://code4reference.com/2013/06/which-one-is-better-valueof-or-tostring/
I have done the following steps to get rid of this issue. Login into the MySQL in your machine using (sudo mysql -p -u root) and hit the following queries.
1. CREATE USER 'jack'@'localhost' IDENTIFIED WITH mysql_native_password BY '<<any password>>';
2. GRANT ALL PRIVILEGES ON *.* TO 'jack'@'localhost';
3. SELECT user,plugin,host FROM mysql.user WHERE user = 'root';
+------+-------------+-----------+
| user | plugin | host |
+------+-------------+-----------+
| root | auth_socket | localhost |
+------+-------------+-----------+
4. ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '<<any password>>';
5. FLUSH PRIVILEGES;
Please try it once if you are still getting the error. I hope this code will help you a lot !!
I fix this problem following this steps:
The FragmentManger's function add and replace can be described as these 1. add means it will add the fragment in the fragment back stack and it will show at given frame you are providing like
getFragmentManager.beginTransaction.add(R.id.contentframe,Fragment1.newInstance(),null)
2.replace means that you are replacing the fragment with another fragment at the given frame
getFragmentManager.beginTransaction.replace(R.id.contentframe,Fragment1.newInstance(),null)
The Main utility between the two is that when you are back stacking the replace will refresh the fragment but add will not refresh previous fragment.
Boostrap Placeholder Mixin:
@mixin placeholder($color: $input-color-placeholder) {
// Firefox
&::-moz-placeholder {
color: $color;
opacity: 1; // Override Firefox's unusual default opacity; see https://github.com/twbs/bootstrap/pull/11526
}
&:-ms-input-placeholder { color: $color; } // Internet Explorer 10+
&::-webkit-input-placeholder { color: $color; } // Safari and Chrome
}
now call it:
@include placeholder($white);
live view Link Jsfiddle
vary simple way you can solve it ..... take a look my new collected code.
$(document).ready(function(){
$(".add-row").click(function(){
var name = $("#name").val();
var email = $("#email").val();
var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + name + "</td><td>" + email + "</td></tr>";
$("table tbody").append(markup);
});
// Find and remove selected table rows
$(".delete-row").click(function(){
$("table tbody").find('input[name="record"]').each(function(){
if($(this).is(":checked")){
$(this).parents("tr").remove();
}
});
});
});
$(document).ready(function() {_x000D_
$(".add-row").click(function() {_x000D_
var name = $("#name").val();_x000D_
var email = $("#email").val();_x000D_
var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + name + "</td><td>" + email + "</td></tr>";_x000D_
$("table tbody").append(markup);_x000D_
});_x000D_
_x000D_
// Find and remove selected table rows_x000D_
$(".delete-row").click(function() {_x000D_
$("table tbody").find('input[name="record"]').each(function() {_x000D_
if ($(this).is(":checked")) {_x000D_
$(this).parents("tr").remove();_x000D_
}_x000D_
});_x000D_
});_x000D_
});
_x000D_
form {_x000D_
margin: 20px 0;_x000D_
}_x000D_
form input,_x000D_
button {_x000D_
padding: 6px;_x000D_
font-size: 18px;_x000D_
}_x000D_
table {_x000D_
width: 100%;_x000D_
margin-bottom: 20px;_x000D_
border-collapse: collapse;_x000D_
background: #fff;_x000D_
}_x000D_
table,_x000D_
th,_x000D_
td {_x000D_
border: 1px solid #cdcdcd;_x000D_
}_x000D_
table th,_x000D_
table td {_x000D_
padding: 10px;_x000D_
text-align: left;_x000D_
}_x000D_
body {_x000D_
background: #ccc;_x000D_
}_x000D_
.add-row,_x000D_
.delete-row {_x000D_
font-size: 16px;_x000D_
font-weight: 600;_x000D_
padding: 8px 16px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form>_x000D_
<input type="text" id="name" placeholder="Name">_x000D_
<input type="text" id="email" placeholder="Email">_x000D_
<input type="button" class="add-row" value="Add Row">_x000D_
</form>_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Select</th>_x000D_
<th>Name</th>_x000D_
<th>Email</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>_x000D_
<input type="checkbox" name="record">_x000D_
</td>_x000D_
<td>Peter Parker</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
<button type="button" class="delete-row">Delete Row</button>
_x000D_
I have been using Google Collections (now called Guava) for this kind of problem. There is a class called Iterables that can take an interface called Predicate as a parameter of a method that is really helpful.
Cat theOne = Iterables.find(cats, new Predicate<Cat>() {
public boolean apply(Cat arg) { return arg.age() == 3; }
});
Check it here!
wt = tt - cpu tm.
Tt = cpu tm + wt.
Where wt
is a waiting time and tt
is turnaround time. Cpu time is also called burst time.
i didn't put my environment variables in the right format as was in the dotenv module documentation e.g. i was doing export TWILIO_CALLER_ID="+wwehehe" and so the dotenv module wasn't parsing my file correctly. When i noticed that i removed the export keyword from the declarations and everything worked fine.
ul > li > a
selects only the direct children. In this case only the first level <a>
of the first level <li>
inside the <ul>
will be selected.
ul li a
on the other hand will select ALL <a>
-s in ALL <li>
-s in the unordered list
Example of ul > li
ul > li.bg {_x000D_
background: red;_x000D_
}
_x000D_
<ul>_x000D_
<li class="bg">affected</li>_x000D_
<li class="bg">affected</li> _x000D_
<li>_x000D_
<ol>_x000D_
<li class="bg">NOT affected</li>_x000D_
<li class="bg">NOT affected</li>_x000D_
</ol>_x000D_
</li>_x000D_
</ul>
_x000D_
if you'd be using ul li
- ALL of the li
-s would be affected
UPDATE The order of more to less efficient CSS selectors goes thus:
#header
.promo
div
h2 + p
li > ul
ul a
*
[type="text"]
a:hover
So your better bet is to use the children
selector instead of just descendant
. However the difference on a regular page (without tens of thousands elements to go through) might be absolutely negligible.
Note that datalist
is not the same as a select
. It allows users to enter a custom value that is not in the list, and it would be impossible to fetch an alternate value for such input without defining it first.
Possible ways to handle user input are to submit the entered value as is, submit a blank value, or prevent submitting. This answer handles only the first two options.
If you want to disallow user input entirely, maybe select
would be a better choice.
To show only the text value of the option
in the dropdown, we use the inner text for it and leave out the value
attribute. The actual value that we want to send along is stored in a custom data-value
attribute:
To submit this data-value
we have to use an <input type="hidden">
. In this case we leave out the name="answer"
on the regular input and move it to the hidden copy.
<input list="suggestionList" id="answerInput">
<datalist id="suggestionList">
<option data-value="42">The answer</option>
</datalist>
<input type="hidden" name="answer" id="answerInput-hidden">
This way, when the text in the original input changes we can use javascript to check if the text also present in the datalist
and fetch its data-value
. That value is inserted into the hidden input and submitted.
document.querySelector('input[list]').addEventListener('input', function(e) {
var input = e.target,
list = input.getAttribute('list'),
options = document.querySelectorAll('#' + list + ' option'),
hiddenInput = document.getElementById(input.getAttribute('id') + '-hidden'),
inputValue = input.value;
hiddenInput.value = inputValue;
for(var i = 0; i < options.length; i++) {
var option = options[i];
if(option.innerText === inputValue) {
hiddenInput.value = option.getAttribute('data-value');
break;
}
}
});
The id answer
and answer-hidden
on the regular and hidden input are needed for the script to know which input belongs to which hidden version. This way it's possible to have multiple input
s on the same page with one or more datalist
s providing suggestions.
Any user input is submitted as is. To submit an empty value when the user input is not present in the datalist, change hiddenInput.value = inputValue
to hiddenInput.value = ""
Working jsFiddle examples: plain javascript and jQuery
You can use guide=FALSE
in scale_..._...()
to suppress legend.
For your example you should use scale_colour_continuous()
because length
is continuous variable (not discrete).
(p3 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
scale_colour_continuous(guide = FALSE) +
geom_point()
)
Or using function guides()
you should set FALSE
for that element/aesthetic that you don't want to appear as legend, for example, fill
, shape
, colour
.
p0 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
geom_point()
p0+guides(colour=FALSE)
Both provided solutions work in new ggplot2
version 2.0.0 but movies
dataset is no longer present in this library. Instead you have to use new package ggplot2movies
to check those solutions.
library(ggplot2movies)
data(movies)
mov <- subset(movies, length != "")
Although this is valid in HTML, you can't use an ID starting with an integer in CSS selectors.
As pointed out, you can use getElementById
instead, but you can also still achieve the same with a querySelector
:
document.querySelector("[id='22']")
I had the same problem. It turns out that I had both "MyPage.aspx" and "Copy of MyPage.aspx" in my project.
if you don't want recursion you could try:
x = [u'sam', [['Test', [['one', [], []]], [(u'file.txt', ['id', 1, 0])]], ['Test2', [], [(u'file2.txt', ['id', 1, 2])]]], []]
layer1=x
layer2=[]
while True:
for i in layer1:
if isinstance(i,list):
for j in i:
layer2.append(j)
else:
print i
layer1[:]=layer2
layer2=[]
if len(layer1)==0:
break
which gives:
sam
Test
Test2
(u'file.txt', ['id', 1, 0])
(u'file2.txt', ['id', 1, 2])
one
(note that it didn't look into the tuples for lists because the tuples aren't lists. You can add tuple to the "isinstance" method if you want to fix this)
It did not worked for me until i created:
#created cc string
cc = ""[email protected];
#added cc to header
msg['Cc'] = cc
and than added cc in recipient [list] like:
s.sendmail(me, [you,cc], msg.as_string())
I've been testing alternatives to C# Web browser component for few days now and here is my list:
1. Using newer IE versions 8,9:
Web Browser component is IE7 not IE8? How to change this?
Pros:
Cons:
This doesn't require much work and you can get some HTML5 and CSS3 support although IE9 lacks some of best CSS3 and HTML5 features. But I'm sure you could get IE10 running same way. The problem would be that target system would have to have IE10 installed, and since is still in preview on Windows 7 I would suggest against it.
OpenWebKitSharp is a .net wrapper for the webkit engine based on the WebKit.NET 0.5 project. WebKit is a layout engine used by Chrome/Safari
Pros:
Cons:
OpenWebKit is quite nice although many features are not yet implemented, I experienced few issues using it with visual studio which throws null object reference here and then in design mode, there are some js problems. Everyone using it will almost immediately notice js alert does nothing. Events like mouseup,mousedown... etc. doesn't work, js drag and drop is buggy and so on..
I also had some difficulties installing it since it requires specific version of VC redistributable installed, so after exception I looked at event log, found version of VC and installed it.
3. GeckoFX
Pros:
Cons:
GeckoFX is a cross platform Webrowser control for embedding into WinForms Applications. This can be used with .NET on Windows and with mono on Linux. Gecko is a layout engine used by Firefox.
I bumped into few information that GeckoFX is not actively developed which is not true, of course it's always one or two versions behind of Firefox but that is normal, I was really impressed by activity and the control itself. It does everything I needed, but I needed some time to get it running, here's a little tutorial to get it running:
If your really must use Chrome, take a look at this product called Awesomium, it's free for non-commercial projects, but license is few thousand dollars for commercial.
SOAP 1.1 uses namespace http://schemas.xmlsoap.org/wsdl/soap/
SOAP 1.2 uses namespace http://schemas.xmlsoap.org/wsdl/soap12/
The wsdl is able to define operations under soap 1.1 and soap 1.2 at the same time in the same wsdl. Thats useful if you need to evolve your wsdl to support new functionality that requires soap 1.2 (eg. MTOM), in this case you dont need to create a new service but just evolve the original one.
Following steps worked for me: 1. Goto Project -> Clean. 2. Delete your previous AVD and create a new one.
It means you don't have privileges to create the trigger with root@localhost user..
try removing definer from the trigger command:
CREATE DEFINER = root
@localhost
FUNCTION fnc_calcWalkedDistance
All other answers show how to calculate the new image height in function of the new image width or vice-versa and how to resize the image using Java Image API. For those people who are looking for a straightforward solution I recommend any java image processing framework that can do this in a single line.
The exemple below uses Marvin Framework:
// 300 is the new width. The height is calculated to maintain aspect.
scale(image.clone(), image, 300);
Necessary import:
import static marvin.MarvinPluginCollection.*
haha, man, I just asked this question a few hours ago (kind of)...try this:
example:
someIntList.ForEach(i=>i+5);
ForEach()
is one of the built in .NET methods
This will modify the list, as opposed to returning a new one.
I think your only option here is a constant. With that said - don't use it - stick with nulls instead of bogus dates.
create table atable
(
atableID int IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
Modified datetime DEFAULT '1/1/1753'
)
The solution for my case is:
On EF core you cannot create Indexes using data annotations.But you can do it using the Fluent API.
Like this inside your {Db}Context.cs
:
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<User>()
.HasIndex(u => u.Email)
.IsUnique();
}
...or if you're using the overload with the buildAction:
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<User>(entity => {
entity.HasIndex(e => e.Email).IsUnique();
});
}
You can read more about it here : Indexes
You can use opendir()
and check if ENOENT == errno
on failure:
#include <dirent.h>
#include <errno.h>
DIR* dir = opendir("mydir");
if (dir) {
/* Directory exists. */
closedir(dir);
} else if (ENOENT == errno) {
/* Directory does not exist. */
} else {
/* opendir() failed for some other reason. */
}
$('#myId').val()
should do it, failing that I would try:
$('#myId option:selected').val()
If I'm understanding correctly:
var properties = string.split(', ');
var obj = {};
properties.forEach(function(property) {
var tup = property.split(':');
obj[tup[0]] = tup[1];
});
I'm assuming that the property name is to the left of the colon and the string value that it takes on is to the right.
Note that Array.forEach
is JavaScript 1.6 -- you may want to use a toolkit for maximum compatibility.
I don't like and understand things, which can be explained visually, by words.
Python Version 2.x will have .pyc when interpreter compiles the code.
Python Version 3.x will have __pycache__ when interpreter compiles the code.
alok@alok:~$ ls
module.py module.pyc __pycache__ test.py
alok@alok:~$
You could use the {display: inline-flex;} this would produce this: inline-flex
The (A==B).all()
solution is very neat, but there are some built-in functions for this task. Namely array_equal
, allclose
and array_equiv
.
(Although, some quick testing with timeit
seems to indicate that the (A==B).all()
method is the fastest, which is a little peculiar, given it has to allocate a whole new array.)
Yet another variation.
Somehow, my formerly working test classes appeared to be running from some other location; my edits would not execute when I ran the tests.
I found that the output folder for my ${project_loc}src/test/java files was not what I expected. It had inadvertently been set to ${project_loc}target/classes. I set it properly in project properties, Java Build Path, Source tab.
Iterator returned by Set is not suppose to return data in Ordered way. See this Two java.util.Iterators to the same collection: do they have to return elements in the same order?
<IF id="if-1">
<TIME from="5pm" to="9pm" />
<ELSE>
<something else />
</ELSE>
</IF>
I don't know if this makes any sense to anyone else or it is actually usable in your program, but I would do it like this.
My point of view: You need to have everything related to your "IF" inside your IF-tag, otherwise you won't know what ELSE belongs to what IF. Secondly, I'd skip the THEN tag because it always follows an IF.
If your DataGridView
is bound to a DataSet
, you can not just add a new row in your DataGridView
display. It will now work properly.
Instead you should add the new row in the DataSet
with this code:
BindingSource[Name].AddNew()
This code will also automatically add a new row in your DataGridView
display.
If have spaces within your string argument, do the following:
Run > Run Configurations > Java Application > Arguments > Program arguments
I'm using MVC3/EntityFramework as back-end, the front-end consumes all of my project controllers via jquery, posting directly (using $.post) doesnt requires the data encription, when you pass params directly other than URL hardcoded. I already tested several chars i even sent an URL(this one http://www.ihackforfun.eu/index.php?title=update-on-url-crazy&more=1&c=1&tb=1&pb=1) as a parameter and had no issue at all even though encodeURIComponent works great when you pass all data in within the URL (hardcoded)
Hardcoded URL i.e.>
var encodedName = encodeURIComponent(name);
var url = "ControllerName/ActionName/" + encodedName + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;; // + name + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;
Otherwise dont use encodeURIComponent and instead try passing params in within the ajax post method
var url = "ControllerName/ActionName/";
$.post(url,
{ name: nameVal, fkKeyword: keyword, description: descriptionVal, linkUrl: linkUrlVal, includeMetrics: includeMetricsVal, FKTypeTask: typeTask, FKProject: project, FKUserCreated: userCreated, FKUserModified: userModified, FKStatus: status, FKParent: parent },
function (data) {.......});
Manually:
int strlen(string s)
{
int len = 0;
while (s[len])
len++;
return len;
}
Another way to do it in Postgres would be to use the idx
function.
SELECT *
FROM comments
ORDER BY idx(array[1,3,2,4], comments.id)
Don't forget to create the idx
function first, as described here: http://wiki.postgresql.org/wiki/Array_Index
Often the reason you want to reverse the vector is because you fill it by pushing all the items on at the end but were actually receiving them in reverse order. In that case you can reverse the container as you go by using a deque
instead and pushing them directly on the front. (Or you could insert the items at the front with vector::insert()
instead, but that would be slow when there are lots of items because it has to shuffle all the other items along for every insertion.) So as opposed to:
std::vector<int> foo;
int nextItem;
while (getNext(nextItem)) {
foo.push_back(nextItem);
}
std::reverse(foo.begin(), foo.end());
You can instead do:
std::deque<int> foo;
int nextItem;
while (getNext(nextItem)) {
foo.push_front(nextItem);
}
// No reverse needed - already in correct order
I wrote some classes for parsing HTML tags in C#. They are nice and simple if they meet your particular needs.
You can read an article about them and download the source code at http://www.blackbeltcoder.com/Articles/strings/parsing-html-tags-in-c.
There's also an article about a generic parsing helper class at http://www.blackbeltcoder.com/Articles/strings/a-text-parsing-helper-class.
Off the top of my head:
document.write
needs to be used in the page load or body load. So if you want to use the script in any other time to update your page content document.write is pretty much useless.
Technically document.write
will only update HTML pages not XHTML/XML. IE seems to be pretty forgiving of this fact but other browsers will not be.
An alternative way is to use MySql Workbench. Go to Administration -> Users and privileges -> and change 'localhost' with '%' in 'Limit to Host Matching' (From host) attribute for users you wont to give remote access Or create new user ( Add account button ) with '%' on this attribute instead localhost.
For the Base64 code like:
"data:image/jpg;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADIAQAAAACFI5MzAAAB9klEQVR42u2YQYorMQxEBbqWQFc36FoG/6pyOpNZ/J20mGGaTiftF2hbLpWU2PnfYX/k55Jl5vhUVTu8luUdaCeFcydejjdwDUyQ5XV2JOcSZnkHZgiejusK51QGycrl2yIR1BwjjKivSFz8YC7fY91GKIj6PL5pp4/wWL54t3MHt/AjFxoJwmkYwosbh6/UEHE817hvi/vGex8gEkTdVRo1/55BM7kjUIgpoMW1DxB6kD+GtCX4PUFws40OwcUm0/lRYjOB3pG9YcguBFQuO0ISJ9UIrUP5CKy/MriXHDkETYmLDax1+RkgWBglQgUyq6T/HCAHBq7iJHd9KWWAlIKoGpiLc6HNDhDkETNYwqeVhym72snKKxA6BJL4UPM5QPYtgGwZeNZ5O0UvgSb0VGdcmVfJCQwQrM+pRiGnYJ497SUlv2NOYfOCX3qU2Equ7W3JAslsN7oDBDWWojcZq+KbEwQRdRYl1wD3ML52rpGc6w24qCXaKh4DRHWJbUPemqtEGyBMKC4Q/QmWiDWzRxkgO1UtSLh3svMaILeDpEGwrwvZ4Bkg9LynK1Y1LJWQdqKGnm3K7VTCz7vS9hIuUyYRd/xKcYRIHGqAViisQ4S/Uozmqo41Pn6bNRI1xS/fk2fMEKpDZYkpjP6B1T0HyN9/Nb+M/AORXDdE4Lb/mQAAAABJRU5ErkJggg=="
Use Swift5.0 code like:
func imageFromBase64(_ base64: String) -> UIImage? {
if let url = URL(string: base64) {
if let data = try? Data(contentsOf: url) {
return UIImage(data: data)
}
}
return nil
}
I am not sure you can dynamically change profiles.
Why not just have an internal properties file with the spring.config.location property set to your desired outside location, and the properties file at that location (outside the jar) have the spring.profiles.active property set?
Better yet, have an internal properties file, specific to dev profile (has spring.profiles.active=dev) and leave it like that, and when you want to deploy in production, specify a new location for your properties file, which has spring.profiles.active=prod:
java -jar myjar.jar --spring.config.location=D:\wherever\application.properties
I was not satisfied with swagger-codegen
when I was looking for a tool to do this, so I wrote my own. Have a look at bootprint-swagger
The main goal compared to swagger-codegen
is to provide an easy setup (though you'll need nodejs).
And it should be easy to adapt styling and templates to your own needs, which is a core functionality of the bootprint-project
This should cover it:
var event;
event = document.createEvent('MouseEvents');
event.initMouseEvent('mousedown', true, true, window);
countries.dispatchEvent(event); //we use countries as it's referred to by ID - but this could be any JS element var
This could be bound for example to a keypress event, so when the element has focus the user can type and it will expand automatically...
--Context--
modal.find("select").not("[readonly]").on("keypress", function(e) {
if (e.keyCode == 13) {
e.preventDefault();
return false;
}
var event;
event = document.createEvent('MouseEvents');
event.initMouseEvent('mousedown', true, true, window);
this.dispatchEvent(event);
});
exit(X)
, where X is a number (according to the doc) should work.
But it is not recommended by Apple and won't be accepted by the AppStore.
Why? Because of these guidelines (one of my app got rejected):
We found that your app includes a UI control for quitting the app. This is not in compliance with the iOS Human Interface Guidelines, as required by the App Store Review Guidelines.
Please refer to the attached screenshot/s for reference.
The iOS Human Interface Guidelines specify,
"Always Be Prepared to Stop iOS applications stop when people press the Home button to open a different application or use a device feature, such as the phone. In particular, people don’t tap an application close button or select Quit from a menu. To provide a good stopping experience, an iOS application should:
Save user data as soon as possible and as often as reasonable because an exit or terminate notification can arrive at any time.
Save the current state when stopping, at the finest level of detail possible so that people don’t lose their context when they start the application again. For example, if your app displays scrolling data, save the current scroll position."
> It would be appropriate to remove any mechanisms for quitting your app.
Plus, if you try to hide that function, it would be understood by the user as a crash.
studentType newStudent() // studentType doesn't exist here
{
struct studentType // it only exists within the function
{
string studentID;
string firstName;
string lastName;
string subjectName;
string courseGrade;
int arrayMarks[4];
double avgMarks;
} newStudent;
...
Move it outside the function:
struct studentType
{
string studentID;
string firstName;
string lastName;
string subjectName;
string courseGrade;
int arrayMarks[4];
double avgMarks;
};
studentType newStudent()
{
studentType newStudent
...
return newStudent;
}
Updated @Hussein solution with preview height that will adapt to the paragraph number of lines.
So with this bit of code : - You can choose the number of lines you want to show in preview, it will works for all screen sizes, even if font-size is responsive. - There is no need to add classes or back-end editing to separate preview from whole content.
http://jsfiddle.net/7Vv8u/5816/
var h = $('div')[0].scrollHeight;
divLineHeight = parseInt($('div').css('line-height'));
divPaddingTop = parseInt($('div').css('padding-top'));
lineToShow = 2;
divPreviewHeight = divLineHeight*lineToShow - divPaddingTop;
$('div').css('height', divPreviewHeight );
$('#more').click(function(e) {
e.stopPropagation();
$('div').animate({
'height': h
})
});
$(document).click(function() {
$('div').animate({
'height': divPreviewHeight
})
})
One more approach is possible : Using SVG.
eg :
<svg height="210" width="500">
<line x1="0" y1="0" x2="0" y2="100" style="stroke:rgb(255,0,0);stroke-width:2" />
Sorry, your browser does not support inline SVG.
</svg>
Pros :
Cons :
Use git config --global core.editor mate -w
or git config --global core.editor open
as @dmckee suggests in the comments.
Reference: http://git-scm.com/docs/git-config
html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css"
</head>
<body>
<ul class="menu">
<li><a href="#">My Dashboard</a>
<ul>
<li><a href="#" class="learn">Learn</a></li>
<li><a href="#" class="teach">Teach</a></li>
<li><a href="#" class="Mylibrary">My Library</a></li>
</ul>
</li>
<li><a href="#">Likes</a>
<ul>
<li><a href="#" class="Pics">Pictures</a></li>
<li><a href="#" class="audio">Audio</a></li>
<li><a href="#" class="Videos">Videos</a></li>
</ul>
</li>
<li><a href="#">Views</a>
<ul>
<li><a href="#" class="documents">Documents</a></li>
<li><a href="#" class="messages">Messages</a></li>
<li><a href="#" class="signout">Videos</a></li>
</ul>
</li>
<li><a href="#">account</a>
<ul>
<li><a href="#" class="SI">Sign In</a></li>
<li><a href="#" class="Reg">Register</a></li>
<li><a href="#" class="Deactivate">Deactivate</a></li>
</ul>
</li>
<li><a href="#">Uploads</a>
<ul>
<li><a href="#" class="Pics">Pictures</a></li>
<li><a href="#" class="audio">Audio</a></li>
<li><a href="#" class="Videos">Videos</a></li>
</ul>
</li>
<li><a href="#">Videos</a>
<ul>
<li><a href="#" class="Add">Add</a></li>
<li><a href="#" class="delete">Delete</a></li>
</ul>
</li>
<li><a href="#">Documents</a>
<ul>
<li><a href="#" class="Add">Upload</a></li>
<li><a href="#" class="delete">Download</a></li>
</ul>
</li>
</ul>
</body>
</html>
css:
.menu,
.menu ul,
.menu li,
.menu a {
margin: 0;
padding: 0;
border: none;
outline: none;
}
body{
max-width:110%;
margin-left:0;
}
.menu {
height: 40px;
width:110%;
margin-left:-4px;
margin-top:-10px;
background: #4c4e5a;
background: -webkit-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
background: -moz-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
background: -o-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
background: -ms-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
background: linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
.menu li {
position: relative;
list-style: none;
float: left;
display: block;
height: 40px;
}
.menu li a {
display: block;
padding: 0 14px;
margin: 6px 0;
line-height: 28px;
text-decoration: none;
border-left: 1px solid #393942;
border-right: 1px solid #4f5058;
font-family: Helvetica, Arial, sans-serif;
font-weight: bold;
font-size: 13px;
color: #f3f3f3;
text-shadow: 1px 1px 1px rgba(0,0,0,.6);
-webkit-transition: color .2s ease-in-out;
-moz-transition: color .2s ease-in-out;
-o-transition: color .2s ease-in-out;
-ms-transition: color .2s ease-in-out;
transition: color .2s ease-in-out;
}
.menu li:first-child a { border-left: none; }
.menu li:last-child a{ border-right: none; }
.menu li:hover > a { color: #8fde62; }
.menu ul {
position: absolute;
top: 40px;
left: 0;
opacity: 0;
background: #1f2024;
-webkit-border-radius: 0 0 5px 5px;
-moz-border-radius: 0 0 5px 5px;
border-radius: 0 0 5px 5px;
-webkit-transition: opacity .25s ease .1s;
-moz-transition: opacity .25s ease .1s;
-o-transition: opacity .25s ease .1s;
-ms-transition: opacity .25s ease .1s;
transition: opacity .25s ease .1s;
}
.menu li:hover > ul { opacity: 1; }
.menu ul li {
height: 0;
overflow: hidden;
padding: 0;
-webkit-transition: height .25s ease .1s;
-moz-transition: height .25s ease .1s;
-o-transition: height .25s ease .1s;
-ms-transition: height .25s ease .1s;
transition: height .25s ease .1s;
}
.menu li:hover > ul li {
height: 36px;
overflow: visible;
padding: 0;
}
.menu ul li a {
width: 100px;
padding: 4px 0 4px 40px;
margin: 0;
border: none;
border-bottom: 1px solid #353539;
}
.menu ul li:last-child a { border: none; }
demo here
try also resizing the browser tab to see it in action
On SourceTree for Mac, right click the files you want to discard (in the Files in the working tree list), and choose Reset.
On SourceTree for Windows, right click the files you want to discard (in the Working Copy Changes list), and choose Discard.
On git, you'd simply do:
git reset --hard
to discard changes made to versioned files;
git clean -xdf
to erase new (untracked) files, including ignored ones (the x
option). d
is to also remove untracked directories and f
to force.
You can also look at my blog article, very similar to crazybobs.
This solution also doesn't compromise certificate checking and explains how to add the trusted certs in your own keystore.
http://blog.antoine.li/index.php/2010/10/android-trusting-ssl-certificates/
Wrap the xml in another element
<wrapper>
<parent>
<child>
Text
</child>
</parent>
<parent>
<child>
<grandchild>
Text
</grandchild>
<grandchild>
Text
</grandchild>
</child>
<child>
Text
</child>
</parent>
</wrapper>