xsl:apply-templates
is usually (but not necessarily) used to process all or a subset of children of the current node with all applicable templates. This supports the recursiveness of XSLT application which is matching the (possible) recursiveness of the processed XML.
xsl:call-template
on the other hand is much more like a normal function call. You execute exactly one (named) template, usually with one or more parameters.
So I use xsl:apply-templates
if I want to intercept the processing of an interesting node and (usually) inject something into the output stream. A typical (simplified) example would be
<xsl:template match="foo">
<bar>
<xsl:apply-templates/>
</bar>
</xsl:template>
whereas with xsl:call-template
I typically solve problems like adding the text of some subnodes together, transforming select nodesets into text or other nodesets and the like - anything you would write a specialized, reusable function for.
As an additional remark to your specific question text:
<xsl:call-template name="nodes"/>
This calls a template which is named 'nodes':
<xsl:template name="nodes">...</xsl:template>
This is a different semantic than:
<xsl:apply-templates select="nodes"/>
...which applies all templates to all children of your current XML node whose name is 'nodes'.
Some interesting excerpts from the bash manpage:
When bash is invoked as an interactive login shell, or as a non-interactive shell with the
--login
option, it first reads and executes commands from the file/etc/profile
, if that file exists. After reading that file, it looks for~/.bash_profile
,~/.bash_login
, and~/.profile
, in that order, and reads and executes commands from the first one that exists and is readable. The--noprofile
option may be used when the shell is started to inhibit this behavior.
...
When an interactive shell that is not a login shell is started, bash reads and executes commands from/etc/bash.bashrc
and~/.bashrc
, if these files exist. This may be inhibited by using the--norc
option. The--rcfile
file option will force bash to read and execute commands from file instead of/etc/bash.bashrc
and~/.bashrc
.
So have a look at /etc/profile
or /etc/bash.bashrc
, these files are the right places for global settings. Put something like this in them to set up an environement variable:
export MY_VAR=xxx
The web server is prompting you for a SPNEGO (Simple and Protected GSSAPI Negotiation Mechanism) token.
This is a Microsoft invention for negotiating a type of authentication to use for Web SSO (single-sign-on):
See:
For this particular relationship, you could use np.sign
:
>>> df["C"] = np.sign(df.A - df.B)
>>> df
A B C
a 2 2 0
b 3 1 1
c 1 3 -1
From Visual Studio 2015 consider to use out of the box Memory Usage diagnostic tool to collect and analyze memory usage data.
The Memory Usage tool lets you take one or more snapshots of the managed and native memory heap to help understand the memory usage impact of object types.
Here is the code for you`r class . but this also contains lot of refactoring. Please add a for each rather than for. cheers :)
static int isLeft(ArrayList<String> left, ArrayList<String> right)
{
int f = 0;
for (int i = 0; i < left.size(); i++) {
for (int j = 0; j < right.size(); j++)
{
if (left.get(i).charAt(0) == right.get(j).charAt(0)) {
System.out.println("Grammar is left recursive");
f = 1;
}
}
}
return f;
}
public static void main(String[] args) {
// TODO code application logic here
ArrayList<String> left = new ArrayList<String>();
ArrayList<String> right = new ArrayList<String>();
Scanner sc = new Scanner(System.in);
System.out.println("enter no of prod");
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
System.out.println("enter left prod");
String leftText = sc.next();
left.add(leftText);
System.out.println("enter right prod");
String rightText = sc.next();
right.add(rightText);
}
System.out.println("the productions are");
for (int i = 0; i < n; i++) {
System.out.println(left.get(i) + "->" + right.get(i));
}
int flag;
flag = isLeft(left, right);
if (flag == 1) {
System.out.println("Removing left recursion");
} else {
System.out.println("No left recursion");
}
}
For those who are using Eclipse IDE.
After installing the full MySQL together with mysql client and mysql server and any mysql dev libraries,
You will need to tell Eclipse IDE about the following
Here is how you go about it.
To Add mysql.h
1. GCC C Compiler -> Includes -> Include paths(-l) then click + and add path to your mysql.h In my case it was /usr/include/mysql
To add mysqlclient library and search path to where mysqlclient library see steps 3 and 4.
2. GCC C Linker -> Libraries -> Libraries(-l) then click + and add mysqlcient
3. GCC C Linker -> Libraries -> Library search path (-L) then click + and add search path to mysqlcient. In my case it was /usr/lib64/mysql because I am using a 64 bit Linux OS and a 64 bit MySQL Database.
Otherwise, if you are using a 32 bit Linux OS, you may find that it is found at /usr/lib/mysql
The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity
changes.
Instead you could try the following approach. Change your markup to the following:
<div ng-controller="myAppController" style="text-align:center">
<p style="font-size:28px;">Enter Quantity:
<input type="text" ng-model="quantity"/>
</p>
<button ng-click="calculateQuantity()">Calculate</button>
<h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>
Next, update your controller:
myAppModule.controller('myAppController', function($scope,calculateService) {
$scope.quantity=1;
$scope.quantityResult = 0;
$scope.calculateQuantity = function() {
$scope.quantityResult = calculateService.calculate($scope.quantity, 10);
};
});
Here's a JSBin example that demonstrates the above approach.
The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity
changes.
This would involve updating the template to add an ng-change
on the input, and an ng-if
on the result:
<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>
and
<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>
In the controller add:
$scope.showQuantityResult = false;
$scope.calculateQuantity = function() {
$scope.quantityResult = calculateService.calculate($scope.quantity, 10);
$scope.showQuantityResult = true;
};
$scope.hideQuantityResult = function() {
$scope.showQuantityResult = false;
};
These updates can be seen in this JSBin demo.
In swift you can do it like this:
let isPointInFrame = frame.contains(point)
"frame" is a CGRect and "point" is a CGPoint
I used this for getting Date and Time in a fragment.
private Handler mHandler = new Handler(Looper.getMainLooper());
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root = inflater.inflate(R.layout.fragment_head_screen, container, false);
dateTextView = root.findViewById(R.id.dateView);
hourTv = root.findViewById(R.id.hourView);
Thread thread = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
mHandler.post(new Runnable() {
@Override
public void run() {
//Calendario para obtener fecha & hora
Date currentTime = Calendar.getInstance().getTime();
SimpleDateFormat date_sdf = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat hour_sdf = new SimpleDateFormat("HH:mm a");
String currentDate = date_sdf.format(currentTime);
String currentHour = hour_sdf.format(currentTime);
dateTextView.setText(currentDate);
hourTv.setText(currentHour);
}
});
}
} catch (InterruptedException e) {
Log.v("InterruptedException", e.getMessage());
}
}
};
}
That isn't the Node.js command prompt window. That is a language shell to run JavaScript commands, also known as a REPL.
In Windows, there should be a Node.js command prompt in your Start menu or start screen:
Which will open a command prompt window that looks like this:
From there you can switch directories using the cd
command.
You can use Like
if(condition1 || condition2 || condition3 || ..........)
{
enter code here
}
You could use ng-init in an outer div:
<div ng-init="param='value';">
<div ng-controller="BasketController" >
<label>param: {{value}}</label>
</div>
</div>
The parameter will then be available in your controller's scope:
function BasketController($scope) {
console.log($scope.param);
}
Why not just use a regular for loop?
for(int i = 0; i < 50 && i < listView.Items.Count; i++)
{
ListViewItem lvi = listView.Items[i];
}
Updated to resolve bug pointed out by Ruben and Pragmatrix.
following CSS class helped me in getting two line ellipsis.
.two-line-ellipsis {
padding-left:2vw;
text-overflow: ellipsis;
overflow: hidden;
width: 325px;
line-height: 25px;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
padding-top: 15px;
}
I have a diary class and so i am not writing setting the values again and again
public Diary() {
this.Like = defaultLike;
this.Dislike = defaultDislike;
}
public Diary(string title, string diary): this()
{
this.Title = title;
this.DiaryText = diary;
}
public Diary(string title, string diary, string category): this(title, diary) {
this.Category = category;
}
public Diary(int id, string title, string diary, string category)
: this(title, diary, category)
{
this.DiaryID = id;
}
You could decorate the property you wish controlling its name with the [JsonProperty]
attribute which allows you to specify a different name:
using Newtonsoft.Json;
// ...
[JsonProperty(PropertyName = "FooBar")]
public string Foo { get; set; }
Documentation: Serialization Attributes
It turned out that TCP/IP was enabled for the IPv4 address, but not for the IPv6 address, of THESERVER
.
Apparently some connection attempts ended up using IPv4 and others used IPv6.
Enabling TCP/IP for both IP versions resolved the issue.
The fact that SSMS worked turned out to be coincidental (the first few attempts presumably used IPv4). Some later attempts to connect through SSMS resulted in the same error message.
To enable TCP/IP for additional IP addresses:
Sometimes your Xcode project file gets messed up, especially if you have an old project and first created it with an older version of Xcode/iPhone SDK.
What you need to do is open up the project file in a text editor, search for the 'long string' from your error and manually erase that line.
In fact, you should just go ahead and erase any line that points to any provisioning profiles. Then reopen the project in Xcode, go to the settings and reselect your new profile. This clears up issues like that most of the time.
The lines that point to the provisioning profiles will look like this:
PROVISIONING_PROFILE = "487F3EAC-05FB-4A2A-9EA0-31F1F35760EB";
"PROVISIONING_PROFILE[sdk=iphoneos*]" = "487F3EAC-05FB-4A2A-9EA0-31F1F35760EB";
use chomp
or strip
functions from Ruby:
"abcd\n".chomp => "abcd"
"abcd\n".strip => "abcd"
changing the complie SDk version to API level 21 fixed it for me. then i ran into others issues of deploying the app to my device. i changed the minimun API level to target to what i want and that fixed it.
incase someone is experiencing this again.
You can use:
vim somefile.txt +"%s/\r/\r/g" +wq
Or the dos2unix utility.
css
has variables as well. You can use them like this:
--primaryColor: #ffffff;
--width: 800px;
body {
width: var(--width);
color: var(--primaryColor);
}
.content{
width: var(--width);
background: var(--primaryColor);
}
in Kotlin I wrote these extensions:
fun MenuItem.setTitleColor(color: Int) {
val hexColor = Integer.toHexString(color).toUpperCase().substring(2)
val html = "<font color='#$hexColor'>$title</font>"
this.title = html.parseAsHtml()
}
@Suppress("DEPRECATION")
fun String.parseAsHtml(): Spanned {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(this, Html.FROM_HTML_MODE_LEGACY)
} else {
Html.fromHtml(this)
}
}
and used like this:
menu.findItem(R.id.main_settings).setTitleColor(Color.RED)
This should also work:
AggregateValues("hello", MyList.ConvertAll(c => c.Name).ToArray())
Use selectionStart
, it is compatible with all major browsers.
document.getElementById('foobar').addEventListener('keyup', e => {
console.log('Caret at: ', e.target.selectionStart)
})
_x000D_
<input id="foobar" />
_x000D_
Update: This works only when no type is defined or type="text"
or type="textarea"
on the input.
You can use map
:
List<String> names =
personList.stream()
.map(Person::getName)
.collect(Collectors.toList());
EDIT :
In order to combine the Lists of friend names, you need to use flatMap
:
List<String> friendNames =
personList.stream()
.flatMap(e->e.getFriends().stream())
.collect(Collectors.toList());
I had a similar issue and tried a number of solutions suggested in this thread but found that the SelectionChanged Event was firing before the ComboBox item had actually updated to show the new selection (i.e. so it always gave the contents of the combobox prior to the change occurring).
In order to overcome this, I found that it was better to use the e parameter that is automatically passed to the event handler rather than trying to load the value directly from the combo box.
XAML:
<Window.Resources>
<x:Array x:Key="Combo" Type="sys:String">
<sys:String>Item 1</sys:String>
<sys:String>Item 2</sys:String>
</x:Array>
</Window.Resources>
<Grid>
<ComboBox Name="myCombo" ItemsSource="{StaticResource Combo}" SelectionChanged="ComboBox_SelectionChanged" />
<TextBlock Name="MyTextBlock"></TextBlock>
</Grid>
C#:
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string chosenValue = e.AddedItems[0].ToString();
}
You need to check out the attr
method in the jQuery docs. You are misusing it. What you are doing within the if statements simply replaces all image tags src
with the string specified in the 2nd parameter.
A better way to approach replacing a series of images source would be to loop through each and check it's source.
Example:
$('img').each(function () {
var curSrc = $(this).attr('src');
if ( curSrc === 'http://example.com/smith.gif' ) {
$(this).attr('src', 'http://example.com/johnson.gif');
}
if ( curSrc === 'http://example.com/williams.gif' ) {
$(this).attr('src', 'http://example.com/brown.gif');
}
});
Looking at :help tabs it doesn't look like vim wants to work the way you do...
Buffers are shared across tabs, so it doesn't seem possible to lock a given buffer to appear only on a certain tab.
It's a good idea, though.
You could probably get the effect you want by using a terminal that supports tabs, like multi-gnome-terminal, then running vim instances in each terminal tab. Not perfect, though...
Here's a simple method:
public static boolean checkDatePattern(String padrao, String data) {
try {
SimpleDateFormat format = new SimpleDateFormat(padrao, LocaleUtils.DEFAULT_LOCALE);
format.parse(data);
return true;
} catch (ParseException e) {
return false;
}
}
The insert or replace query would insert a new record if id=1 does not already exist.
The update query would only oudate id=1 if it aready exist, it would not create a new record if it didn't exist.
The default size of the arraylist is 10. When we add the 11th ....arraylist increases the size (n*2). The values stored in old arraylist are copied into the new arraylist whose size is 20.
Instead of RenderViewToString
I prefer a approach like
return Json(new { Url = Url.Action("Evil", model) });
then you can catch the result in your javascript and do something like
success: function(data) {
$.post(data.Url, function(partial) {
$('#IdOfDivToUpdate').html(partial);
});
}
Just another note that you can a id/string enum with the following:
class EnumyObjects{
public static BOUNCE={str:"Bounce",id:1};
public static DROP={str:"Drop",id:2};
public static FALL={str:"Fall",id:3};
}
You should remove .Value
from all option buttons because option buttons don't hold the resultant value, the option group control does. If you omit .Value
then the default interface will report the option button status, as you are expecting. You should write all relevant code under commandbutton_click events because whenever the commandbutton is clicked the option button action will run.
If you want to run action code when the optionbutton is clicked then don't write an if loop for that.
EXAMPLE:
Sub CommandButton1_Click
If OptionButton1 = true then
(action code...)
End if
End sub
Sub OptionButton1_Click
(action code...)
End sub
What it seems like to me is that by calling the keys method you're returning to python a dictionary object when it's looking for a list or a tuple. So try taking all of the keys in the dictionary, putting them into a list and then using the for loop.
Is it so important to use IN
statement? Try to use FIND_IN_SET
op.
For example, there is a query in PDO like that
SELECT * FROM table WHERE FIND_IN_SET(id, :array)
Then you only need to bind an array of values, imploded with comma, like this one
$ids_string = implode(',', $array_of_smth); // WITHOUT WHITESPACES BEFORE AND AFTER THE COMMA
$stmt->bindParam('array', $ids_string);
and it's done.
UPD: As some people pointed out in comments to this answer, there are some issues which should be stated explciitly.
FIND_IN_SET
doesn't use index in a table, and it is still not implemented yet - see this record in the MYSQL bug tracker. Thanks to @BillKarwin for the notice.implode
since you use comma symbol as a separator. Thanks to @VaL for the note.In fine, if you are not heavily dependent on indexes and do not use strings with comma for search, my solution will be much easier, simpler, and faster than solutions listed above.
The short version is: The efficient way to use readlines()
is to not use it. Ever.
I read some doc notes on
readlines()
, where people has claimed that thisreadlines()
reads whole file content into memory and hence generally consumes more memory compared to readline() or read().
The documentation for readlines()
explicitly guarantees that it reads the whole file into memory, and parses it into lines, and builds a list
full of str
ings out of those lines.
But the documentation for read()
likewise guarantees that it reads the whole file into memory, and builds a str
ing, so that doesn't help.
On top of using more memory, this also means you can't do any work until the whole thing is read. If you alternate reading and processing in even the most naive way, you will benefit from at least some pipelining (thanks to the OS disk cache, DMA, CPU pipeline, etc.), so you will be working on one batch while the next batch is being read. But if you force the computer to read the whole file in, then parse the whole file, then run your code, you only get one region of overlapping work for the entire file, instead of one region of overlapping work per read.
You can work around this in three ways:
readlines(sizehint)
, read(size)
, or readline()
.mmap
the file, which allows you to treat it as a giant string without first reading it in.For example, this has to read all of foo
at once:
with open('foo') as f:
lines = f.readlines()
for line in lines:
pass
But this only reads about 8K at a time:
with open('foo') as f:
while True:
lines = f.readlines(8192)
if not lines:
break
for line in lines:
pass
And this only reads one line at a time—although Python is allowed to (and will) pick a nice buffer size to make things faster.
with open('foo') as f:
while True:
line = f.readline()
if not line:
break
pass
And this will do the exact same thing as the previous:
with open('foo') as f:
for line in f:
pass
Meanwhile:
but should the garbage collector automatically clear that loaded content from memory at the end of my loop, hence at any instant my memory should have only the contents of my currently processed file right ?
Python doesn't make any such guarantees about garbage collection.
The CPython implementation happens to use refcounting for GC, which means that in your code, as soon as file_content
gets rebound or goes away, the giant list of strings, and all of the strings within it, will be freed to the freelist, meaning the same memory can be reused again for your next pass.
However, all those allocations, copies, and deallocations aren't free—it's much faster to not do them than to do them.
On top of that, having your strings scattered across a large swath of memory instead of reusing the same small chunk of memory over and over hurts your cache behavior.
Plus, while the memory usage may be constant (or, rather, linear in the size of your largest file, rather than in the sum of your file sizes), that rush of malloc
s to expand it the first time will be one of the slowest things you do (which also makes it much harder to do performance comparisons).
Putting it all together, here's how I'd write your program:
for filename in os.listdir(input_dir):
with open(filename, 'rb') as f:
if filename.endswith(".gz"):
f = gzip.open(fileobj=f)
words = (line.split(delimiter) for line in f)
... my logic ...
Or, maybe:
for filename in os.listdir(input_dir):
if filename.endswith(".gz"):
f = gzip.open(filename, 'rb')
else:
f = open(filename, 'rb')
with contextlib.closing(f):
words = (line.split(delimiter) for line in f)
... my logic ...
It's weird that no one has mentioned the obvious - foreach allocates memory (in the form of an iterator), whereas a normal for loop does not allocate any memory. For games on Android, this is a problem, because it means that the garbage collector will run periodically. In a game you don't want the garbage collector to run... EVER. So don't use foreach loops in your draw (or render) method.
Since Xcode's newest version there is a better solution to this:
With @IBInspectable
you can set Attributes directly from within the Attributes Inspector
.
This sets the User Defined Runtime Attributes
for you:
There are two approaches to set this up:
Option 1 (with live updating in Storyboard)
MyCustomView
.UIView
.@IBDesignable
(this makes the View update live).*@IBInspectable
MyCustomView
`
@IBDesignable
class MyCustomView: UIView {
@IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = cornerRadius > 0
}
}
@IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable var borderColor: UIColor? {
didSet {
layer.borderColor = borderColor?.CGColor
}
}
}
* @IBDesignable
only works when set at the start of class MyCustomView
Option 2 (not working since Swift 1.2, see comments)
Extend your UIView Class:
extension UIView {
@IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = cornerRadius > 0
}
}
@IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable var borderColor: UIColor? {
didSet {
layer.borderColor = borderColor?.CGColor
}
}
}
This way, your default View always has those extra editable fields in Attributes Inspector
. Another advantage is that you don't have to change the class to MycustomView
every time.
However, one drawback to this is that you will only see your changes when you run your app.
Select ValidUntil + 1
from Documents
The above SQL won't work with a DateTime2 field. It returns and error "Operand type clash: datetime2 is incompatible with int"
Adding 1 to get the next day is something developers have been doing with dates for years. Now Microsoft have a super new datetime2 field that cannot handle this simple functionality.
"Let's use this new type that is worse than the old one", I don't think so!
Fragments lives within the Activity and has:
Think of Fragments as a sub activity of the main activity it belongs to, it cannot exist of its own and it can be called/reused again and again. Hope this helps :)
I solved a similar problem by enveloping all css instructions in a php echo and then saving it as a php file (ofcourse starting and ending the file with the php tags), and then included the php file. This was a necessity as a redirect followed (header ("somefilename.php")) and no html code is allowed before a redirect.
Restart Netbeans & it solved my problem.
Huffman encoding is a sensible option here. Gzip and friends do this, but the way they work is to build a Huffman tree for the input, send that, then send the data encoded with the tree. If the tree is large relative to the data, there may be no not saving in size.
However, it is possible to avoid sending a tree: instead, you arrange for the sender and receiver to already have one. It can't be built specifically for every string, but you can have a single global tree used to encode all strings. If you build it from the same language as the input strings (English or whatever), you should still get good compression, although not as good as with a custom tree for every input.
That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:
DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87
Double check your table definition. Maybe you just missed adding something.
I also tried google-ing this problem and saw this:
http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode
cd $ANDROID_HOME/tools/bin
yes | ./sdkmanager --update
or
yes | $ANDROID_HOME/tools/bin/sdkmanager --update
I got this same error and managed to fix it by closing Skype and running XAMP as Administrator, works perfectly now. So right click THE XAMP icon and click run as admin.
Let's say you generate a bunch of views that are similar. You could set an OnClickListener
for each view individually:
button1.setOnClickListener(new OnClickListener ... );
button2.setOnClickListener(new OnClickListener ... );
...
Then you have to create a unique onClick
method for each view even if they do the similar things, like:
public void onClick(View v) {
doAction(1); // 1 for button1, 2 for button2, etc.
}
This is because onClick
has only one parameter, a View
, and it has to get other information from instance variables or final local variables in enclosing scopes. What we really want is to get information from the views themselves.
Enter getTag
/setTag
:
button1.setTag(1);
button2.setTag(2);
Now we can use the same OnClickListener for every button:
listener = new OnClickListener() {
@Override
public void onClick(View v) {
doAction(v.getTag());
}
};
It's basically a way for views to have memories.
As per 'dtb' you need to use HttpStatusCode, but following 'zeldi' you need to be extra careful with code responses >= 400.
This has worked for me:
HttpWebResponse response = null;
HttpStatusCode statusCode;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException we)
{
response = (HttpWebResponse)we.Response;
}
statusCode = response.StatusCode;
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
sResponse = reader.ReadToEnd();
Console.WriteLine(sResponse);
Console.WriteLine("Response Code: " + (int)statusCode + " - " + statusCode.ToString());
I made a **
automatic-network-drive connector
** using a batch file.
Suddenly there was a networkdrive called "Data for Analysation", and yeah with the double quotes it works proper!
looks a little bit different but works:
net use y: "\\share.blabla.com\Folder\Subfolder\Data for Analysation" /USER:domain\username PW /PERSISTENT:YES
Thx for the Hint :)
this works (i only tested ie & ff):
<html>
<head>
<style type="text/css">
#parent {
height: 300px;
width: 300px;
background-color: #ccc;
border: 1px solid red;
position: relative;
}
#child {
height: 100px;
width: 30px;
background-color: #eee;
border: 1px solid green;
position: absolute;
bottom: 0;
left: 0;
}
</style>
</head>
<body>
<div id="parent">parent
<div id="child">child</div>
</div>
outside
</body>
</html>
hope that helps.
You probably need to use STR_TO_DATE function:
select * from hockey_stats
where
game_date between STR_TO_DATE('11/3/2012 00:00:00', '%c/%e/%Y %H:%i:%s')
and STR_TO_DATE('11/5/2012 23:59:00', '%c/%e/%Y %H:%i:%s')
order by game_date desc;
(if game_date is a string, you might need to use STR_TO_DATE on it)
Most devices have some form of emulated storage. if they support sd cards they are usually mounted to /sdcard
(or some variation of that name) which is usually symlinked to to a directory in /storage
like /storage/sdcard0
or /storage/0
sometimes the emulated storage is mounted to /sdcard
and the actual path is something like /storage/emulated/legacy. You should be able to use to get the downloads directory. You are best off using the api calls to get directories.
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Since the filesystems and sdcard support varies among devices.
see similar question for more info how to access downloads folder in android?
Usually the DownloadManager handles downloads and the files are then accessed by requesting the file's uri fromthe download manager using a file id to get where file was places which would usually be somewhere in the sdcard/ real or emulated since apps can only read data from certain places on the filesystem outside of their data directory like the sdcard
# spliting a string by the length of the string
def len_split(string,sub_string):
n,sub,str1=list(string),len(sub_string),')/^0*/-'
for i in range(sub,len(n)+((len(n)-1)//sub),sub+1):
n.insert(i,str1)
n="".join(n)
n=n.split(str1)
return n
x="divyansh_looking_for_intership_actively_contact_Me_here"
sub="four"
print(len_split(x,sub))
# Result-> ['divy', 'ansh', 'tiwa', 'ri_l', 'ooki', 'ng_f', 'or_i', 'nter', 'ship', '_con', 'tact', '_Me_', 'here']
It can be done with a little bit of extra overhead.
Simply wrap your link in a div, and separate the animation.
the html ..
<div class="animateOnce">
<a class="animateOnHover">me!</a>
</div>
.. and the css ..
.animateOnce {
animation: splash 1s normal forwards ease-in-out;
}
.animateOnHover:hover {
animation: hover 1s infinite alternate ease-in-out;
}
Without explicitly defining the height
I determined I need to apply the flex
value to the parent and grandparent div
elements...
<div style="display: flex;">
<div style="display: flex;">
<img alt="No, he'll be an engineer." src="theknack.png" style="margin: auto;" />
</div>
</div>
If you're using a single element (e.g. dead-centered text in a single flex
element) use the following:
align-items: center;
display: flex;
justify-content: center;
It works for me. Please check if you are using the right imports?
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
Try with cURL request for cross-domain.
If you are working through third party APIs or getting data through CROSS-DOMAIN, it is always recommended to use cURL script (server side) which is more secure.
I always prefer cURL script.
You can also import only ZipFile
:
from zipfile import ZipFile
zf = ZipFile('path_to_file/file.zip', 'r')
zf.extractall('path_to_extract_folder')
zf.close()
Works in Python 2 and Python 3.
One thing missing here: if you have a varying number of elements that you want to put together to something like
WHERE [...] AND (field LIKE '%abc%' OR field LIKE '%def%')
and dont want to assemble a DQL-String yourself, you can use the orX
mentioned above like this:
$patterns = ['abc', 'def'];
$orStatements = $qb->expr()->orX();
foreach ($patterns as $pattern) {
$orStatements->add(
$qb->expr()->like('field', $qb->expr()->literal('%' . $pattern . '%'))
);
}
$qb->andWhere($orStatements);
To know the usage of the specific directory in GB's or TB's in linux the command is,
df -h /dir/inner_dir/
or
df -sh /dir/inner_dir/
and to know the usage of the specific directory in bits in linux the command is,
df-k /dir/inner_dir/
Easiest solution
<button type="button" onclick="window.location.href='{{ url_for( 'move_forward') }}';">Forward</button>
`You can do it by simple loop using Math.trunc() function. if in interview interviewer ask to do it without converting it into string`
let num = 555194154234 ;
let len = 0 ;
const numLen = (num) => {
for(let i = 0; i < num || num == 1 ; i++){
num = Math.trunc(num/10);
len++ ;
}
return len + 1 ;
}
console.log(numLen(num));
restart: on-failure
did the trick for me..see below
---
version: '2.1'
services:
consumer:
image: golang:alpine
volumes:
- ./:/go/src/srv-consumer
working_dir: /go/src/srv-consumer
environment:
AMQP_DSN: "amqp://guest:guest@rabbitmq:5672"
command: go run cmd/main.go
links:
- rabbitmq
restart: on-failure
rabbitmq:
image: rabbitmq:3.7-management-alpine
ports:
- "15672:15672"
- "5672:5672"
Yes the tab character is one character. You can match it in java with "\t".
Internally, Chrome maintains a stack, where $0 is the selected element, $1 is the element that was last selected, $2 would be the one that was selected before $1 and so on.
Here are some of its applications:
Looking at about:config
on Firefox 33 on GNU/Linux (Ubuntu), and searching connections
I found:
network.http.max-connections: 256
That is likely to answer the part is there any limit to the number of active connections per browser, across all domain
network.http.max-persistent-connections-per-proxy: 32
network.http.max-persistent-connections-per-server: 6
skipped two properties...
network.websocket.max-connections: 200
(interesting, seems like they are not limited per server but have a default value lower than global http connections)
Instead of [ngIf] you should use *ngIf like this:
<div *ngIf="isAuth" id="sidebar">
Create your assets directory the same as lib level
like this
projectName
-android
-ios
-lib
-assets
-pubspec.yaml
then your pubspec.yaml like
flutter:
assets:
- assets/images/
now you can use Image.asset("/assets/images/")
There is no real limit -- everything is named with a 160-bit name. The size of the file must be representable in a 64 bit number so no real limit there either.
There is a practical limit, though. I have a repository that's ~8GB with >880,000 files and git gc takes a while. The working tree is rather large so operations that inspect the entire working directory take quite a while. This repo is only used for data storage, though, so it's just a bunch of automated tools that handle it. Pulling changes from the repo is much, much faster than rsyncing the same data.
%find . -type f | wc -l
791887
%time git add .
git add . 6.48s user 13.53s system 55% cpu 36.121 total
%time git status
# On branch master
nothing to commit (working directory clean)
git status 0.00s user 0.01s system 0% cpu 47.169 total
%du -sh .
29G .
%cd .git
%du -sh .
7.9G .
Is that an actual compiler error or a Code Analysis error? Some times the code analysis can be a bit sketchy and report non-valid errors.
To turn off code analysis for the project, right click on your project in the Project Explorer, click on Properties, then go to the C/C++ General tab, then Code Analysis. Then click on "Use Project Settings" and disable the ones that you do not wish for.
Also, are you sure you are compiling with the C++11 compiler?
A good option is to use an API like Docverter. Docverter will allow you to convert HTML to PDF or DOCX using an API.
There are several ways to go about this, it depends what your purpose is, if you just want to execute the function as well and in the same context, you can use .apply()
:
function init(){
doSomething();
}
function myFunc(){
init.apply(this, arguments);
doSomethingHereToo();
}
If you want to replace it with a newer init
, it'd look like this:
function init(){
doSomething();
}
//anytime later
var old_init = init;
init = function() {
old_init.apply(this, arguments);
doSomethingHereToo();
};
This code creates a nice vertical scrollbar for me in Firefox and Chrome:
#answerform {
position: absolute;
border: 5px solid gray;
padding: 5px;
background: white;
width: 300px;
height: 400px;
overflow-y: scroll;
}
_x000D_
<div id='answerform'>
badger<br><br>badger<br><br>badger<br><br>badger<br><br>badger<br><br> mushroom
<br><br>mushroom<br><br> a badger<br><br>badger<br><br>badger<br><br>badger<br><br>badger<br><br>
</div>
_x000D_
Here is a JS fiddle demo proving the above works.
Somewhere you have to keep track of what button had been pressed. When things happen, you need to store something in a variable so you can recall the information or it's gone forever.
When someone pressed one of the operator buttons, don't just let them type in another value. Save the operator symbol, then let them type in another value. You could literally just have a String operator
that gets the text of the operator button pressed. Then, when the equals button is pressed, you have to check to see which operator you stored. You could do this with an if/else if/else chain.
So, in your symbol's button press event, store the symbol text in a variable, then, in the = button press event, check to see which symbol is in the variable and act accordingly.
Alternatively, if you feel comfortable enough with enums (looks like you're just starting, so if you're not to that point yet, ignore this), you could have an enumeration of symbols that lets you check symbols easily with a switch.
awk
and tools like it (I'm staring at you sed
...) should be relegated to the dustbin of old projects, with code that everyone is too afraid to touch since it was written in a read-never language.
Or you're the relatively rare project that needs to prioritize CPU usage optimization over code maintenance optimization... in which case, carry on.
If not, though, why not instead just use something readable and explicit, such as python
? Your fellow coders and future self will thank you. You can use python
inline with bash just like all the others.
num1=3.17648E-22
num2=1.5
if python -c "exit(0 if $num1 < $num2 else 1)"; then
echo "yes, $num1 < $num2"
else
echo "no, $num1 >= $num2"
fi
Note: The title of this question used to be something like "How to printf in python?"
Since people may come here looking for it based on the title, Python also supports printf-style substitution:
>>> strings = [ "one", "two", "three" ]
>>>
>>> for i in xrange(3):
... print "Item %d: %s" % (i, strings[i])
...
Item 0: one
Item 1: two
Item 2: three
And, you can handily multiply string values:
>>> print "." * 10
..........
You can use this, in a controller method or in an inline function of a route:
try {
DB::connection()->getPdo();
if(DB::connection()->getDatabaseName()){
echo "Yes! Successfully connected to the DB: " . DB::connection()->getDatabaseName();
}else{
die("Could not find the database. Please check your configuration.");
}
} catch (\Exception $e) {
die("Could not open connection to database server. Please check your configuration.");
}
arrays:
malloc
);sizeof
(hence the common idiom sizeof(arr)/sizeof(*arr)
, that however fails silently when used inadvertently on a pointer);std::vector
:
&vec[0]
is guaranteed to work as expected);begin()
/end()
methods, the usual STL typedef
s, ...)Also consider the "modern alternative" to arrays - std::array
; I already described in another answer the difference between std::vector
and std::array
, you may want to have a look at it.
brew switch libfoo mycopy
You can use brew switch
to switch between versions of the same package, if it's installed as versioned subdirectories under Cellar/<packagename>/
This will list versions installed ( for example I had Cellar/sdl2/2.0.3
, I've compiled into Cellar/sdl2/2.0.4
)
brew info sdl2
Then to switch between them
brew switch sdl2 2.0.4
brew info
Info now shows *
next to the 2.0.4
To install under Cellar/<packagename>/<version>
from source you can do for example
cd ~/somewhere/src/foo-2.0.4
./configure --prefix $(brew --Cellar)/foo/2.0.4
make
check where it gets installed with
make install -n
if all looks correct
make install
Then from cd $(brew --Cellar)
do the switch between version.
I'm using brew version 0.9.5
Consider a post url with parameters user and email
params object will be
var data = {user:'john', email:'[email protected]'};
$http({
url: "login.php",
method: "POST",
params: data
})
it doenst work for me but it prints the correct element to the console
this is the code:
function click(x, y)
{
var ev = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true,
'screenX': x,
'screenY': y
});
var el = document.elementFromPoint(x, y);
console.log(el); //print element to console
el.dispatchEvent(ev);
}
click(400, 400);
The easiest solution would be to use Wireshark and trace the HTTP tcp flow.
Along with the points made by others, the $=
selector is the "ends with" selector. You will want the *=
(contains) selector, like so:
$('a').each(function() {
if ($(this).is('[href*="?"')) {
alert("Contains questionmark");
}
});
As noted by Matt Ball, unless you will need to also manipulate links without a question mark (which may be the case, since you say your example is simplified), it would be less code and much faster to simply select only the links you want to begin with:
$('a[href*="?"]').each(function() {
alert("Contains questionmark");
});
The Best solution is this badass one-liner:
String hex=DatatypeConverter.printHexBinary(byte[] b);
as mentioned here
Short answer:
As written in xsd:
<xs:attribute name="minOccurs" type="xs:nonNegativeInteger" use="optional" default="1"/>
<xs:attribute name="maxOccurs" type="xs:allNNI" use="optional" default="1"/>
If you provide an attribute with number, then the number is boundary. Otherwise attribute should appear exactly once.
You can do something like
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next().toString();
Integer value = map.get(key);
System.out.println(key + " " + value);
}
Here 'map' is your concurrent HashMap.
Can em.flush() cause any harm when using it within a transaction?
Yes, it may hold locks in the database for a longer duration than necessary.
Generally, When using JPA you delegates the transaction management to the container (a.k.a CMT - using @Transactional annotation on business methods) which means that a transaction is automatically started when entering the method and commited / rolled back at the end. If you let the EntityManager handle the database synchronization, sql statements execution will be only triggered just before the commit, leading to short lived locks in database. Otherwise your manually flushed write operations may retain locks between the manual flush and the automatic commit which can be long according to remaining method execution time.
Notes that some operation automatically triggers a flush : executing a native query against the same session (EM state must be flushed to be reachable by the SQL query), inserting entities using native generated id (generated by the database, so the insert statement must be triggered thus the EM is able to retrieve the generated id and properly manage relationships)
You need to put that code into the constructor of your class:
private Reminders reminder = new Reminders();
private dynamic defaultReminder;
public YourClass()
{
defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)];
}
The reason is that you can't use one instance variable to initialize another one using a field initializer.
That's also my last problem. Here my solution I use data Model and adapter for my RecyclerView
/*Firstly, register your new data to your model*/
DataModel detail = new DataModel(id, name, sat, image);
/*after that, use set to replace old value with the new one*/
int index = 4;
mData.set(index, detail);
/*finally, refresh your adapter*/
if(adapter!=null)
adapter.notifyItemChanged(index);
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class ErrorDialog {
public static void main(String argv[]) {
String message = "\"The Comedy of Errors\"\n"
+ "is considered by many scholars to be\n"
+ "the first play Shakespeare wrote";
JOptionPane.showMessageDialog(new JFrame(), message, "Dialog",
JOptionPane.ERROR_MESSAGE);
}
}
var example = "I am too long string";
var result;
// Slice is JS function
result = example.slice(0, 10)+'...'; //if you need dots after the string you can add
Result variable contains "I am too l..."
I am using a custom static class which makes- shows and hides a dialog. this class is being used by other activities too not only one activiy. Now the problem you described also appeared to me and i have stayed overnight to find a solution..
Finally i present you the solution!
if you want to show or dismiss a dialog and you dont know which activity initiated the dialog in order to touch it then the following code is for you..
static class CustomDialog{
public static void initDialog(){
...
//init code
...
}
public static void showDialog(){
...
//init code for show dialog
...
}
/****This is your Dismiss dialog code :D*******/
public static void dismissProgressDialog(Context context) {
//Can't touch other View of other Activiy..
//http://stackoverflow.com/questions/23458162/dismiss-progress-dialog-in-another-activity-android
if ( (progressdialog != null) && progressdialog.isShowing()) {
//is it the same context from the caller ?
Log.w("ProgressDIalog dismiss", "the dialog is from"+progressdialog.getContext());
Class caller_context= context.getClass();
Activity call_Act = (Activity)context;
Class progress_context= progressdialog.getContext().getClass();
Boolean is_act= ( (progressdialog.getContext()) instanceof Activity )?true:false;
Boolean is_ctw= ( (progressdialog.getContext()) instanceof ContextThemeWrapper )?true:false;
if (is_ctw) {
ContextThemeWrapper cthw=(ContextThemeWrapper) progressdialog.getContext();
Boolean is_same_acivity_with_Caller= ((Activity)(cthw).getBaseContext() == call_Act )?true:false;
if (is_same_acivity_with_Caller){
progressdialog.dismiss();
progressdialog = null;
}
else {
Log.e("ProgressDIalog dismiss", "the dialog is NOT from the same context! Can't touch.."+((Activity)(cthw).getBaseContext()).getClass());
progressdialog = null;
}
}
}
}
}
In the construct you have provided, you don't need a CONTINUE. Once the exception is handled, the statement after the END is performed, assuming your EXCEPTION block doesn't terminate the procedure. In other words, it will continue on to the next iteration of the user_rec loop.
You also need to SELECT INTO a variable inside your BEGIN block:
SELECT attr INTO v_attr FROM attribute_table...
Obviously you must declare v_attr as well...
I had the same issue here. As Magnus said above, for me it was happening due to an SDK update to version 22.0.5.
After performing a full update in my Android SDK (including Google Play Services) and Android plugins in Eclipse, I was able to use play services lib in my application.
Try a using namespace std;
at the top of game.h
or use the fully-qualified std::string
instead of string
.
The namespace
in game.cpp
is after the header is included.
You do not have to install urllib3
. You can choose any HTTP-request-making library that fits your needs and feed the response to BeautifulSoup
. The choice is though usually requests
because of the rich feature set and convenient API. You can install requests
by entering pip install requests
in the command line. Here is a basic example:
from bs4 import BeautifulSoup
import requests
url = "url"
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
Based on the docs, xhr
Ajax event would fire when an Ajax request is completed. So you can do something like this:
let data_table = $('#example-table').dataTable({
ajax: "data.json"
});
data_table.on('xhr.dt', function ( e, settings, json, xhr ) {
// Do some staff here...
$('#status').html( json.status );
} )
I had the same issue with XUnit. The problem was with my database connection. Check your connection string is correct or not.
This is the only way that worked for me. Installing packages and reinstalling PIL didn't work.
On ubuntu, install the required package:
sudo apt-get install libjpeg-dev
(you may also want to install libfreetype6 libfreetype6-dev zlib1g-dev
to enable other decoders).
Then replace PIL with pillow:
pip uninstall PIL
pip install pillow
sc delete "service name"
will delete a service. I find that the sc utility is much easier to locate than digging around for installutil. Remember to stop the service if you have not already.
You need to stringify the json, not calling toString
var buf = Buffer.from(JSON.stringify(obj));
And for converting string to json obj :
var temp = JSON.parse(buf.toString());
By default git push
updates all the remote branches. But you can configure git to update only the current branch to it's upstream.
git config push.default upstream
It means git will update only the current (checked out) branch when you do git push.
Other valid options are:
nothing
: Do not push anything (error out) unless a refspec is explicitly given. This is primarily meant for people who want to avoid mistakes by always being explicit.matching
: Push all branches having the same name on both ends. (default option prior to Ver 1.7.11) upstream
: Push the current branch to its upstream
branch. This mode only makes sense if you are pushing to the same repository you would normally pull from (i.e. central workflow). No need to have the same name for local and remote branch.tracking
: Deprecated, use upstream
instead.current
: Push the current branch to the remote branch of the same name on the receiving end. Works in both central and non-central workflows.simple
: [available since Ver 1.7.11] in centralized workflow, work like upstream
with an added safety to refuse to push if the upstream branch’s name is different from the local one. When pushing to a remote that is different from the remote you normally pull from, work as current
. This is the safest option and is suited for beginners. This mode has become the default in Git 2.0.Since macOS 10.12.1 it is possible to remap Caps Lock to Esc natively (System Preferences -> Keyboard -> Modifier Keys).
cycles, arrays, regexp... for what? It can be much quicker :)
function isVowel(char)
{
return char === 'a' || char === 'e' || char === 'i' || char === 'o' || char === 'u' || false;
}
If you are really about to work on multi-gigabyte text files then do not use PowerShell. Even if you find a way to read it faster processing of huge amount of lines will be slow in PowerShell anyway and you cannot avoid this. Even simple loops are expensive, say for 10 million iterations (quite real in your case) we have:
# "empty" loop: takes 10 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) {} }
# "simple" job, just output: takes 20 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) { $i } }
# "more real job": 107 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) { $i.ToString() -match '1' } }
UPDATE: If you are still not scared then try to use the .NET reader:
$reader = [System.IO.File]::OpenText("my.log")
try {
for() {
$line = $reader.ReadLine()
if ($line -eq $null) { break }
# process the line
$line
}
}
finally {
$reader.Close()
}
UPDATE 2
There are comments about possibly better / shorter code. There is nothing wrong with the original code with for
and it is not pseudo-code. But the shorter (shortest?) variant of the reading loop is
$reader = [System.IO.File]::OpenText("my.log")
while($null -ne ($line = $reader.ReadLine())) {
$line
}
You have to disable or enable the individual elements. This is how I did it:
$(':input').keydown(function(e){
var allowTab = true;
var id = $(this).attr('name');
// insert your form fields here -- (:'') is required after
var inputArr = {username:'', email:'', password:'', address:''}
// allow or disable the fields in inputArr by changing true / false
if(id in inputArr) allowTab = false;
if(e.keyCode==9 && allowTab==false) e.preventDefault();
});
Ignoring the specific needs of this question, and while its never a good idea to cast a string to a bool, one way would be to use the ToBoolean() method on the Convert class:
bool val = Convert.ToBoolean("true");
or an extension method to do whatever weird mapping you're doing:
public static class StringExtensions
{
public static bool ToBoolean(this string value)
{
switch (value.ToLower())
{
case "true":
return true;
case "t":
return true;
case "1":
return true;
case "0":
return false;
case "false":
return false;
case "f":
return false;
default:
throw new InvalidCastException("You can't cast that value to a bool!");
}
}
}
apache-tomcat-8.0.33
If you want to enable debug logging in tomcat for TLD scanned jars then you have to change /conf/logging.properties file in tomcat directory.
uncomment the line :
org.apache.jasper.servlet.TldScanner.level = FINE
FINE level is for debug log.
This should work for normal tomcat.
If the tomcat is running under eclipse. Then you have to set the path of tomcat logging.properties in eclipse.
Now the jar files that scanned for TLDs should show in the log.
e.stopPropagation()
is a correct solution, but in case you don't want to attach any event handler to your inner anchor, you can simply attach this handler to your outer div:
e => { e.target === e.currentTarget && window.location = URL; }
Download newest Support library with the sdk manager and include
compile 'com.android.support:appcompat-v7:23.1.1'
in gradle.app and set compile version to api 23
I ran into this problem when using tomcat-embed-core::7.0.47
, from Maven. I'm not sure why they didn't add tomcat-util
as a runtime dependency, so I added my own runtime dependency to my own project.
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-util</artifactId>
<version><!-- version from tomcat-embed-core --></version>
<scope>runtime</scope>
</dependency>
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) _
Handles Button3.Click
Dim box = New AboutBox1()
box.Show()
End Sub
This what worked for me. set HeaderStyle-Width="5%", in the footer set textbox width Width="15",also set the width of your gridview to 100%. following is the one of the column of my gridview.
<asp:TemplateField HeaderText = "sub" HeaderStyle-ForeColor="White" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:Label ID="sub" runat="server" Font-Size="small" Text='<%# Eval("sub")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_sub" runat="server" Text='<%# Eval("sub")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txt_sub" runat="server" Width="15"></asp:TextBox>
</FooterTemplate>
>>> l = raw_input()
1 2 3 4 5 6 7 8 9 10
>>> l = l.split()
>>> l.pop(0)
'1'
>>> sum(map(int, l)) #or simply sum(int(x) for x in l) , you've to convert the elements to integer first, before applying sum()
54
Try this
cd repo1
This will remove all the directories except the ones mentioned, preserving history only for these directories
git filter-branch --index-filter 'git rm --ignore-unmatch --cached -qr -- . && git reset -q $GIT_COMMIT -- dir1/ dir2/ dir3/ ' --prune-empty -- --all
Now you can add your new repo in your git remote and push it to that
git remote remove origin <old-repo>
git remote add origin <new-repo>
git push origin <current-branch>
add -f
to overwrite
I'm using 64 bit Eclipse for PHP Devleopers Version: Helios Service Release 2
It cam with RSE..
None of the above solutions worked for me... What I did was similar to scubabble's answer, but after clicking the down arrow (view menu) in the top of the RSE package explorer I had to mouseover "Preferences" and click on "Remote Systems"
I then opened the "Remote Systems" nav tree in the left of the preferences window that came u and went to "Files"
Underneath a list of File types is a checkbox that was unchecked: "Show hidden files"
CHECK IT!
Just wrap your WebElement into Select Object as shown below
Select dropdown = new Select(driver.findElement(By.id("identifier")));
Once this is done you can select the required value in 3 ways. Consider an HTML file like this
<html>
<body>
<select id = "designation">
<option value = "MD">MD</option>
<option value = "prog"> Programmer </option>
<option value = "CEO"> CEO </option>
</option>
</select>
<body>
</html>
Now to identify dropdown do
Select dropdown = new Select(driver.findElement(By.id("designation")));
To select its option say 'Programmer' you can do
dropdown.selectByVisibleText("Programmer ");
or
dropdown.selectByIndex(1);
or
dropdown.selectByValue("prog");
Happy Coding :)
Use //NOSONAR on the line you get warning if it is something you cannot help your code with. It works!
I also agree with the OP that all these things should come with Python already set. I guess we will have to deal with it until that day comes. Here is a solution that actually worked for me :
installing easy_install faster and easier
I hope it helps you or anyone with the same problem!
Another way, using cut
instead of sed
.
result=`echo $pid | cut -c 5-`
Lift-json is at version 2.6 and it works really well (and is also very well supported, the maintainer is always ready to fix any bugs users may find. You can find examples using it on the github repository
The maintainer (Joni Freeman) is always reachable on the Lift mailing list. There are also other users on the mailing list who are very helpful as well.
As @Alexey points out, if you want to use the library with other Scala version, say 2.11.x
, change scalaVersion
and use %%
as follows:
scalaVersion := "2.11.5"
"net.liftweb" %% "lift-json" % "2.6"
You can check the liftweb.net site to find out the latest version as time goes by.
I am going to use a very simple snippet to illustrate the difference:
test = pd.DataFrame({'id':[1,2,3,1,2,3,1,2,3], 'price':[1,2,3,2,3,1,3,1,2]})
grouping = test.groupby('id')['price']
The DataFrame looks like this:
id price
0 1 1
1 2 2
2 3 3
3 1 2
4 2 3
5 3 1
6 1 3
7 2 1
8 3 2
There are 3 customer IDs in this table, each customer made three transactions and paid 1,2,3 dollars each time.
Now, I want to find the minimum payment made by each customer. There are two ways of doing it:
Using apply
:
grouping.min()
The return looks like this:
id
1 1
2 1
3 1
Name: price, dtype: int64
pandas.core.series.Series # return type
Int64Index([1, 2, 3], dtype='int64', name='id') #The returned Series' index
# lenght is 3
Using transform
:
grouping.transform(min)
The return looks like this:
0 1
1 1
2 1
3 1
4 1
5 1
6 1
7 1
8 1
Name: price, dtype: int64
pandas.core.series.Series # return type
RangeIndex(start=0, stop=9, step=1) # The returned Series' index
# length is 9
Both methods return a Series
object, but the length
of the first one is 3 and the length
of the second one is 9.
If you want to answer What is the minimum price paid by each customer
, then the apply
method is the more suitable one to choose.
If you want to answer What is the difference between the amount paid for each transaction vs the minimum payment
, then you want to use transform
, because:
test['minimum'] = grouping.transform(min) # ceates an extra column filled with minimum payment
test.price - test.minimum # returns the difference for each row
Apply
does not work here simply because it returns a Series of size 3, but the original df's length is 9. You cannot integrate it back to the original df easily.
Here is a really simple way to set the timeout:
RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());
private ClientHttpRequestFactory getClientHttpRequestFactory() {
int timeout = 5000;
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory =
new HttpComponentsClientHttpRequestFactory();
clientHttpRequestFactory.setConnectTimeout(timeout);
return clientHttpRequestFactory;
}
You can optionally overload the = operator for the variable and can put the breakpoint inside the overloaded function on specific condition.
Parcelable state;
@Override
public void onPause() {
// Save ListView state @ onPause
Log.d(TAG, "saving listview state");
state = listView.onSaveInstanceState();
super.onPause();
}
...
@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Set new items
listView.setAdapter(adapter);
...
// Restore previous state (including selected item index and scroll position)
if(state != null) {
Log.d(TAG, "trying to restore listview state");
listView.onRestoreInstanceState(state);
}
}
list is mutable
Change
last_list=last_list.append(p.last_name)
to
last_list.append(p.last_name)
will work
My problem was Cisco Anyconnect VPN interfered with internal docker networking
to fix this go to:
Cisco Anyconnect Settings > Preferences >
check Allow local (LAN) access when using VPN
In the Bootstrap 3 .LESS source code, there is a variable defined in variables.less
called @grid-float-breakpoint
which has the following helpful comment:
//**Point at which the navbar becomes uncollapsed
@grid-float-breakpoint: @screen-sm-min;
The matching @grid-float-breakpoint-max
value is set to that minus 1px:
//**Point at which the navbar begins collapsing
@grid-float-breakpoint-max: (@grid-float-breakpoint-max - 1);
So just set the @grid-float-breakpoint
value to 1000px instead and rebuild bootstrap.less
into bootstrap.css
:
e.g.
@grid-float-breakpoint: 1000px;
function getFeed(sender, uri) {
jQuery.getFeed({
url: 'proxy.php?url=' + uri,
success: function(feed) {
jQuery(sender).append('<h2>'
+ '<a href="'
+ feed.link
+ '">'
+ feed.title
+ '</a>'
+ '</h2>');
var html = '';
for(var i = 0; i < feed.items.length && i < 5; i++) {
var item = feed.items[i];
html += '<h3>'
+ '<a href="'
+ item.link
+ '">'
+ item.title
+ '</a>'
+ '</h3>';
html += '<div class="updated">'
+ item.updated
+ '</div>';
html += '<div>'
+ item.description
+ '</div>';
}
jQuery(sender).append(html);
}
});
}
<div id="getanewbrowser">
<script type="text/javascript">
getFeed($("#getanewbrowser"), 'http://feeds.feedburner.com/getanewbrowser')
</script>
</div>
A pixel is the smallest unit value to render something with, but you can trick thickness with optical illusions by modifying colors (the eye can only see up to a certain resolution too).
Here is a test to prove this point:
div { border-color: blue; border-style: solid; margin: 2px; }
div.b1 { border-width: 1px; }
div.b2 { border-width: 0.1em; }
div.b3 { border-width: 0.01em; }
div.b4 { border-width: 1px; border-color: rgb(160,160,255); }
_x000D_
<div class="b1">Some text</div>
<div class="b2">Some text</div>
<div class="b3">Some text</div>
<div class="b4">Some text</div>
_x000D_
Which gives the illusion that the last DIV
has a smaller border width, because the blue border blends more with the white background.
Alpha values may also be used to simulate the same effect, without the need to calculate and manipulate RGB values.
.container {
border-style: solid;
border-width: 1px;
margin-bottom: 10px;
}
.border-100 { border-color: rgba(0,0,255,1); }
.border-75 { border-color: rgba(0,0,255,0.75); }
.border-50 { border-color: rgba(0,0,255,0.5); }
.border-25 { border-color: rgba(0,0,255,0.25); }
_x000D_
<div class="container border-100">Container 1 (alpha = 1)</div>
<div class="container border-75">Container 2 (alpha = 0.75)</div>
<div class="container border-50">Container 3 (alpha = 0.5)</div>
<div class="container border-25">Container 4 (alpha = 0.25)</div>
_x000D_
if you want to display date along with time when you export to Excel then you can use this
xlWorkSheet.Cells(nRow, 3).NumberFormat = "dd/mm/yy h:mm AM/PM"
You were almost there.
Remove protected $dates = ['license_expire']
and then change your LicenseExpire
accessor to:
public function getLicenseExpireAttribute($date)
{
return Carbon::parse($date);
}
This way it will return a Carbon
instance no matter what.
So for your form you would just have $employee->license_expire->format('Y-m-d')
(or whatever format is required) and diffForHumans()
should work on your home page as well.
Hope this helps!
In jsFiddle by default the code you type into the script block is wrapped in a function executed on window.onload:
<script type='text/javascript'>//<![CDATA[
window.onload = function () {
function myFunc(id){
alert(id);
}
}
//]]>
</script>
Because of this, your function myFunc
is not in the global scope so is not available to your html buttons. By changing the option to No-wrap in <head>
as Sergio suggests your code isn't wrapped:
<script type='text/javascript'>//<![CDATA[
function myFunc(id){
alert(id);
}
//]]>
</script>
and so the function is in the global scope and available to your html buttons.
Here is sample c# code that are sending 2 parameters to a bat/cmd file for answer this question.
Comment: how can I pass parameters and read a result of command execution?
Option 1 : Without hiding the console window, passing arguments and without getting the outputs
using System;
using System.Diagnostics;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
System.Diagnostics.Process.Start(@"c:\batchfilename.bat", "\"1st\" \"2nd\"");
}
}
}
Option 2 : Hiding the console window, passing arguments and taking outputs
using System;
using System.Diagnostics;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
var process = new Process();
var startinfo = new ProcessStartInfo(@"c:\batchfilename.bat", "\"1st_arg\" \"2nd_arg\" \"3rd_arg\"");
startinfo.RedirectStandardOutput = true;
startinfo.UseShellExecute = false;
process.StartInfo = startinfo;
process.OutputDataReceived += (sender, argsx) => Console.WriteLine(argsx.Data); // do whatever processing you need to do in this handler
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
}
}
}
Here is another way of doing this by using es6 template literals dynamically at runtime.
const str = 'My name is ${name} and my age is ${age}.'_x000D_
const obj = {name:'Simon', age:'33'}_x000D_
_x000D_
_x000D_
const result = new Function('const {' + Object.keys(obj).join(',') + '} = this.obj;return `' + str + '`').call({obj})_x000D_
_x000D_
document.body.innerHTML = result
_x000D_
Try the following:
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
Also, you can also redirect based on port number, for example:
RewriteCond %{SERVER_PORT} ^80$
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
This will redirect all requests received on port 80 to HTTPS.
You can use the setsockopt function to set a timeout on receive operations:
SO_RCVTIMEO
Sets the timeout value that specifies the maximum amount of time an input function waits until it completes. It accepts a timeval structure with the number of seconds and microseconds specifying the limit on how long to wait for an input operation to complete. If a receive operation has blocked for this much time without receiving additional data, it shall return with a partial count or errno set to [EAGAIN] or [EWOULDBLOCK] if no data is received. The default for this option is zero, which indicates that a receive operation shall not time out. This option takes a timeval structure. Note that not all implementations allow this option to be set.
// LINUX
struct timeval tv;
tv.tv_sec = timeout_in_seconds;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
// WINDOWS
DWORD timeout = timeout_in_seconds * 1000;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof timeout);
// MAC OS X (identical to Linux)
struct timeval tv;
tv.tv_sec = timeout_in_seconds;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
Reportedly on Windows this should be done before calling bind
. I have verified by experiment that it can be done either before or after bind
on Linux and OS X.
add path(:/usr/local/bin/) in profile.
mac: $home/.bash_profile
export PATH=$GOPATH/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/git/bin:$PATH
In addition to other answers need to add that parameters not only helps prevent sql injection but can improve performance of queries. Sql server caching parameterized query plans and reuse them on repeated queries execution. If you not parameterized your query then sql server would compile new plan on each query(with some exclusion) execution if text of query would differ.
A gc-friendly piece of code:
public static<X> X[] arrayOfNotNull(X[] array) {
for (int p=0, N=array.length; p<N; ++p) {
if (array[p] == null) {
int m=p; for (int i=p+1; i<N; ++i) if (array[i]!=null) ++m;
X[] res = Arrays.copyOf(array, m);
for (int i=p+1; i<N; ++i) if (array[i]!=null) res[p++] = array[i];
return res;
}
}
return array;
}
It returns the original array if it contains no nulls. It does not modify the original array.
<div style="position: relative; width:600px;">_x000D_
<p>Content of unknown length</p>_x000D_
<div>Content of unknown height</div>_x000D_
<div id="spacer" style="width: 200px; height: 100px; float:left; display:inline-block"></div>_x000D_
<div class="btn" style="position: absolute; right: 0; bottom: 0; width: 200px; height: 100px;"></div>_x000D_
</div>
_x000D_
This should be a comment but I don't have enough reputation yet. The solution works, but visual studio code told me the following putting it into a css sheet:
inline-block is ignored due to the float. If 'float' has a value other than 'none', the box is floated and 'display' is treated as 'block'
So I did it like this
.spacer {
float: left;
height: 20px;
width: 200px;
}
And it works just as well.
Case 1:Only two activity A and B:
Here Activity flow is A->B .On clicking backbutton from B we need to close the application then while starting Activity B from A just call finish() this will prevent android from storing Activity A in to the Backstack.eg for activity A is Loding/Splash screen of application.
Intent newIntent = new Intent(A.this, B.class);
startActivity(newIntent);
finish();
Case 2:More than two activitiy:
If there is a flow like A->B->C->D->B and on clicking back button in Activity B while coming from Activity D.In that case we should use.
Intent newIntent = new Intent(D.this,B.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(newIntent);
Here Activity B will be started from the backstack rather than a new instance because of Intent.FLAG_ACTIVITY_CLEAR_TOP and Intent.FLAG_ACTIVITY_NEW_TASK clears the stack and makes it the top one.So when we press back button the whole application will be terminated.
You can use (hidden) cells as variables. E.g., you could hide Column C, set C1 to
=20
and use it as
=c1*20
Alternatively you can write VBA Macros which set and read a global variable.
Edit: AKX renders my Answer partially incorrect. I had no idea you could name cells in Excel.
I'll answer for Windows guests. If you have VMware Tools installed, then the taskbar's notification area (near the clock) has an icon for VMware Tools. Double-click that and set your options.
If you don't have VMware Tools installed, you can still set the clock's option for internet time to sync with some NTP server. If your physical machine serves the NTP protocol to your guest machines then you can get that done with host-only networking. Otherwise you'll have to let your guests sync with a genuine NTP server out on the internet, for example time.windows.com.
You have to include the jquery framework in your document head from a cdn for example:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
Then you have to include a own script for example:
(function( $ ) {
$(document).ready(function(){
$('input').click(function() {
$(this).css('background-color', 'green');
}
});
$(window).load(function() {
});
})( jQuery );
This part is a mapping of the $ to jQuery, so actually it is jQuery('selector').function();
(function( $ ) {
})( jQuery );
Here you can find die api of jquery where all functions are listed with examples and explanation: http://api.jquery.com/
For those of you who would rather not go with Regex and are on the .NET 2.0 Framework (AKA no LINQ):
Only Letters:
public static bool IsAllLetters(string s)
{
foreach (char c in s)
{
if (!Char.IsLetter(c))
return false;
}
return true;
}
Only Numbers:
public static bool IsAllDigits(string s)
{
foreach (char c in s)
{
if (!Char.IsDigit(c))
return false;
}
return true;
}
Only Numbers Or Letters:
public static bool IsAllLettersOrDigits(string s)
{
foreach (char c in s)
{
if (!Char.IsLetterOrDigit(c))
return false;
}
return true;
}
Only Numbers Or Letters Or Underscores:
public static bool IsAllLettersOrDigitsOrUnderscores(string s)
{
foreach (char c in s)
{
if (!Char.IsLetterOrDigit(c) && c != '_')
return false;
}
return true;
}
If the server responds to an OPTIONS method and to GET and POST (whichever of them you're using) with a header like:
Access-Control-Allow-Origin: *
It might work OK. Seems to in FireFox 3.5 and rekonq 0.4.0. Apparently, with that header and the initial response to OPTIONS, the server is saying to the browser, "Go ahead and let this cross-domain request go through."
Without any libraries, you could do this instead:
def to_frequency_table(data):
frequencytable = {}
for key in data:
if key in frequencytable:
frequencytable[key] += 1
else:
frequencytable[key] = 1
return frequencytable
Example:
to_frequency_table([1,1,1,1,2,3,4,4])
>>> {1: 4, 2: 1, 3: 1, 4: 2}
I've written a gem that does this for Rails ActiveRecord objects. The example uses created_at, but it will also work on updated_at or anything with the class ActiveSupport::TimeWithZone.
Just gem install and call the 'pretty' method on your TimeWithZone instance.
A semaphore is a counting synchronization mechanism, a mutex isn't.
POST and GET are two HTTP request methods. GET is usually intended to retrieve some data, and is expected to be idempotent (repeating the query does not have any side-effects) and can only send limited amounts of parameter data to the server. GET requests are often cached by default by some browsers if you are not careful.
POST is intended for changing the server state. It carries more data, and repeating the query is allowed (and often expected) to have side-effects such as creating two messages instead of one.
At times you do not want to simply remove the characters, but just remove the accents. I came up with the following utility class which I use in my Java REST web projects whenever I need to include a String in an URL:
import java.text.Normalizer;
import java.text.Normalizer.Form;
import org.apache.commons.lang.StringUtils;
/**
* Utility class for String manipulation.
*
* @author Stefan Haberl
*/
public abstract class TextUtils {
private static String[] searchList = { "Ä", "ä", "Ö", "ö", "Ü", "ü", "ß" };
private static String[] replaceList = { "Ae", "ae", "Oe", "oe", "Ue", "ue",
"sz" };
/**
* Normalizes a String by removing all accents to original 127 US-ASCII
* characters. This method handles German umlauts and "sharp-s" correctly
*
* @param s
* The String to normalize
* @return The normalized String
*/
public static String normalize(String s) {
if (s == null)
return null;
String n = null;
n = StringUtils.replaceEachRepeatedly(s, searchList, replaceList);
n = Normalizer.normalize(n, Form.NFD).replaceAll("[^\\p{ASCII}]", "");
return n;
}
/**
* Returns a clean representation of a String which might be used safely
* within an URL. Slugs are a more human friendly form of URL encoding a
* String.
* <p>
* The method first normalizes a String, then converts it to lowercase and
* removes ASCII characters, which might be problematic in URLs:
* <ul>
* <li>all whitespaces
* <li>dots ('.')
* <li>(semi-)colons (';' and ':')
* <li>equals ('=')
* <li>ampersands ('&')
* <li>slashes ('/')
* <li>angle brackets ('<' and '>')
* </ul>
*
* @param s
* The String to slugify
* @return The slugified String
* @see #normalize(String)
*/
public static String slugify(String s) {
if (s == null)
return null;
String n = normalize(s);
n = StringUtils.lowerCase(n);
n = n.replaceAll("[\\s.:;&=<>/]", "");
return n;
}
}
Being a German speaker I've included proper handling of German umlauts as well - the list should be easy to extend for other languages.
HTH
EDIT: Note that it may be unsafe to include the returned String in an URL. You should at least HTML encode it to prevent XSS attacks.
It sounds like you want the object parameter to be optional, and also each of the properties in the object to be optional. In the example, as provided, overload syntax isn't needed. I wanted to point out some bad practices in some of the answers here. Granted, it's not the smallest possible expression of essentially writing box = { x: 0, y: 87, width: 4, height: 0 }
, but this provides all the code hinting niceties you could possibly want from the class as described. This example allows you to call a function with one, some, all, or none of the parameters and still get default values.
/** @class */
class Box {
public x?: number;
public y?: number;
public height?: number;
public width?: number;
constructor(params: Box = {} as Box) {
// Define the properties of the incoming `params` object here.
// Setting a default value with the `= 0` syntax is optional for each parameter
let {
x = 0,
y = 0,
height = 1,
width = 1
} = params;
// If needed, make the parameters publicly accessible
// on the class ex.: 'this.var = var'.
/** Use jsdoc comments here for inline ide auto-documentation */
this.x = x;
this.y = y;
this.height = height;
this.width = width;
}
}
Need to add methods? A verbose but more extendable alternative:
The Box
class above can work double-duty as the interface since they are identical. If you choose to modify the above class, you will need to define and reference a new interface for the incoming parameters object since the Box
class no longer would look exactly like the incoming parameters. Notice where the question marks (?:
) denoting optional properties move in this case. Since we're setting default values within the class, they are guaranteed to be present, yet they are optional within the incoming parameters object:
interface BoxParams {
x?: number;
// Add Parameters ...
}
class Box {
public x: number;
// Copy Parameters ...
constructor(params: BoxParams = {} as BoxParams) {
let { x = 0 } = params;
this.x = x;
}
doSomething = () => {
return this.x + this.x;
}
}
Whichever way you choose to define your class, this technique offers the guardrails of type safety, yet the flexibility write any of these:
const box1 = new Box();
const box2 = new Box({});
const box3 = new Box({x:0});
const box4 = new Box({x:0, height:10});
const box5 = new Box({x:0, y:87,width:4,height:0});
// Correctly reports error in TypeScript, and in js, box6.z is undefined
const box6 = new Box({z:0});
Compiled, you see how the default settings are only used if an optional value is undefined; it avoids the pitfalls of a widely used (but error-prone) fallback syntax of var = isOptional || default;
by checking against void 0
, which is shorthand for undefined
:
var Box = (function () {
function Box(params) {
if (params === void 0) { params = {}; }
var _a = params.x, x = _a === void 0 ? 0 : _a, _b = params.y, y = _b === void 0 ? 0 : _b, _c = params.height, height = _c === void 0 ? 1 : _c, _d = params.width, width = _d === void 0 ? 1 : _d;
this.x = x;
this.y = y;
this.height = height;
this.width = width;
}
return Box;
}());
||
(or) operatorConsider the danger of ||
/or operators when setting default fallback values as shown in some other answers. This code below illustrates the wrong way to set defaults. You can get unexpected results when evaluating against falsey values like 0, '', null, undefined, false, NaN:
var myDesiredValue = 0;
var result = myDesiredValue || 2;
// This test will correctly report a problem with this setup.
console.assert(myDesiredValue === result && result === 0, 'Result should equal myDesiredValue. ' + myDesiredValue + ' does not equal ' + result);
In my tests, using es6/typescript destructured object can be 15-90% faster than Object.assign. Using a destructured parameter only allows methods and properties you've assigned to the object. For example, consider this method:
class BoxTest {
public x?: number = 1;
constructor(params: BoxTest = {} as BoxTest) {
Object.assign(this, params);
}
}
If another user wasn't using TypeScript and attempted to place a parameter that didn't belong, say, they might try putting a z
property
var box = new BoxTest({x: 0, y: 87, width: 4, height: 0, z: 7});
// This test will correctly report an error with this setup. `z` was defined even though `z` is not an allowed property of params.
console.assert(typeof box.z === 'undefined')
There is an official Microsoft answer to this question at the following knowledge base article:
Unfortunately, it doesn't appear to work, because the mscorlib.dll version in the 2.0 directory has a 2.0 version, and there is no mscorlib.dll version in either the 3.0 or 3.5 directories even though 3.5 SP1 is installed ... why would the official Microsoft answer be so misinformed?
When I had an error Access Error: 404 -- Not Found
I fixed it by doing the following:
8080
and look at its PID
number/code.PID
number. Then right click it and stop the process.To add to the previous answer, an extreme way of "cleaning" your project is to delete it (that is deleting its reference from the workspace, not deleting the actual files), and then re-import it.
Sometimes, it helps...
I had this problem on Mac OS X 10.12.1 with Cordova 6.4.0 and Android Studio 2.2.3.
When I installed Android Studio it installed Platform 25, but not 24. To install 24:
Android Studio Menu > Preferences
.Appearance & Behavior > System Settings > Android SDK
Android 7.0 (Nougat) | 24
Try:
#your_div_id {
width: 855px;
margin:0 auto;
text-align: center;
}
You could check if the index is less than the length of the array. This doesn't check for nulls or other odd cases where the index can be assigned a value but hasn't been given one explicitly.
A couple of plain old foreach
loops provides a clean solution:
foreach (XElement level1Element in XElement.Load("data.xml").Elements("level1"))
{
result.AppendLine(level1Element.Attribute("name").Value);
foreach (XElement level2Element in level1Element.Elements("level2"))
{
result.AppendLine(" " + level2Element.Attribute("name").Value);
}
}
If you are on linux you implement a non-blocking implementation in python in the following way.
import subprocess
subprocess.call('xterm -title log -hold -e \"tail -f filename\"&', shell=True, executable='/bin/csh')
print "Done"
First you have to exhaustively identify the special characters that you want to check.
Then you can write a regular expression and use
public boolean matches(String regex)
SO what i have decided to do finally is here and its working fine on all mobile browsers including iPhones and Androids.
$(document).ready(function(){_x000D_
_x000D_
$('input[type="date"]').each(function(e) {_x000D_
var $el = $(this), _x000D_
$this_placeholder = $(this).closest('label').find('.custom-placeholder');_x000D_
$el.on('change',function(){_x000D_
if($el.val()){_x000D_
$this_placeholder.text('');_x000D_
}else {_x000D_
$this_placeholder.text($el.attr('placeholder'));_x000D_
}_x000D_
});_x000D_
});_x000D_
_x000D_
});
_x000D_
label {_x000D_
position: relative; _x000D_
}_x000D_
.custom-placeholder {_x000D_
#font > .proxima-nova-light(26px,40px);_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
z-index: 10;_x000D_
color: #999;_x000D_
}
_x000D_
<label>_x000D_
<input type="date" placeholder="Date">_x000D_
<span class="custom-placeholder">Date</span>_x000D_
</label>
_x000D_
Date
This might be too little too late but what helped me is the cool sounding 'nuclear' option. Basically using the command filter-branch
you can remove files or change something over a large number of files throughout your entire git history.
It is best explained here.
smaller-size version:
#register a:link {color: #fff}
The easiest way to solve is the to recognize that in javascript dates are just numbers. It starts 0
or 'Wed Dec 31 1969 18:00:00 GMT-0600 (CST)
. Every 1
represents a millisecond. You can add or subtract milliseconds by getting the value and instantiating a new date using that value. You can manage it pretty easy with that mind.
const minutesToAdjust = 10;
const millisecondsPerMinute = 60000;
const originalDate = new Date('11/20/2017 10:00 AM');
const modifiedDate1 = new Date(originalDate.valueOf() - (minutesToAdjust * millisecondsPerMinute));
const modifiedDate2 = new Date(originalDate.valueOf() + (minutesToAdjust * millisecondsPerMinute));
console.log(originalDate); // Mon Nov 20 2017 10:00:00 GMT-0600 (CST)
console.log(modifiedDate1); // Mon Nov 20 2017 09:50:00 GMT-0600 (CST)
console.log(modifiedDate2); // Mon Nov 20 2017 10:10:00 GMT-0600 (CST)
I'm using the Hibernate 4.2.7.SP1 with Postgres 9.3 and following works for me:
@Entity
public class ConfigAttribute {
@Lob
public byte[] getValueBuffer() {
return m_valueBuffer;
}
}
as Oracle has no trouble with that, and for Postgres I'm using custom dialect:
public class PostgreSQLDialectCustom extends PostgreSQL82Dialect {
@Override
public SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) {
if (sqlTypeDescriptor.getSqlType() == java.sql.Types.BLOB) {
return BinaryTypeDescriptor.INSTANCE;
}
return super.remapSqlTypeDescriptor(sqlTypeDescriptor);
}
}
the advantage of this solution I consider, that I can keep hibernate jars untouched.
For more Postgres/Oracle compatibility issues with Hibernate, see my blog post.
Dictionaries in Python are data structures that store key-value pairs. You can use them like associative arrays. Curly braces are used when declaring dictionaries:
d = {'One': 1, 'Two' : 2, 'Three' : 3 }
print d['Two'] # prints "2"
Curly braces are not used to denote control levels in Python. Instead, Python uses indentation for this purpose.
I think you really need some good resources for learning Python in general. See https://stackoverflow.com/q/175001/10077
The function:
function () {}
returns nothing (or undefined).
Sometimes we want to call a function right as we create it. You might be tempted to try this:
function () {}()
but it results in a SyntaxError
.
Using the !
operator before the function causes it to be treated as an expression, so we can call it:
!function () {}()
This will also return the boolean opposite of the return value of the function, in this case true
, because !undefined
is true
. If you want the actual return value to be the result of the call, then try doing it this way:
(function () {})()
I'm pretty certain it is because the DbContext is not at all thread safe. So sharing the thing is never a good idea.
You have to set the weight property of your elements. Create three RelativeLayouts as children to your LinearLayout and set weights 0.15, 0.70, 0.15. Then add your buttons to the second RelativeLayout(the one with weight 0.70).
Like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:id="@+id/layoutContainer" android:orientation="horizontal">
<RelativeLayout
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="0.15">
</RelativeLayout>
<RelativeLayout
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="0.7">
<!-- This is the part that's 70% of the total width. I'm inserting a LinearLayout and buttons.-->
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="vertical">
<Button
android:text="Button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
<Button
android:text="Button2"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
<Button
android:text="Button3"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
</LinearLayout>
<!-- 70% Width End-->
</RelativeLayout>
<RelativeLayout
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="0.15">
</RelativeLayout>
</LinearLayout>
Why are the weights 0.15, 0.7 and 0.15? Because the total weight is 1 and 0.7 is 70% of the total.
Result:
Edit: Thanks to @SimonVeloper for pointing out that the orientation should be horizontal and not vertical and to @Andrew for pointing out that weights can be decimals instead of integers.
Thanks for the help guys. I found another culprit. Recently SimplifyMedia added a photo sharing option. Apparently it too uses port 80 and prevented Apache from starting up. I hope this helps someone out.
How can I remove the middle character, i.e., M from it?
You can't, because strings in Python are immutable.
Do strings in Python end in any special character?
No. They are similar to lists of characters; the length of the list defines the length of the string, and no character acts as a terminator.
Which is a better way - shifting everything right to left starting from the middle character OR creation of a new string and not copying the middle character?
You cannot modify the existing string, so you must create a new one containing everything except the middle character.
Make a list of tuples with your data and then create a DataFrame with it:
d = []
for p in game.players.passing():
d.append((p, p.team, p.passer_rating()))
pd.DataFrame(d, columns=('Player', 'Team', 'Passer Rating'))
A list of tuples should have less overhead than a list dictionaries. I tested this below, but please remember to prioritize ease of code understanding over performance in most cases.
Testing functions:
def with_tuples(loop_size=1e5):
res = []
for x in range(int(loop_size)):
res.append((x-1, x, x+1))
return pd.DataFrame(res, columns=("a", "b", "c"))
def with_dict(loop_size=1e5):
res = []
for x in range(int(loop_size)):
res.append({"a":x-1, "b":x, "c":x+1})
return pd.DataFrame(res)
Results:
%timeit -n 10 with_tuples()
# 10 loops, best of 3: 55.2 ms per loop
%timeit -n 10 with_dict()
# 10 loops, best of 3: 130 ms per loop
The read_sql
docs say this params
argument can be a list, tuple or dict (see docs).
To pass the values in the sql query, there are different syntaxes possible: ?
, :1
, :name
, %s
, %(name)s
(see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2
in your case I suppose).
In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2
documentation, they support the %(name)s
style (and so not the :name
I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:
df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
index_col=['Timestamp'])
There are multiple problems with yaluna's answer, also property names are case sensitive, Installed
is the correct spelling (INSTALLED
will not work).
The table above should've been this:
Also assuming a full repair & uninstall the actual values of properties could be:
The WiX Expression Syntax documentation says:
In these expressions, you can use property names (remember that they are case sensitive).
The properties are documented at the Windows Installer Guide (e.g. Installed)
EDIT: Small correction to the first table; evidently "Uninstall" can also happen with just REMOVE
being True
.
I had the same problem. But just restarting my computer after setting up the Maven path resolved the issue.
Variable Name: M2_Home Variable Value:C:\Apache\apache-maven-3.3.9
Variable Name: Path Variable Value:C:\ProgramData\Oracle\Java\javapath;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;%JAVA_HOME%\bin\;%M2_HOME%\bin\
There is another simple solution to provide custom background for "Flat" buttons while keeping their "Material" effects.
i.e. :
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/blue">
<Button
style="?android:attr/buttonStyleSmall"
android:background="?android:attr/selectableItemBackground"
android:textColor="@android:color/white"
android:textAllCaps="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button1"
/>
</FrameLayout>
Can be used for Flat buttons, it works on API >=11, and you will get ripple effect on >=21 devices, keeping regular buttons on pre-21 till AppCompat is updated to support ripple there as well.
You can also use selectableItemBackgroundBorderless for >=21 buttons only.
The message indicates that the last line of the file doesn't end with an End Of Line (EOL) character (linefeed (\n
) or carriage return+linefeed (\r\n
)). The original intention of this message was to warn you that the file may be incomplete; most datafiles have an EOL character as the very last character in the file.
The remedy is simple:
Since Horse
is a subclass of Animal
, you can just change
print(Animal.SIZES[1])
with
print(self.SIZES[1])
Still, you need to remember that SIZES[1]
means "big", so probably you could improve your code by doing something like:
class Animal:
SIZE_HUGE="Huge"
SIZE_BIG="Big"
SIZE_MEDIUM="Medium"
SIZE_SMALL="Small"
class Horse(Animal):
def printSize(self):
print(self.SIZE_BIG)
Alternatively, you could create intermediate classes: HugeAnimal
, BigAnimal
, and so on. That would be especially helpful if each animal class will contain different logic.
If you want to use the reset_index
method and also preserve your existing index you should use:
df.reset_index().set_index('index', drop=False)
or to change it in place:
df.reset_index(inplace=True)
df.set_index('index', drop=False, inplace=True)
For example:
print(df)
gi ptt_loc
0 384444683 593
4 384444684 594
9 384444686 596
print(df.reset_index())
index gi ptt_loc
0 0 384444683 593
1 4 384444684 594
2 9 384444686 596
print(df.reset_index().set_index('index', drop=False))
index gi ptt_loc
index
0 0 384444683 593
4 4 384444684 594
9 9 384444686 596
And if you want to get rid of the index label you can do:
df2 = df.reset_index().set_index('index', drop=False)
df2.index.name = None
print(df2)
index gi ptt_loc
0 0 384444683 593
4 4 384444684 594
9 9 384444686 596
There are a few more differences regarding the structure you could mention.
Characteristics
member of IMAGE_FILE_HEADER
inside IMAGE_NT_HEADERS
. For a DLL, it has the IMAGE_FILE_DLL
(0x2000) flag turned on. For a EXE it's the IMAGE_FILE_EXECUTABLE_IMAGE
(0x2) flag.IMAGE_OPTIONAL_HEADER
) is the ImageBase
member. It specifies the virtual address at which the PE assumes it will be loaded. If it is loaded at another address, some pointers could point to the wrong memory. As EXE files are amongst the first to be loaded into their new address space, the Windows loader can assure a constant load address and that's usually 0x00400000. That luxury doesn't exist for a DLL. Two DLL files loaded into the same process can request the same address. This is why a DLL has another data directory called Base Relocation Directory that usually resides in its own section - .reloc
. This directory contains a list of places in the DLL that need to be rebased/patched so they'll point to the right memory. Most EXE files don't have this directory, but some old compilers do generate them.You can read more on this topic @ MSDN.
My experience in Visual Studio 2010 is that there are two changes needed so as to not need DLL's. From the project property page (right click on the project name in the Solution Explorer window):
Under Configuration Properties --> General, change the "Use of MFC" field to "Use MFC in a Static Library".
Under Configuration Properties --> C/C++ --> Code Generation, change the "Runtime Library" field to "Multi-Threaded (/MT)"
Not sure why both were needed. I used this to remove a dependency on glut32.dll.
Added later: When making these changes to the configurations, you should make them to "All Configurations" --- you can select this at the top of the Properties window. If you make the change to just the Debug configuration, it won't apply to the Release configuration, and vice-versa.
Get these values from attributes:
int[] attrs = new int[] { android.R.attr.textColorSecondary };
TypedArray a = getTheme().obtainStyledAttributes(R.style.AppTheme, attrs);
DEFAULT_TEXT_COLOR = a.getColor(0, Color.RED);
a.recycle();
I have had good experiences with Rational Purify. I have also heard nice things about Valgrind
To get rid of the bad looking datepicker you need to add jquery-ui css
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css">
Turn the String into a char[], replace the letter by index, then convert the array back into a String.
String myName = "domanokz";
char[] myNameChars = myName.toCharArray();
myNameChars[4] = 'x';
myName = String.valueOf(myNameChars);
In SVG (contrasted with HTML), you will want to use <image>
instead of <img>
for elements.
Try changing your last block with:
var imgs = svg.selectAll("image").data([0]);
imgs.enter()
.append("svg:image")
...
If you're on Windows:
HANDLE h;
CHAR_INFO v3;
COORD v4;
SMALL_RECT v5;
CONSOLE_SCREEN_BUFFER_INFO v6;
if ((h = (HANDLE)GetStdHandle(0xFFFFFFF5), (unsigned int)GetConsoleScreenBufferInfo(h, &v6)))
{
v5.Right = v6.dwSize.X;
v5.Bottom = v6.dwSize.Y;
v3.Char.UnicodeChar = 32;
v4.Y = -v6.dwSize.Y;
v3.Attributes = v6.wAttributes;
v4.X = 0;
*(DWORD *)&v5.Left = 0;
ScrollConsoleScreenBufferW(h, &v5, 0, v4, &v3);
v6.dwCursorPosition = { 0 };
HANDLE v1 = GetStdHandle(0xFFFFFFF5);
SetConsoleCursorPosition(v1, v6.dwCursorPosition);
}
This is what the system("cls"); does without having to create a process to do it.
I disagree with yydi answer saying:
If Android decides to recreate your Fragment later, it's going to call the no-argument constructor of your fragment. So overloading the constructor is not a solution.
I think it is a solution and a good one, this is exactly the reason it been developed by Java core language.
Its true that Android system can destroy and recreate your Fragment
. So you can do this:
public MyFragment() {
// An empty constructor for Android System to use, otherwise exception may occur.
}
public MyFragment(int someInt) {
Bundle args = new Bundle();
args.putInt("someInt", someInt);
setArguments(args);
}
It will allow you to pull someInt
from getArguments()
latter on, even if the Fragment
been recreated by the system. This is more elegant solution than static
constructor.
For my opinion static
constructors are useless and should not be used. Also they will limit you if in the future you would like to extend this Fragment
and add more functionality to the constructor. With static
constructor you can't do this.
Update:
Android added inspection that flag all non-default constructors with an error.
I recommend to disable it, for the reasons mentioned above.
Add a parameter of type UriComponentsBuilder
to your controller method. Spring will give you an instance that's preconfigured with the URI for the current request, and you can then customize it (such as by using MvcUriComponentsBuilder.relativeTo
to point at a different controller using the same prefix).
Is the assembly in the Global Assembly Cache (GAC) or any place the might be overriding the assembly that you think is being loaded? This is usually the result of an incorrect assembly being loaded, for me it means I usually have something in the GAC overriding the version I have in bin/Debug.
When you are going back and forth between scripts it may only sometimes be necessary to unload a package. Here's a simple IF statement that will prevent warnings that would appear if you tried to unload a package that was not currently loaded.
if("package:vegan" %in% search()) detach("package:vegan", unload=TRUE)
Including this at the top of a script might be helpful.
I hope that makes your day!
Class which can have both concrete and non-concrete methods i.e. with and without body.
This is why you should always import the base datetime
module: import datetime
, rather than the datetime
class within that module: from datetime import datetime
.
The other mistake you have made is to actually call the function in the default, with the ()
. This means that all models will get the date at the time the class is first defined - so if your server stays up for days or weeks without restarting Apache, all elements will get same the initial date.
So the field should be:
import datetime
date = models.DateField(_("Date"), default=datetime.date.today)
out.write(c.toString());
out.newLine();
here is a simple solution, I hope it works
EDIT: I was using "\n" which was obviously not recommended approach, modified answer.
If all you're doing is attaching a string, you could do it in just 2 lines:
mail.Attachments.Add(Attachment.CreateAttachmentFromString("1,2,3", "text/csv");
mail.Attachments.Last().ContentDisposition.FileName = "filename.csv";
I wasn't able to get mine to work using our mail server with StreamWriter.
I think maybe because with StreamWriter you're missing a lot of file property information and maybe our server didn't like what was missing.
With Attachment.CreateAttachmentFromString() it created everything I needed and works great!
Otherwise, I'd suggest taking your file that is in memory and opening it using MemoryStream(byte[]), and skipping the StreamWriter all together.
Dim: you are defining a variable (here: r is a variable of type Range)
Set: you are setting the property (here: set the value of r to Range("A1") - this is not a type, but a value).
You have to use set with objects, if r were a simple type (e.g. int, string), then you would just write:
Dim r As Integer
r=5