The first parameter is the number of arguments provided and the second parameter is a list of strings representing those arguments.
Ravi's comment is essentially the answer. Functions take their own arguments. If you want them to be the same as the command-line arguments, you must pass them in. Otherwise, you're clearly calling a function without arguments.
That said, you could if you like store the command-line arguments in a global array to use within other functions:
my_function() {
echo "stored arguments:"
for arg in "${commandline_args[@]}"; do
echo " $arg"
done
}
commandline_args=("$@")
my_function
You have to access the command-line arguments through the commandline_args
variable, not $@
, $1
, $2
, etc., but they're available. I'm unaware of any way to assign directly to the argument array, but if someone knows one, please enlighten me!
Also, note the way I've used and quoted $@
- this is how you ensure special characters (whitespace) don't get mucked up.
argc
is the number of command line arguments given to the program at runtime, and argv
is an array of arrays of characters (rather, an array of C-strings) containing these arguments. If you know you're not going to need the command line arguments, you can declare your main at taking a void
argument, instead:
int main(void) {
/* ... */
}
Those are the only two prototypes defined for main
as per the standards, but some compilers allow a return type of void
as well. More on this on Wikipedia.
I also struggled with this and found no way to tell hive to skip first row, like there is e.g. in Greenplum. So finally I had to remove it from the files. e.g. "cat File.csv | grep -v RecordId > File_no_header.csv"
You can use either one. But I think Sleep()
is easy, clear and shorter to implement.
Itertools has a function just for that:
import itertools
it = itertools.repeat(e,n)
Of course itertools
gives you a iterator instead of a list. [e] * n
gives you a list, but, depending on what you will do with those sequences, the itertools
variant can be much more efficient.
You can get active store information like this:
Mage::app()->getStore(); // for store object
Mage::app()->getStore()->getStoreId; // for store ID
For anyone else who came here looking to do the same with docker-compose
you just need to prepend bash -c
and enclose multiple commands in quotes, joined together with &&
.
So in the OPs example docker-compose run image bash -c "cd /path/to/somewhere && python a.py"
If you knew that the enum values were sequential, for example the Qt:Key enum, you could:
Qt::Key shortcut_key = Qt::Key_0;
for (int idx = 0; etc...) {
....
if (shortcut_key <= Qt::Key_9) {
fileMenu->addAction("abc", this, SLOT(onNewTab()),
QKeySequence(Qt::CTRL + shortcut_key));
shortcut_key = (Qt::Key) (shortcut_key + 1);
}
}
It works as expected.
You could use imagemagick and write a script that fires everytime you load a webpage.
Here's what the creator of Rails, David Heinemeier Hansson has to say:
Rails [Ruby] is for the vast majority of web applications Fast Enough. We got sites doing millions of dynamic page views per day. If you end up being with the Yahoo or Amazon front page, it's unlikely that an off-the-shelve framework in ANY language will do you much good. You'll probably have to roll your own. But sure, I'd like free CPU cycles too. I just happen to care much more about free developer cycles and am willing to trade the former for the latter.
i.e. throwing more hardware or machines at the problem is cheaper than hiring more developers and using a faster, but harder to maintain language. After all, few people write web applications in C.
Ruby 1.9 is a vast improvement over 1.8. The biggest problems with Ruby 1.8 are its interpreted nature (no bytecode, no compilation) and that method calls, one of the most common operations in Ruby, are particularly slow.
It doesn't help that pretty much everything is a method lookup in Ruby - adding two numbers, indexing an array. Where other languages expose hacks (Python's __add__
method, Perl's overload.pm) Ruby does pure OO in all cases, and this can hurt performance if the compiler/interpreter is not clever enough.
If I were writing a popular web application in Ruby, my focus would be on caching. Caching a page reduces the processing time for that page to zero, whatever language you are using. For web applications, database overhead and other I/O begins to matter a lot more than the speed of the language, so I would focus on optimising that.
Numpy is required by pandas (and by virtually all numerical tools for Python). Scipy is not strictly required for pandas but is listed as an "optional dependency". I wouldn't say that pandas is an alternative to Numpy and/or Scipy. Rather, it's an extra tool that provides a more streamlined way of working with numerical and tabular data in Python. You can use pandas data structures but freely draw on Numpy and Scipy functions to manipulate them.
I would add an android:onClick
to the layout and then change the layout in the activity.
So in the layout
<ImageView
(Other things like source etc.)
android:onClick="changelayout"
/>
Then in the activity add the following:
public void changelayout(View view){
setContentView(R.layout.second_layout);
}
Move all of your state and your handleClick
function from Header
to your MainWrapper
component.
Then pass values as props to all components that need to share this functionality.
class MainWrapper extends React.Component {
constructor() {
super();
this.state = {
sidbarPushCollapsed: false,
profileCollapsed: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
profileCollapsed: !this.state.profileCollapsed
});
}
render() {
return (
//...
<Header
handleClick={this.handleClick}
sidbarPushCollapsed={this.state.sidbarPushCollapsed}
profileCollapsed={this.state.profileCollapsed} />
);
Then in your Header's render() method, you'd use this.props
:
<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>
You must add "include fastcgi.conf" in
location ~ \.$php{
#......
include fastcgi.conf;
}
Overloading Example
class overload {
public $name;
public function __construct($agr) {
$this->name = $agr;
}
public function __call($methodname, $agrument) {
if($methodname == 'sum2') {
if(count($agrument) == 2) {
$this->sum($agrument[0], $agrument[1]);
}
if(count($agrument) == 3) {
echo $this->sum1($agrument[0], $agrument[1], $agrument[2]);
}
}
}
public function sum($a, $b) {
return $a + $b;
}
public function sum1($a,$b,$c) {
return $a + $b + $c;
}
}
$object = new overload('Sum');
echo $object->sum2(1,2,3);
using JQuery:
myelement=$("#myelement")
[myelement.offset().left, myelement.offset().top, myelement.width(), myelement.height()]
you should give permission on your db
grant execute on (packageName or tableName) to user;
I have found another solution to prevent negative number.
<input type="number" name="test_name" min="0" oninput="validity.valid||(value='');">
For deploying the war file over tomcat, Follow the below steps :
you will get one folder inside E:\Tomcat_Installation\webapps**put**
In this way you can deploy your war file in Apache Tomcat.
I like that the long lines are displayed over more than one terminal line
This sort of visual/virtual line wrapping is enabled with the wrap
window option:
set wrap
I don’t like that vim inserts newlines into my actual text.
To turn off physical line wrapping, clear both the textwidth
and wrapmargin
buffer options:
set textwidth=0 wrapmargin=0
If the size of strings is relatively big (hundreds of bytes or more) and c++17 is available, you might want to use Boyer-Moore-Horspool searcher (example from cppreference.com):
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
int main()
{
std::string in = "Lorem ipsum dolor sit amet, consectetur adipiscing elit,"
" sed do eiusmod tempor incididunt ut labore et dolore magna aliqua";
std::string needle = "pisci";
auto it = std::search(in.begin(), in.end(),
std::boyer_moore_searcher(
needle.begin(), needle.end()));
if(it != in.end())
std::cout << "The string " << needle << " found at offset "
<< it - in.begin() << '\n';
else
std::cout << "The string " << needle << " not found\n";
}
<form method="post" action="servletName">
<input type="submit" id="btn1" name="btn1"/>
<input type="submit" id="btn2" name="btn2"/>
</form>
on pressing it request will go to servlet on the servlet page check which button is pressed and then accordingly call the needed method as objectName.method
You can use the following:
MainActivity.this.getApplicationContext();
MainActivity.java:
...
public class MainActivity ... {
static MainActivity ma;
...
public void onCreate(Bundle b) {
super...
ma=this;
...
Any other class:
public ...
public ANY_METHOD... {
Context c = MainActivity.ma.getApplicationContext();
In Ubuntu /etc/init.d has been replaced by /usr/lib/systemd. Scripts can still be started and stoped by 'service'. But the primary command is now 'systemctl'. The chkconfig command was left behind, and now you do this with systemctl.
So instead of:
chkconfig enable apache2
You should look for the service name, and then enable it
systemctl status apache2
systemctl enable apache2.service
Systemd has become more friendly about figuring out if you have a systemd script, or an /etc/init.d script, and doing the right thing.
So what are you doing is with append and concat is almost equivalent. The difference is the empty DataFrame. For some reason this causes a big slowdown, not sure exactly why, will have to look at some point. Below is a recreation of basically what you did.
I almost always use concat (though in this case they are equivalent, except for the empty frame); if you don't use the empty frame they will be the same speed.
In [17]: df1 = pd.DataFrame(dict(A = range(10000)),index=pd.date_range('20130101',periods=10000,freq='s'))
In [18]: df1
Out[18]:
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 10000 entries, 2013-01-01 00:00:00 to 2013-01-01 02:46:39
Freq: S
Data columns (total 1 columns):
A 10000 non-null values
dtypes: int64(1)
In [19]: df4 = pd.DataFrame()
The concat
In [20]: %timeit pd.concat([df1,df2,df3])
1000 loops, best of 3: 270 us per loop
This is equavalent of your append
In [21]: %timeit pd.concat([df4,df1,df2,df3])
10 loops, best of
3: 56.8 ms per loop
CSS-Transforms are not possible to animate with jQuery, yet. You can do something like this:
function AnimateRotate(angle) {
// caching the object for performance reasons
var $elem = $('#MyDiv2');
// we use a pseudo object for the animation
// (starts from `0` to `angle`), you can name it as you want
$({deg: 0}).animate({deg: angle}, {
duration: 2000,
step: function(now) {
// in the step-callback (that is fired each step of the animation),
// you can use the `now` paramter which contains the current
// animation-position (`0` up to `angle`)
$elem.css({
transform: 'rotate(' + now + 'deg)'
});
}
});
}
You can read more about the step-callback here: http://api.jquery.com/animate/#step
And, btw: you don't need to prefix css3 transforms with jQuery 1.7+
You can wrap this in a jQuery-plugin to make your life a bit easier:
$.fn.animateRotate = function(angle, duration, easing, complete) {
return this.each(function() {
var $elem = $(this);
$({deg: 0}).animate({deg: angle}, {
duration: duration,
easing: easing,
step: function(now) {
$elem.css({
transform: 'rotate(' + now + 'deg)'
});
},
complete: complete || $.noop
});
});
};
$('#MyDiv2').animateRotate(90);
http://jsbin.com/ofagog/2/edit
I optimized it a bit to make the order of easing
, duration
and complete
insignificant.
$.fn.animateRotate = function(angle, duration, easing, complete) {
var args = $.speed(duration, easing, complete);
var step = args.step;
return this.each(function(i, e) {
args.complete = $.proxy(args.complete, e);
args.step = function(now) {
$.style(e, 'transform', 'rotate(' + now + 'deg)');
if (step) return step.apply(e, arguments);
};
$({deg: 0}).animate({deg: angle}, args);
});
};
Thanks to matteo who noted an issue with the this
-context in the complete-callback
. If fixed it by binding the callback with jQuery.proxy
on each node.
I've added the edition to the code before from Update 2.
This is a possible modification if you want to do something like toggle the rotation back and forth. I simply added a start parameter to the function and replaced this line:
$({deg: start}).animate({deg: angle}, args);
If anyone knows how to make this more generic for all use cases, whether or not they want to set a start degree, please make the appropriate edit.
Mainly you've two ways to reach the desired result. But at the first, let's take a look on the arguments:
jQuery.fn.animateRotate(angle, duration, easing, complete)
Except of "angle" are all of them optional and fallback to the default jQuery.fn.animate
-properties:
duration: 400
easing: "swing"
complete: function () {}
This way is the short one, but looks a bit unclear the more arguments we pass in.
$(node).animateRotate(90);
$(node).animateRotate(90, function () {});
$(node).animateRotate(90, 1337, 'linear', function () {});
I prefer to use objects if there are more than three arguments, so this syntax is my favorit:
$(node).animateRotate(90, {
duration: 1337,
easing: 'linear',
complete: function () {},
step: function () {}
});
What you are describing is actually what FontAwesome is doing already. They apply the FontAwesome font-family to the ::before
pseudo element of any element that has a class that starts with "icon-".
[class^="icon-"]:before,
[class*=" icon-"]:before {
font-family: FontAwesome;
font-weight: normal;
font-style: normal;
display: inline-block;
text-decoration: inherit;
}
Then they use the pseudo element ::before
to place the icon in the element with the class. I just went to http://fortawesome.github.com/Font-Awesome/ and inspected the code to find this:
.icon-cut:before {
content: "\f0c4";
}
So if you are looking to add the icon again, you could use the ::after
element to achieve this. Or for your second part of your question, you could use the ::after
pseudo element to insert the bullet character to look like a list item. Then use absolute positioning to place it to the left, or something similar.
i:after{ content: '\2022';}
Currently, I am using Ubuntu 16.04 LTS. Me too was facing same problem while Fetching the Postgress Database values using Php so i resolved it by using the below commands.
Mine PHP version is 7.0, so i tried the below command.
apt-get install php-pgsql
Remember to restart Apache.
/etc/init.d/apache2 restart
You can try that one:
$string = preg_replace('/[^0-9]/', '', $string);
Cheers.
My two cents:
from itertools import repeat
list(repeat(f(), x)) # for pure f
[f() for f in repeat(f, x)] # for impure f
If your server is still listening on port 80, check the permission on the DocumentRoot folder and if DirectoryIndex file existed.
/path/to/project
Copy projects into workspace
and Add project to working sets
I think there's a more easy way to do that.
As edited by the accepted answer, now you can use a third party plugin cocoapods-deintegrate, it's reliable because its made by a CocoaPods core team member.
But,there're still some files remain:
Podfile
Podfile.lock
Workspace
You could remove them from your project manually,but there's also another tool for helping you to clean them, thanks cocoapods-clean.
Finally, the uninstallation work is still not completed, cocoapods-clean
don't clean the Podfile
, just run:
rm Podfile
Cheers!
Before removing you should ensure you have a backup of your project!
Note: Use CSS counters
to create nested numbering in a modern browser. See the accepted answer. The following is for historical interest only.
If the browser supports content
and counter
,
.foo {_x000D_
counter-reset: foo;_x000D_
}_x000D_
.foo li {_x000D_
list-style-type: none;_x000D_
}_x000D_
.foo li::before {_x000D_
counter-increment: foo;_x000D_
content: "1." counter(foo) " ";_x000D_
}
_x000D_
<ol class="foo">_x000D_
<li>uno</li>_x000D_
<li>dos</li>_x000D_
<li>tres</li>_x000D_
<li>cuatro</li>_x000D_
</ol>
_x000D_
Range<Long> timeRange = Range.create(model.getFrom(), model.getTo());
if(timeRange.contains(systemtime)){
Toast.makeText(context, "green!!", Toast.LENGTH_SHORT).show();
}
My way
>>>v = [1,2,3,4,5]
>>>[v[i] - v[i-1] for i, value in enumerate(v[1:], 1)]
[1, 1, 1, 1]
I believe
rgba( 0, 0, 0, 0.8 )
is equivalent in shade with #333
.
Live demo: http://jsfiddle.net/8MVC5/1/
Network tracing also available for next objects (see article on msdn)
Put next lines of code to the configuration file
<configuration>
<system.diagnostics>
<sources>
<source name="System.Net" tracemode="includehex" maxdatasize="1024">
<listeners>
<add name="System.Net"/>
</listeners>
</source>
<source name="System.Net.Cache">
<listeners>
<add name="System.Net"/>
</listeners>
</source>
<source name="System.Net.Http">
<listeners>
<add name="System.Net"/>
</listeners>
</source>
<source name="System.Net.Sockets">
<listeners>
<add name="System.Net"/>
</listeners>
</source>
<source name="System.Net.WebSockets">
<listeners>
<add name="System.Net"/>
</listeners>
</source>
</sources>
<switches>
<add name="System.Net" value="Verbose"/>
<add name="System.Net.Cache" value="Verbose"/>
<add name="System.Net.Http" value="Verbose"/>
<add name="System.Net.Sockets" value="Verbose"/>
<add name="System.Net.WebSockets" value="Verbose"/>
</switches>
<sharedListeners>
<add name="System.Net"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="network.log"
/>
</sharedListeners>
<trace autoflush="true"/>
</system.diagnostics>
</configuration>
use .NET3.5 it worked for me for similar issue.
mkdir -p newDir/subdir{1..8}
ls newDir/
subdir1 subdir2 subdir3 subdir4 subdir5 subdir6 subdir7 subdir8
If you use the library sugar.js, you can write arr.min() and arr.max() as you suggest. You can also get min and max values from non-numeric arrays.
min( map , all = false ) Returns the element in the array with the lowest value. map may be a function mapping the value to be checked or a string acting as a shortcut. If all is true, will return all min values in an array.
max( map , all = false ) Returns the element in the array with the greatest value. map may be a function mapping the value to be checked or a string acting as a shortcut. If all is true, will return all max values in an array.
Examples:
[1,2,3].min() == 1
['fee','fo','fum'].min('length') == "fo"
['fee','fo','fum'].min('length', true) == ["fo"]
['fee','fo','fum'].min(function(n) { return n.length; }); == "fo"
[{a:3,a:2}].min(function(n) { return n['a']; }) == {"a":2}
['fee','fo','fum'].max('length', true) == ["fee","fum"]
Libraries like Lo-Dash and underscore.js also provide similar powerful min and max functions:
Example from Lo-Dash:
_.max([4, 2, 8, 6]) == 8
var characters = [
{ 'name': 'barney', 'age': 36 },
{ 'name': 'fred', 'age': 40 }
];
_.max(characters, function(chr) { return chr.age; }) == { 'name': 'fred', 'age': 40 }
select case when [am or _pm] ='PM' and datepart(HOUR,time_received)<>12
then dateadd(hour,12,time_received)
else time_received
END
from table
works
If you want an empty string default then a preferred way is one of these (depending on your need):
$str_value = strval($_GET['something']);
$trimmed_value = trim($_GET['something']);
$int_value = intval($_GET['somenumber']);
If the url parameter something
doesn't exist in the url then $_GET['something']
will return null
strval($_GET['something'])
-> strval(null)
-> ""
and your variable $value
is set to an empty string.
trim()
might be prefered over strval()
depending on code (e.g. a Name parameter might want to use it)intval()
if only numeric values are expected and the default is zero. intval(null)
-> 0
Cases to consider:
...&something=value1&key2=value2
(typical)
...&key2=value2
(parameter missing from url $_GET will return null for it)
...&something=+++&key2=value
(parameter is " "
)
Why this is a preferred approach:
$value = isset($_GET['something']) ? $_GET['something'] : '';
$value=isset($_GET['something'])?$_GET['somthing']:'';
Update Strict mode may require something like this:
$str_value = strval(@$_GET['something']);
$trimmed_value = trim(@$_GET['something']);
$int_value = intval(@$_GET['somenumber']);
There are many libraries to help with this. For example, using immutability-helper:
import update from 'immutability-helper';
const newState = update(this.state, {
someProperty: {flag: {$set: false}},
};
this.setState(newState);
Using lodash/fp set:
import {set} from 'lodash/fp';
const newState = set(["someProperty", "flag"], false, this.state);
Using lodash/fp merge:
import {merge} from 'lodash/fp';
const newState = merge(this.state, {
someProperty: {flag: false},
});
I find it quite overkill enforce the validity of the href attribute with such a complex and cryptic pattern while a simple expression such as
<a\s+(?:[^>]*?\s+)?href="([^"]*)"
would suffice to capture all URLs. If you want to make sure they contain at least a query string, you could just use
<a\s+(?:[^>]*?\s+)?href="([^"]+\?[^"]+)"
st = @"((www\.|https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+ \w\d:#@%/;$()~_?\+-=\\\.&]*)";
st = @"<a href[^>]*>(.*?)</a>";
st = @"((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)";
st = @"((?:(?:https?|ftp|gopher|telnet|file|notes|ms-help):(?://|\\\\)(?:www\.)?|www\.)[\w\d:#@%/;$()~_?\+,\-=\\.&]+)";
st = @"(?:(?:https?|ftp|gopher|telnet|file|notes|ms-help):(?://|\\\\)(?:www\.)?|www\.)";
st = @"(((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+)|(www\.)[\w\d:#@%/;$()~_?\+-=\\\.&]*)";
st = @"href=[""'](?<url>(http|https)://[^/]*?\.(com|org|net|gov))(/.*)?[""']";
st = @"(<a.*?>.*?</a>)";
st = @"(?:hrefs*=)(?:[s""']*)(?!#|mailto|location.|javascript|.*css|.*this.)(?.*?)(?:[s>""'])";
st = @"http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?";
st = @"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?";
st = @"(http|https)://([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?";
st = @"((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)";
st = @"http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?";
st = @"http(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$";
st = @"(?<Protocol>\w+):\/\/(?<Domain>[\w.]+\/?)\S*";
my choice is
@"(?<Protocol>\w+):\/\/(?<Domain>[\w.]+\/?)\S*"
Second Use this:
st = "(.*)?(.*)=(.*)";
I also encountered a similar problem. I run Ubuntu 11.04 on VMware on a Windows 7 host OS. Virtual machines can't expose the physical wireless cards. All of that is using a virtualization layer.
In one answer above:
The simplest & the best solution:
mylist.OrderBy(s => s.GetType().GetProperty("PropertyName").GetValue(s));
There is an syntax error, ,null
must be added:
mylist.OrderBy(s => s.GetType().GetProperty("PropertyName").GetValue(s,null));
It means that you wrote to some variables on the stack in an illegal way, most likely as the result of a Buffer overflow.
Or, the most performance-friendly way is to overload drawRect, simply like that:
@interface TPActionSheetButton : UIButton
@property (assign) BOOL drawsTopLine;
@property (assign) BOOL drawsBottomLine;
@property (assign) BOOL drawsRightLine;
@property (assign) BOOL drawsLeftLine;
@property (strong, nonatomic) UIColor * lineColor;
@end
@implementation TPActionSheetButton
- (void) drawRect:(CGRect)rect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(ctx, 0.5f * [[UIScreen mainScreen] scale]);
CGFloat red, green, blue, alpha;
[self.lineColor getRed:&red green:&green blue:&blue alpha:&alpha];
CGContextSetRGBStrokeColor(ctx, red, green, blue, alpha);
if(self.drawsTopLine) {
CGContextBeginPath(ctx);
CGContextMoveToPoint(ctx, CGRectGetMinX(rect), CGRectGetMinY(rect));
CGContextAddLineToPoint(ctx, CGRectGetMaxX(rect), CGRectGetMinY(rect));
CGContextStrokePath(ctx);
}
if(self.drawsBottomLine) {
CGContextBeginPath(ctx);
CGContextMoveToPoint(ctx, CGRectGetMinX(rect), CGRectGetMaxY(rect));
CGContextAddLineToPoint(ctx, CGRectGetMaxX(rect), CGRectGetMaxY(rect));
CGContextStrokePath(ctx);
}
if(self.drawsLeftLine) {
CGContextBeginPath(ctx);
CGContextMoveToPoint(ctx, CGRectGetMinX(rect), CGRectGetMinY(rect));
CGContextAddLineToPoint(ctx, CGRectGetMinX(rect), CGRectGetMaxY(rect));
CGContextStrokePath(ctx);
}
if(self.drawsRightLine) {
CGContextBeginPath(ctx);
CGContextMoveToPoint(ctx, CGRectGetMaxX(rect), CGRectGetMinY(rect));
CGContextAddLineToPoint(ctx, CGRectGetMaxX(rect), CGRectGetMaxY(rect));
CGContextStrokePath(ctx);
}
[super drawRect:rect];
}
@end
In the discipline of speech recognition, users are divided into goats and sheeps.
For instance, here on page 89:
Sheeps are people for whom speech recognition works exceptionally well, and goats are people for whom it works exceptionally poorly. Only the voice recognizer knows what separates them. People can't predict whose voice will be recognized easily and whose won't. The best policy is to design the interface so it can handle all kinds of voices in all kinds of environments
Maybe, it is planned to mark Android users as goats in the future to be able to configure the speech recognition engine for goats' needs. ;-)
simply,
select sysdate-1 from dual
there's a bunch more info and detail here: http://www.orafaq.com/faq/how_does_one_add_a_day_hour_minute_second_to_a_date_value
Put it this way
where ("R"."TIME_STAMP">=TO_DATE ('03-02-2013 00:00:00', 'DD-MM-YYYY HH24:MI:SS')
AND "R"."TIME_STAMP"<=TO_DATE ('09-02-2013 23:59:59', 'DD-MM-YYYY HH24:MI:SS'))
Where
R is table name.
TIME_STAMP is FieldName in Table R.
$Group
is an object, but you will actually need to check if $Group.samaccountname.StartsWith("string")
.
Change $Group.StartsWith("S_G_")
to $Group.samaccountname.StartsWith("S_G_")
.
I had similar problem, i solve using css ":before".. the code looks likes this:
.widgets li:before{
content:"• ";
}
By default, a maximum of 10 listeners can be registered for any single event.
If it's your code, you can specify maxListeners via:
const emitter = new EventEmitter()
emitter.setMaxListeners(100)
// or 0 to turn off the limit
emitter.setMaxListeners(0)
But if it's not your code you can use the trick to increase the default limit globally:
require('events').EventEmitter.prototype._maxListeners = 100;
Of course you can turn off the limits but be careful:
// turn off limits by default (BE CAREFUL)
require('events').EventEmitter.prototype._maxListeners = 0;
BTW. The code should be at the very beginning of the app.
ADD: Since node 0.11 this code also works to change the default limit:
require('events').EventEmitter.defaultMaxListeners = 0
If you are using Bootstrap 4, you can simple use a color utility class (e.g. text-success
, text-danger
, etc... ).
You can also create your own classes (e.g. text-my-own-color
)
Both options are shown in the example below, run the code snippet to see a live demo.
.text-my-own-color {
color: #663300 !important; // Define your own color in your CSS
}
.text-my-own-color:hover, .text-my-own-color:active {
color: #664D33 !important; // Define your own color's darkening/lightening in your CSS
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="navbar-collapse">
<ul class="nav pull-right">
<!-- Bootstrap's color utility class -->
<li class="active"><a class="text-success" href="#">? ???</a></li>
<!-- Bootstrap's color utility class -->
<li><a class="text-danger" href="#">??? ??? ????????</a></li>
<!-- Bootstrap's color utility class -->
<li><a class="text-warning" href="#">????</a></li>
<!-- Custom color utility class -->
<li><a class="text-my-own-color" href="#">????????</a></li>
</ul>
</div>
_x000D_
On Docker for Windows and Mac, and probably others too, it is possible to use the tail option. For example:
docker logs -f --tail 100
This way, only the last 100 lines are shown, and you don't have first to scroll through 1M lines...
(And thus, deleting the log is probably unnecessary)
MD5 has its weaknesses (see Wikipedia), so there are some projects, which try to precompute Hashes. Wikipedia does also hint at some of these projects. One I know of (and respect) is ophrack. You can not tell the user their own password, but you might be able to tell them a password that works. But i think: Just mail thrm a new password in case they forgot.
I don't think it's possible with bluetooth, but you could try looking into WiFi Peer-to-Peer,
which allows one-to-many connections.
If you find by alphabet in plist, it should be "Application supports iTunes file sharing".
Question 1: How can I know which conda environment is my jupyter notebook running on?
Launch your Anaconda Prompt and run the command conda env list
to list all the available conda environments.
You can clearly see that I've two different conda environments installed on my PC, with my currently active environment being root(Python 2.7), indicated by the asterisk(*) symbol ahead of the path.
Question 2: How can I launch jupyter from a new conda environment?
Now, to launch the desired conda environment, simply run activate <environment name>
. In this case, activate py36
For more info, check out this link and this previous Stack Overflow question..
SELECT *
FROM customer
WHERE joiningdate >= NOW();
this error usually shows if the name of your struct is different from the initialization of your struct in the code, so normally, c will find the name of the struct you put and if the original struct is not found, this would usually appear, or if you point a pointer pointed into that pointer, the error will show up.
For those using Flask, put this in your __init__.py
:
def clever_function():
return u'HELLO'
app.jinja_env.globals.update(clever_function=clever_function)
and in your template call it with {{ clever_function() }}
As for the meaning of each character described in C Primer Plus, what you expected is an 'correct' answer. It should be true for some computer architectures and compilers, but unfortunately not yours.
I wrote a simple c program to repeat your test, and got that 'correct' answer. I was using Mac OS and gcc.
Also, I am very curious what is the compiler that you were using. :)
I'm a little late, but I have a little snippet to do this, it essentially maintains all of JScripts truthey/falsey/filthy-ness but includes "false"
as an acceptible value for false.
I prefer this method to the ones mentioned because it doesn't rely on a 3rd party to parse the code (i.e: eval/JSON.parse), which is overkill in my mind, it's short enough to not require a utility function and maintains other truthey/falsey conventions.
var value = "false";
var result = (value == "false") != Boolean(value);
// value = "true" => result = true
// value = "false" => result = false
// value = true => result = true
// value = false => result = false
// value = null => result = false
// value = [] => result = true
// etc..
byte[] IntToByteArray( int data ) {
byte[] result = new byte[4];
result[0] = (byte) ((data & 0xFF000000) >> 24);
result[1] = (byte) ((data & 0x00FF0000) >> 16);
result[2] = (byte) ((data & 0x0000FF00) >> 8);
result[3] = (byte) ((data & 0x000000FF) >> 0);
return result;
}
What about using CSS3 transform
property and use scale
which ill give a zoom like effect, this can be done like so,
HTML
<div class="thumbnail">
<div class="image">
<img src="http://placehold.it/320x240" alt="Some awesome text"/>
</div>
</div>
CSS
.thumbnail {
width: 320px;
height: 240px;
}
.image {
width: 100%;
height: 100%;
}
.image img {
-webkit-transition: all 1s ease; /* Safari and Chrome */
-moz-transition: all 1s ease; /* Firefox */
-ms-transition: all 1s ease; /* IE 9 */
-o-transition: all 1s ease; /* Opera */
transition: all 1s ease;
}
.image:hover img {
-webkit-transform:scale(1.25); /* Safari and Chrome */
-moz-transform:scale(1.25); /* Firefox */
-ms-transform:scale(1.25); /* IE 9 */
-o-transform:scale(1.25); /* Opera */
transform:scale(1.25);
}
Here's a demo fiddle. I removed some of the element to make it simpler, you can always add overflow hidden to the .image
to hide the overflow of the scaled image.
zoom
property only works in IE
Step 1: Go to directory where the classes are kept using command prompt (or Linux shell prompt)
Like for Project.
C:/workspace/MyProj/bin/classess/com/test/*.class
Go directory bin using command:
cd C:/workspace/MyProj/bin
Step 2: Use below command to generate jar file.
jar cvf helloworld.jar com\test\hello\Hello.class com\test\orld\HelloWorld.class
Using the above command the classes will be placed in a jar in a directory structure.
Use this in your code:
String.valueOf(x);
To create a property class please select your package where you wants to create your property file.
Right click on the package and select other. Now select File and type your file name with (.properties) suffix. For example: db.properties. Than click finish. Now you can write your code inside this property file.
Here is a generic wrapper which can be used to convert a binary function to multi-parameters function. The benefit of this solution is that it is very generic and can be applied to any binary functions. You just need to do it once and then you can apply it any where.
To demo the idea, I use simple recursion to implement. It can be of course implemented with more elegant way that benefits from R's good support for functional paradigm.
fold_left <- function(f) {
return(function(...) {
args <- list(...)
return(function(...){
iter <- function(result,rest) {
if (length(rest) == 0) {
return(result)
} else {
return(iter(f(result, rest[[1]], ...), rest[-1]))
}
}
return(iter(args[[1]], args[-1]))
})
})}
Then you can simply wrap any binary functions with it and call with positional parameters (usually data.frames) in the first parentheses and named parameters in the second parentheses (such as by =
or suffix =
). If no named parameters, leave second parentheses empty.
merge_all <- fold_left(merge)
merge_all(df1, df2, df3, df4, df5)(by.x = c("var1", "var2"), by.y = c("var1", "var2"))
left_join_all <- fold_left(left_join)
left_join_all(df1, df2, df3, df4, df5)(c("var1", "var2"))
left_join_all(df1, df2, df3, df4, df5)()
You can get separate component of a NSDate using NSDateFormatter:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"dd"];
myDayString = [df stringFromDate:[NSDate date]];
[df setDateFormat:@"MMM"];
myMonthString = [df stringFromDate:[NSDate date]];
[df setDateFormat:@"yy"];
myYearString = [df stringFromDate:[NSDate date]];
If you wish to get month's number instead of abbreviation, use "MM". If you wish to get integers, use [myDayString intValue];
Starting with Node.js version 13 you can take advantage of ES6 Modules.
export function foo() {
return 'foo';
}
export function bar() {
return foo();
}
Following the Class approach:
class MyClass {
foo() {
return 'foo';
}
bar() {
return this.foo();
}
}
module.exports = new MyClass();
This will instantiate the class only once, due to Node's module caching:
https://nodejs.org/api/modules.html#modules_caching
Lifecycle hooks, like OnInit()
work with Directives and Components. They do not work with other types, like a service in your case. From docs:
A Component has a lifecycle managed by Angular itself. Angular creates it, renders it, creates and renders its children, checks it when its data-bound properties change and destroy it before removing it from the DOM.
Directive and component instances have a lifecycle as Angular creates, updates, and destroys them.
It should be extremely risky... but you can use exec():
a = 'b=5'
exec(a)
c = b*2
print (c)
Result: 10
I would simply make the assignment happen in the ng-mouseover and ng-mouseleave; no need to bother js file :)
<ul ng-repeat="task in tasks">
<li ng-mouseover="hoverEdit = true" ng-mouseleave="hoverEdit = false">{{task.name}}</li>
<span ng-show="hoverEdit"><a>Edit</a></span>
</ul>
Maybe you were trying to do this?
#include <stdio.h>
int func(int * B){
/* B + OFFSET = 5 () You are pointing to the same region as B[OFFSET] */
*(B + 2) = 5;
}
int main(void) {
int B[10];
func(B);
/* Let's say you edited only 2 and you want to show it. */
printf("b[0] = %d\n\n", B[2]);
return 0;
}
Something along the lines:
<VirtualHost hostname:80>
...
SetEnv VARIABLE_NAME variable_value
...
</VirtualHost>
On Linux/Unix, you can append files to the .gitignore file with the echo
command. For example if you want to ignore all .svn
folders, run this from the root of the project:
echo .svn/ >> .gitignore
Just run this verbatim.
import nltk
nltk.download('tagsets')
nltk.help.upenn_tagset()
nltk.tag._POS_TAGGER
won't work. It will give AttributeError: module 'nltk.tag' has no attribute '_POS_TAGGER'. It's not available in NLTK 3 anymore.
if all solutions up did not work for you, make sure the service is running and not set to Disabled
!
Go to Services
from Control panel and open Services
,
Search for Apache2.4
and mysql
then switch it to enabled
, in the column of status it should be switched to Running
First, you don't need the .class files if they are compiled from your .java classes.
To import your files, you need to create an empty Java project. They you either import them one by one (New -> File -> Advanced -> Link file) or directly copy them into their corresponding folder/package and refresh the project.
An identifying relationship is when the existence of a row in a child table depends on a row in a parent table. This may be confusing because it's common practice these days to create a pseudokey for a child table, but not make the foreign key to the parent part of the child's primary key. Formally, the "right" way to do this is to make the foreign key part of the child's primary key. But the logical relationship is that the child cannot exist without the parent.
Example: A Person
has one or more phone numbers. If they had just one phone number, we could simply store it in a column of Person
. Since we want to support multiple phone numbers, we make a second table PhoneNumbers
, whose primary key includes the person_id
referencing the Person
table.
We may think of the phone number(s) as belonging to a person, even though they are modeled as attributes of a separate table. This is a strong clue that this is an identifying relationship (even if we don't literally include person_id
in the primary key of PhoneNumbers
).
A non-identifying relationship is when the primary key attributes of the parent must not become primary key attributes of the child. A good example of this is a lookup table, such as a foreign key on Person.state
referencing the primary key of States.state
. Person
is a child table with respect to States
. But a row in Person
is not identified by its state
attribute. I.e. state
is not part of the primary key of Person
.
A non-identifying relationship can be optional or mandatory, which means the foreign key column allows NULL or disallows NULL, respectively.
See also my answer to Still Confused About Identifying vs. Non-Identifying Relationships
Here's a one-liner:
ps -ef| awk '{print $2}'| xargs -I '{}' sh -c 'echo examining process {}; pfiles {}| grep 80'
'echo examining process PID' will be printed before each search, so once you see an output referencing port 80, you'll know which process is holding the handle.
Alternatively use:ps -ef| grep $USER|awk '{print $2}'| xargs -I '{}' sh -c 'echo examining process {}; pfiles {}| grep 80'
Since 'pfiles' might not like that you're trying to access other user's processes, unless you're root of course.
Make sure that your windows host file (located at c://windows/system32/drivers/etc.host
) has following line. If not, add it at the end
127.0.0.1 localhost
::1 localhost
Sometimes mysql can not trigger Windows to force start host services if firewall blocks it, so start it manually
win+run>>services.msc, select the "MySQL_xx" where "xx" is the name you have assigned to MySQL host services during setup. Click on 'start' to start from hyperlink appeared on left side.
Primary keys always need to be unique, foreign keys need to allow non-unique values if the table is a one-to-many relationship. It is perfectly fine to use a foreign key as the primary key if the table is connected by a one-to-one relationship, not a one-to-many relationship.
A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.
So if you are using Moq, and want to mock the result of an Extension method, then you can use SetupReturnsDefault<ReturnTypeOfExtensionMethod>(new ConcreteInstanceToReturn())
on the instance of the mock class that has the extension method you are trying to mock.
It is not perfect, but for unit testing purposes it works well.
The best way to fix it I have looked for the code or trick how to center nav menu and found the real solutions it works for all browsers and for my friends ;)
Here is how I have done:
body {
margin: 0;
padding: 0;
}
div maincontainer {
margin: 0 auto;
width: ___px;
text-align: center;
}
ul {
margin: 0;
padding: 0;
}
ul li {
margin-left: auto;
margin-right: auto;
}
and do not forget to set doctype html5
In this case both strconv
and fmt.Sprintf
do the same job but using the strconv
package's Itoa
function is the best choice, because fmt.Sprintf
allocate one more object during conversion.
check the benchmark here: https://gist.github.com/evalphobia/caee1602969a640a4530
see https://play.golang.org/p/hlaz_rMa0D for example.
In more explanation for n. 'pronouns' m.
's answer,
Public-key crypto is not for encrypting arbitrarily long files. One uses a symmetric cipher (say AES) to do the normal encryption. Each time a new random symmetric key is generated, used, and then encrypted with the RSA cipher (public key). The ciphertext together with the encrypted symmetric key is transferred to the recipient. The recipient decrypts the symmetric key using his private key, and then uses the symmetric key to decrypt the message.
There is the flow of Encryption:
+---------------------+ +--------------------+
| | | |
| generate random key | | the large file |
| (R) | | (F) |
| | | |
+--------+--------+---+ +----------+---------+
| | |
| +------------------+ |
| | |
v v v
+--------+------------+ +--------+--+------------+
| | | |
| encrypt (R) with | | encrypt (F) |
| your RSA public key | | with symmetric key (R) |
| | | |
| ASym(PublicKey, R) | | EF = Sym(F, R) |
| | | |
+----------+----------+ +------------+-----------+
| |
+------------+ +--------------+
| |
v v
+--------------+-+---------------+
| |
| send this files to the peer |
| |
| ASym(PublicKey, R) + EF |
| |
+--------------------------------+
And the flow of Decryption:
+----------------+ +--------------------+
| | | |
| EF = Sym(F, R) | | ASym(PublicKey, R) |
| | | |
+-----+----------+ +---------+----------+
| |
| |
| v
| +-------------------------+-----------------+
| | |
| | restore key (R) |
| | |
| | R <= ASym(PrivateKey, ASym(PublicKey, R)) |
| | |
| +---------------------+---------------------+
| |
v v
+---+-------------------------+---+
| |
| restore the file (F) |
| |
| F <= Sym(Sym(F, R), R) |
| |
+---------------------------------+
Besides, you can use this commands:
# generate random symmetric key
openssl rand -base64 32 > /config/key.bin
# encryption
openssl rsautl -encrypt -pubin -inkey /config/public_key.pem -in /config/key.bin -out /config/key.bin.enc
openssl aes-256-cbc -a -pbkdf2 -salt -in $file_name -out $file_name.enc -k $(cat /config/key.bin)
# now you can send this files: $file_name.enc + /config/key.bin.enc
# decryption
openssl rsautl -decrypt -inkey /config/private_key.pem -in /config/key.bin.enc -out /config/key.bin
openssl aes-256-cbc -d -a -in $file_name.enc -out $file_name -k $(cat /config/key.bin)
The string has a substring method that returns the string at the specified position.
String name="123456789";
System.out.println(name.substring(0,1));
Matplotlib doesn't work with pixels directly, but rather physical sizes and DPI. If you want to display a figure with a certain pixel size, you need to know the DPI of your monitor. For example this link will detect that for you.
If you have an image of 3841x7195 pixels it is unlikely that you monitor will be that large, so you won't be able to show a figure of that size (matplotlib requires the figure to fit in the screen, if you ask for a size too large it will shrink to the screen size). Let's imagine you want an 800x800 pixel image just for an example. Here's how to show an 800x800 pixel image in my monitor (my_dpi=96
):
plt.figure(figsize=(800/my_dpi, 800/my_dpi), dpi=my_dpi)
So you basically just divide the dimensions in inches by your DPI.
If you want to save a figure of a specific size, then it is a different matter. Screen DPIs are not so important anymore (unless you ask for a figure that won't fit in the screen). Using the same example of the 800x800 pixel figure, we can save it in different resolutions using the dpi
keyword of savefig
. To save it in the same resolution as the screen just use the same dpi:
plt.savefig('my_fig.png', dpi=my_dpi)
To to save it as an 8000x8000 pixel image, use a dpi 10 times larger:
plt.savefig('my_fig.png', dpi=my_dpi * 10)
Note that the setting of the DPI is not supported by all backends. Here, the PNG backend is used, but the pdf and ps backends will implement the size differently. Also, changing the DPI and sizes will also affect things like fontsize. A larger DPI will keep the same relative sizes of fonts and elements, but if you want smaller fonts for a larger figure you need to increase the physical size instead of the DPI.
Getting back to your example, if you want to save a image with 3841 x 7195 pixels, you could do the following:
plt.figure(figsize=(3.841, 7.195), dpi=100)
( your code ...)
plt.savefig('myfig.png', dpi=1000)
Note that I used the figure dpi of 100 to fit in most screens, but saved with dpi=1000
to achieve the required resolution. In my system this produces a png with 3840x7190 pixels -- it seems that the DPI saved is always 0.02 pixels/inch smaller than the selected value, which will have a (small) effect on large image sizes. Some more discussion of this here.
in my case it was not related to the path or filename. If filemtime(), fileatime() or filectime() don't work, try stat().
$filedate = date_create(date("Y-m-d", filectime($file)));
becomes
$stat = stat($directory.$file);
$filedate = date_create(date("Y-m-d", $stat['ctime']));
that worked for me.
Complete snippet for deleting files by number of days:
$directory = $_SERVER['DOCUMENT_ROOT'].'/directory/';
$files = array_slice(scandir($directory), 2);
foreach($files as $file)
{
$extension = substr($file, -3, 3);
if ($extension == 'jpg') // in case you only want specific files deleted
{
$stat = stat($directory.$file);
$filedate = date_create(date("Y-m-d", $stat['ctime']));
$today = date_create(date("Y-m-d"));
$days = date_diff($filedate, $today, true);
if ($days->days > 1)
{
unlink($directory.$file);
}
}
}
The best way to get substring in Android is using (as @user2503849 said) TextUtlis.substring(CharSequence, int, int)
method. I can explain why. If you will take a look at the String.substring(int, int)
method from android.jar
(newest API 22), you will see:
public String substring(int start) {
if (start == 0) {
return this;
}
if (start >= 0 && start <= count) {
return new String(offset + start, count - start, value);
}
throw indexAndLength(start);
}
Ok, than... How do you think the private constructor String(int, int, char[])
looks like?
String(int offset, int charCount, char[] chars) {
this.value = chars;
this.offset = offset;
this.count = charCount;
}
As we can see it keeps reference to the "old" value char[]
array. So, the GC can not free it.
In the newest Java it was fixed:
String(int offset, int charCount, char[] chars) {
this.value = Arrays.copyOfRange(chars, offset, offset + charCount);
this.offset = offset;
this.count = charCount;
}
Arrays.copyOfRange(...)
uses native array copying inside.
That's it :)
Best regards!
If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40)
.
If you use pyplot
programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40)
or afterwards with ax.yaxis.label.set_size(40)
.
import codecs
decode_hex = codecs.getdecoder("hex_codec")
# for an array
msgs = [decode_hex(msg)[0] for msg in msgs]
# for a string
string = decode_hex(string)[0]
As alluded to by Eric, you can use environ with ComputerName argument like so:
MsgBox Environ("USERNAME")
Some additional information that might be helpful for you to know:
Sub EnumSEVars()
Dim strVar As String
Dim i As Long
For i = 1 To 255
strVar = Environ$(i)
If LenB(strVar) = 0& Then Exit For
Debug.Print strVar
Next
End Sub
If all the above methods are not working then change implementation 'com.google.firebase:firebase-core:12.0.0'
to implementation 'com.google.firebase:firebase-core:10.0.0'
in your app level build.gradle file.
This would surely work.
You can use this library, which both initially sizes your iframe correctly and also keeps it at the right size by detecting whenever the size of the iframe's content changes (either via regular checking in a setInterval
or via MutationObserver
) and resizing it.
https://github.com/davidjbradshaw/iframe-resizer
Their is also a React version.
https://github.com/davidjbradshaw/iframe-resizer-react
This works with both cross and same domain iframes.
matrix.reset();
matrix.setTranslate( anchor.x, anchor.y );
matrix.postRotate((float) rotation , 0,0);
matrix.postTranslate(positionOfAnchor.x, positionOfAnchor.x);
c.drawBitmap(bitmap, matrix, null);
A lot of the answers on this page only apply to a single cell, and OP asked for all the selected cells.
If all you want is the cell contents, and you don't care about references to the actual cells that are selected, you can just do this:
Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim SelectedThings As String = DataGridView1.GetClipboardContent().GetText().Replace(ChrW(9), ",")
TextBox1.Text = SelectedThings
End Sub
When Button1
is clicked, this will fill TextBox1
with the comma-separated values of the selected cells.
This is exceedingly tricky in standard Unix, and most solutions run foul of newlines or some other character. However, if you are using the GNU tool set, then you can exploit the find
option -print0
and use xargs
with the corresponding option -0
(minus-zero). There are two characters that cannot appear in a simple filename; those are slash and NUL '\0'. Obviously, slash appears in pathnames, so the GNU solution of using a NUL '\0' to mark the end of the name is ingenious and fool-proof.
Recommendation. Do not use user-added REM statements to block batch steps. Use conditional GOTO instead. That way you can predefine and test the steps and options. The users also get much simpler changes and better confidence.
@Echo on
rem Using flags to control command execution
SET ExecuteSection1=0
SET ExecuteSection2=1
@echo off
IF %ExecuteSection1%==0 GOTO EndSection1
ECHO Section 1 Here
:EndSection1
IF %ExecuteSection2%==0 GOTO EndSection2
ECHO Section 2 Here
:EndSection2
The usual way to check if the value of a property is the special value undefined
, is:
if(o.myProperty === undefined) {
alert("myProperty value is the special value `undefined`");
}
To check if an object does not actually have such a property, and will therefore return undefined
by default when you try and access it:
if(!o.hasOwnProperty('myProperty')) {
alert("myProperty does not exist");
}
To check if the value associated with an identifier is the special value undefined
, or if that identifier has not been declared. Note: this method is the only way of referring to an undeclared (note: different from having a value of undefined
) identifier without an early error:
if(typeof myVariable === 'undefined') {
alert('myVariable is either the special value `undefined`, or it has not been declared');
}
In versions of JavaScript prior to ECMAScript 5, the property named "undefined" on the global object was writeable, and therefore a simple check foo === undefined
might behave unexpectedly if it had accidentally been redefined. In modern JavaScript, the property is read-only.
However, in modern JavaScript, "undefined" is not a keyword, and so variables inside functions can be named "undefined" and shadow the global property.
If you are worried about this (unlikely) edge case, you can use the void operator to get at the special undefined
value itself:
if(myVariable === void 0) {
alert("myVariable is the special value `undefined`");
}
IF EXIST "somefile.txt" (
IF EXIST "someotherfile.txt" (
SET var="somefile.txt","someotherfile.txt"
)
) ELSE (
CALL :SUB
)
:SUB
ECHO Sorry... nothin' there.
GOTO:EOF
Is this feasible?
SETLOCAL ENABLEDELAYEDEXPANSION
IF EXIST "somefile.txt" (
SET var="somefile.txt"
IF EXIST "someotherfile.txt" (
SET var=!var!,"someotherfile.txt"
)
) ELSE (
IF EXIST "someotherfile.txt" (
SET var="someotherfile.txt"
) ELSE (
GOTO:EOF
)
)
If you only want to perform some specific operations by your second SP and do not require values back from the SP then simply do:
Exec secondSPName @anyparams
Else, if you need values returned by your second SP inside your first one, then create a temporary table variable with equal numbers of columns and with same definition of column return by second SP. Then you can get these values in first SP as:
Insert into @tep_table
Exec secondSPName @anyparams
Update:
To pass parameter to second sp, do this:
Declare @id ID_Column_datatype
Set @id=(Select id from table_1 Where yourconditions)
Exec secondSPName @id
Update 2:
Suppose your second sp returns Id
and Name
where type of id
is int
and name
is of varchar(64)
type.
now, if you want to select these values in first sp then create a temporary table
variable and insert values into it:
Declare @tep_table table
(
Id int,
Name varchar(64)
)
Insert into @tep_table
Exec secondSP
Select * From @tep_table
This will return you the values returned by second SP.
Hope, this clear all your doubts.
It's been awhile since I used a GridView, but I think you need to set the grid's SortDirection property to whatever it currently is before leaving the OnSorting method.
So....
List<V_ReportPeriodStatusEntity> items = GetPeriodStatusesForScreenSelection();
items.Sort(new Helpers.GenericComparer<V_ReportPeriodStatusEntity>(e.SortExpression, e.SortDirection));
grdHeader.SortDirection = e.SortDirection.Equals(SortDirection.Ascending) ? SortDirection.Descending : SortDirection.Ascending;
grdHeader.DataSource = items;
grdHeader.DataBind();
Try this:
find . -name .svn -exec rm -rf '{}' \;
Before running a command like that, I often like to run this first:
find . -name .svn -exec ls '{}' \;
In C++, the size of int
isn't specified explicitly. It just tells you that it must be at least the size of short int
, which must be at least as large as signed char
. The size of char
in bits isn't specified explicitly either, although sizeof(char) is defined to be 1. If you want a 64 bit int, C++11 specifies long long
to be at least 64 bits.
#include <string>
#include <stdlib.h>
Here, is another easy way to convert int to string
int n = random(65,90);
std::string str1=(__String::createWithFormat("%c",n)->getCString());
you may visit this link for more methods https://www.geeksforgeeks.org/what-is-the-best-way-in-c-to-convert-a-number-to-a-string/
Every write to the database has lots of potential side effects.
Delete: a row must be removed, indexes updated, foreign keys checked and possibly cascade-deleted, etc. Insert: a row must be allocated - this might be in place of a deleted row, might not be; indexes must be updated, foreign keys checked, etc. Update: one or more values must be updated; perhaps the row's data no longer fits into that block of the database so more space must be allocated, which may cascade into multiple blocks being re-written, or lead to fragmented blocks; if the value has foreign key constraints they must be checked, etc.
For a very small number of columns or if the whole row is updated Delete+insert might be faster, but the FK constraint problem is a big one. Sure, maybe you have no FK constraints now, but will that always be true? And if you have a trigger it's easier to write code that handles updates if the update operation is truly an update.
Another issue to think about is that sometimes inserting and deleting hold different locks than updating. The DB might lock the entire table while you are inserting or deleting, as opposed to just locking a single record while you are updating that record.
In the end, I'd suggest just updating a record if you mean to update it. Then check your DB's performance statistics and the statistics for that table to see if there are performance improvements to be made. Anything else is premature.
An example from the ecommerce system I work on: We were storing credit-card transaction data in the database in a two-step approach: first, write a partial transaction to indicate that we've started the process. Then, when the authorization data is returned from the bank update the record. We COULD have deleted then re-inserted the record but instead we just used update. Our DBA told us that the table was fragmented because the DB was only allocating a small amount of space for each row, and the update caused block-chaining since it added a lot of data. However, rather than switch to DELETE+INSERT we just tuned the database to always allocate the whole row, this means the update could use the pre-allocated empty space with no problems. No code change required, and the code remains simple and easy to understand.
To install it, just run the command
npm install jquery
or
yarn add jquery
then you can import it in your file like
import $ from 'jquery';
Use the -L
option to follow redirects:
curl -L https://github.com/pinard/Pymacs/tarball/v0.24-beta2 | tar zx
The function read_csv and read_table is almost the same. But you must assign the delimiter “,” when you use the function read_table in your program.
def get_from_action_data(fname, chunk_size=100000):
reader = pd.read_csv(fname, header=0, iterator=True)
chunks = []
loop = True
while loop:
try:
chunk = reader.get_chunk(chunk_size)[["user_id", "type"]]
chunks.append(chunk)
except StopIteration:
loop = False
print("Iteration is stopped")
df_ac = pd.concat(chunks, ignore_index=True)
AngularJS provides the $http
service that does exactly what you want: Sending AJAX requests to web services and receiving data from them, using JSON (which is perfectly for talking to REST services).
To give an example (taken from the AngularJS documentation and slightly adapted):
$http({ method: 'GET', url: '/foo' }).
success(function (data, status, headers, config) {
// ...
}).
error(function (data, status, headers, config) {
// ...
});
Please note that there is also another service in AngularJS, the $resource
service which provides access to REST services in a more high-level fashion (example again taken from AngularJS documentation):
var Users = $resource('/user/:userId', { userId: '@id' });
var user = Users.get({ userId: 123 }, function () {
user.abc = true;
user.$save();
});
Moreover, there are also third-party solutions, such as Restangular. See its documentation on how to use it. Basically, it's way more declarative and abstracts more of the details away from you.
In VB its normally Dir
to find the directory of the file. If it's not blank then it exists and then use Kill
to get rid of the file.
test = Dir(Filename)
If Not test = "" Then
Kill (Filename)
End If
Just to add to the thread as a POSSIBLE solution, I faced a similar issue when developing on a Linux system that was behind a company firewall. However, using a Windows XP machine, Eclipse was able to access different update sites just fine as both the manual and native network connection providers worked just fine using the company proxy.
After stumbling around for some time, I came across a discussion about using NTLMv2 and an implementation to be found at http://cntlm.sourceforge.net/. To whomever posted this, I give much credit to as it helped me get past the issue running on Linux. As a side note, I was using Eclipse 3.6.2 / Helios on both the Linux and Windows distros.
Best of luck on finding a solution!
(But use this in rare occasions, because HTML method is PREFERRED WAY).
.container{_x000D_
position:relative;_x000D_
}_x000D_
.container::before{ _x000D_
content:"";_x000D_
width: 100%; height: 100%; position: absolute; background: black; opacity: 0.3; z-index: 1; top: 0; left: 0;_x000D_
background: black;_x000D_
}_x000D_
.container::after{ _x000D_
content: "Your Text"; position: absolute; top: 0; left: 0; bottom: 0; right: 0; z-index: 3; overflow: hidden; font-size: 2em; color: red; text-align: center; text-shadow: 0px 0px 5px black; background: #0a0a0a8c; padding: 5px;_x000D_
animation-name: blinking;_x000D_
animation-duration: 1s;_x000D_
animation-iteration-count: infinite;_x000D_
animation-direction: alternate;_x000D_
}_x000D_
@keyframes blinking {_x000D_
0% {opacity: 0;}_x000D_
100% {opacity: 1;}_x000D_
}
_x000D_
<div class="container">here is main content, text , <br/> images and other page details</div>
_x000D_
Remove the alpha channel using this command in the folder 'Images.xcassets', this command will remove all alpha channels from your .png files and it will put the background color to white
for i in `ls *.png`; do convert $i -background white -alpha remove -alpha off $i; done
There is probably a way (or three) to do this... however, I see one issue with your goal: how do you know when all the files have been uploaded? To rephrase in a way that makes more sense... how do you know what "all" means? According to the documentation, init
gets called at the initialization of the Dropzone itself, and then you set up the complete
event handler to do something when each file that's uploaded is complete. But, what mechanism is the user given to allow the program to know when he's dropped all the files he's intended to drop? If you are assuming that he/she will do a batch drop (i.e., drop onto the Dropzone 2-whatever number of files, at once, in one drop action), then the following code could/possibly should work:
Dropzone.options.filedrop = {
maxFilesize: 4096,
init: function () {
var totalFiles = 0,
completeFiles = 0;
this.on("addedfile", function (file) {
totalFiles += 1;
});
this.on("removed file", function (file) {
totalFiles -= 1;
});
this.on("complete", function (file) {
completeFiles += 1;
if (completeFiles === totalFiles) {
doSomething();
}
});
}
};
Basically, you watch any time someone adds/removes files from the Dropzone, and keep a count in closure variables. Then, when each file download is complete, you increment the completeFiles
progress counter var, and see if it now equals the totalCount you'd been watching and updating as the user placed things in the Dropzone. (Note: never used the plug-in/JS lib., so this is best guess as to what you could do to get what you want.)
It is always better to use create a namespace and declare a variable in it instead of adding it to the global object. We can also create a function to get and set the value
See the below code snippet:
//creating a namespace in which all the variables will be defined.
var myObjects={};
//function that will set the name property in the myObjects namespace
function setName(val){
myObjects.Name=val;
}
//function that will return the name property in the myObjects namespace
function getName(){
return myObjects.Name;
}
//now we can use it like:
setName("kevin");
var x = getName();
var y = x;
console.log(y) //"kevin"
var z = "y";
console.log(z); //"y"
console.log(eval(z)); //"kevin"
In this similar way, we can declare and use multiple variables. Although this will increase the line of code but the code will be more robust and less error-prone.
Looks like niether is faster or slower
public static void main(String arguments[]) {
//Build a long string
StringBuilder sb = new StringBuilder();
for(int j = 0; j < 10000; j++) {
sb.append("a really, really long string");
}
String str = sb.toString();
for (int testscount = 0; testscount < 10; testscount ++) {
//Test 1
long start = System.currentTimeMillis();
for(int c = 0; c < 10000000; c++) {
for (int i = 0, n = str.length(); i < n; i++) {
char chr = str.charAt(i);
doSomethingWithChar(chr);//To trick JIT optimistaion
}
}
System.out.println("1: " + (System.currentTimeMillis() - start));
//Test 2
start = System.currentTimeMillis();
char[] chars = str.toCharArray();
for(int c = 0; c < 10000000; c++) {
for (int i = 0, n = chars.length; i < n; i++) {
char chr = chars[i];
doSomethingWithChar(chr);//To trick JIT optimistaion
}
}
System.out.println("2: " + (System.currentTimeMillis() - start));
System.out.println();
}
}
public static void doSomethingWithChar(char chr) {
int newInt = chr << 2;
}
For long strings I'll chose the first one. Why copy around long strings? Documentations says:
public char[] toCharArray() Converts this string to a new character array.
Returns: a newly allocated character array whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string.
//Edit 1
I've changed the test to trick JIT optimisation.
//Edit 2
Repeat test 10 times to let JVM warm up.
//Edit 3
Conclusions:
First of all str.toCharArray();
copies entire string in memory. It can be memory consuming for long strings. Method String.charAt( )
looks up char in char array inside String class checking index before.
It looks like for short enough Strings first method (i.e. chatAt
method) is a bit slower due to this index check. But if the String is long enough, copying whole char array gets slower, and the first method is faster. The longer the string is, the slower toCharArray
performs. Try to change limit in for(int j = 0; j < 10000; j++)
loop to see it.
If we let JVM warm up code runs faster, but proportions are the same.
After all it's just micro-optimisation.
PHP 7.0: Using the explode function and create a list of all the results.
list($subdomain,$host) = explode('.', $_SERVER["SERVER_NAME"]);
Example: sub.domain.com
echo $subdomain;
Result: sub
echo $host;
Result: domain
This is 2 step process
If you want to push your branch code to remote repo then do
grep
matches, grep -v
does the inverse. If you need to "match A but not B" you usually use pipes:
grep "${PATT}" file | grep -v "${NOTPATT}"
The problem appears to be internal bubbling within the <video>
element ... so when you click on the "Play" button the code triggers and then the play button itself get triggered :(
I couldn't find a simple (reliable) way to stop the click bubbling through (logic tells me there should be a way, but... it escapes me right now)
Anyway, the solution I found to this was to put a transparent <div>
over the video sized to fit down to where the controls appear... so if you click on the div then your script controls play/pause but if the user clicks on the controls themselves then the <video>
element handles that for you.
The sample below was sized for my video so you may need to juggle sizes of the relative <div>
s but it should get you started
<div id="vOverlay" style="position:relative; width:600px; height:300px; z-index:2;"></div>
<video style="position:relative; top:-300px; z-index:1;width:600px;height:340px;" width="600" height="409" id=videoPlayer controls="controls">
<source src="video.mp4" type="video/mp4">
</video>
<script>
var v = document.getElementById('videoPlayer');
var vv = document.getElementById('vOverlay');
<!-- Auto play, Half volume -->
v.play()
v.volume = 0.5;
v.firstChild.nodeValue = "Play";
<!-- Play, Pause -->
vv.addEventListener('click',function(e){
if (!v.paused) {
console.log("pause playback");
v.pause();
v.firstChild.nodeValue = 'Pause';
} else {
console.log("start playback")
v.play();
v.firstChild.nodeValue = 'Play';
}
});
</script>
When I tried to access the result from
Object.keys(a).forEach(function (key){
console.log(a[key]);
});
it was plain text result with no key-value pairs Here is an example
var fruits = {
apple: "fruits/apple.png",
banana: "fruits/banana.png",
watermelon: "watermelon.jpg",
grapes: "grapes.png",
orange: "orange.jpg"
}
Now i want to get all links in a separated array , but with this code
function linksOfPics(obJect){
Object.keys(obJect).forEach(function(x){
console.log('\"'+obJect[x]+'\"');
});
}
the result of :
linksOfPics(fruits)
"fruits/apple.png"
"fruits/banana.png"
"watermelon.jpg"
"grapes.png"
"orange.jpg"
undefined
I figured out this one which solves what I'm looking for
console.log(Object.values(fruits));
["fruits/apple.png", "fruits/banana.png", "watermelon.jpg", "grapes.png", "orange.jpg"]
I just add this line exactly as it appears below (if you need a second delay):
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
// Process exception
}
I find the catch IS necessary (Your app can crash due to Android OS as much as your own code).
I think you're looking for;
string[] skus = myLines.Select(x => x.Sku).ToArray();
However, if you're going to iterate over the sku's in subsequent code I recommend not using the ToArray()
bit as it forces the queries execution prematurely and makes the applications performance worse. Instead you can just do;
var skus = myLines.Select(x => x.Sku); // produce IEnumerable<string>
foreach (string sku in skus) // forces execution of the query
java.lang.StringBuilder. Use int constructor to create an initial size.
Yes we can do it. First convert the tuple into an list, then delete the element in the list after that again convert back into tuple.
Demo:
my_tuple = (10, 20, 30, 40, 50)
# converting the tuple to the list
my_list = list(my_tuple)
print my_list # output: [10, 20, 30, 40, 50]
# Here i wanna delete second element "20"
my_list.pop(1) # output: [10, 30, 40, 50]
# As you aware that pop(1) indicates second position
# Here i wanna remove the element "50"
my_list.remove(50) # output: [10, 30, 40]
# again converting the my_list back to my_tuple
my_tuple = tuple(my_list)
print my_tuple # output: (10, 30, 40)
Thanks
Isn´t it a strange behavior? In my case, the mistake was that I added a jar-lib. But this lib was faulty, so I removed the lib. But, no matter what I´ve done, the error still exists. I removed the jar-file, even with the eclipse option "remove from build-path", deleted it on my project-folders and cleaned my project, but nothing worked. Only after I´ve done the way Qwert has described, it worked. But sould an IDE not independent from error messages? The error was fixed, only the messages caused the problem. Thanks to Qwert (if I got enough reputations, I will vote your answer. But now I am not able to, sorry).
Here's how I do multiline comments in bash.
This mechanism has two advantages that I appreciate. One is that comments can be nested. The other is that blocks can be enabled by simply commenting out the initiating line.
#!/bin/bash
# : <<'####.block.A'
echo "foo {" 1>&2
fn data1
echo "foo }" 1>&2
: <<'####.block.B'
fn data2 || exit
exit 1
####.block.B
echo "can't happen" 1>&2
####.block.A
In the example above the "B" block is commented out, but the parts of the "A" block that are not the "B" block are not commented out.
Running that example will produce this output:
foo {
./example: line 5: fn: command not found
foo }
can't happen
Even after doing all the method suggested, i was getting the same error. After trying hard, i got to know that hibernate's maven dependency was added in my pom.xml, as i removed it, application started successfully.
I removed this dependency:
<dependency> <groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
Best example for this Question, SDK - Software Development Kit - Ex: Netbeans JDK - Java Development Kit.(This is Java compiler). Without JDK, we unable to run java programs in SDK.
Try this:
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");
Or alternatively if you have the XML in a string use the LoadXml
method.
Once you have it loaded, you can use SelectNodes
and SelectSingleNode
to query specific values, for example:
XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "[email protected]"
Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:
<Data>
<Employee>
<Name>Test</Name>
<ID>123</ID>
</Employee>
<Company>
<Name>ABC</Name>
<Email>[email protected]</Email>
</Company>
</Data>
Try this:
import java.util.Scanner;
/* Logic: Consider first character in the string and start counting occurrence of
this character in the entire string. Now add this character to a empty
string "temp" to keep track of the already counted characters.
Next start counting from next character and start counting the character
only if it is not present in the "temp" string( which means only if it is
not counted already)
public class Counting_Occurences {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter String");
String str=input.nextLine();
int count=0;
String temp=""; // An empty string to keep track of counted
// characters
for(int i=0;i<str.length();i++)
{
char c=str.charAt(i); // take one character (c) in string
for(int j=i;j<str.length();j++)
{
char k=str.charAt(j);
// take one character (c) and compare with each character (k) in the string
// also check that character (c) is not already counted.
// if condition passes then increment the count.
if(c==k && temp.indexOf(c)==-1)
{
count=count+1;
}
}
if(temp.indexOf(c)==-1) // if it is not already counted
{
temp=temp+c; // append the character to the temp indicating
// that you have already counted it.
System.out.println("Character " + c + " occurs " + count + " times");
}
// reset the counter for next iteration
count=0;
}
}
}
The Homebrew package manager includes launchctl plists to start automatically. For more information, run brew info postgres
.
pg_ctl -D /usr/local/var/postgres start
pg_ctl -D /usr/local/var/postgres stop
"To have launchd start postgresql now and restart at login:"
brew services start postgresql
What is the result of pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start
?
What is the result of pg_ctl -D /usr/local/var/postgres status
?
Are there any error messages in the server.log?
Make sure tcp localhost connections are enabled in pg_hba.conf:
# IPv4 local connections:
host all all 127.0.0.1/32 trust
Check the listen_addresses and port in postgresql.conf:
egrep 'listen|port' /usr/local/var/postgres/postgresql.conf
#listen_addresses = 'localhost' # What IP address(es) to listen on;
#port = 5432 # (change requires restart)
Cleaning up
PostgreSQL was most likely installed via Homebrew, Fink, MacPorts or the EnterpriseDB installer.
Check the output of the following commands to determine which package manager it was installed with:
brew && brew list|grep postgres
fink && fink list|grep postgres
port && port installed|grep postgres
Check Metrix++ http://metrixplusplus.sourceforge.net/. It may require some extensions which are specific for your needs.
It’s easy; just do the following:
rvm implode
or
rm -rf ~/.rvm
And don’t forget to remove the script calls in the following files:
~/.bashrc
~/.bash_profile
~/.profile
And maybe others depending on whatever shell you’re using.
If the image is part of the layout it might be "View.VISIBLE" but that doesn't mean it's within the confines of the visible screen. If that's what you're after; this will work:
Rect scrollBounds = new Rect();
scrollView.getHitRect(scrollBounds);
if (imageView.getLocalVisibleRect(scrollBounds)) {
// imageView is within the visible window
} else {
// imageView is not within the visible window
}
Look at the ToLookup
and/or ToDictionary
extension methods.
Quite similar approve as already posted above. However it's easier to read.
/**
* Remove all empty spaces from array a string array
* @param arr array
* @return array without ""
*/
public static String[] removeAllEmpty(String[] arr) {
if (arr == null)
return arr;
String[] result = new String[arr.length];
int amountOfValidStrings = 0;
for (int i = 0; i < arr.length; i++) {
if (!arr[i].equals(""))
result[amountOfValidStrings++] = arr[i];
}
result = Arrays.copyOf(result, amountOfValidStrings);
return result;
}
Double.MAX_VALUE is the maximum value a double can represent (somewhere around 1.7*10^308).
This should end in some calculation problems, if you try to subtract the maximum possible value of a data type.
Even though when you are dealing with money you should never use floating point values especially while rounding this can cause problems (you will either have to much or less money in your system then).
Use doubleval()
. But be very careful about using decimals in financial transactions, and validate that user input very carefully.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double x=54.999999999999943157;
int y=ceil(x);//The ceil() function returns the smallest integer no less than x
return 0;
}
For figures you can use the method described here :
http://texblog.net/latex-archive/layout/centering-figure-table/
namely, do something like this:
\begin{figure}[h]
\makebox[\textwidth]{%
\includegraphics[width=1.5\linewidth]{bla.png}
}
\end{figure}
Notice that if you have subfigures in the figure, you'll probably want to enter into paragraph mode inside the box, like so:
\begin{figure}[h]
\makebox[\textwidth]{\parbox{1.5\textwidth}{ %
\centering
\subfigure[]{\includegraphics[width=0.7\textwidth]{a.png}}
\subfigure[]{\includegraphics[width=0.7\textwidth]{b.png}}
\end{figure}
For allowing the figure to be centered in the page, protruding into both margins rather than only the right margin.
This usually does the trick for images. Notice that with this method, the caption of the image will still be in the delimited by the normal margins of the page (which is a good thing).
Set current branch name like master
git pull --rebase origin master
git push origin master
Or branch name develop
git pull --rebase origin develop
git push origin develop
I sometimes do a mysqldump and pipe the output into another mysql command to import it into a different database.
mysqldump --add-drop-table -u wordpress -p wordpress | mysql -u wordpress -p wordpress_backup
You can manually force disconnection by a Thread sleep. This is an example:
URLConnection con = url.openConnection();
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
new Thread(new InterruptThread(con)).start();
then
public class InterruptThread implements Runnable {
HttpURLConnection con;
public InterruptThread(HttpURLConnection con) {
this.con = con;
}
public void run() {
try {
Thread.sleep(5000); // or Thread.sleep(con.getConnectTimeout())
} catch (InterruptedException e) {
}
con.disconnect();
System.out.println("Timer thread forcing to quit connection");
}
}
1 additional caveat (besides the answer by kanaka/peter): if you use WSS, and the server certificate is not acceptable to the browser, you may not get any browser rendered dialog (like it happens for Web pages). This is because WebSockets is treated as a so-called "subresource", and certificate accept / security exception / whatever dialogs are not rendered for subresources.
I am not sure if you have edited right configuration file. Try following steps
open %userprofile%\ducuments\iisexpress\config\applicationhost.config
By default bellow given entries are commented in the applicationhost.config file. uncomment these entries.
<add name="WebDAVModule" image="%IIS_BIN%\webdav.dll" /> <add name="WebDAVModule" />
<add name="WebDAV" path="*"
verb="PROPFIND,PROPPATCH,MKCOL,PUT,COPY,DELETE,MOVE,LOCK,UNLOCK"
modules="WebDAVModule" resourceType="Unspecified" requireAccess="None"
/>
I just discovered a workaround: You can make your local machine accessible by using http://localtunnel.com . You'll need to (temporarily) change some URLs used in your app code / html so links point to the temporary domain, but at least facebook can reach your machine.
If you would like to get the same information given when an exception isn't handled you can do something like this. Do import traceback
and then:
try:
...
except Exception as e:
print(traceback.print_tb(e.__traceback__))
I'm using Python 3.7.
Check if you have any element such as button or text view duplicated (copied twice) in the screen where this encounters. I did this unnoticed and had to face the same issue.
Don't forget to include
import Image
In order to show it use this :
Image.open('pathToFile').show()
TortoiseSVN 1.7 has an option for installing the command line tools.
It isn't checked by default, but you can run the installer again and select it. It will also automatically update your PATH environment variable.
Android handles transparency across views and drawables (including PNG images) natively, so the scenario you describe (a partially transparent ImageView
in front of a Gallery
) is certainly possible.
If you're having problems it may be related to either the layout or your image. I've replicated the layout you describe and successfully achieved the effect you're after. Here's the exact layout I used.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gallerylayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Gallery
android:id="@+id/overview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<ImageView
android:id="@+id/navigmaske"
android:background="#0000"
android:src="@drawable/navigmask"
android:scaleType="fitXY"
android:layout_alignTop="@id/overview"
android:layout_alignBottom="@id/overview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</RelativeLayout>
Note that I've changed the parent RelativeLayout
to a height and width of fill_parent
as is generally what you want for a main Activity. Then I've aligned the top and bottom of the ImageView
to the top and bottom of the Gallery
to ensure it's centered in front of it.
I've also explicitly set the background of the ImageView
to be transparent.
As for the image drawable itself, if you put the PNG file somewhere for me to look at I can use it in my project and see if it's responsible.
For anyone that also need to add into 2d associative array, you can also use answer given above, and use the code like this
$data[$category]["test"] = $question
you can then call it (to test out the result by:
echo $data[$category]["test"];
which should print $question
carlpett's find
-based answer (find . -maxdepth 1 -type f
) works in principle, but is not quite the same as using ls
: you get a potentially unsorted list of filenames all prefixed with ./
, and you lose the ability to apply ls
's many options;
also find
invariably finds hidden items too, whereas ls
' behavior depends on the presence or absence of the -a
or -A
options.
An improvement, suggested by Alex Hall in a comment on the question is to combine shell globbing with find
:
find * -maxdepth 0 -type f # find -L * ... includes symlinks to files
ls
's many other sorting / output-format options.Hans Roggeman's ls
+ grep
answer is pragmatic, but locks you into using long (-l
) output format.
To address these limitations I wrote the fls
(filtering ls) utility,
ls
while also providing type-filtering capability,f
for files, d
for directories, and l
for symlinks before a list of ls
arguments (run fls --help
or fls --man
to learn more).Examples:
fls f # list all files in current dir.
fls d -tA ~ # list dirs. in home dir., including hidden ones, most recent first
fls f^l /usr/local/bin/c* # List matches that are files, but not (^) symlinks (l)
Supported platforms
Note: Even if you don't use Node.js, its package manager, npm
, works across platforms and is easy to install; try
curl -L https://git.io/n-install | bash
With Node.js installed, install as follows:
[sudo] npm install fls -g
Note:
Whether you need sudo
depends on how you installed Node.js / io.js and whether you've changed permissions later; if you get an EACCES
error, try again with sudo
.
The -g
ensures global installation and is needed to put fls
in your system's $PATH
.
bash
script as fls
.chmod +x fls
.$PATH
, such as /usr/local/bin
(macOS) or /usr/bin
(Linux).If I understand your question correctly, I've made a fiddle that has this working correctly. This issue is with how you're assigning the event handlers and as others have said you have over riding event handlers. The current jQuery best practice is to use on()
to register event handlers. Here's a link to the jQuery docs about on
: link
Your original solution was pretty close but the way you added the event handlers is a bit confusing. It's considered best practice to not add events to HTML elements. I recommend reading up on Unobstrusive JavaScript.
Here's the JavaScript code. I added a counter variable so you can see that it is working correctly.
$('#answer').on('click', function() {
feedback('hey there');
});
var counter = 0;
function feedback(message) {
$('#feedback').remove();
$('.answers').append('<div id="feedback">' + message + ' ' + counter + '</div>');
counter++;
}
I would strongly recommend not to use synchronous (blocking) functions, as they hold other concurrent operations. Instead, use asynchronous fs.promises:
const fs = require('fs').promises
const setValue = (fn, value) =>
fs.readFile(fn)
.then(body => JSON.parse(body))
.then(json => {
// manipulate your data here
json.value = value
return json
})
.then(json => JSON.stringify(json))
.then(body => fs.writeFile(fn, body))
.catch(error => console.warn(error))
Remeber that setValue
returns a pending promise, you'll need to use .then function or, within async functions, the await operator.
// await operator
await setValue('temp.json', 1) // save "value": 1
await setValue('temp.json', 2) // then "value": 2
await setValue('temp.json', 3) // then "value": 3
// then-sequence
setValue('temp.json', 1) // save "value": 1
.then(() => setValue('temp.json', 2)) // then save "value": 2
.then(() => setValue('temp.json', 3)) // then save "value": 3
Are you mixing C and C++? One issue that can occur is that the declarations in the .h
file for a .c
file need to be surrounded by:
#if defined(__cplusplus)
extern "C" { // Make sure we have C-declarations in C++ programs
#endif
and:
#if defined(__cplusplus)
}
#endif
Note: if unable / unwilling to modify the .h
file(s) in question, you can surround their inclusion with extern "C"
:
extern "C" {
#include <abc.h>
} //extern
It is possible the other branch you try to pull from is out of synch; so before adding and removing remote try to (if you are trying to pull from master)
git pull origin master
for me that simple call solved those error messages:
Don't use File constructor with String.
This may not work!
Instead of this use URI:
File f = new File(new URI("file:///"+filePathString.replace('\\', '/')));
if(f.exists() && !f.isDirectory()) {
// to do
}
h5py provides a model of datasets and groups. The former is basically arrays and the latter you can think of as directories. Each is named. You should look at the documentation for the API and examples:
http://docs.h5py.org/en/latest/quick.html
A simple example where you are creating all of the data upfront and just want to save it to an hdf5 file would look something like:
In [1]: import numpy as np
In [2]: import h5py
In [3]: a = np.random.random(size=(100,20))
In [4]: h5f = h5py.File('data.h5', 'w')
In [5]: h5f.create_dataset('dataset_1', data=a)
Out[5]: <HDF5 dataset "dataset_1": shape (100, 20), type "<f8">
In [6]: h5f.close()
You can then load that data back in using: '
In [10]: h5f = h5py.File('data.h5','r')
In [11]: b = h5f['dataset_1'][:]
In [12]: h5f.close()
In [13]: np.allclose(a,b)
Out[13]: True
Definitely check out the docs:
Writing to hdf5 file depends either on h5py or pytables (each has a different python API that sits on top of the hdf5 file specification). You should also take a look at other simple binary formats provided by numpy natively such as np.save
, np.savez
etc:
For the special date of January 1, 1970 there are multiple options.
For any other starting date you need to get the difference between the two dates in seconds. Subtracting two dates gives a timedelta
object, which as of Python 2.7 has a total_seconds()
function.
>>> (t-datetime.datetime(1970,1,1)).total_seconds()
1256083200.0
The starting date is usually specified in UTC, so for proper results the datetime
you feed into this formula should be in UTC as well. If your datetime
isn't in UTC already, you'll need to convert it before you use it, or attach a tzinfo
class that has the proper offset.
As noted in the comments, if you have a tzinfo
attached to your datetime
then you'll need one on the starting date as well or the subtraction will fail; for the example above I would add tzinfo=pytz.utc
if using Python 2 or tzinfo=timezone.utc
if using Python 3.
I had similar issue and the project had some build errors. I did sudo -R 777 to the project and then I cleaned my project. After that it worked fine.
Hope it helps.
You could use the string formatting operator for that:
>>> '%.2f' % 1.234
'1.23'
>>> '%.2f' % 5.0
'5.00'
The result of the operator is a string, so you can store it in a variable, print etc.
This is the VB.net version which works fine for me ported from the C code in BlaM's post.
There's a C implementation here:
http://www.cs.rit.edu/~ncs/color/t_convert.html
Should be very straightforward to convert to C#, as almost no functions are called - just > calculations.
Public Sub HSVtoRGB(ByRef r As Double, ByRef g As Double, ByRef b As Double, ByVal h As Double, ByVal s As Double, ByVal v As Double)
Dim i As Integer
Dim f, p, q, t As Double
If (s = 0) Then
' achromatic (grey)
r = v
g = v
b = v
Exit Sub
End If
h /= 60 'sector 0 to 5
i = Math.Floor(h)
f = h - i 'factorial part of h
p = v * (1 - s)
q = v * (1 - s * f)
t = v * (1 - s * (1 - f))
Select Case (i)
Case 0
r = v
g = t
b = p
Exit Select
Case 1
r = q
g = v
b = p
Exit Select
Case 2
r = p
g = v
b = t
Exit Select
Case 3
r = p
g = q
b = v
Exit Select
Case 4
r = t
g = p
b = v
Exit Select
Case Else 'case 5:
r = v
g = p
b = q
Exit Select
End Select
End Sub
I had the same problem, but I noticed that my datagrid lost the rows's header after the datagrid.visible
property changed.
Try to update the rows's headers with the Datagrid.visiblechanged
event.
I am posting this because this took me hours to find so i hope it may help someone.
I had a problem that the shadow/elevation was not showing though i created a simple activity and placed the toolbar as follows:
<androidx.appcompat.widget.Toolbar
android:id="@+id/mt_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
android:background="@color/colorPrimaryDark"
android:elevation="12dp"/>
It turns out that in the manifest
setting android:hardwareAccelerated="false"
was causing it! once i removed it, the shadow appeared
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Floating-point numbers cannot represent all the numbers. In particular, 2.51 cannot be represented by a floating-point number, and is represented by a number very close to it:
>>> print "%.16f" % 2.51
2.5099999999999998
>>> 2.51*100
250.99999999999997
>>> 4.02*100
401.99999999999994
If you use int, which truncates the numbers, you get:
250
401
Have a look at the Decimal type.
“Insensitive to space” is an oversimplification. A more accurate description is that consecutive whitespace characters (spaces, tabs, newlines) are equivalent to a single space, in normal content.
You make empty spaces between words using space characters: “hello world”. I you want more space, you should consider what you are doing, since in normal text content, that does not make sense. For spacing elements, use CSS margin
properties.
To get useful example codes, you need to describe a specific problem, like markup and a description of desired rendering.
Even though the question is old and answered. There is a simpler answer to that than the above mentioned. You don't need to use any other variables. You can create the buttons on action bar whatever the fragment you want, instead of doing the visibility stuff(show/hide).
Add the following in the fragment whatever u need the menu item.
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
Sample menu.xml file:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_addFlat"
android:icon="@drawable/add"
android:showAsAction="ifRoom|withText"
android:title="@string/action_addFlat"/>
</menu>
Handling onclick events is as usual.
This post got me to my answer even though the answer is missing from this post. I felt I should give back.
The challenge here is in the inconsistent behavior of BeautifulSoup.find
when searching with and without text.
Note: If you have BeautifulSoup, you can test this locally via:
curl https://gist.githubusercontent.com/RichardBronosky/4060082/raw/test.py | python
Code: https://gist.github.com/4060082
# Taken from https://gist.github.com/4060082
from BeautifulSoup import BeautifulSoup
from urllib2 import urlopen
from pprint import pprint
import re
soup = BeautifulSoup(urlopen('https://gist.githubusercontent.com/RichardBronosky/4060082/raw/test.html').read())
# I'm going to assume that Peter knew that re.compile is meant to cache a computation result for a performance benefit. However, I'm going to do that explicitly here to be very clear.
pattern = re.compile('Fixed text')
# Peter's suggestion here returns a list of what appear to be strings
columns = soup.findAll('td', text=pattern, attrs={'class' : 'pos'})
# ...but it is actually a BeautifulSoup.NavigableString
print type(columns[0])
#>> <class 'BeautifulSoup.NavigableString'>
# you can reach the tag using one of the convenience attributes seen here
pprint(columns[0].__dict__)
#>> {'next': <br />,
#>> 'nextSibling': <br />,
#>> 'parent': <td class="pos">\n
#>> "Fixed text:"\n
#>> <br />\n
#>> <strong>text I am looking for</strong>\n
#>> </td>,
#>> 'previous': <td class="pos">\n
#>> "Fixed text:"\n
#>> <br />\n
#>> <strong>text I am looking for</strong>\n
#>> </td>,
#>> 'previousSibling': None}
# I feel that 'parent' is safer to use than 'previous' based on http://www.crummy.com/software/BeautifulSoup/bs4/doc/#method-names
# So, if you want to find the 'text' in the 'strong' element...
pprint([t.parent.find('strong').text for t in soup.findAll('td', text=pattern, attrs={'class' : 'pos'})])
#>> [u'text I am looking for']
# Here is what we have learned:
print soup.find('strong')
#>> <strong>some value</strong>
print soup.find('strong', text='some value')
#>> u'some value'
print soup.find('strong', text='some value').parent
#>> <strong>some value</strong>
print soup.find('strong', text='some value') == soup.find('strong')
#>> False
print soup.find('strong', text='some value') == soup.find('strong').text
#>> True
print soup.find('strong', text='some value').parent == soup.find('strong')
#>> True
Though it is most certainly too late to help the OP, I hope they will make this as the answer since it does satisfy all quandaries around finding by text.
It seems that you are looking to parse commandline arguments into your bash script. I have searched for this recently myself. I came across the following which I think will assist you in parsing the arguments:
http://rsalveti.wordpress.com/2007/04/03/bash-parsing-arguments-with-getopts/
I added the snippet below as a tl;dr
#using : after a switch variable means it requires some input (ie, t: requires something after t to validate while h requires nothing.
while getopts “ht:r:p:v” OPTION
do
case $OPTION in
h)
usage
exit 1
;;
t)
TEST=$OPTARG
;;
r)
SERVER=$OPTARG
;;
p)
PASSWD=$OPTARG
;;
v)
VERBOSE=1
;;
?)
usage
exit
;;
esac
done
if [[ -z $TEST ]] || [[ -z $SERVER ]] || [[ -z $PASSWD ]]
then
usage
exit 1
fi
./script.sh -t test -r server -p password -v
Someone should mention that in the question there is a little trap. #ifdef
will only check if the following symbol has been defined via #define
or by command line, but its value (its substitution in fact) is irrelevant. You could even write
#define one
precompilers accept that.
But if you use #if
it's another thing.
#define one 0
#if one
printf("one evaluates to a truth ");
#endif
#if !one
printf("one does not evaluate to truth ");
#endif
will give one does not evaluate to truth
. The keyword defined
allows to get the desired behaviour.
#if defined(one)
is therefore equivalent to #ifdef
The advantage of the #if
construct is to allow a better handling of code paths, try to do something like that with the old #ifdef
/#ifndef
pair.
#if defined(ORA_PROC) || defined(__GNUC) && __GNUC_VERSION > 300
You could also try jARVEST.
It is based on a JRuby DSL over a pure-Java engine to spider-scrape-transform web sites.
Example:
Find all links inside a web page (wget
and xpath
are constructs of the jARVEST's language):
wget | xpath('//a/@href')
Inside a Java program:
Jarvest jarvest = new Jarvest();
String[] results = jarvest.exec(
"wget | xpath('//a/@href')", //robot!
"http://www.google.com" //inputs
);
for (String s : results){
System.out.println(s);
}
Using the Datejs library, this can be as easy as:
Date.parse("05/05/2010").toString("MMMM yyyy");
// parse date convert to
// string with
// custom format
Simple:
[DataType(DataType.Date)]
Public DateTime Ldate {get;set;}
Well you're right, REST is stateless. If you use a session the processing will become stateful, subsequent requests will be able to use state (from a session).
In order for a session to be rehydrated, you'll need to supply a key to associate the state. In a normal asp.net application that key is supplied by using a cookie (cookie-sessions) or url parameter (cookieless sessions).
If you need a session forget rest, sessions are irrelevant in REST based designs. If you need a session for validation then use a token or authorise by IP addresses.
This is what finally worked for me.
Configure your Android emulator's proxy to use your IP address as host name and the port your backend is running on as port (in my case: 192.168.1.86:8080
Have your Android app send requests to the same URL (192.168.1.86:8080) (sending requests to localhost, and http://10.0.2.2 did not work for me)
With new pandas version, it is easy to get as dataframe
unique_count = pd.groupby(['YEARMONTH'], as_index=False).agg(uniq_CLIENTCODE =('CLIENTCODE',pd.Series.count))
in "stdapi.h"
StrToInt
This function tells you the result, and how many characters participated in the conversion.
[object Object]
This means somewhere the object is being converted to a string.
Converted to a string:
//Copy and paste in the browser console to see result
var product = {'name':'test'};
JSON.stringify(product + '');
Not converted to a string:
//Copy and paste in the browser console to see result
var product = {'name':'test'};
JSON.stringify(product);
You are mixing razor and aspx syntax,if your view engine is razor just do this:
<button class="btn btn-info" type="button" id="addressSearch"
onclick="location.href='@Url.Action("List", "Search")'">
The function c.query() has two argument
c.query("Fetch Data", "Post-Processing of Data")
The operation "Fetch Data" in this case is a DB-Query, now this may be handled by Node.js by spawning off a worker thread and giving it this task of performing the DB-Query. (Remember Node.js can create thread internally). This enables the function to return instantaneously without any delay
The second argument "Post-Processing of Data" is a callback function, the node framework registers this callback and is called by the event loop.
Thus the statement c.query (paramenter1, parameter2)
will return instantaneously, enabling node to cater for another request.
P.S: I have just started to understand node, actually I wanted to write this as comment to @Philip but since didn't have enough reputation points so wrote it as an answer.
For many it's a permission issue, but for me it turns out the error was brought about by a mistake in the form I was trying to submit. To be specific i had accidentally put a "greater than" sign after the value of "action". So I would suggest you take a second look at your code.
You can get around this even more easily with the Rebase extension, just use hg pull --rebase
and your commits are automatically re-comitted to the pulled revision, avoiding the branching issue.
All of the javascript functions given here won't work for an xml document having unspecified white spaces between the end tag '>' and the start tag '<'. To fix them, you just need to replace the first line in the functions
var reg = /(>)(<)(\/*)/g;
by
var reg = /(>)\s*(<)(\/*)/g;
In High Sierra, the cacerts is located at : /Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/jre/lib/security/cacerts
Root node is the DocumentElement
property of XmlDocument
XmlElement root = xmlDoc.DocumentElement
If you only have the node, you can get the root node by
XmlElement root = xmlNode.OwnerDocument.DocumentElement
In Asp.net Core 3+ Vesrion
Controller: If wants to return anything related to IActionResult & Data also, go for Controllercontroller
ApiController: Used as attribute/notation in API controller. That inherits ControllerBase Class
ControllerBase: If wants to return data only go for ControllerBase class
I needed an overload for:
public ActionResult Index(string i);
public ActionResult Index(int groupId, int itemId);
There were few enough arguments where I ended up doing this:
public ActionResult Index(string i, int? groupId, int? itemId)
{
if (!string.IsNullOrWhitespace(i))
{
// parse i for the id
}
else if (groupId.HasValue && itemId.HasValue)
{
// use groupId and itemId for the id
}
}
It's not a perfect solution, especially if you have a lot of arguments, but it works well for me.
CURLOPT_USERPWD
basically sends the base64 of the user:password
string with http header like below:
Authorization: Basic dXNlcjpwYXNzd29yZA==
So apart from the CURLOPT_USERPWD
you can also use the HTTP-Request
header option as well like below with other headers:
$headers = array(
'Content-Type:application/json',
'Authorization: Basic '. base64_encode("user:password") // <---
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
Did some tests both on linux and windows. I use a test file containing lines ending in LF and also lines ending in CRLF.
File is committed , removed and then checked out.
The value of core.autocrlf is set before commit and also before checkout.
The result is below.
commit core.autocrlf false, remove, checkout core.autocrlf false: LF=>LF CRLF=>CRLF
commit core.autocrlf false, remove, checkout core.autocrlf input: LF=>LF CRLF=>CRLF
commit core.autocrlf false, remove, checkout core.autocrlf true : LF=>LF CRLF=>CRLF
commit core.autocrlf input, remove, checkout core.autocrlf false: LF=>LF CRLF=>LF
commit core.autocrlf input, remove, checkout core.autocrlf input: LF=>LF CRLF=>LF
commit core.autocrlf input, remove, checkout core.autocrlf true : LF=>CRLF CRLF=>CRLF
commit core.autocrlf true, remove, checkout core.autocrlf false: LF=>LF CRLF=>LF
commit core.autocrlf true, remove, checkout core.autocrlf input: LF=>LF CRLF=>LF
commit core.autocrlf true, remove, checkout core.autocrlf true : LF=>CRLF CRLF=>CRLF
I found a git pre-commit hook that removes trailing whitespace.
#!/bin/sh
if git-rev-parse --verify HEAD >/dev/null 2>&1 ; then
against=HEAD
else
# Initial commit: diff against an empty tree object
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
# Find files with trailing whitespace
for FILE in `exec git diff-index --check --cached $against -- | sed '/^[+-]/d' | sed -r 's/:[0-9]+:.*//' | uniq` ; do
# Fix them!
sed -i 's/[[:space:]]*$//' "$FILE"
git add "$FILE"
done
exit