You have a lot of variants for using @RequestParam
with additional optional elements, e.g.
@RequestParam(required = false, defaultValue = "someValue", value="someAttr") String someAttr
If you don't put required = false
- param will be required by default.
defaultValue = "someValue"
- the default value to use as a fallback when the request parameter is not provided or has an empty value.
If request and method param are the same - you don't need value = "someAttr"
Don't disable it; instead set it to readonly, though this has no effect as per not allowing the user to change the state. But you can use jQuery to enforce this (prevent the user from changing the state of the checkbox:
$('input[type="checkbox"][readonly="readonly"]').click(function(e){
e.preventDefault();
});
This assumes that all the checkboxes you don't want to be modified have the "readonly" attribute. eg.
<input type="checkbox" readonly="readonly">
Opera, Chrome, Safari supports SSE, Chrome, Safari supports SSE inside of SharedWorker Firefox supports XMLHttpRequest readyState interactive, so we can make EventSource polyfil for Firefox
Just another clean way:
function validateIp($var_ip){
$ip = trim($var_ip);
return (!empty($ip) &&
$ip != '::1' &&
$ip != '127.0.0.1' &&
filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false)
? $ip : false;
}
function getClientIp() {
$ip = @$this->validateIp($_SERVER['HTTP_CLIENT_IP']) ?:
@$this->validateIp($_SERVER['HTTP_X_FORWARDED_FOR']) ?:
@$this->validateIp($_SERVER['HTTP_X_FORWARDED']) ?:
@$this->validateIp($_SERVER['HTTP_FORWARDED_FOR']) ?:
@$this->validateIp($_SERVER['HTTP_FORWARDED']) ?:
@$this->validateIp($_SERVER['REMOTE_ADDR']) ?:
'LOCAL OR UNKNOWN ACCESS';
return $ip;
}
Your code can be fixed as follows:
import numpy as np, cv
vis = np.zeros((384, 836), np.float32)
h,w = vis.shape
vis2 = cv.CreateMat(h, w, cv.CV_32FC3)
vis0 = cv.fromarray(vis)
cv.CvtColor(vis0, vis2, cv.CV_GRAY2BGR)
Short explanation:
np.uint32
data type is not supported by OpenCV (it supports uint8
, int8
, uint16
, int16
, int32
, float32
, float64
)cv.CvtColor
can't handle numpy arrays so both arguments has to be converted to OpenCV type. cv.fromarray
do this conversion.cv.CvtColor
must have the same depth. So I've changed source type to 32bit float to match the ddestination.Also I recommend you use newer version of OpenCV python API because it uses numpy arrays as primary data type:
import numpy as np, cv2
vis = np.zeros((384, 836), np.float32)
vis2 = cv2.cvtColor(vis, cv2.COLOR_GRAY2BGR)
My answer, cobbling together others' answers. This should correct for the failure to compensate for numeric keys:
function array_to_xml($array, $root, $element) {
$xml = new SimpleXMLElement("<{$root}/>");
foreach ($array as $value) {
$elem = $xml->addChild($element);
xml_recurse_child($elem, $value);
}
return $xml;
}
function xml_recurse_child(&$node, $child) {
foreach ($child as $key=>$value) {
if(is_array($value)) {
foreach ($value as $k => $v) {
if(is_numeric($k)){
xml_recurse_child($node, array($key => $v));
}
else {
$subnode = $node->addChild($key);
xml_recurse_child($subnode, $value);
}
}
}
else {
$node->addChild($key, $value);
}
}
}
The array_to_xml()
function presumes that the array is made up of numeric keys first. If your array had an initial element, you would drop the foreach()
and $elem
statements from the array_to_xml()
function and just pass $xml
instead.
scrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// Ready, move up
scrollView.fullScroll(View.FOCUS_UP);
}
});
While AngularJS allows you to get a hand on a click event (and thus a target of it) with the following syntax (note the $event
argument to the setMaster
function; documentation here: http://docs.angularjs.org/api/ng.directive:ngClick):
function AdminController($scope) {
$scope.setMaster = function(obj, $event){
console.log($event.target);
}
}
this is not very angular-way of solving this problem. With AngularJS the focus is on the model manipulation. One would mutate a model and let AngularJS figure out rendering.
The AngularJS-way of solving this problem (without using jQuery and without the need to pass the $event
argument) would be:
<div ng-controller="AdminController">
<ul class="list-holder">
<li ng-repeat="section in sections" ng-class="{active : isSelected(section)}">
<a ng-click="setMaster(section)">{{section.name}}</a>
</li>
</ul>
<hr>
{{selected | json}}
</div>
where methods in the controller would look like this:
$scope.setMaster = function(section) {
$scope.selected = section;
}
$scope.isSelected = function(section) {
return $scope.selected === section;
}
Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/WXJ3p/15/
You can use a MultiBinding
combined with the StringFormat
property. Usage would resemble the following:
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0} + {1}">
<Binding Path="Name" />
<Binding Path="ID" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
Giving Name
a value of Foo
and ID
a value of 1
, your output in the TextBlock would then be Foo + 1
.
Note:
that this is only supported in .NET 3.5 SP1 and 3.0 SP2 or later.
Yeah, your current solution is prone to SQL injection attacks.
The best solution that I've found is to use a function that splits text into words (there are a few posted here, or you can use this one from my blog) and then join that to your table. Something like:
SELECT d.[Name]
FROM Department d
JOIN dbo.SplitWords(@DepartmentIds) w ON w.Value = d.DepartmentId
For Arch Linux, it is pacman -S lib32-zlib
from multilib, not zlib
.
Swift 2.0 For 'Not Running' State (Local & Remote Notification)
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Handle notification
if (launchOptions != nil) {
// For local Notification
if let localNotificationInfo = launchOptions?[UIApplicationLaunchOptionsLocalNotificationKey] as? UILocalNotification {
if let something = localNotificationInfo.userInfo!["yourKey"] as? String {
self.window!.rootViewController = UINavigationController(rootViewController: YourController(yourMember: something))
}
} else
// For remote Notification
if let remoteNotification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as! [NSObject : AnyObject]? {
if let something = remoteNotification["yourKey"] as? String {
self.window!.rootViewController = UINavigationController(rootViewController: YourController(yourMember: something))
}
}
}
return true
}
Here is a code to get the child elements (In java):
String childTag = childElement.getTagName();
if(childTag.equals("html"))
{
return "/html[1]"+current;
}
WebElement parentElement = childElement.findElement(By.xpath(".."));
List<WebElement> childrenElements = parentElement.findElements(By.xpath("*"));
int count = 0;
for(int i=0;i<childrenElements.size(); i++)
{
WebElement childrenElement = childrenElements.get(i);
String childrenElementTag = childrenElement.getTagName();
if(childTag.equals(childrenElementTag))
{
count++;
}
}
Here is an example which answers the question of returning the parameters of a class. Moreover, it still respects the chain of inheritance, i.e. only the parameters of the class itself are returned. The function get_params
is added as a simple example, but other functionalities can be added thanks to the inspect module.
import inspect
class Parent:
@classmethod
def get_params(my_class):
return list(inspect.signature(my_class).parameters.keys())
class OtherParent:
def __init__(self, a, b, c):
pass
class Child(Parent, OtherParent):
def __init__(self, x, y, z):
pass
print(Child.get_params())
>>['x', 'y', 'z']
In Mono For Android....
try
{
System.IO.Stream StrIn = this.Assets.Open("MyMessage.txt");
string Content = string.Empty;
using (System.IO.StreamReader StrRead = new System.IO.StreamReader(StrIn))
{
try
{
Content = StrRead.ReadToEnd();
StrRead.Close();
}
catch (Exception ex) { csFunciones.MostarMsg(this, ex.Message); }
}
StrIn.Close();
StrIn = null;
}
catch (Exception ex) { csFunciones.MostarMsg(this, ex.Message); }
You can name cells. This is done by clicking the Name Box (that thing next to the formula bar which says "A1" for example) and typing a name, such as, "myvar". Now you can use that name instead of the cell reference:
= myvar*25
This post suggests that you should be able to get the IE Developer Toolbar to show you the XPath for an element you click on if you turn on the "select element by click" option. http://blog.balfes.net/?p=62
Alternatively this post suggests either bookmarklets, or IE debugbar: Equivalent of Firebug's "Copy XPath" in Internet Explorer?
// http://hostname.com/mywebapp/servlet/MyServlet/a/b;c=123?d=789
public static String getUrl(HttpServletRequest req) {
String reqUrl = req.getRequestURL().toString();
String queryString = req.getQueryString(); // d=789
if (queryString != null) {
reqUrl += "?"+queryString;
}
return reqUrl;
}
You can use WebKit.NET. This is a C# wrapper for WebKit, which is the rendering engine used by Chrome.
Stack frame is the packed information related to a function call. This information generally includes arguments passed to th function, local variables and where to return upon terminating. Activation record is another name for a stack frame. The layout of the stack frame is determined in the ABI by the manufacturer and every compiler supporting the ISA must conform to this standard, however layout scheme can be compiler dependent. Generally stack frame size is not limited but there is a concept called "red/protected zone" to allow system calls...etc to execute without interfering with a stack frame.
There is always a SP but on some ABIs (ARM's and PowerPC's for example) FP is optional. Arguments that needed to be placed onto the stack can be offsetted using the SP only. Whether a stack frame is generated for a function call or not depends on the type and number of arguments, local variables and how local variables are accessed generally. On most ISAs, first, registers are used and if there are more arguments than registers dedicated to pass arguments these are placed onto the stack (For example x86 ABI has 6 registers to pass integer arguments). Hence, sometimes, some functions do not need a stack frame to be placed on the stack, just the return address is pushed onto the stack.
The inherit
value, when used, means that the value of the property is set to the value of the same property of the parent element. For the root element (in HTML documents, for the html
element) there is no parent element; by definition, the value used is the initial value of the property. The initial value is defined for each property in CSS specifications.
The font-family
property is special in the sense that the initial value is not fixed in the specification but defined to be browser-dependent. This means that the browser’s default font family is used. This value can be set by the user.
If there is a continuous chain of elements (in the sense of parent-child relationships) from the root element to the current element, all with font-family
set to inherit
or not set at all in any style sheet (which also causes inheritance), then the font is the browser default.
This is rather uninteresting, though. If you don’t set fonts at all, browsers defaults will be used. Your real problem might be different – you seem to be looking at the part of style sheets that constitute a browser style sheet. There are probably other, more interesting style sheets that affect the situation.
You can either use the numerical indices ($row[0]
) or better, use AS
in the MySQL:
SELECT *, user.id AS user_id FROM ...
Actually this error occurs when server makes connection but can't build due to failure in identifying connection function identifier. This problem can be solved by typing connection function in code. For this I take a simple example. In this case function is con your may be different.
SqlCommand cmd = new SqlCommand("insert into ptb(pword,rpword) values(@a,@b)",con);
here are my personal ~/.vimrc backup settings
" backup to ~/.tmp
set backup
set backupdir=~/.vim-tmp,~/.tmp,~/tmp,/var/tmp,/tmp
set backupskip=/tmp/*,/private/tmp/*
set directory=~/.vim-tmp,~/.tmp,~/tmp,/var/tmp,/tmp
set writebackup
You could run it without the -jar
command line argument if you happen to know the name of the main class you wish to run:
java -classpath .;myjar.jar;lib/referenced-class.jar my.package.MainClass
If perchance you are using linux, you should use ":" instead of ";" in the classpath.
Go with range for these reasons:
1) xrange will be going away in newer Python versions. This gives you easy future compatibility.
2) range will take on the efficiencies associated with xrange.
In my experience, to use wmic
in a script, you need to get the nested quoting right:
wmic product where "name = 'Windows Azure Authoring Tools - v2.3'" call uninstall /nointeractive
quoting both the query and the name. But wmic will only uninstall things installed via windows installer.
In PyCharm go to
C:\Miniconda3\envs\my_env\python.exe
, where my_env is the environment you want to useAlternatively, in step 3 use C:\Miniconda3\python.exe
if you did not create any further environments (if you never invoked conda create -n my_env python=3
).
You can get a list of your current environments with conda info -e
and switch to one of them using activate my_env
.
From what you printed, it seems var2
is an array containing one string. Or actually, it appears to hold the result of running .inspect
on an array containing one string. It would be helpful to show how you are initializing them.
irb(main):005:0* v1 = "test"
=> "test"
irb(main):006:0> v2 = ["test"]
=> ["test"]
irb(main):007:0> v3 = v2.inspect
=> "[\"test\"]"
irb(main):008:0> puts v1,v2,v3
test
test
["test"]
You don't have to click anything. Use find by xpath or whatever you choose and then use send keys
For your example: HTML:
<select id="fruits01" class="select" name="fruits">
<option value="0">Choose your fruits:</option>
<option value="1">Banana</option>
<option value="2">Mango</option>
</select>
Python:
fruit_field = browser.find_element_by_xpath("//input[@name='fruits']")
fruit_field.send_keys("Mango")
That's it.
Do you mean that you've got code like
if(map.containsKey(key)) doSomethingWith(map.get(key))
all over the place ? Then you should simply check whether map.get(key)
returned null and that's it.
By the way, HashMap doesn't throw exceptions for missing keys, it returns null instead. The only case where containsKey
is needed is when you're storing null values, to distinguish between a null value and a missing value, but this is usually considered bad practice.
@K Scott Piel wrote a great answer here, but I want to add one important point.
Note that the stdout
stream is usually line-buffered, so to ensure the output is actually printed and not just left sitting in the buffer waiting to be written you must flush the buffer by either ending your printf
statement with a \n
Ex:
printf("hello world\n");
or
printf("hello world");
printf("\n");
or similar, OR you must call fflush(stdout);
after your printf
call.
Ex:
printf("hello world");
fflush(stdout);
Read more here: Why does printf not flush after the call unless a newline is in the format string?
Just add a new form and add buttons and a label. Give the value to be shown and the text of the button, etc. in its constructor, and call it from anywhere you want in the project.
In project -> Add Component -> Windows Form and select a form
Add some label and buttons.
Initialize the value in constructor and call it from anywhere.
public class form1:System.Windows.Forms.Form
{
public form1()
{
}
public form1(string message,string buttonText1,string buttonText2)
{
lblMessage.Text = message;
button1.Text = buttonText1;
button2.Text = buttonText2;
}
}
// Write code for button1 and button2 's click event in order to call
// from any where in your current project.
// Calling
Form1 frm = new Form1("message to show", "buttontext1", "buttontext2");
frm.ShowDialog();
Since it depends on the version of your JRE which is used to run the maven command you propably dont want to disable DocLint
per default in your pom.xml
Hence, from command line you can use the switch -Dadditionalparam=-Xdoclint:none
.
Example: mvn clean install -Dadditionalparam=-Xdoclint:none
I think that there is a more simple approach to all given here, and is the method Number.toFixed()
already implemented in JavaScript.
simply write:
var myNumber = 2;
myNumber.toFixed(2); //returns "2.00"
myNumber.toFixed(1); //returns "2.0"
etc...
Often you have an array of related records, I find it easy and fairly declarative to fill select
this way:
selectEl.innerHTML = array.map(c => '<option value="'+c.id+'">'+c.name+'</option>').join('');
This will replace existing options.
You can use selectEl.insertAdjacentHTML('afterbegin', str);
to add them to the top instead.
And selectEl.insertAdjacentHTML('beforeend', str);
to add them to the bottom of the list.
IE11 compatible syntax:
array.map(function (c) { return '<option value="'+c.id+'">'+c.name+'</option>'; }).join('');
It means you allow every (*
) user-agent/crawler to access the root (/
) of your site. You're okay.
Please note that the tr -s ' '
option will not remove any single leading spaces. If your column is right-aligned (as with ps
pid)...
$ ps h -o pid,user -C ssh,sshd | tr -s " "
1543 root
19645 root
19731 root
Then cutting will result in a blank line for some of those fields if it is the first column:
$ <previous command> | cut -d ' ' -f1
19645
19731
Unless you precede it with a space, obviously
$ <command> | sed -e "s/.*/ &/" | tr -s " "
Now, for this particular case of pid numbers (not names), there is a function called pgrep
:
$ pgrep ssh
However, in general it is actually still possible to use shell functions in a concise manner, because there is a neat thing about the read
command:
$ <command> | while read a b; do echo $a; done
The first parameter to read, a
, selects the first column, and if there is more, everything else will be put in b
. As a result, you never need more variables than the number of your column +1.
So,
while read a b c d; do echo $c; done
will then output the 3rd column. As indicated in my comment...
A piped read will be executed in an environment that does not pass variables to the calling script.
out=$(ps whatever | { read a b c d; echo $c; })
arr=($(ps whatever | { read a b c d; echo $c $b; }))
echo ${arr[1]} # will output 'b'`
So we then end up with the answer by @frayser which is to use the shell variable IFS which defaults to a space, to split the string into an array. It only works in Bash though. Dash and Ash do not support it. I have had a really hard time splitting a string into components in a Busybox thing. It is easy enough to get a single component (e.g. using awk) and then to repeat that for every parameter you need. But then you end up repeatedly calling awk on the same line, or repeatedly using a read block with echo on the same line. Which is not efficient or pretty. So you end up splitting using ${name%% *}
and so on. Makes you yearn for some Python skills because in fact shell scripting is not a lot of fun anymore if half or more of the features you are accustomed to, are gone. But you can assume that even python would not be installed on such a system, and it wasn't ;-).
You can add join type as well:
Criteria c2 = c.createCriteria("mother", "mother", CriteriaSpecification.LEFT_JOIN);
Criteria c3 = c2.createCriteria("kind", "kind", CriteriaSpecification.LEFT_JOIN);
Let's not over complicate things...:
(Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property capacity -Sum).sum /1gb
basename
does remove the directory prefix of a path:
$ basename /usr/local/svn/repos/example
example
$ echo "/server/root/$(basename /usr/local/svn/repos/example)"
/server/root/example
Use "\t". That's the tab space character.
You can find a list of many of the Java escape characters here: http://java.sun.com/docs/books/tutorial/java/data/characters.html
Running a .C file using the terminal is a two-step process. The first step is to type gcc in the terminal and drop the .C file to the terminal, and then press Enter:
username$ gcc /Desktop/test.c
In the second step, run the following command:
username$ ~/a.out
You could finish your Activity by calling Activity.finish(). However take care of the Android Activity life-cycle.
Why and when you should mark the request
parameter as implicit
:
Some methods that you will make use of in the body of your action have an implicit parameter list like, for example, Form.scala defines a method:
def bindFromRequest()(implicit request: play.api.mvc.Request[_]): Form[T] = { ... }
You don't necessarily notice this as you would just call myForm.bindFromRequest()
You don't have to provide the implicit arguments explicitly. No, you leave the compiler to look for any valid candidate object to pass in every time it comes across a method call that requires an instance of the request. Since you do have a request available, all you need to do is to mark it as implicit
.
You explicitly mark it as available for implicit use.
You hint the compiler that it's "OK" to use the request object sent in by the Play framework (that we gave the name "request" but could have used just "r" or "req") wherever required, "on the sly".
myForm.bindFromRequest()
see it? it's not there, but it is there!
It just happens without your having to slot it in manually in every place it's needed (but you can pass it explicitly, if you so wish, no matter if it's marked implicit
or not):
myForm.bindFromRequest()(request)
Without marking it as implicit, you would have to do the above. Marking it as implicit you don't have to.
When should you mark the request as implicit
? You only really need to if you are making use of methods that declare an implicit parameter list expecting an instance of the Request. But to keep it simple, you could just get into the habit of marking the request implicit
always. That way you can just write beautiful terse code.
In MVC4 WebAPI 404 can be handle in the following way,
COURSES APICONTROLLER
// GET /api/courses/5
public HttpResponseMessage<Courses> Get(int id)
{
HttpResponseMessage<Courses> resp = null;
var aCourse = _courses.Where(c => c.Id == id).FirstOrDefault();
resp = aCourse == null ? new HttpResponseMessage<Courses>(System.Net.HttpStatusCode.NotFound) : new HttpResponseMessage<Courses>(aCourse);
return resp;
}
HOME CONTROLLER
public ActionResult Course(int id)
{
return View(id);
}
VIEW
<div id="course"></div>
<script type="text/javascript">
var id = @Model;
var course = $('#course');
$.ajax({
url: '/api/courses/' + id,
success: function (data) {
course.text(data.Name);
},
statusCode: {
404: function()
{
course.text('Course not available!');
}
}
});
</script>
GLOBAL
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
RESULTS
Other guys and gals give the solutions, but maybe I can tell you why.
git checkout test which does nothing
Does nothing
doesn't equal doesn't work
, so I guess when you type 'git checkout test' in your terminal and press enter key, no message appears and no error occurs. Am I right?
If the answer is 'yes', I can tell you the cause.
The cause is that there is a file (or folder) named 'test' in your work tree.
When git checkout xxx
parsed,
xxx
as a branch name at first, but there isn't any branch named test.xxx
is a path, and fortunately (or unfortunately), there is a file named test. So git checkout xxx
means discard any modification in xxx
file.xxx
either, then Git will try to create the xxx
according to some rules. One of the rules is create a branch named xxx
if remotes/origin/xxx
exists.while(inFile1.hasNext()){
token1 = inFile1.nextLine();
// put each value into an array with String#split();
String[] numStrings = line.split(", ");
// parse number string into doubles
double[] nums = new double[numString.length];
for (int i = 0; i < nums.length; i++){
nums[i] = Double.parseDouble(numStrings[i]);
}
}
You can use Popen in subprocess
as they suggest.
with os
, which is not recomment, it's like below:
import os
a = os.popen('pwd').readlines()
This is simple way to convert files to Base64 and avoid "maximum call stack size exceeded at FileReader.reader.onload" with the file has big size.
document.querySelector('#fileInput').addEventListener('change', function () {_x000D_
_x000D_
var reader = new FileReader();_x000D_
var selectedFile = this.files[0];_x000D_
_x000D_
reader.onload = function () {_x000D_
var comma = this.result.indexOf(',');_x000D_
var base64 = this.result.substr(comma + 1);_x000D_
console.log(base64);_x000D_
}_x000D_
reader.readAsDataURL(selectedFile);_x000D_
}, false);
_x000D_
<input id="fileInput" type="file" />
_x000D_
To check the accurate usage for your services be it is free (as per always free or 12 months free) or Pay-As-You-Go, it is important to monitor the usage so that you know upfront on the cost incurred or when to upgrade your service tier.
To check your free service usage and its limits, Go to search in Portal, search with "Subscription" and click on it. you will see the details of each service that you have used.
In case of free azure from Microsoft, you get to see the cost incurred for each one.
Visit Check usage of free services included with your Azure free account
Hope this helps someone!
The error log is straightforward. As it suggested,You need to add 198.211.99.20 to your ALLOWED_HOSTS
setting.
In your project settings.py file,set ALLOWED_HOSTS
like this :
ALLOWED_HOSTS = ['198.211.99.20', 'localhost', '127.0.0.1']
For further reading read from here.
try this it's very easy to use and tested on IE and Safari and FF and worked fine and beside no need for many div
around it just add id
and it will work fine, after you link you Js and Css files. FaceScroll Custom scrollbar
hope it help's
Edit Step 1: Add the below script to the section of your page:
<link href="general.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script type="text/javascript" src="jquery.ui.touch-punch.min.js"></script>
<script type="text/javascript" src="facescroll.js"></script>
<script type="text/javascript">
jQuery(function(){ // on page DOM load
$('#demo1').alternateScroll();
$('#demo2').alternateScroll({ 'vertical-bar-class': 'styled-v-bar', 'hide-bars': false });
})
</script>
Step 2: Then in the BODY of your page, add the below sample HTML block to your page.
<p><b>Scrollbar (default style) shows onMouseover</b></p>
<div id="demo1" style="width:300px; height:250px; padding:8px; background:lightyellow; border:1px solid gray; resize:both; overflow:scroll">
From Wikipedia- Gunpowder, also known since in the late 19th century as black powder, was the first chemical explosive and the only one known until the mid 1800s.[2] It is a mixture of sulfur, charcoal, and potassium nitrate (saltpeter) - with the sulfur and charcoal acting as fuels, while the saltpeter works as an oxidizer.[3] Because of its
</div>
<br />
<p><b>Scrollbar (alternate style), always shown</b></p>
<div id="demo2" style="width:400px; height:130px; padding:10px; padding-right:8px; background:lightyellow; border:1px solid gray; overflow:scroll; resize:both;">
From Wikipedia- Gunpowder, also known since in the late 19th century as black powder, was the first chemical explosive and the only one known until the mid 1800s.[2] It is a mixture of sulfur, charcoal, and potassium nitrate (saltpeter) - with the sulfur and charcoal acting as fuels, while the saltpeter works as an oxidizer.[3] Because of its
</div>
Another way of doing this is using nested IF statements. Suppose you have companies table and you want to count number of records in it. A sample query would be something like this
SELECT IF(
count(*) > 15,
'good',
IF(
count(*) > 10,
'average',
'poor'
)
) as data_count
FROM companies
Here second IF condition works when the first IF condition fails. So Sample Syntax of the IF statement would be IF ( CONDITION, THEN, ELSE). Hope it helps someone.
Most of the answers do not indicate that the container must run before docker cp
will work:
docker build -t IMAGE_TAG .
docker run -d IMAGE_TAG
CONTAINER_ID=$(docker ps -alq)
# If you do not know the exact file name, you'll need to run "ls"
# FILE=$(docker exec CONTAINER_ID sh -c "ls /path/*.zip")
docker cp $CONTAINER_ID:/path/to/file .
docker stop $CONTAINER_ID
Really, I tested saving values like 'é' and 'e' in column with unique index and they cause duplicate error on both 'utf8_unicode_ci' and 'utf8_general_ci'. You can save them only in 'utf8_bin' collated column.
And mysql docs (in http://dev.mysql.com/doc/refman/5.7/en/charset-applications.html) suggest into its examples set 'utf8_general_ci' collation.
[mysqld]
character-set-server=utf8
collation-server=utf8_general_ci
Perhaps it is indirect to gdb (because it's an IDE), but my recommendations would be KDevelop. Being quite spoiled with Visual Studio's debugger (professionally at work for many years), I've so far felt the most comfortable debugging in KDevelop (as hobby at home, because I could not afford Visual Studio for personal use - until Express Edition came out). It does "look something similar to" Visual Studio compared to other IDE's I've experimented with (including Eclipse CDT) when it comes to debugging step-through, step-in, etc (placing break points is a bit awkward because I don't like to use mouse too much when coding, but it's not difficult).
First of all: you should always import mockito static, this way the code will be much more readable (and intuitive):
import static org.mockito.Mockito.*;
There are actually many ways to achieve this, however it's (arguably) cleaner to use the
verify(yourMock, times(0)).someMethod();
method all over your tests, when on other Tests you use it to assert a certain amount of executions like this:
verify(yourMock, times(5)).someMethod();
Alternatives are:
verify(yourMock, never()).someMethod();
Alternatively - when you really want to make sure a certain mocked Object is actually NOT called at all - you can use:
verifyZeroInteractions(yourMock)
Use the sed delete
command with a range address. For example:
sed 1,100d file.txt # Print file.txt omitting lines 1-100.
Alternatively, if you want to only print a known range, use the print command with the -n
flag:
sed -n 201,300p file.txt # Print lines 201-300 from file.txt
This solution should work reliably on all Unix systems, regardless of the presence of GNU utilities.
New-style classes inherit from object
, or from another new style class:
class SomeObject(object):
pass
class SubObject(SomeObject):
pass
Old-style classes don't:
class SomeObject:
pass
This only applies to Python 2 - in Python 3 all the above will create new-style classes.
See 9. Classes (Python tutorial), NewClassVsClassicClass and What is the difference between old style and new style classes in Python? for details.
I'm not sure which version you had, but this question was asked for long time ago. Currently with Angular 1.5, I can use the ng-keypress
event and debounce
function from Lodash to emulate similar behavior like ng-change
, so I can capture the $event
<input type="text" ng-keypress="edit($event)" ng-model="myModel">
$scope.edit = _.debounce(function ($event) { console.log("$event", $event) }, 800)
Consider the alternative:
<properties>
<javac.src.version>1.8</javac.src.version>
<javac.target.version>1.8</javac.target.version>
</properties>
It should be the same thing of maven.compiler.source/maven.compiler.target
but the above solution works for me, otherwise the second one gets the parent specification (I have a matrioska of .pom)
Could you post the fragment's onCreate
and onCreateView
methods? I had exactly same exception which was caused by an exception in the fragment onCreate
method, when I fixed that problem it fixed the Error inflating class fragment.
For me, it worked as given below:
<div ng-repeat="product in products | filter: { color: 'red'||'blue' }">
<div ng-repeat="product in products | filter: { color: 'red'} | filter: { color:'blue' }">
extensionsToCheck = ('.pdf', '.doc', '.xls')
'test.doc'.endswith(extensionsToCheck) # returns True
'test.jpg'.endswith(extensionsToCheck) # returns False
If you do not want to define a separate class for nested json , Defining nested json object as JsonNode should work ,for example :
{"id":2,"socket":"0c317829-69bf-43d6-b598-7c0c550635bb","type":"getDashboard","data":{"workstationUuid":"ddec1caa-a97f-4922-833f-632da07ffc11"},"reply":true}
@JsonProperty("data")
private JsonNode data;
You're applying transitions only to the :hover
pseudo-class, and not to the element itself.
.item {
height:200px;
width:200px;
background:red;
-webkit-transition: opacity 1s ease-in-out;
-moz-transition: opacity 1s ease-in-out;
-ms-transition: opacity 1s ease-in-out;
-o-transition: opacity 1s ease-in-out;
transition: opacity 1s ease-in-out;
}
.item:hover {
zoom: 1;
filter: alpha(opacity=50);
opacity: 0.5;
}
Demo: http://jsfiddle.net/7uR8z/6/
If you don't want the transition to affect the mouse-over
event, but only mouse-out
, you can turn transitions off for the :hover
state :
.item:hover {
-webkit-transition: none;
-moz-transition: none;
-ms-transition: none;
-o-transition: none;
transition: none;
zoom: 1;
filter: alpha(opacity=50);
opacity: 0.5;
}
I couldn't find the code in the doc suggested by the accepted answer but I found the updated equivalent here:
File System Programming Guide :: Accessing Files and Directories »
- (NSURL*)applicationDataDirectory {
NSFileManager* sharedFM = [NSFileManager defaultManager];
NSArray* possibleURLs = [sharedFM URLsForDirectory:NSApplicationSupportDirectory
inDomains:NSUserDomainMask];
NSURL* appSupportDir = nil;
NSURL* appDirectory = nil;
if ([possibleURLs count] >= 1) {
// Use the first directory (if multiple are returned)
appSupportDir = [possibleURLs objectAtIndex:0];
}
// If a valid app support directory exists, add the
// app's bundle ID to it to specify the final directory.
if (appSupportDir) {
NSString* appBundleID = [[NSBundle mainBundle] bundleIdentifier];
appDirectory = [appSupportDir URLByAppendingPathComponent:appBundleID];
}
return appDirectory;
}
It discourages use of NSSearchPathForDirectoriesInDomain:
The NSSearchPathForDirectoriesInDomains function behaves like the URLsForDirectory:inDomains: method but returns the directory’s location as a string-based path. You should use the URLsForDirectory:inDomains: method instead.
Here are some other useful directory constants to play with. No doubt not all of these are supported in iOS. Also you can use the NSHomeDirectory() function which:
In iOS, the home directory is the application’s sandbox directory. In OS X, it is the application’s sandbox directory or the current user’s home directory (if the application is not in a sandbox)
From NSPathUtilities.h
NSApplicationDirectory = 1, // supported applications (Applications)
NSDemoApplicationDirectory, // unsupported applications, demonstration versions (Demos)
NSDeveloperApplicationDirectory, // developer applications (Developer/Applications). DEPRECATED - there is no one single Developer directory.
NSAdminApplicationDirectory, // system and network administration applications (Administration)
NSLibraryDirectory, // various documentation, support, and configuration files, resources (Library)
NSDeveloperDirectory, // developer resources (Developer) DEPRECATED - there is no one single Developer directory.
NSUserDirectory, // user home directories (Users)
NSDocumentationDirectory, // documentation (Documentation)
NSDocumentDirectory, // documents (Documents)
NSCoreServiceDirectory, // location of CoreServices directory (System/Library/CoreServices)
NSAutosavedInformationDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 11, // location of autosaved documents (Documents/Autosaved)
NSDesktopDirectory = 12, // location of user's desktop
NSCachesDirectory = 13, // location of discardable cache files (Library/Caches)
NSApplicationSupportDirectory = 14, // location of application support files (plug-ins, etc) (Library/Application Support)
NSDownloadsDirectory NS_ENUM_AVAILABLE(10_5, 2_0) = 15, // location of the user's "Downloads" directory
NSInputMethodsDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 16, // input methods (Library/Input Methods)
NSMoviesDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 17, // location of user's Movies directory (~/Movies)
NSMusicDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 18, // location of user's Music directory (~/Music)
NSPicturesDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 19, // location of user's Pictures directory (~/Pictures)
NSPrinterDescriptionDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 20, // location of system's PPDs directory (Library/Printers/PPDs)
NSSharedPublicDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 21, // location of user's Public sharing directory (~/Public)
NSPreferencePanesDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 22, // location of the PreferencePanes directory for use with System Preferences (Library/PreferencePanes)
NSApplicationScriptsDirectory NS_ENUM_AVAILABLE(10_8, NA) = 23, // location of the user scripts folder for the calling application (~/Library/Application Scripts/code-signing-id)
NSItemReplacementDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 99, // For use with NSFileManager's URLForDirectory:inDomain:appropriateForURL:create:error:
NSAllApplicationsDirectory = 100, // all directories where applications can occur
NSAllLibrariesDirectory = 101, // all directories where resources can occur
NSTrashDirectory NS_ENUM_AVAILABLE(10_8, NA) = 102 // location of Trash directory
And finally, some convenience methods in an NSURL category http://club15cc.com/code/ios/easy-ios-file-directory-paths-with-this-handy-nsurl-category
You have to use the escaped unicode :
Like
.breadcrumbs a:before {
content: '\0000a0';
}
More info on : http://www.evotech.net/blog/2007/04/named-html-entities-in-numeric-order/
If you use Gulp then try:
npm install gulp-sass
I had the same problem and the gulp-sass
package was the problem.
The bootstrap 4.0.0 file you are getting from cdn doesn't have a pull-right (or pull-left) class. The v4 is in alpha, so there are many issues like that.
There are 2 options:
1) Reverse to bootstrap 3.3.7
2) Write your own CSS.
Google Finance has an API - you probably have to apply for a developers key, but at least you'd save yourself the hassle of screen-scraping: http://code.google.com/apis/finance/reference.html
Answers suggesting to disable CURLOPT_SSL_VERIFYPEER
should not be accepted. The question is "Why doesn't it work with cURL", and as correctly pointed out by Martijn Hols, it is dangerous.
The error is probably caused by not having an up-to-date bundle of CA root certificates. This is typically a text file with a bunch of cryptographic signatures that curl uses to verify a host’s SSL certificate.
You need to make sure that your installation of PHP has one of these files, and that it’s up to date (otherwise download one here: http://curl.haxx.se/docs/caextract.html).
Then set in php.ini:
curl.cainfo = <absolute_path_to> cacert.pem
If you are setting it at runtime, use:
curl_setopt ($ch, CURLOPT_CAINFO, dirname(__FILE__)."/cacert.pem");
In my case, I am not using the built in ajax api to feed Json to the table (this is due to some formatting that was rather difficult to implement inside the datatable's render callback).
My solution was to create the variable in the outer scope of the onload functions and the function that handles the data refresh (var table = null
, for example).
Then I instantiate my table in the on load method
$(function () {
//.... some code here
table = $("#detailReportTable").DataTable();
.... more code here
});
and finally, in the function that handles the refresh, i invoke the clear() and destroy() method, fetch the data into the html table, and re-instantiate the datatable, as such:
function getOrderDetail() {
table.clear();
table.destroy();
...
$.ajax({
//.....api call here
});
....
table = $("#detailReportTable").DataTable();
}
I hope someone finds this useful!
Looks like you want git diff and/or git log. Also check out gitk
gitk path/to/file
git diff path/to/file
git log path/to/file
This is a sledgehammer approach to replacing raw UNICODE with HTML. I haven't seen any other place to put this solution, but I assume others have had this problem.
Apply this str_replace function to the RAW JSON, before doing anything else.
function unicode2html($str){
$i=65535;
while($i>0){
$hex=dechex($i);
$str=str_replace("\u$hex","&#$i;",$str);
$i--;
}
return $str;
}
This won't take as long as you think, and this will replace ANY unicode with HTML.
Of course this can be reduced if you know the unicode types that are being returned in the JSON.
For example my code was getting lots of arrows and dingbat unicode. These are between 8448 an 11263. So my production code looks like:
$i=11263;
while($i>08448){
...etc...
You can look up the blocks of Unicode by type here: http://unicode-table.com/en/ If you know you're translating Arabic or Telegu or whatever, you can just replace those codes, not all 65,000.
You could apply this same sledgehammer to simple encoding:
$str=str_replace("\u$hex",chr($i),$str);
Try this:
Update users
Set username = 'Jack', password='123'
Where ID = '1'
Or if you're actually trying to insert:
Insert Into users (id, username, password) VALUES ('1', 'Jack','123');
http://msdn.microsoft.com/en-us/library/aa691090.aspx
C# supports two forms of string literals: regular string literals and verbatim string literals.
A regular string literal consists of zero or more characters enclosed in double quotes, as in "hello", and may include both simple escape sequences (such as \t for the tab character) and hexadecimal and Unicode escape sequences.
A verbatim string literal consists of an @ character followed by a double-quote character, zero or more characters, and a closing double-quote character. A simple example is @"hello". In a verbatim string literal, the characters between the delimiters are interpreted verbatim, the only exception being a quote-escape-sequence. In particular, simple escape sequences and hexadecimal and Unicode escape sequences are not processed in verbatim string literals. A verbatim string literal may span multiple lines.
No magic involved, just subtract from the offset top of the element
$('html, body').animate({scrollTop: $('#contact').offset().top -100 }, 'slow');
I just want to build upon Serpens answer and add the line:
logger.setLevel('DEBUG')
This will allow you to chose what level of message gets logged.
For example in Serpens example,
logger.info('Info message')
Will not get recorded as it defaults to only recording Warnings and above.
More about levels used can be read about here
When the propagation setting is PROPAGATION_REQUIRED, a logical transaction scope is created for each method upon which the setting is applied. Each such logical transaction scope can determine rollback-only status individually, with an outer transaction scope being logically independent from the inner transaction scope. Of course, in case of standard PROPAGATION_REQUIRED behavior, all these scopes will be mapped to the same physical transaction. So a rollback-only marker set in the inner transaction scope does affect the outer transaction's chance to actually commit (as you would expect it to).
http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/transaction.html
I think this should be:
$('.home').click(function() {
$(this).css('background', 'url(images/tabs3.png)');
});
and remove this:
<div class="home" onclick="function()">
//-----------^^^^^^^^^^^^^^^^^^^^---------no need for this
You have to make sure you have a correct path to your image.
You remove the original image here:
newImg.animate(css, SPEED, function() {
img.remove();
newImg.removeClass('morpher');
(callback || function() {})();
});
And all that's left behind is newImg
. Then you reset link references the image using #rocket
:
$("#rocket").attr('src', ...
But your newImg
doesn't have an id
attribute let alone an id
of rocket
.
To fix this, you need to remove img
and then set the id
attribute of newImg
to rocket
:
newImg.animate(css, SPEED, function() {
var old_id = img.attr('id');
img.remove();
newImg.attr('id', old_id);
newImg.removeClass('morpher');
(callback || function() {})();
});
And then you'll get the shiny black rocket back again: http://jsfiddle.net/ambiguous/W2K9D/
UPDATE: A better approach (as noted by mellamokb) would be to hide the original image and then show it again when you hit the reset button. First, change the reset action to something like this:
$("#resetlink").click(function(){
clearInterval(timerRocket);
$("#wrapper").css('top', '250px');
$('.throbber, .morpher').remove(); // Clear out the new stuff.
$("#rocket").show(); // Bring the original back.
});
And in the newImg.load
function, grab the images original size:
var orig = {
width: img.width(),
height: img.height()
};
And finally, the callback for finishing the morphing animation becomes this:
newImg.animate(css, SPEED, function() {
img.css(orig).hide();
(callback || function() {})();
});
New and improved: http://jsfiddle.net/ambiguous/W2K9D/1/
The leaking of $('.throbber, .morpher')
outside the plugin isn't the best thing ever but it isn't a big deal as long as it is documented.
Use %03d
in the format specifier for the integer. The 0
means that the number will be zero-filled if it is less than three (in this case) digits.
See the Formatter
docs for other modifiers.
I'm using VS 2017 with projects hosted with Git on visualstudio.com hosting (msdn)
The link above worked for me with the "GITHUB FOR WINDOWS" instructions.
http://www.scootersoftware.com/support.php?zz=kb_vcs#githubwindows
The config file was located where it indicated at "c:\users\username\.gitconfig" and I just changed the BC4's to BC3's for my situation and used the appropriate path:
C:/Program Files (x86)/Beyond Compare 3/bcomp.exe
I think you're using the CodeIgniter URI routing wrong: http://ellislab.com/codeigniter%20/user-guide/general/routing.html
Basically if you had a Products_controller with a method called delete($id)
and the url you created was of the form http://localhost/designs2/index.php/products_controller/delete/4
, the delete function would receive the $id
as a parameter.
Using what you have there I think you can get the id by using $this->input->get('product_id);
Start here http://docs.python.org/tutorial/datastructures.html#dictionaries
Then here http://docs.python.org/library/stdtypes.html#mapping-types-dict
Then here http://docs.python.org/library/stdtypes.html#dict.get
characters.get( key, default )
key is a character
default is 0
If the character is in the dictionary, characters
, you get the dictionary object.
If not, you get 0.
Syntax:
get(key[, default])
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to
None
, so that this method never raises aKeyError
.
For this example you will need to create your own type, that would be an array. Then you create a bigger array which elements are of type you have just created.
To run my example you will need to fill columns A and B in Sheet1 with some values. Then run test(). It will read first two rows and add the values to the BigArr. Then it will check how many rows of data you have and read them all, from the place it has stopped reading, i.e., 3rd row.
Tested in Excel 2007.
Option Explicit
Private Type SmallArr
Elt() As Variant
End Type
Sub test()
Dim x As Long, max_row As Long, y As Long
'' Define big array as an array of small arrays
Dim BigArr() As SmallArr
y = 2
ReDim Preserve BigArr(0 To y)
For x = 0 To y
ReDim Preserve BigArr(x).Elt(0 To 1)
'' Take some test values
BigArr(x).Elt(0) = Cells(x + 1, 1).Value
BigArr(x).Elt(1) = Cells(x + 1, 2).Value
Next x
'' Write what has been read
Debug.Print "BigArr size = " & UBound(BigArr) + 1
For x = 0 To UBound(BigArr)
Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
Next x
'' Get the number of the last not empty row
max_row = Range("A" & Rows.Count).End(xlUp).Row
'' Change the size of the big array
ReDim Preserve BigArr(0 To max_row)
Debug.Print "new size of BigArr with old data = " & UBound(BigArr)
'' Check haven't we lost any data
For x = 0 To y
Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
Next x
For x = y To max_row
'' We have to change the size of each Elt,
'' because there are some new for,
'' which the size has not been set, yet.
ReDim Preserve BigArr(x).Elt(0 To 1)
'' Take some test values
BigArr(x).Elt(0) = Cells(x + 1, 1).Value
BigArr(x).Elt(1) = Cells(x + 1, 2).Value
Next x
'' Check what we have read
Debug.Print "BigArr size = " & UBound(BigArr) + 1
For x = 0 To UBound(BigArr)
Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
Next x
End Sub
The value of PYTHONHASHSEED might be used to initialize the hash values.
Try:
PYTHONHASHSEED python -c 'print(hash('http://stackoverflow.com'))'
An MSI is a Windows Installer database. Windows Installer (a service installed with Windows) uses this to install software on your system (i.e. copy files, set registry values, etc...).
A setup.exe may either be a bootstrapper or a non-msi installer. A non-msi installer will extract the installation resources from itself and manage their installation directly. A bootstrapper will contain an MSI instead of individual files. In this case, the setup.exe will call Windows Installer to install the MSI.
Some reasons you might want to use a setup.exe:
On your DBA account, give USERB the right to create a procedure using grant grant create any procedure to USERB
The procedure will look
CREATE OR REPLACE PROCEDURE USERB.USERB_PROCEDURE
--Must add the line below
AUTHID CURRENT_USER AS
BEGIN
--DO SOMETHING HERE
END
END
GRANT EXECUTE ON USERB.USERB_PROCEDURE TO USERA
I know this is a very old question but I am hoping I could chip it a bit.
You have a process that is already using that port. netstat -tulpn
will enable one to find the process ID of that is using a particular port.
Just be aware of TempData persistence, it's a bit tricky. For example if you even simply read TempData inside the current request, it would be removed and consequently you don't have it for the next request. Instead, you can use Peek
method. I would recommend reading this cool article:
SIMPLE ANSWER HERE
\begin{equation}
\begin{split}
equation \\
here
\end{split}
\end{equation}
Adding to the mentions of jwplayer and possible TOS violations, I would like to to link to the following repository on github: YouTube Audio Player Generation Library, that allows to generate the following output:
Library has the support for the playlists and PHP autorendering given the video URL and the configuration options.
This might be an old thread, but I'd like to mention Appcelerator Titanium, which allows anyone versed in HTML5/JavaScript/CSS to develop iOS applications.
A simplistic approach would be to have a way to preserve the header.
Let's say you have a file.csv like:
user, topic, hits
om, scala, 120
daniel, spark, 80
3754978, spark, 1
We can define a header class that uses a parsed version of the first row:
class SimpleCSVHeader(header:Array[String]) extends Serializable {
val index = header.zipWithIndex.toMap
def apply(array:Array[String], key:String):String = array(index(key))
}
That we can use that header to address the data further down the road:
val csv = sc.textFile("file.csv") // original file
val data = csv.map(line => line.split(",").map(elem => elem.trim)) //lines in rows
val header = new SimpleCSVHeader(data.take(1)(0)) // we build our header with the first line
val rows = data.filter(line => header(line,"user") != "user") // filter the header out
val users = rows.map(row => header(row,"user")
val usersByHits = rows.map(row => header(row,"user") -> header(row,"hits").toInt)
...
Note that the header
is not much more than a simple map of a mnemonic to the array index. Pretty much all this could be done on the ordinal place of the element in the array, like user = row(0)
PS: Welcome to Scala :-)
Probably the best way is this one here.
fileprivate func NSLocalizedString(_ key: String) -> String {
return NSLocalizedString(key, comment: "")
}
and
import Foundation
extension String {
static let Hello = NSLocalizedString("Hello")
static let ThisApplicationIsCreated = NSLocalizedString("This application is created by the swifting.io team")
static let OpsNoFeature = NSLocalizedString("Ops! It looks like this feature haven't been implemented yet :(!")
}
you can then use it like this
let message: String = .ThisApplicationIsCreated
print(message)
to me this is the best because
Assuming that you have your data in a 2d array, this should work:
import numpy
import pylab
xy = numpy.zeros((2, 1000))
xy[0] = range(1000)
xy[1] = range(1000)
colors = [int(i % 23) for i in xy[0]]
pylab.scatter(xy[0], xy[1], c=colors)
pylab.show()
You can also set a cmap
attribute to control which colors will appear through use of a colormap; i.e. replace the pylab.scatter
line with:
pylab.scatter(xy[0], xy[1], c=colors, cmap=pylab.cm.cool)
A list of color maps can be found here
I tried Gaby's answer (+1) above but it only partially solved my problem. Instead I used the following CSS, where content-box was changed to border-box:
input, select {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
Include this in your "app.config":
$httpProvider.interceptors.push('myHttpInterceptor');
And add this code:
app.factory('myHttpInterceptor', function ($q, $window,$rootScope) {
$rootScope.ActiveAjaxConectionsWithouthNotifications = 0;
var checker = function(parameters,status){
//YOU CAN USE parameters.url TO IGNORE SOME URL
if(status == "request"){
$rootScope.ActiveAjaxConectionsWithouthNotifications+=1;
$('#loading_view').show();
}
if(status == "response"){
$rootScope.ActiveAjaxConectionsWithouthNotifications-=1;
}
if($rootScope.ActiveAjaxConectionsWithouthNotifications<=0){
$rootScope.ActiveAjaxConectionsWithouthNotifications=0;
$('#loading_view').hide();
}
};
return {
'request': function(config) {
checker(config,"request");
return config;
},
'requestError': function(rejection) {
checker(rejection.config,"request");
return $q.reject(rejection);
},
'response': function(response) {
checker(response.config,"response");
return response;
},
'responseError': function(rejection) {
checker(rejection.config,"response");
return $q.reject(rejection);
}
};
});
This works if you are on ubuntu/trusty64 box:
vagrant ssh
Once you are in the ubuntu box:
sudo su
Now you are root user. You can update root password as shown below:
sudo -i
passwd
Now edit the below line in the file /etc/ssh/sshd_config
PermitRootLogin yes
Also, it is convenient to create your own alternate username:
adduser johndoe
Wait until it asks for password.
Use the pandas.DataFrame.rename funtion. Check this link for description.
data.rename(columns = {'gdp': 'log(gdp)'}, inplace = True)
If you intend to rename multiple columns then
data.rename(columns = {'gdp': 'log(gdp)', 'cap': 'log(cap)', ..}, inplace = True)
Need to do normal
forever start script.js
to start, and to check console/error logs use
forever logs
this will print list of all logs being stored by forever
and then you can use tail -f /path/to/logs/file.log
and this will print live logs to your window. hit ctrl+z to stop logs print.
Assuming your div has some CSS classes already...
<div id="classMe" CssClass="first"></div>
The following won't replace existing definitions:
ClassMe.CssClass += " second";
And if you are not sure until the very last moment...
string classes = ClassMe.CssClass;
ClassMe.CssClass += (classes == "") ? "second" : " second";
You declare
int countlines(char *filename)
to take a char *
argument.
You call it like this
countlines(fp)
passing in a FILE *.
That is why you get that compile error.
You probably should change that second line to
countlines("Test.txt")
since you open the file in countlines
Your current code is attempting to open the file in two different places.
You can use this in app.js
file .
var apiurl = express.Router();
apiurl.use(function(req, res, next) {
var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
next();
});
app.use('/', apiurl);
Tip: It's always good to use the -Script
switch for migration commands if you're not sure. It also really helps understand what Update-Database
actually does.
I run the following to update the database, then I get a script I can apply manually (or just run it again without the -Script tag).
For Update-Database
I would run the following :
Update-Database -Script -ConfigurationTypeName Configuration_ASPNETIdentity -ConnectionStringName SQL_AzureLive
Where SQL_AzureLive
is the named connection string in my config.
Then I can verify the SQL looks right, apply it and be done. As many others have said if the connection string is wrong or invalid you'll get this error.
$("#select_id option:selected").prop("selected", false);
It's hard for us to bind a specific USB device to a docker container which is also specific. As you can see, the recommended way to achieve is:
docker run -t -i --privileged -v /dev/bus/usb:/dev/bus/usb ubuntu bash
It will bind all the devices to this container. It's unsafe. Every containers were granted to operate all of them.
Another way is binding devices by devpath. It may looks like:
docker run -t -i --privileged -v /dev/bus/usb/001/002:/dev/bus/usb/001/002 ubuntu bash
or --device
(better, no privileged
):
docker run -t -i --device /dev/bus/usb/001/002 ubuntu bash
Much safer. But actually it is hard to know what the devpath of a specific device is.
I have wrote this repo to solve this problem.
https://github.com/williamfzc/usb2container
After deploying this server, you can easily get all the connected devices' information via HTTP request:
curl 127.0.0.1:9410/api/device
and get:
{
"/devices/pci0000:00/0000:00:14.0/usb1/1-13": {
"ACTION": "add",
"DEVPATH": "/devices/pci0000:00/0000:00:14.0/usb1/1-13",
"DEVTYPE": "usb_device",
"DRIVER": "usb",
"ID_BUS": "usb",
"ID_FOR_SEAT": "xxxxx",
"ID_MODEL": "xxxxx",
"ID_MODEL_ID": "xxxxx",
"ID_PATH": "xxxxx",
"ID_PATH_TAG": "xxxxx",
"ID_REVISION": "xxxxx",
"ID_SERIAL": "xxxxx",
"ID_SERIAL_SHORT": "xxxxx",
"ID_USB_INTERFACES": "xxxxx",
"ID_VENDOR": "xxxxx",
"ID_VENDOR_ENC": "xxxxx",
"ID_VENDOR_FROM_DATABASE": "",
"ID_VENDOR_ID": "xxxxx",
"INTERFACE": "",
"MAJOR": "189",
"MINOR": "119",
"MODALIAS": "",
"PRODUCT": "xxxxx",
"SEQNUM": "xxxxx",
"SUBSYSTEM": "usb",
"TAGS": "",
"TYPE": "0/0/0",
"USEC_INITIALIZED": "xxxxx",
"adb_user": "",
"_empty": false,
"DEVNAME": "/dev/bus/usb/001/120",
"BUSNUM": "001",
"DEVNUM": "120",
"ID_MODEL_ENC": "xxxxx"
},
...
}
and bind them to your containers. For example, you can see the DEVNAME of this device is /dev/bus/usb/001/120
:
docker run -t -i --device /dev/bus/usb/001/120 ubuntu bash
Maybe it will help.
autoconf
and automake
:configure
, make
and sudo make install
:./configure # Creates Makefile (from Makefile.in).
make # Creates the application (from the Makefile just created).
sudo make install # Installs the application
# Often, by default its files are installed into /usr/local
Notation below is roughly: inputs --> programs --> outputs
DEVELOPER runs these:
configure.ac -> autoconf -> configure (script) --- (*.ac = autoconf)
configure.in --> autoconf -> configure (script) --- (configure.in
depreciated. Use configure.ac)
Makefile.am -> automake -> Makefile.in ----------- (*.am = automake)
INSTALLER runs these:
Makefile.in -> configure -> Makefile (*.in = input file)
Makefile -> make ----------> (puts new software in your downloads or temporary directory)
Makefile -> make install -> (puts new software in system directories)
"autoconf is an extensible package of M4 macros that produce shell scripts to automatically configure software source code packages. These scripts can adapt the packages to many kinds of UNIX-like systems without manual user intervention. Autoconf creates a configuration script for a package from a template file that lists the operating system features that the package can use, in the form of M4 macro calls."
"automake is a tool for automatically generating Makefile.in files compliant with the GNU Coding Standards. Automake requires the use of Autoconf."
Manuals:
GNU AutoTools (The definitive manual on this stuff)
m4 (used by autoconf)
Free online tutorials:
The main configure.ac used to build LibreOffice is over 12k lines of code, (but there are also 57 other configure.ac files in subfolders.)
From this my generated configure is over 41k lines of code.
And while the Makefile.in and Makefile are both only 493 lines of code. (But, there are also 768 more Makefile.in's in subfolders.)
You can do it in following ways;
You can go to control panel/cpanel and add host % It means now the database server can be accessed from your local machine. Now you can install and use MySQL Administrator or Navicat to import and export database with out using PHP-Myadmin, I used it several times to upload 200 MB to 500 MB of data with no issues
Use gzip, bzip2 compressions for exporting and importing. I am using PEA ZIP software (free) in Windows. Try to avoid Winrar and Winzip
Use MySQL Splitter that splits up the sql file into several parts. In my personal suggestion, Not recommended
Using PHP INI setting (dynamically change the max upload and max execution time) as already mentioned by other friends is fruitful but not always.
I tried to run insertion of random data into MyISAM and InnoDB tables. The result was quite shocking. MyISAM needed a few seconds less for inserting 1 million rows than InnoDB for just 10 thousand!
I wrote one for use with C++, it's very fast, works with streams, free, and open source:
https://tmplusplus.svn.sourceforge.net/svnroot/tmplusplus/trunk/src/
Feel free to use it if it fits your purpose.
Edit: Added code inline by request.
The performance boost is acieved by using a lookup table for encoding and decoding. _UINT8
is an unsigned char
on most OS's.
/** Static Base64 character encoding lookup table */
const char CBase64::encodeCharacterTable[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/** Static Base64 character decoding lookup table */
const char CBase64::decodeCharacterTable[256] = {
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21
,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1};
/*!
\brief Encodes binary data to base 64 character data
\param in The data to encode
\param out The encoded data as characters
*/
void CBase64::Encode(std::istream &in, std::ostringstream &out)
{
char buff1[3];
char buff2[4];
_UINT8 i=0, j;
while(in.readsome(&buff1[i++], 1))
if (i==3)
{
out << encodeCharacterTable[(buff1[0] & 0xfc) >> 2];
out << encodeCharacterTable[((buff1[0] & 0x03) << 4) + ((buff1[1] & 0xf0) >> 4)];
out << encodeCharacterTable[((buff1[1] & 0x0f) << 2) + ((buff1[2] & 0xc0) >> 6)];
out << encodeCharacterTable[buff1[2] & 0x3f];
i=0;
}
if (--i)
{
for(j=i;j<3;j++) buff1[j] = '\0';
buff2[0] = (buff1[0] & 0xfc) >> 2;
buff2[1] = ((buff1[0] & 0x03) << 4) + ((buff1[1] & 0xf0) >> 4);
buff2[2] = ((buff1[1] & 0x0f) << 2) + ((buff1[2] & 0xc0) >> 6);
buff2[3] = buff1[2] & 0x3f;
for (j=0;j<(i+1);j++) out << encodeCharacterTable[buff2[j]];
while(i++<3) out << '=';
}
}
/*!
\brief Decodes base 64 character data to binary data
\param in The character data to decode
\param out The decoded data
*/
void CBase64::Decode(std::istringstream &in, std::ostream &out)
{
char buff1[4];
char buff2[4];
_UINT8 i=0, j;
while(in.readsome(&buff2[i], 1) && buff2[i] != '=')
{
if (++i==4)
{
for (i=0;i!=4;i++)
buff2[i] = decodeCharacterTable[buff2[i]];
out << (char)((buff2[0] << 2) + ((buff2[1] & 0x30) >> 4));
out << (char)(((buff2[1] & 0xf) << 4) + ((buff2[2] & 0x3c) >> 2));
out << (char)(((buff2[2] & 0x3) << 6) + buff2[3]);
i=0;
}
}
if (i)
{
for (j=i;j<4;j++) buff2[j] = '\0';
for (j=0;j<4;j++) buff2[j] = decodeCharacterTable[buff2[j]];
buff1[0] = (buff2[0] << 2) + ((buff2[1] & 0x30) >> 4);
buff1[1] = ((buff2[1] & 0xf) << 4) + ((buff2[2] & 0x3c) >> 2);
buff1[2] = ((buff2[2] & 0x3) << 6) + buff2[3];
for (j=0;j<(i-1); j++) out << (char)buff1[j];
}
}
Use this example
System.Globalization.CultureInfo culInfo = new System.Globalization.CultureInfo("en-GB",true);
decimal currency_usd = decimal.Parse(GetRateFromCbrf("usd"),culInfo);
decimal currency_eur = decimal.Parse(GetRateFromCbrf("eur"), culInfo);
Try the read
shell builtin:
read -p "Continue (y/n)?" CONT
if [ "$CONT" = "y" ]; then
echo "yaaa";
else
echo "booo";
fi
Perhaps I am missing something, but although the other solutions do call the parent scope function there is no ability to pass arguments from directive code, this is because the update-fn
is calling updateFn()
with fixed parameters, in for example {msg: "Hello World"}
. A slight change allows the directive to pass arguments, which I would think is far more useful.
<test color1="color1" update-fn="updateFn"></test>
Note the HTML is passing a function reference, i.e., without ()
brackets.
JS
var app = angular.module('dr', []);
app.controller("testCtrl", function($scope) {
$scope.color1 = "color";
$scope.updateFn = function(msg) {
alert(msg);
}
});
app.directive('test', function() {
return {
restrict: 'E',
scope: {
color1: '=',
updateFn: '&'
},
// object is passed while making the call
template: "<button ng-click='callUpdate()'>
Click</button>",
replace: true,
link: function(scope, elm, attrs) {
scope.callUpdate = function() {
scope.updateFn()("Directive Args");
}
}
}
});
So in the above, the HTML is calling local scope callUpdate
function, which then 'fetches' the updateFn from the parent scope and calls the returned function with parameters that the directive can generate.
$("[style*=block]").hide();
uniq
should do fine if you're file is/can be sorted, if you can't sort the file for some reason you can use awk
:
awk '{a[$0]++}END{for(i in a)if(a[i]<2)print i}'
EDIT: Handlebars now has a built-in way of accomplishing this; see the selected answer above. When working with plain Mustache, the below still applies.
Mustache can iterate over items in an array. So I'd suggest creating a separate data object formatted in a way Mustache can work with:
var o = {
bob : 'For sure',
roger: 'Unknown',
donkey: 'What an ass'
},
mustacheFormattedData = { 'people' : [] };
for (var prop in o){
if (o.hasOwnProperty(prop)){
mustacheFormattedData['people'].push({
'key' : prop,
'value' : o[prop]
});
}
}
Now, your Mustache template would be something like:
{{#people}}
{{key}} : {{value}}
{{/people}}
Check out the "Non-Empty Lists" section here: https://github.com/janl/mustache.js
I think registering for the UIApplicationWillEnterForegroundNotification is risky as you may end up with more than one controller reacting to that notification. Nothing garanties that these controllers are still visible when the notification is received.
Here is what I do: I force call viewDidAppear on the active controller directly from the App's delegate didBecomeActive method:
Add the code below to - (void)applicationDidBecomeActive:(UIApplication *)application
UIViewController *activeController = window.rootViewController;
if ([activeController isKindOfClass:[UINavigationController class]]) {
activeController = [(UINavigationController*)window.rootViewController topViewController];
}
[activeController viewDidAppear:NO];
public class Global : System.Web.HttpApplication
{
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (Request.Url.AbsolutePath.EndsWith("/"))
{
Server.Transfer("~/index.aspx");
}
}
}
if the zipcode field is not a required field then add null=True and blank=True, then run makemigrations and migrate command to successfully reflect the changes in the database.
This snippet could help you with it in a few lines of jQuery 1.9+: http://jsfiddle.net/4MBUG/2/
$('input[type=button]').on('click', function() {
var cursorPos = $('#text').prop('selectionStart');
var v = $('#text').val();
var textBefore = v.substring(0, cursorPos);
var textAfter = v.substring(cursorPos, v.length);
$('#text').val(textBefore + $(this).val() + textAfter);
});
This should work. You can get body using response.json() if its a json response.
this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
subscribe((res: Response.json()) => {
console.log(res);
})
C++
constexpr hash function:
constexpr unsigned int hash(const char *s, int off = 0) {
return !s[off] ? 5381 : (hash(s, off+1)*33) ^ s[off];
}
switch( hash(str) ){
case hash("one") : // do something
case hash("two") : // do something
}
From this news group posting by Mark Zbikowski himself:
The differences between .CMD and .BAT as far as CMD.EXE is concerned are: With extensions enabled, PATH/APPEND/PROMPT/SET/ASSOC in .CMD files will set ERRORLEVEL regardless of error. .BAT sets ERRORLEVEL only on errors.
In other words, if ERRORLEVEL is set to non-0 and then you run one of those commands, the resulting ERRORLEVEL will be:
setGame
has been discontinued. You must use client.user.setActivity
.
Don't forget, if you are setting a streaming status, you MUST specify a Twitch URL
An example is here:
client.user.setActivity("with depression", {
type: "STREAMING",
url: "https://www.twitch.tv/example-url"
});
Please try this one works for me:
<ImageView android:id="@+id/image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxWidth="60dp"
android:layout_gravity="center"
android:maxHeight="60dp"
android:scaleType="fitCenter"
android:src="@drawable/icon"
/>
Use docstrings.
This is the built-in suggested convention in PyCharm for describing function using docstring comments:
def test_function(p1, p2, p3):
"""
test_function does blah blah blah.
:param p1: describe about parameter p1
:param p2: describe about parameter p2
:param p3: describe about parameter p3
:return: describe what it returns
"""
pass
Everybody describes issue with getting annotations, but the problem is in definition of your annotation. You should to add to your annotation definition a @Retention(RetentionPolicy.RUNTIME)
:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAnnotation{
int id();
}
for x in y[:-1]
If y
is a generator, then the above will not work.
Whatever urllib is using to figure out Content-Length seems to get confused by json, so you have to calculate that yourself.
import json
import urllib2
data = json.dumps([1, 2, 3])
clen = len(data)
req = urllib2.Request(url, data, {'Content-Type': 'application/json', 'Content-Length': clen})
f = urllib2.urlopen(req)
response = f.read()
f.close()
Took me for ever to figure this out, so I hope it helps someone else.
The reason could be that the summation exceeded the required number of digits - 4. If you increase the size of the decimal to decimal(10,2)
, it should work
SELECT SUM(convert(decimal(10,2), Stuff)) as result FROM table
OR
SELECT SUM(CAST(Stuff AS decimal(6,2))) as result FROM table
isset() tests if a variable is set and not null:
http://us.php.net/manual/en/function.isset.php
empty() can return true when the variable is set to certain values:
http://us.php.net/manual/en/function.empty.php
<?php
$the_var = 0;
if (isset($the_var)) {
echo "set";
} else {
echo "not set";
}
echo "\n";
if (empty($the_var)) {
echo "empty";
} else {
echo "not empty";
}
?>
None of the above answers fixed this issue for me. I did it as following (Laravel with Ubuntu server):
<?php
$footerFile = '/var/www/website/main/resources/views/emails/elements/emailfooter.blade.php';
include($footerFile);
?>
You will need to add external Repository to your pom, since this is using Mulsoft-Release
repository not Maven Central
<project>
...
<repositories>
<repository>
<id>mulesoft-releases</id>
<name>MuleSoft Repository</name>
<url>http://repository.mulesoft.org/releases/</url>
<layout>default</layout>
</repository>
</repositories>
...
</project>
I believe you are getting an empty array because PHP is expecting the posted data to be in a Querystring format (key=value&key1=value1).
Try changing your curl request to:
curl -i -X POST -d 'json={"screencast":{"subject":"tools"}}' \
http://localhost:3570/index.php/trainingServer/screencast.json
and see if that helps any.
You could use wmic command:
wmic logicaldisk where drivetype=2 get <DeviceID, VolumeName, Description, ...>
Drivetype 2 indicates that its a removable disk.
I had the same issue, but I wanted a solution that didn't use locks.
Problem: I have at most one thread consuming from a queue. Multiple producer threads are constantly inserting into the queue and need to notify the consumer if it's waiting. The queue is lock-free so using locks for notification causes unnecessary blocking in producer threads. Each producer thread needs to acquire the lock before it can notify the waiting consumer. I believe I came up with a lock-free solution using LockSupport
and AtomicReferenceFieldUpdater
. If a lock-free barrier exists within the JDK, I couldn't find it. Both CyclicBarrier
and CoundDownLatch
use locks internally from what I could find.
This is my slightly abbreviated code. Just to be clear, this code will only allow one thread to wait at a time. It could be modified to allow for multiple awaiters/consumers by using some type of atomic collection to store multiple owner (a ConcurrentMap
may work).
I have used this code and it seems to work. I have not tested it extensively. I suggest you read the documentation for LockSupport
before use.
/* I release this code into the public domain.
* http://unlicense.org/UNLICENSE
*/
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.concurrent.locks.LockSupport;
/**
* A simple barrier for awaiting a signal.
* Only one thread at a time may await the signal.
*/
public class SignalBarrier {
/**
* The Thread that is currently awaiting the signal.
* !!! Don't call this directly !!!
*/
@SuppressWarnings("unused")
private volatile Thread _owner;
/** Used to update the owner atomically */
private static final AtomicReferenceFieldUpdater<SignalBarrier, Thread> ownerAccess =
AtomicReferenceFieldUpdater.newUpdater(SignalBarrier.class, Thread.class, "_owner");
/** Create a new SignalBarrier without an owner. */
public SignalBarrier() {
_owner = null;
}
/**
* Signal the owner that the barrier is ready.
* This has no effect if the SignalBarrer is unowned.
*/
public void signal() {
// Remove the current owner of this barrier.
Thread t = ownerAccess.getAndSet(this, null);
// If the owner wasn't null, unpark it.
if (t != null) {
LockSupport.unpark(t);
}
}
/**
* Claim the SignalBarrier and block until signaled.
*
* @throws IllegalStateException If the SignalBarrier already has an owner.
* @throws InterruptedException If the thread is interrupted while waiting.
*/
public void await() throws InterruptedException {
// Get the thread that would like to await the signal.
Thread t = Thread.currentThread();
// If a thread is attempting to await, the current owner should be null.
if (!ownerAccess.compareAndSet(this, null, t)) {
throw new IllegalStateException("A second thread tried to acquire a signal barrier that is already owned.");
}
// The current thread has taken ownership of this barrier.
// Park the current thread until the signal. Record this
// signal barrier as the 'blocker'.
LockSupport.park(this);
// If a thread has called #signal() the owner should already be null.
// However the documentation for LockSupport.unpark makes it clear that
// threads can wake up for absolutely no reason. Do a compare and set
// to make sure we don't wipe out a new owner, keeping in mind that only
// thread should be awaiting at any given moment!
ownerAccess.compareAndSet(this, t, null);
// Check to see if we've been unparked because of a thread interrupt.
if (t.isInterrupted())
throw new InterruptedException();
}
/**
* Claim the SignalBarrier and block until signaled or the timeout expires.
*
* @throws IllegalStateException If the SignalBarrier already has an owner.
* @throws InterruptedException If the thread is interrupted while waiting.
*
* @param timeout The timeout duration in nanoseconds.
* @return The timeout minus the number of nanoseconds that passed while waiting.
*/
public long awaitNanos(long timeout) throws InterruptedException {
if (timeout <= 0)
return 0;
// Get the thread that would like to await the signal.
Thread t = Thread.currentThread();
// If a thread is attempting to await, the current owner should be null.
if (!ownerAccess.compareAndSet(this, null, t)) {
throw new IllegalStateException("A second thread tried to acquire a signal barrier is already owned.");
}
// The current thread owns this barrier.
// Park the current thread until the signal. Record this
// signal barrier as the 'blocker'.
// Time the park.
long start = System.nanoTime();
LockSupport.parkNanos(this, timeout);
ownerAccess.compareAndSet(this, t, null);
long stop = System.nanoTime();
// Check to see if we've been unparked because of a thread interrupt.
if (t.isInterrupted())
throw new InterruptedException();
// Return the number of nanoseconds left in the timeout after what we
// just waited.
return Math.max(timeout - stop + start, 0L);
}
}
To give a vague example of usage, I'll adopt james large's example:
SignalBarrier barrier = new SignalBarrier();
Consumer thread (singular, not plural!):
try {
while(!conditionIsTrue()) {
barrier.await();
}
doSomethingThatRequiresConditionToBeTrue();
} catch (InterruptedException e) {
handleInterruption();
}
Producer thread(s):
doSomethingThatMakesConditionTrue();
barrier.signal();
The first answer is too complex, historic, and uninformative for my tastes.
It's actually rather simple. Docker provides for a functionality called multi-stage builds the basic idea here is to,
Let's start with the first. Very often with something like Debian you'll see.
RUN apt-get update \
&& apt-get dist-upgrade \
&& apt-get install <whatever> \
&& apt-get clean
We can explain all of this in terms of the above. The above command is chained together so it represents a single change with no intermediate Images required. If it was written like this,
RUN apt-get update ;
RUN apt-get dist-upgrade;
RUN apt-get install <whatever>;
RUN apt-get clean;
It would result in 3 more temporary intermediate Images. Having it reduced to one image, there is one remaining problem: apt-get clean
doesn't clean up artifacts used in the install. If a Debian maintainer includes in his install a script that modifies the system that modification will also be present in the final solution (see something like pepperflashplugin-nonfree
for an example of that).
By using a multi-stage build you get all the benefits of a single changed action, but it will require you to manually whitelist and copy over files that were introduced in the temporary image using the COPY --from
syntax documented here. Moreover, it's a great solution where there is no alternative (like an apt-get clean
), and you would otherwise have lots of un-needed files in your final image.
See also
The following query returns SQL statements that perform large numbers of disk reads (also includes the offending user and the number of times the query has been run):
SELECT t2.username, t1.disk_reads, t1.executions,
t1.disk_reads / DECODE(t1.executions, 0, 1, t1.executions) as exec_ratio,
t1.command_type, t1.sql_text
FROM v$sqlarea t1, dba_users t2
WHERE t1.parsing_user_id = t2.user_id
AND t1.disk_reads > 100000
ORDER BY t1.disk_reads DESC
Run the query as SYS and adjust the number of disk reads depending on what you deem to be excessive (100,000 works for me).
I have used this query very recently to track down users who refuse to take advantage of Explain Plans
before executing their statements.
I found this query in an old Oracle SQL tuning book (which I unfortunately no longer have), so apologies, but no attribution.
Here is one solution:
div.row {
border: 1px solid;
border-bottom: 0px;
}
.container div.row:last-child {
border-bottom: 1px solid;
}
I'm not 100% its the most effiecent, but it works :D
If you want to use something like an INI file to hold settings, consider using configparser which loads key value pairs from a text file, and can easily write back to the file.
INI file has the format:
[Section]
key = value
key with spaces = somevalue
The simple way is to create table as textfile and move the file to the appropriate location
CREATE EXTERNAL TABLE mytable(col1 string, col2 string)
row format delimited fields terminated by '|' stored as textfile;
Copy the file to the HDFS Location where table is created.
Hope this helps!!!
That's not a JSON object, that's a Javascript object created via object literal notation. (JSON is a textual notation for data exchange (more). If you're dealing with JavaScript source code, and not dealing with a string, you're not dealing with JSON.)
There's no way within the object initializer to refer to another key of the object being initialized, because there's no way to get a reference to the object being created until the initializer is finished. (There's no keyword akin to this
or something for this situation.)
One thing that wasn't mentioned completely (although @BlooB kinda mentioned it) is that map returns a map object NOT a list. This is a big difference when it comes to time performance on initialization and iteration. Consider these two tests.
import time
def test1(iterable):
a = time.clock()
map(str, iterable)
a = time.clock() - a
b = time.clock()
[ str(x) for x in iterable ]
b = time.clock() - b
print(a,b)
def test2(iterable):
a = time.clock()
[ x for x in map(str, iterable)]
a = time.clock() - a
b = time.clock()
[ str(x) for x in iterable ]
b = time.clock() - b
print(a,b)
test1(range(2000000)) # Prints ~1.7e-5s ~8s
test2(range(2000000)) # Prints ~9s ~8s
As you can see initializing the map function takes almost no time at all. However iterating through the map object takes longer than simply iterating through the iterable. This means that the function passed to map() is not applied to each element until the element is reached in the iteration. If you want a list use list comprehension. If you plan to iterate through in a for loop and will break at some point, then use map.
You'll need to run this command from the MySQL prompt:
REPAIR TABLE tbl_name USE_FRM;
From MySQL's documentation on the Repair command:
The USE_FRM option is available for use if the .MYI index file is missing or if its header is corrupted. This option tells MySQL not to trust the information in the .MYI file header and to re-create it using information from the .frm file. This kind of repair cannot be done with myisamchk.
I've been using something like this. Just set up a simple HTML page with an textinput. Make sure that the textinput always has focus. When you scan a barcode with your barcode scanner you will receive the code and after that a 'enter'. Realy simple then; just capture the incoming keystrokes and when the 'enter' comes in you can use AJAX to handle your code.
Qt has a method for copying files:
#include <QFile>
QFile::copy("originalFile.example","copiedFile.example");
Note that to use this you have to install Qt (instructions here) and include it in your project (if you're using Windows and you're not an administrator, you can download Qt here instead). Also see this answer.
Here is a non-numpy solution:
>>> a = [[40, 10], [50, 11]]
>>> [float(sum(l))/len(l) for l in zip(*a)]
[45.0, 10.5]
You can use CountDownTimer
which is much more efficient than any other solution posted. You can also produce regular notifications on intervals along the way using its onTick(long)
method
Have a look at this example showing a 30seconds countdown
new CountDownTimer(30000, 1000) {
public void onFinish() {
// When timer is finished
// Execute your code here
}
public void onTick(long millisUntilFinished) {
// millisUntilFinished The amount of time until finished.
}
}.start();
here I'm providing solution to setup terraform enviroment variable in windows to beginners.
Open system variables, select the path > edit > new > place the terraform.exe file location like > C:\Programfile\terraform\
and Save it.
Code snippet for piping content from web via http(s) to filesystem. As @starbeamrainbowlabs noticed event finish
does job
var tmpFile = "/tmp/somefilename.doc";
var ws = fs.createWriteStream(tmpFile);
ws.on('finish', function() {
// pipe done here, do something with file
});
var client = url.slice(0, 5) === 'https' ? https : http;
client.get(url, function(response) {
return response.pipe(ws);
});
If you are looking for a direct approach and using a local
File in that case.
Try
<div
style={{ background-image: 'url(' + Image + ')', background-size: 'auto' }}
/>
This is the case of JS
with inline styling where Image
is a local file that you must have imported with a path.
To list files based on size in asending order.
find ./ -size +1000M -exec ls -tlrh {} \; |awk -F" " '{print $5,$9}' | sort -n\
Adding this as an answer as it might help someone later.
I had to force jvm to use the IPv4 stack to resolve the error. My application used to work within company network, but while connecting from home it gave the same exception. No proxy involved. Added the jvm argument
-Djava.net.preferIPv4Stack=true
and all the https
requests were behaving normally.
another solution that works fine is to create empty list as a reference empty list.
empt_list = []
for example you have a list as a_list = [1,2,3]
. To clear it just make the following:
a_list = list(empt_list)
this will make a_list
an empty list just like the empt_list
.
Wouldn't it be nice to just type debug
in front of any command to be able to debug it with gdb
on shell level?
Below it this function. It even works with following:
"$program" "$@" < <(in) 1> >(out) 2> >(two) 3> >(three)
This is a call where you cannot control anything, everything is variable, can contain spaces, linefeeds and shell metacharacters. In this example, in
, out
, two
, and three
are arbitrary other commands which consume or produce data which must not be harmed.
Following bash
function invokes gdb
nearly cleanly in such an environment [Gist]:
debug()
{
1000<&0 1001>&1 1002>&2 \
0</dev/tty 1>/dev/tty 2>&0 \
/usr/bin/gdb -q -nx -nw \
-ex 'set exec-wrapper /bin/bash -c "exec 0<&1000 1>&1001 2>&1002 \"\$@\"" exec' \
-ex r \
--args "$@";
}
Example on how to apply this: Just type debug
in front:
Before:
p=($'\n' $'I\'am\'evil' " yay ")
"b u g" "${p[@]}" < <(in) 1> >(out) 2> >(two) 3> >(three)
After:
p=($'\n' $'I\'am\'evil' " yay ")
debug "b u g" "${p[@]}" < <(in) 1> >(out) 2> >(two) 3> >(three)
That's it. Now it's an absolute no-brainer to debug with gdb
. Except for a few details or more:
gdb
does not quit automatically and hence keeps the IO redirection open until you exit gdb
. But I call this a feature.
You cannot easily pass argv0
to the program like with exec -a arg0 command args
. Following should do this trick: After exec-wrapper
change "exec
to "exec -a \"\${DEBUG_ARG0:-\$1}\"
.
There are FDs above 1000 open, which are normally closed. If this is a problem, change 0<&1000 1>&1001 2>&1002
to read 0<&1000 1>&1001 2>&1002 1000<&- 1001>&- 1002>&-
You cannot run two debuggers in parallel. There also might be issues, if some other command consumes /dev/tty
(or STDIN). To fix that, replace /dev/tty
with "${DEBUGTTY:-/dev/tty}"
. In some other TTY type tty; sleep inf
and then use the printed TTY (i. E. /dev/pts/60
) for debugging, as in DEBUGTTY=/dev/pts/60 debug command arg..
. That's the Power of Shell, get used to it!
Function explained:
1000<&0 1001>&1 1002>&2
moves away the first 3 FDs
0</dev/tty 1>/dev/tty 2>&0
restores the first 3 FDs to point to your current TTY. So you can control gdb
./usr/bin/gdb -q -nx -nw
runs gdb
invokes gdb
on shell-ex 'set exec-wrapper /bin/bash -c "exec 0<&1000 1>&1001 2>&1002 \"\$@\""
creates a startup wrapper, which restores the first 3 FDs which were saved to 1000 and above-ex r
starts the program using the exec-wrapper
--args "$@"
passes the arguments as givenWasn't that easy?
"C:\Program Files (x86)\ffmpegX86shared\bin\ffmpeg.exe" -y -i "C:\testfile.ts" -an -vcodec libx264 -g 75 -keyint_min 12 -vb 4000k -vprofile high -level 40 -s 1920x1080 -y -threads 0 -r 25 "C:\testfile.h264"
The above worked for me on a Windows machine using a FFmpeg Win32 shared build by Kyle Schwarz. The build was compiled on: Feb 22 2013, at: 01:09:53
Note that -an defines that audio should be skipped.
Don't manually edit the .designer files in visual studio that usually leads to headaches. Instead either specify it in the properties section of your DataGridRow which should be contained within a DataGrid element. Or if you just want VS to do it for you find the double click event within the properties page->events (little lightning bolt icon) and double click the text area where you would enter a function name for that event.
This link should help
http://msdn.microsoft.com/en-us/library/6w2tb12s(v=vs.90).aspx
@ModelAttribute
is a Spring mapping of request parameters to a particular object type. so your parameters might look like userClient.username
and userClient.firstName
, etc. as MockMvc imitates a request from a browser, you'll need to pass in the parameters that Spring would use from a form to actually build the UserClient
object.
(i think of ModelAttribute is kind of helper to construct an object from a bunch of fields that are going to come in from a form, but you may want to do some reading to get a better definition)
I like Aacini's response. I added to it to handle the day and also enable it to handle centiseconds (%TIME%
outputs H:MM:SS.CC
):
:delay
SET DELAYINPUT=%1
SET /A DAYS=DELAYINPUT/8640000
SET /A DELAYINPUT=DELAYINPUT-(DAYS*864000)
::Get ending centisecond (10 milliseconds)
FOR /F "tokens=1-4 delims=:." %%A IN ("%TIME%") DO SET /A H=%%A, M=1%%B%%100, S=1%%C%%100, X=1%%D%%100, ENDING=((H*60+M)*60+S)*100+X+DELAYINPUT
SET /A DAYS=DAYS+ENDING/8640000
SET /A ENDING=ENDING-(DAYS*864000)
::Wait for such a centisecond
:delay_wait
FOR /F "tokens=1-4 delims=:." %%A IN ("%TIME%") DO SET /A H=%%A, M=1%%B%%100, S=1%%C%%100, X=1%%D%%100, CURRENT=((H*60+M)*60+S)*100+X
IF DEFINED LASTCURRENT IF %CURRENT% LSS %LASTCURRENT% SET /A DAYS=DAYS-1
SET LASTCURRENT=%CURRENT%
IF %CURRENT% LSS %ENDING% GOTO delay_wait
IF %DAYS% GTR 0 GOTO delay_wait
GOTO :EOF
in my case, this error is raised due to sequence was not created..
CREATE SEQUENCE J.SOME_SEQ MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 1 CACHE 20 NOORDER NOCYCLE ;
Create a function to execute the current buffer using it's shebang (assuming one is set) and call it with crtl-x.
map <C-X> :call CallInterpreter()<CR>
au BufEnter *
\ if match (getline(1) , '^\#!') == 0 |
\ execute("let b:interpreter = getline(1)[2:]") |
\ endif
fun! CallInterpreter()
if exists("b:interpreter")
exec("! ".b:interpreter." %")
endif
endfun
I'm late to the party, but did not see this answer yet. When you don't want to use a batch file or type the command. You can just set focus to the desktop and then use Alt + F4.
Windows will ask you what you want to do, select shutdown or restart.
For screenshots and even a video, see: https://tinkertry.com/how-to-shutdown-or-restart-windows-over-rdp
I am going to show you two methods by which you can dynamically apply ng-class
By using ternary operator
<div ng-class="condition?'class1':'class2'"></div>
If your condition is true then class1 will be applied to your element else class2 will be applied.
When you will try to change the conditional value at run time the class somehow will not changed. So I will suggest you to go for step2 if you have requirement like dynamic class change.
<div ng-class="{value1:'class1', value2:'class2'}[condition]"></div>
if your condition matches with value1 then class1 will be applied to your element, if matches with value2 then class2 will be applied and so on. And dynamic class change will work fine with it.
Hope this will help you.
For me it happened because I had 2 versions of python installed - python 27 and python 3.3. Both these folder had path variable set, and hence there was this issue. To fix, this, I moved python27 to temp folder, as I was ok with python 3.3. So do check environment variables like PATH,PYTHONHOME as it may be a issue. Thanks.
If you're after the 'name', why does your code snippet look like an attempt to get the 'characters'?
Anyways, this is no different from any other list- or array-like operation: you just need to iterate over the dataset and grab the information you're interested in. Retrieving all the names should look somewhat like this:
List<String> allNames = new ArrayList<String>();
JSONArray cast = jsonResponse.getJSONArray("abridged_cast");
for (int i=0; i<cast.length(); i++) {
JSONObject actor = cast.getJSONObject(i);
String name = actor.getString("name");
allNames.add(name);
}
(typed straight into the browser, so not tested).
To add an exclusion for logback from Netbeans IDE
Right click on the jar and select Exclude Dependency as shown below. This excludes the logback jar on the pom.xml like this;
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
you can try this:
command = 'echo content |clip'
subprocess.check_call(command, shell=True)
Thanks for the tip, i used this to get my date "20071122" parsed, I needed to add datetimestyles, I used none and it worked:
DateTime dt = DateTime.MinValue;
DateTime.TryParseExact("20071122", "yyyyMMdd", null,System.Globalization.DateTimeStyles.None, out dt);
Although @amr ali's code was great, I had an instance where my bat file contained >
<
signs, and it choked on them for some reason.
I found this instead. Just put it all before your code, and it works perfectly.
REM --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
echo Requesting administrative privileges...
goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
exit /B
:gotAdmin
if exist "%temp%\getadmin.vbs" ( del "%temp%\getadmin.vbs" )
pushd "%CD%"
CD /D "%~dp0"
:--------------------------------------
As mentioned here: Re: BUG #4243: Idle in transaction it is probably best to check your pg_locks table to see what is being locked and that might give you a better clue where the problem lies.
From Tomcat documentation, For blocking I/O (BIO), the default value of maxConnections
is the value of maxThreads
unless Executor (thread pool) is used in which case, the value of 'maxThreads' from Executor will be used instead. For Non-blocking IO, it doesn't seem to be dependent on maxThreads
.
The following 2 examples make use of either
Example 1: using System.Web.Script.Serialization
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Web.Script.Serialization;
namespace Tests
{
[TestClass]
public class JsonTests
{
[TestMethod]
public void Test()
{
var json = "{\"user\":{\"name\":\"asdf\",\"teamname\":\"b\",\"email\":\"c\",\"players\":[\"1\",\"2\"]}}";
JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic jsonObject = serializer.Deserialize<dynamic>(json);
dynamic x = jsonObject["user"]; // result is Dictionary<string,object> user with fields name, teamname, email and players with their values
x = jsonObject["user"]["name"]; // result is asdf
x = jsonObject["user"]["players"]; // result is object[] players with its values
}
}
}
Usage: JSON object to Custom C# object
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Web.Script.Serialization;
using System.Linq;
namespace Tests
{
[TestClass]
public class JsonTests
{
[TestMethod]
public void TestJavaScriptSerializer()
{
var json = "{\"user\":{\"name\":\"asdf\",\"teamname\":\"b\",\"email\":\"c\",\"players\":[\"1\",\"2\"]}}";
User user = new User(json);
Console.WriteLine("Name : " + user.name);
Console.WriteLine("Teamname : " + user.teamname);
Console.WriteLine("Email : " + user.email);
Console.WriteLine("Players:");
foreach (var player in user.players)
Console.WriteLine(player);
}
}
public class User {
public User(string json) {
JavaScriptSerializer serializer = new JavaScriptSerializer();
var jsonObject = serializer.Deserialize<dynamic>(json);
name = (string)jsonObject["user"]["name"];
teamname = (string)jsonObject["user"]["teamname"];
email = (string)jsonObject["user"]["email"];
players = jsonObject["user"]["players"];
}
public string name { get; set; }
public string teamname { get; set; }
public string email { get; set; }
public Array players { get; set; }
}
}
Example 2: using System.Web.Helpers
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Web.Helpers;
namespace Tests
{
[TestClass]
public class JsonTests
{
[TestMethod]
public void TestJsonDecode()
{
var json = "{\"user\":{\"name\":\"asdf\",\"teamname\":\"b\",\"email\":\"c\",\"players\":[\"1\",\"2\"]}}";
dynamic jsonObject = Json.Decode(json);
dynamic x = jsonObject.user; // result is dynamic json object user with fields name, teamname, email and players with their values
x = jsonObject.user.name; // result is asdf
x = jsonObject.user.players; // result is dynamic json array players with its values
}
}
}
Usage: JSON object to Custom C# object
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Web.Helpers;
using System.Linq;
namespace Tests
{
[TestClass]
public class JsonTests
{
[TestMethod]
public void TestJsonDecode()
{
var json = "{\"user\":{\"name\":\"asdf\",\"teamname\":\"b\",\"email\":\"c\",\"players\":[\"1\",\"2\"]}}";
User user = new User(json);
Console.WriteLine("Name : " + user.name);
Console.WriteLine("Teamname : " + user.teamname);
Console.WriteLine("Email : " + user.email);
Console.WriteLine("Players:");
foreach (var player in user.players)
Console.WriteLine(player);
}
}
public class User {
public User(string json) {
var jsonObject = Json.Decode(json);
name = (string)jsonObject.user.name;
teamname = (string)jsonObject.user.teamname;
email = (string)jsonObject.user.email;
players = (DynamicJsonArray) jsonObject.user.players;
}
public string name { get; set; }
public string teamname { get; set; }
public string email { get; set; }
public Array players { get; set; }
}
}
This code requires adding System.Web.Helpers namespace found in,
%ProgramFiles%\Microsoft ASP.NET\ASP.NET Web Pages{VERSION}\Assemblies\System.Web.Helpers.dll
Or
%ProgramFiles(x86)%\Microsoft ASP.NET\ASP.NET Web Pages{VERSION}\Assemblies\System.Web.Helpers.dll
Hope this helps!
I did something like that awhile back. I was pretty new to JavaScript, so I'm sure you can do better, but here is a starting point:
function fixxedtext() {
if (navigator.appName.indexOf("Microsoft") != -1) {
if (document.body.offsetWidth > 960) {
var width = document.body.offsetWidth - 960;
width = width / 2;
document.getElementById("side").style.marginRight = width + "px";
}
if (document.body.offsetWidth < 960) {
var width = 960 - document.body.offsetWidth;
document.getElementById("side").style.marginRight = "-" + width + "px";
}
}
else {
if (window.innerWidth > 960) {
var width = window.innerWidth - 960;
width = width / 2;
document.getElementById("side").style.marginRight = width + "px";
}
if (window.innerWidth < 960) {
var width = 960 - window.innerWidth;
document.getElementById("side").style.marginRight = "-" + width + "px";
}
}
window.setTimeout("fixxedtext()", 2500)
}
You will need to set your width, and then it gets the window width and changes the margin every few seconds. I know it is heavy, but it works.
Try this command:
/home/user/ directory - find ./ -type f \
-exec sed -i -e 's/a.example.com/b.example.com/g' {} \;
Following this resource page, if the length of x is varying, we can use:
', '.join(['%.2f']*len(x))
to create a place holder for each element from the list x
. Here is the example:
x = [1/3.0, 1/6.0, 0.678]
s = ("elements in the list are ["+', '.join(['%.2f']*len(x))+"]") % tuple(x)
print s
>>> elements in the list are [0.33, 0.17, 0.68]
For clear frame, first need to destroy all widgets inside the frame,. it will clear frame.
import tkinter as tk
from tkinter import *
root = tk.Tk()
frame = Frame(root)
frame.pack(side="top", expand=True, fill="both")
lab = Label(frame, text="hiiii")
lab.grid(row=0, column=0, padx=10, pady=5)
def clearFrame():
# destroy all widgets from frame
for widget in frame.winfo_children():
widget.destroy()
# this will clear frame and frame will be empty
# if you want to hide the empty panel then
frame.pack_forget()
frame.but = Button(frame, text="clear frame", command=clearFrame)
frame.but.grid(row=0, column=1, padx=10, pady=5)
# then whenever you add data in frame then you can show that frame
lab2 = Label(frame, text="hiiii")
lab2.grid(row=1, column=0, padx=10, pady=5)
frame.pack()
root.mainloop()
Try one of these:
gdb -p 12271
gdb /path/to/exe 12271
gdb /path/to/exe
(gdb) attach 12271
Major difference between lock and synchronized:
There is and it is not dependent on post build events.
Add the file to your project, then in the file properties select under "Copy to Output Directory" either "Copy Always" or "Copy if Newer".
See MSDN.
I tried pasting Endoro's command (Thanks Endoro) directly into the command prompt to add a prefix to files but encountered an error. Solution was to reduce %% to %, so:
for /f "delims=" %i in ('dir /b /a-d *.*') do ren "%~i" "Service.Enviro.%~ni%~xi"
To compare entire revisions, it's simply:
svn diff -r 8979:11390
If you want to compare the last committed state against your currently saved working files, you can use convenience keywords:
svn diff -r PREV:HEAD
(Note, without anything specified afterwards, all files in the specified revisions are compared.)
You can compare a specific file if you add the file path afterwards:
svn diff -r 8979:HEAD /path/to/my/file.php
you should change cr_date(str) to datetime object then you 'll change the date to the specific format:
cr_date = '2013-10-31 18:23:29.000227'
cr_date = datetime.datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
cr_date = cr_date.strftime("%m/%d/%Y")
// Used In TypeScript For Angular 4+
const viewArray = [
{id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
{id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
{id: 3, question: "Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
{id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
{id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
{id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
{id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
{id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
{id: 10, question: "Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
{id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
{id: 12, question: "Do you feel a sense of peace and contentment in your home? ", category: "Home Environment", subs: []},
{id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
{id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
{id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
];
const arrayObj = any;
const objectData = any;
for (let index = 0; index < this.viewArray.length; index++) {
this.arrayObj = this.viewArray[index];
this.arrayObj.filter((x) => {
if (x.id === id) {
this.objectData = x;
}
});
console.log('Json Object Data by ID ==> ', this.objectData);
}
};
You don't need jQuery for this. You can use JavaScript's .childNodes.length
.
Just make sure to subtract 1 if you don't want to include the default text node (which is empty by default). Thus, you'd use the following:
var count = elem.childNodes.length - 1;
UPDATE 2016-02: NetBeans 8 now has a Darcula plugin, better and more complete than the alternatives discussed in old version of this Answer.
The attractive and productive Darcula theme in JetBrains IntelliJ is now available in NetBeans 8.0 & 8.1!
This plugin provides the real Darcula, not an imitation.
Konstantin Bulenkov of the JetBrains company open-sourced the Darcula look-and-feel originally built for the IntelliJ IDE. This NetBeans plugin discussed here wraps that original implementation, adapting it to NetBeans. So we see close fidelity to the original Darcula. [By the way, there are many other reasons beyond Darcula to use IntelliJ – both IntelliJ and NetBeans are truly excellent and amazing products.]
This NetBeans plugin is itself open-source as well.
Comes in two parts:
Fonts & Colors
profileThe plugin Darcula LAF for NetBeans is easily available through the usual directory within NetBeans.
Choose Tools
> Plugins
. On the Available Plugins
tab, scroll or search for "Darcula LAF for NetBeans". As per usual, check the checkbox and click the Install
button. Restart NetBeans.
NetBeans
> Preferences
> Fonts & Colors
(tab) > Profile (popup menu), choose the new Darcula
item.Apply
button.I suggest also hitting Duplicate
in case you ever make any modifications (discussed below).
You may find the background color of lines of code may be too bright such as lines marked with a breakpoint, or the currently executing line in the debugger. These are categories listed on the Annotations
tab of the Fonts & Colors
tab.
Of course you can change the background color of each Category
manually but that is tedious.
Workaround: Click the Restore
button found to the right of the Profile
name. Double-check to make sure you have Darcula
as the selected Profile
of course. Then click the Apply
and OK
buttons at the bottom.
You may want to change the font in the method editor. I most highly recommend the commercial font for programmers, PragmataPro. For a free-of-cost and open-source font, the best is Hack. Hack was built on the very successful DejaVu font which in turn was built on Bitstream Vera.
To change the font, add these steps to the above to duplicate the profile as a backup before making your modification:
Duplicate
button.Apply
button. While in that same Fonts & Colors
tab, select Default
in the Category
list and hit the …
button to choose a font.
You might also want to change the font seen in the Output and the Terminal panes. From that Fonts & Colors
tab, switch to the sibling tab Miscellaneous
. Then see both the Output
tab and the Terminal
tab.
While still new I am reserving final judgement on Darcula. So far, so good. Already the makers have had a few updates fixing a few glitches, so that is good to see. This seems to be a very thorough product. As a plugin this affects the entire user interface of NetBeans; that can be very tricky to get right.
There was a similar plugin product predating Darcula: the “Dark Look And Feel Themes” plugin. While I was grateful to use that for a while, I am much happier with Darcula. That other one was more clunky and I had to spend much time tweaking colors of “Norway Today” to work together. Also, that plugin was not savvy with Mac OS X menus so the main Mac menu bar was nearly empty while NetBeans’ own menu bar was embedded within the window. The Darcula plugin has no such problem; the Mac menu bar appears normally.
The rest of this Answer is left intact for history, and for alternatives if Darcula proves problematic.
At least in NetBeans 8.0, two dark profiles are now built-in. Profile names:
The profiles affect only the code editing pane, not the entire NetBeans user-interface. That should mean much less risk of side-effects and bugs than a plugin.
Tip: You can alter the font in either theme, while preserving the other aspects. Perhaps Menlo on a Mac, or its parent DejaVu. Or my fav, the commercial font Pragmata.
Unfortunately, neither theme suits my eyes. They do not begin to compare to the excellent Darcula theme in JetBrains IntelliJ.
On a Mac, the menu path is Netbeans
> Preferences
> Fonts & Colors
(tab) > Profile
(popup menu).
On other host operating systems, the menu path may be Tools
> Options
> Fonts & Colors
. Not sure, but it was so in previous versions.
Please Try This one:
Try Adding input
Css like this:
-webkit-appearance: none;
border-radius: 0;
You can install from nuget as the the below image:
Or, run the below command line on Package Manager Console:
Install-Package Microsoft.AspNet.WebApi
Answers here are a bit outdated. Though the code remains the same there are some changes in the behavior.
public class MyListActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
TextView footerView = (TextView) ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_view, null, false);
getListView().addFooterView(footerView);
setListAdapter(new ArrayAdapter<String>(this, getResources().getStringArray(R.array.news)));
}
}
Info about addFooterView()
method
Add a fixed view to appear at the bottom of the list. If
addFooterView()
is called more than once, the views will appear in the order they were added. Views added using this call can take focus if they want.
Most of the answers above stress very important point -
addFooterView()
must be called before callingsetAdapter()
.This is so ListView can wrap the supplied cursor with one that will also account for header and footer views.
From Kitkat this has changed.
Note: When first introduced, this method could only be called before setting the adapter with setAdapter(ListAdapter). Starting with KITKAT, this method may be called at any time. If the ListView's adapter does not extend HeaderViewListAdapter, it will be wrapped with a supporting instance of WrapperListAdapter.
If you are lucky enough to develop with Kotlin,
you can use take
to achieve your goal.
val someString = "hello"
someString.take(10) // result is "hello"
someString.take(4) // result is "hell" )))
Your JRE_HOME does not need to point to the "bin" directory. Just set it to C:\Program Files\Java\jre1.8.0_25
I use this to open a workbook and then copy that workbook's data to the template.
Private Sub CommandButton24_Click()
Set Template = ActiveWorkbook
With Application.FileDialog(msoFileDialogOpen)
.InitialFileName = "I:\Group - Finance" ' Yu can select any folder you want
.Filters.Clear
.Title = "Your Title"
If Not .Show Then
MsgBox "No file selected.": Exit Sub
End If
Workbooks.OpenText .SelectedItems(1)
'The below is to copy the file into a new sheet in the workbook and paste those values in sheet 1
Set myfile = ActiveWorkbook
ActiveWorkbook.Sheets(1).Copy after:=ThisWorkbook.Sheets(1)
myfile.Close
Template.Activate
ActiveSheet.Cells.Select
Selection.Copy
Sheets("Sheet1").Select
Cells.Select
ActiveSheet.Paste
End With
Instead of using the placeholder text, you'll want to set the actual text
property of the field to MM/YYYY, set the delegate of the text field and listen for this method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { // update the text of the label }
Inside that method, you can figure out what the user has typed as they type, which will allow you to update the label accordingly.
The substitute of fcntl
on windows are win32api
calls. The usage is completely different. It is not some switch you can just flip.
In other words, porting a fcntl
-heavy-user module to windows is not trivial. It requires you to analyze what exactly each fcntl
call does and then find the equivalent win32api
code, if any.
There's also the possibility that some code using fcntl
has no windows equivalent, which would require you to change the module api and maybe the structure/paradigm of the program using the module you're porting.
If you provide more details about the fcntl
calls people can find windows equivalents.
You can use a padding for the button and you can play with drawablePadding
<Button
style="@style/botonesMenu"
android:padding="15dp"
android:drawablePadding="-15dp"
android:text="@string/actualizarBD"
android:textAlignment="gravity"
android:gravity="center"
android:layout_row="1"
android:layout_column="0"
android:drawableTop="@drawable/actualizar"
android:id="@+id/btnActualizar"
android:onClick="actualizarBD" />
you can use a specific padding depends where put your drawable, with android:paddingLeft="10dp" or android:paddingBottom="10dp" or android:paddingRight="10dp" or android:paddingTop="10dp"
For python3.5, you can use the following code:
import urllib.request
res = urllib.request.urlopen(starturl)
finalurl = res.geturl()
print(finalurl)