UITextView *textview= [[UITextView alloc]initWithFrame:CGRectMake(10, 130, 250, 170)];
NSString *str = @"This is <font color='red'>simple</font>";
[textview setValue:str forKey:@"contentToHTMLString"];
textview.textAlignment = NSTextAlignmentLeft;
textview.editable = NO;
textview.font = [UIFont fontWithName:@"vardana" size:20.0];
[UIView addSubview:textview];
work fine for me
java -classpath Predit.jar your.package.name.MainClass
One practical use is if you have committed to your local repo already (ie. git commit -m ) then you can reverse that last commit by doing git reset --soft HEAD~1
Also for your knowledge, if you have staged your changes already (ie with git add .) then you can reverse the staging by doing git reset --mixed HEAD or i've commonly also just used git reset
lastly, git reset --hard wipes everything out including your local changes. The ~ after head tells you how many commits to go to from the top.
For what was actually asked, my approach is to put those if
s inside a one-looped loop
while (True):
if (some_condition):
...
if (condition_a):
# do something
# and then exit the outer if block
break
...
if (condition_b):
# do something
# and then exit the outer if block
break
# more code here
# make sure it is looped once
break
Test it:
conditions = [True,False]
some_condition = True
for condition_a in conditions:
for condition_b in conditions:
print("\n")
print("with condition_a", condition_a)
print("with condition_b", condition_b)
while (True):
if (some_condition):
print("checkpoint 1")
if (condition_a):
# do something
# and then exit the outer if block
print("checkpoint 2")
break
print ("checkpoint 3")
if (condition_b):
# do something
# and then exit the outer if block
print("checkpoint 4")
break
print ("checkpoint 5")
# more code here
# make sure it is looped once
break
I think this simple "decision tree" by Julie Lerman the author of "Programming Entity Framework" should help making the decision with more confidence:
More info Here.
I assume you're talking about a UIButton with UIButtonTypeRoundedRect
?
You can't change the background color of that. When you try changing it's background color you're rather changing the color of the rect the button is drawn on (which is usually clear).
So there are two ways to go. Either you subclass UIButton and overwrite its -drawRect:
method or you create images for the different button states (which is perfectly fine to do).
If you set the background images in Interface Builder you should notice that IB doesn't support setting images for all the states the button can have, so I recommend setting the images in code like this:
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
[myButton setBackgroundImage:[UIImage imageNamed:@"normal.png"] forState:UIControlStateNormal];
[myButton setBackgroundImage:[UIImage imageNamed:@"disabled.png"] forState:UIControlStateDisabled];
[myButton setBackgroundImage:[UIImage imageNamed:@"selected.png"] forState:UIControlStateSelected];
[myButton setBackgroundImage:[UIImage imageNamed:@"higligted.png"] forState:UIControlStateHighlighted];
[myButton setBackgroundImage:[UIImage imageNamed:@"highlighted+selected.png"] forState:(UIControlStateHighlighted | UIControlStateSelected)];
The last line shows how to set an image for the selected & highlighted state (that's the one IB can't set). You don't need the selected images (line 4 & 6) if you're button dosn't need a selected state.
You can sort a int array with Arrays.sort( array )
.
For anyone who has upgraded recently from 6.x to 6.7.0.
Deleting the /Users/{YOUR USERNAME}/.npm
folder solved my issues with npm install
.
I also, ran some of these commands suggested by https://npm.community/t/crash-npm-err-cb-never-called/858/93?u=jasonfoglia
sudo npm cache clean -f
sudo npm install -g n
But I'm not sure which actually worked until I deleted the folder. So if you experience this issue and just delete the .npm folder fixing your issue please note that in the comments.
It became a popular question and I got a notification. I am sorry, I forgot to answer before which I should have done. I solved it long back.
net use \\10.100.110.120\C$ MyPassword /user:domain\username /persistent:Yes
Run it in a batch file and you should get what you are looking for.
I've been trying to do something very similar but not using the nodes. However, my xml structure is a little different.
You have it like this:
<Metrics>
<Metric id="TransactionCleanupThread.RefundOldTrans" type="timer" ...>
If it were like this instead:
<Metrics>
<Metric>
<id>TransactionCleanupThread.RefundOldTrans</id>
<type>timer</type>
.
.
.
Then you could simply use this SQL statement.
SELECT
Sqm.SqmId,
Data.value('(/Sqm/Metrics/Metric/id)[1]', 'varchar(max)') as id,
Data.value('(/Sqm/Metrics/Metric/type)[1]', 'varchar(max)') AS type,
Data.value('(/Sqm/Metrics/Metric/unit)[1]', 'varchar(max)') AS unit,
Data.value('(/Sqm/Metrics/Metric/sum)[1]', 'varchar(max)') AS sum,
Data.value('(/Sqm/Metrics/Metric/count)[1]', 'varchar(max)') AS count,
Data.value('(/Sqm/Metrics/Metric/minValue)[1]', 'varchar(max)') AS minValue,
Data.value('(/Sqm/Metrics/Metric/maxValue)[1]', 'varchar(max)') AS maxValue,
Data.value('(/Sqm/Metrics/Metric/stdDeviation)[1]', 'varchar(max)') AS stdDeviation,
FROM Sqm
To me this is much less confusing than using the outer apply or cross apply.
I hope this helps someone else looking for a simpler solution!
No, @media
rules and media queries cannot exist in inline style attributes as they can only contain property: value
declarations. As the spec puts it:
The value of the style attribute must match the syntax of the contents of a CSS declaration block
The only way to apply styles to an element only in certain media is with a separate rule in your stylesheet, which means you'll need to come up with a selector for it.
A dummy span
selector would look like this, but if you're targeting a very specific element you will need a more specific selector:
span { background-image: url(particular_ad.png); }
@media (max-width: 300px) {
span { background-image: url(particular_ad_small.png); }
}
If you take a look at @types/node-fetch you will see the body definition
export class Body {
bodyUsed: boolean;
body: NodeJS.ReadableStream;
json(): Promise<any>;
json<T>(): Promise<T>;
text(): Promise<string>;
buffer(): Promise<Buffer>;
}
That means that you could use generics in order to achieve what you want. I didn't test this code, but it would looks something like this:
import { Actor } from './models/actor';
fetch(`http://swapi.co/api/people/1/`)
.then(res => res.json<Actor>())
.then(res => {
let b:Actor = res;
});
I assume you are using integers to represent your year, month, and day? If you want to remain consistent, use the Date methods.
Calendar cal = new Calendar();
int currentYear, currentMonth, currentDay;
currentYear = cal.get(Calendar.YEAR);
currentMonth = cal.get(Calendar.MONTH);
currentDay = cal.get(Calendar.DAY_OF_WEEK);
if(startYear < currentYear)
{
message = message + "Start Date is Before Today" + "\n";
}
else if(startMonth < currentMonth && startYear <= currentYear)
{
message = message + "Start Date is Before Today" + "\n";
}
else if(startDay < currentDay && startMonth <= currentMonth && startYear <= currentYear)
{
message = message + "Start Date is Before Today" + "\n";
}
In java you don't check if a key is pressed, instead you listen to KeyEvent
s.
The right way to achieve your goal is to register a KeyEventDispatcher
, and implement it to maintain the state of the desired key:
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
public class IsKeyPressed {
private static volatile boolean wPressed = false;
public static boolean isWPressed() {
synchronized (IsKeyPressed.class) {
return wPressed;
}
}
public static void main(String[] args) {
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
@Override
public boolean dispatchKeyEvent(KeyEvent ke) {
synchronized (IsKeyPressed.class) {
switch (ke.getID()) {
case KeyEvent.KEY_PRESSED:
if (ke.getKeyCode() == KeyEvent.VK_W) {
wPressed = true;
}
break;
case KeyEvent.KEY_RELEASED:
if (ke.getKeyCode() == KeyEvent.VK_W) {
wPressed = false;
}
break;
}
return false;
}
}
});
}
}
Then you can always use:
if (IsKeyPressed.isWPressed()) {
// do your thing.
}
You can, of course, use same method to implement isPressing("<some key>")
with a map of keys and their state wrapped inside IsKeyPressed
.
an Event will fire multiple time when it is registered multiple times (even if to the same handler).
eg $("ctrl").on('click', somefunction)
if this piece of code is executed every time the page is partially refreshed, the event is being registered each time too. Hence even if the ctrl is clicked only once it may execute "somefunction" multiple times - how many times it execute will depend on how many times it was registered.
this is true for any event registered in javascript.
solution:
ensure to call "on" only once.
and for some reason if you cannot control the architecture then do this:
$("ctrl").off('click');
$("ctrl").on('click', somefunction);
If you have a list of lists, you only needed to use ...
import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)
per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.
Another reason crontab will fail: Special handling of the %
character.
From the man file:
The entire command portion of the line, up to a newline or a
"%" character, will be executed by /bin/sh or by the shell specified
in the SHELL variable of the cronfile. A "%" character in the
command, unless escaped with a backslash (\), will be changed into
newline characters, and all data after the first % will be sent to
the command as standard input.
In my particular case, I was using date --date="7 days ago" "+%Y-%m-%d"
to produce parameters to my script, and it was failing silently. I finally found out what was going on when I checked syslog
and saw my command was truncated at the %
symbol. You need to escape it like this:
date --date="7 days ago" "+\%Y-\%m-\%d"
See here for more details:
http://www.ducea.com/2008/11/12/using-the-character-in-crontab-entries/
Revisiting this page and I have more information to share with others.
Debugging environment (using Visual Studio)
1a) Stephen Walter's link to set the startup page on MVC using the project properties is only applicable when you are debugging your MVC application.
1b) Right mouse click on the .aspx page in Solution Explorer and select the "Set As Start Page" behaves the same.
Note: in both the above cases, the startup page setting is only recognised by your Visual Studio Development Server. It is not recognised by your deployed server.
Deployed environment
2a) To set the startup page, assuming that you have not change any of the default routings, change the content of /Views/Home/Index.aspx to do a "Server.Transfer" or a "Response.Redirect" to your desired page.
2b) Change your default routing in your global.asax.cs to your desired page.
Are there any other options that the readers are aware of? Which of the above (including your own option) would be your preferred solution (and please share with us why)?
removeChild
should be invoked on the parent, i.e.:
parent.removeChild(child);
In your example, you should be doing something like:
if (frameid) {
frameid.parentNode.removeChild(frameid);
}
With current versions of Docker, you can use the --device
flag to achieve what you want, without needing to give access to all USB devices.
For example, if you wanted to make only /dev/ttyUSB0
accessible within your Docker container, you could do something like:
docker run -t -i --device=/dev/ttyUSB0 ubuntu bash
if you don't like the double brackets or you don't want to write a function, you can just use a variable.
$path = Test-Path C:\Code
if (!$path) {
write "it doesn't exist!"
}
An array variable is simply a pointer, so you just pass it like so:
PrintA(arrayw);
Edit:
A little more elaboration. If what you want to do is create a COPY of an array, you'll have to pass the array into the method and then manually create a copy there (not sure if Java has something like Array.CopyOf()
). Otherwise, you'll be passing around a REFERENCE of the array, so if you change any values of the elements in it, it will be changed for other methods as well.
Please check in logs if you have http.HttpWagon$__sisu1:Cannot find 'basicAuthScope' this error or warning also, if so you need to use maven 3.2.5 version, which will resolve error.
These steps work for me:
Good to go!!!
library(Rcpp)
library(ggplot2)
matrix multiplication, see the following example:
> A <- matrix (c(1,3,4, 5,8,9, 1,3,3), 3,3)
> A
[,1] [,2] [,3]
[1,] 1 5 1
[2,] 3 8 3
[3,] 4 9 3
>
> B <- matrix (c(2,4,5, 8,9,2, 3,4,5), 3,3)
>
> B
[,1] [,2] [,3]
[1,] 2 8 3
[2,] 4 9 4
[3,] 5 2 5
>
>
> A %*% B
[,1] [,2] [,3]
[1,] 27 55 28
[2,] 53 102 56
[3,] 59 119 63
> B %*% A
[,1] [,2] [,3]
[1,] 38 101 35
[2,] 47 128 43
[3,] 31 86 26
Also see:
http://en.wikipedia.org/wiki/Matrix_multiplication
If this does not follow the size of matrix rule you will get the error:
> A <- matrix(c(1,2,3,4,5,6), 3,2)
> A
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
> B <- matrix (c(3,1,3,4,4,4,4,4,3), 3,3)
> B
[,1] [,2] [,3]
[1,] 3 4 4
[2,] 1 4 4
[3,] 3 4 3
> A%*%B
Error in A %*% B : non-conformable arguments
In my opinion, to answer this question, you need to think in terms of project life cycle and version control. In other words, does the parent pom have its own life cycle i.e. can it be released separately of the other modules or not?
If the answer is yes (and this is the case of most projects that have been mentioned in the question or in comments), then the parent pom needs his own module from a VCS and from a Maven point of view and you'll end up with something like this at the VCS level:
root
|-- parent-pom
| |-- branches
| |-- tags
| `-- trunk
| `-- pom.xml
`-- projectA
|-- branches
|-- tags
`-- trunk
|-- module1
| `-- pom.xml
|-- moduleN
| `-- pom.xml
`-- pom.xml
This makes the checkout a bit painful and a common way to deal with that is to use svn:externals
. For example, add a trunks
directory:
root
|-- parent-pom
| |-- branches
| |-- tags
| `-- trunk
| `-- pom.xml
|-- projectA
| |-- branches
| |-- tags
| `-- trunk
| |-- module1
| | `-- pom.xml
| |-- moduleN
| | `-- pom.xml
| `-- pom.xml
`-- trunks
With the following externals definition:
parent-pom http://host/svn/parent-pom/trunk
projectA http://host/svn/projectA/trunk
A checkout of trunks
would then result in the following local structure (pattern #2):
root/
parent-pom/
pom.xml
projectA/
Optionally, you can even add a pom.xml
in the trunks
directory:
root
|-- parent-pom
| |-- branches
| |-- tags
| `-- trunk
| `-- pom.xml
|-- projectA
| |-- branches
| |-- tags
| `-- trunk
| |-- module1
| | `-- pom.xml
| |-- moduleN
| | `-- pom.xml
| `-- pom.xml
`-- trunks
`-- pom.xml
This pom.xml
is a kind of "fake" pom: it is never released, it doesn't contain a real version since this file is never released, it only contains a list of modules. With this file, a checkout would result in this structure (pattern #3):
root/
parent-pom/
pom.xml
projectA/
pom.xml
This "hack" allows to launch of a reactor build from the root after a checkout and make things even more handy. Actually, this is how I like to setup maven projects and a VCS repository for large builds: it just works, it scales well, it gives all the flexibility you may need.
If the answer is no (back to the initial question), then I think you can live with pattern #1 (do the simplest thing that could possibly work).
Now, about the bonus questions:
- Where is the best place to define the various shared configuration as in source control, deployment directories, common plugins etc. (I'm assuming the parent but I've often been bitten by this and they've ended up in each project rather than a common one).
Honestly, I don't know how to not give a general answer here (like "use the level at which you think it makes sense to mutualize things"). And anyway, child poms can always override inherited settings.
- How do the maven-release plugin, hudson and nexus deal with how you set up your multi-projects (possibly a giant question, it's more if anyone has been caught out when by how a multi-project build has been set up)?
The setup I use works well, nothing particular to mention.
Actually, I wonder how the maven-release-plugin deals with pattern #1 (especially with the <parent>
section since you can't have SNAPSHOT dependencies at release time). This sounds like a chicken or egg problem but I just can't remember if it works and was too lazy to test it.
Solution works very well,
public List<String> savePerson(@RequestBody Person[] personArray)
For this signature you can pass Person
array from postman like
[
{
"empId": "10001",
"tier": "Single",
"someting": 6,
"anything": 0,
"frequency": "Quaterly"
}, {
"empId": "10001",
"tier": "Single",
"someting": 6,
"anything": 0,
"frequency": "Quaterly"
}
]
Don't forget to add consumes
tag:
@RequestMapping(value = "/getEmployeeList", method = RequestMethod.POST, consumes="application/json", produces = "application/json")
public List<Employee> getEmployeeDataList(@RequestBody Employee[] employeearray) { ... }
this should do:
//Main Class
public class SomeClass {
//Sub-Class
public static class AnotherClass {
public enum MyEnum {
VALUE_A, VALUE_B
}
public MyEnum myEnum;
}
public void someMethod() {
AnotherClass.MyEnum enumExample = AnotherClass.MyEnum.VALUE_A; //...
switch (enumExample) {
case VALUE_A: { //<-- error on this line
//..
break;
}
}
}
}
The following script is tested and gives exactly the results, that are expected
\#!/bin/bash
echo "Enter the file name"
read file
echo "enter the word to be found"
read word
count=0
for i in \`cat $file`
do
if [ $i == $word ]
then
count=\`expr $count + 1`
fi
done
echo "The number of words are $count"
I'll elaborate a bit more on ChrisR awesome answer and bring images from his awesome reference.
A valid JSON always starts with either curly braces {
or square brackets [
, nothing else.
{
will start an object
:{ "key": value, "another key": value }
Hint: although javascript accepts single quotes
'
, JSON only takes double ones"
.
[
will start an array
:[value, value]
Hint: spaces among elements are always ignored by any JSON parser.
value
is an object
, array
, string
, number
, bool
or null
:So yeah, ["a", "b"]
is a perfectly valid JSON, like you could try on the link Manish pointed.
Here are a few extra valid JSON examples, one per block:
{}
[0]
{"__comment": "json doesn't accept comments and you should not be commenting even in this way", "avoid!": "also, never add more than one key per line, like this"}
[{ "why":null} ]
{
"not true": [0, false],
"true": true,
"not null": [0, 1, false, true, {
"obj": null
}, "a string"]
}
None of the answers here show the difference, which could be helpful for folks struggling to understand the difference. Consider this sample code:
using System;
using System.Collections.Generic;
namespace ExceptionDemo
{
class Program
{
static void Main(string[] args)
{
void fail()
{
(null as string).Trim();
}
void bareThrow()
{
try
{
fail();
}
catch (Exception e)
{
throw;
}
}
void rethrow()
{
try
{
fail();
}
catch (Exception e)
{
throw e;
}
}
void innerThrow()
{
try
{
fail();
}
catch (Exception e)
{
throw new Exception("outer", e);
}
}
var cases = new Dictionary<string, Action>()
{
{ "Bare Throw:", bareThrow },
{ "Rethrow", rethrow },
{ "Inner Throw", innerThrow }
};
foreach (var c in cases)
{
Console.WriteLine(c.Key);
Console.WriteLine(new string('-', 40));
try
{
c.Value();
} catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
}
Which generates the following output:
Bare Throw:
----------------------------------------
System.NullReferenceException: Object reference not set to an instance of an object.
at ExceptionDemo.Program.<Main>g__fail|0_0() in C:\...\ExceptionDemo\Program.cs:line 12
at ExceptionDemo.Program.<>c.<Main>g__bareThrow|0_1() in C:\...\ExceptionDemo\Program.cs:line 19
at ExceptionDemo.Program.Main(String[] args) in C:\...\ExceptionDemo\Program.cs:line 64
Rethrow
----------------------------------------
System.NullReferenceException: Object reference not set to an instance of an object.
at ExceptionDemo.Program.<>c.<Main>g__rethrow|0_2() in C:\...\ExceptionDemo\Program.cs:line 35
at ExceptionDemo.Program.Main(String[] args) in C:\...\ExceptionDemo\Program.cs:line 64
Inner Throw
----------------------------------------
System.Exception: outer ---> System.NullReferenceException: Object reference not set to an instance of an object.
at ExceptionDemo.Program.<Main>g__fail|0_0() in C:\...\ExceptionDemo\Program.cs:line 12
at ExceptionDemo.Program.<>c.<Main>g__innerThrow|0_3() in C:\...\ExceptionDemo\Program.cs:line 43
--- End of inner exception stack trace ---
at ExceptionDemo.Program.<>c.<Main>g__innerThrow|0_3() in C:\...\ExceptionDemo\Program.cs:line 47
at ExceptionDemo.Program.Main(String[] args) in C:\...\ExceptionDemo\Program.cs:line 64
The bare throw, as indicated in the previous answers, clearly shows both the original line of code that failed (line 12) as well as the two other points active in the call stack when the exception occurred (lines 19 and 64).
The output of the re-throw case shows why it's a problem. When the exception is rethrown like this the exception won't include the original stack information. Note that only the throw e
(line 35) and outermost call stack point (line 64) are included. It would be difficult to track down the fail() method as the source of the problem if you throw exceptions this way.
The last case (innerThrow) is most elaborate and includes more information than either of the above. Since we're instantiating a new exception we get the chance to add contextual information (the "outer" message, here but we can also add to the .Data dictionary on the new exception) as well as preserving all of the information in the original exception (including help links, data dictionary, etc.).
I like the idea of seting tomcat6 memory based on available server memory (it is cool because I don't have to change the setup after hardware upgrade). Here is my (a bit extended memory setup):
export CATALINA_OPTS="-Xmx
`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.75 } '`
k -Xms`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.75 } '`
k -XX:NewSize=`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.15 } '`
k -XX:MaxNewSize=`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.15 } '`
k -XX:PermSize=`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.15 } '`
k -XX:MaxPermSize=`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.15 } '`
k"
Put it to: "{tomcat}/bin/startup.sh" (e.g. "/usr/share/tomcat6/bin" for Ubuntu 10.10)
add JAVA_HOME to the file:
/etc/environment
for it to be available to the entire system (you would need to restart Ubuntu though)
Please find the below query also split the string with delimeter.
Select Substring(@String1,0,CharIndex(@delimeter,@String1))
I'm using Compact Framework 3.5, and not has a "char.Parse" method. I think is not bad to use the Convert class. (See CLR via C#, Jeffrey Richter)
char letterA = Convert.ToChar(65);
Console.WriteLine(letterA);
letterA = '?';
ushort valueA = Convert.ToUInt16(letterA);
Console.WriteLine(valueA);
char japaneseA = Convert.ToChar(valueA);
Console.WriteLine(japaneseA);
Works with ASCII char or Unicode char
It depends on what the zip contains. Take a look to see if it got content.jar and artifacts.jar. If it does, it is an archived updated site. Install from it the same way as you install from a remote site.
If the zip doesn't contain content.jar and artifacts.jar, go to your Eclipse install's dropins directory, create a subfolder (name doesn't matter) and expand your zip into that folder. Restart Eclipse.
/q isn't a valid parameter. /y: Suppresses prompting to confirm overwriting
Also ..\txt means directory txt under the parent directory, not the root directory. The root directory would be: \ And please mention the error you get
Try:
move files\*.txt \
Edit: Try:
move \files\*.txt \
Edit 2:
move C:\files\*.txt C:\txt
First of all disable child views autoresizing
UIView *view1, *view2;
[childview setTranslatesAutoresizingMaskIntoConstraints:NO];
If you are UIView+Autolayout or Purelayout:
[view1 autoAlignAxis:ALAxisHorizontal toSameAxisOfView:view2];
[view1 autoAlignAxis:ALAxisVertical toSameAxisOfView:view2];
If you are using only UIKit level autolayout methods:
[view1 addConstraints:({
@[ [NSLayoutConstraint
constraintWithItem:view1
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:view2
attribute:NSLayoutAttributeCenterX
multiplier:1.f constant:0.f],
[NSLayoutConstraint
constraintWithItem:view1
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:view2
attribute:NSLayoutAttributeCenterY
multiplier:1.f constant:0.f] ];
})];
I prefer:
UIView *parentView, *childView;
[childView setFrame:({
CGRect frame = childView.frame;
frame.origin.x = (parentView.frame.size.width - frame.size.width) / 2.0;
frame.origin.y = (parentView.frame.size.height - frame.size.height) / 2.0;
CGRectIntegral(frame);
})];
I was having difficulty getting the answer by @fernando-aguirre using WindowChrome
to work. It was not working in my case because I was overriding OnSourceInitialized
in the MainWindow
and not calling the base class method.
protected override void OnSourceInitialized(EventArgs e)
{
ViewModel.Initialize(this);
base.OnSourceInitialized(e); // <== Need to call this!
}
This stumped me for a very long time.
If you want a less verbose hack:
void deleteDirectory(String path) {
Runtime.getRuntime().exec(String.format("rm -rf %s", path));
}
Well you have to setup the click event first then you can trigger it and see what happens:
//good habits first let's cache our selector
var $myLink = $('#titleee').find('a');
$myLink.click(function (evt) {
evt.preventDefault();
alert($(this).attr('href'));
});
// now the manual trigger
$myLink.trigger('click');
I had a very similar problem after moving a working project to a new subdirectory on my file system. It turned out I had failed to move the file named .angular-cli.json
to the subfolder along with everything else. After noticing that and moving the file into the subdirectory, all was back to normal.
You can inject dependencies in attributes like AuthorizeAttribute in this way
var someservice = (ISomeService)context.HttpContext.RequestServices.GetService(typeof(ISomeService));
If your app is one of:
{
".sh": "bash",
".py": "python",
".rb": "ruby",
".coffee" : "coffee",
".php": "php",
".pl" : "perl",
".js" : "node"
}
and you don't mind a NodeJS dependency then install NodeJS and then:
npm install -g pm2
pm2 start yourapp.yourext --name "fred" # where .yourext is one of the above
pm2 start yourapp.yourext -i 0 --name "fred" # run your app on all cores
pm2 list
To keep all apps running on reboot (and daemonise pm2):
pm2 startup
pm2 save
Now you can:
service pm2 stop|restart|start|status
(also easily allows you to watch for code changes in your app directory and auto restart the app process when a code change happens)
Here are some solutions for all types of dialogs including a solution for AlertDialog.Builder that will work on all API levels (works below API 8, which the other answer here does not). There are solutions for AlertDialogs using AlertDialog.Builder, DialogFragment, and DialogPreference.
Below are the code examples showing how to override the default common button handler and prevent the dialog from closing for these different forms of dialogs. All the examples show how to prevent the positive button from closing the dialog.
Note: A description of how the dialog closing works under the hood for the base android classes and why the following approaches are chosen follows after the examples, for those who want more details
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Test for preventing dialog close");
builder.setPositiveButton("Test",
new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
//Do nothing here because we override this button later to change the close behaviour.
//However, we still need this because on older versions of Android unless we
//pass a handler the button doesn't get instantiated
}
});
final AlertDialog dialog = builder.create();
dialog.show();
//Overriding the handler immediately after show is probably a better approach than OnShowListener as described below
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Boolean wantToCloseDialog = false;
//Do stuff, possibly set wantToCloseDialog to true then...
if(wantToCloseDialog)
dialog.dismiss();
//else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
}
});
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Test for preventing dialog close");
builder.setPositiveButton("Test",
new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
//Do nothing here because we override this button later to change the close behaviour.
//However, we still need this because on older versions of Android unless we
//pass a handler the button doesn't get instantiated
}
});
return builder.create();
}
//onStart() is where dialog.show() is actually called on
//the underlying dialog, so we have to do it there or
//later in the lifecycle.
//Doing it in onResume() makes sure that even if there is a config change
//environment that skips onStart then the dialog will still be functioning
//properly after a rotation.
@Override
public void onResume()
{
super.onResume();
final AlertDialog d = (AlertDialog)getDialog();
if(d != null)
{
Button positiveButton = (Button) d.getButton(Dialog.BUTTON_POSITIVE);
positiveButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Boolean wantToCloseDialog = false;
//Do stuff, possibly set wantToCloseDialog to true then...
if(wantToCloseDialog)
d.dismiss();
//else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
}
});
}
}
@Override
protected void onPrepareDialogBuilder(Builder builder)
{
super.onPrepareDialogBuilder(builder);
builder.setPositiveButton("Test", this); //Set the button here so it gets created
}
@Override
protected void showDialog(Bundle state)
{
super.showDialog(state); //Call show on default first so we can override the handlers
final AlertDialog d = (AlertDialog) getDialog();
d.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Boolean wantToCloseDialog = false;
//Do stuff, possibly set wantToCloseDialog to true then...
if(wantToCloseDialog)
d.dismiss();
//else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
}
});
}
Explanation of approaches:
Looking through Android source code the AlertDialog default implementation works by registering a common button handler to all the actual buttons in OnCreate(). When a button is clicked the common button handler forwards the click event to whatever handler you passed in setButton() then calls dismisses the dialog.
If you wish to prevent a dialog box from closing when one of these buttons is pressed you must replace the common button handler for the actual view of the button. Because it is assigned in OnCreate(), you must replace it after the default OnCreate() implementation is called. OnCreate is called in the process of the show() method. You could create a custom Dialog class and override OnCreate() to call the super.OnCreate() then override the button handlers, but if you make a custom dialog you don't get the Builder for free, in which case what is the point?
So, in using a dialog the way it is designed but with controlling when it is dismissed, one approach is to call dialog.Show() first, then obtain a reference to the button using dialog.getButton() to override the click handler. Another approach is to use setOnShowListener() and implement finding the button view and replacing the handler in the OnShowListener. The functional difference between the two is 'almost' nill, depending on what thread originally creates the dialog instance. Looking through the source code, the onShowListener gets called by a message posted to a handler running on the thread that created that dialog. So, since your OnShowListener is called by a message posted on the message queue it is technically possible that calling your listener is delayed some time after show completes.
Therefore, I believe the safest approach is the first: to call show.Dialog(), then immediately in the same execution path replace the button handlers. Since your code that calls show() will be operating on the main GUI thread, it means whatever code you follow show() with will be executed before any other code on that thread, whereas the timing of the OnShowListener method is at the mercy of the message queue.
I too got the same error and struggled a lot in fixing this issue. Spent quiet a bit time in searching Google and found the following solution and my issue got resolved.
the issue was due to, missing Struts2 Libraries in the deployment path. Most of the folks may put the libraries for compilation and tend to forget to attach required libraries for run-time. So I added the same libraries in the web deployment assembly, and the issue was OFF.
I think the problem you are facing is almost this: -
str = str.replace("-", ' ');
You need to re-assign the result of the replacement to str
, to see the reflected change.
From MSDN Javascript reference: -
The result of the replace method is a copy of stringObj after the specified replacements have been made.
To replace all the -
, you would need to use /g
modifier with a regex parameter: -
str = str.replace(/-/g, ' ');
The simplest way is create a static folder inside the main project folder. Static folder containing .css files.
main folder
/Main Folder
/Main Folder/templates/foo.html
/Main Folder/static/foo.css
/Main Folder/application.py(flask script)
Image of main folder containing static and templates folders and flask script
flask
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def login():
return render_template("login.html")
html (layout)
<!DOCTYPE html>
<html>
<head>
<title>Project(1)</title>
<link rel="stylesheet" href="/static/styles.css">
</head>
<body>
<header>
<div class="container">
<nav>
<a class="title" href="">Kamook</a>
<a class="text" href="">Sign Up</a>
<a class="text" href="">Log In</a>
</nav>
</div>
</header>
{% block body %}
{% endblock %}
</body>
</html>
html
{% extends "layout.html" %}
{% block body %}
<div class="col">
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" required>
<input type="submit" value="Login">
</div>
{% endblock %}
top, parent, opener (as well as window, self, and iframe) are all window objects.
window.opener
-> returns the window that opens or launches the current popup window.window.top
-> returns the topmost window, if you're using frames, this is the frameset window, if not using frames, this is the same as window or self.window.parent
-> returns the parent frame of the current frame or iframe. The parent frame may be the frameset window or another frame if you have nested frames. If not using frames, parent is the same as the current window or selfAll the setting are stored in .metadata file in your workspace delete this and you are good to go
I did want to obmit a old big history and start from a fresh commit i choosed to:
rsync -a --exclude '.git' old-repo/ new-repo/
cd new-repo
git push
when now old-repo changes i can apply the patches to the new-repo to rebase them on the new-repo.
This is what I do:
Then everything will be added on your solution from folders to files, and files inside those folders.
The followed works on ubuntu 12.04:
pip uninstall PIL
apt-get install libjpeg-dev
apt-get install libfreetype6-dev
apt-get install zlib1g-dev
apt-get install libpng12-dev
pip install PIL --upgrade
when your see "-- JPEG support avaliable" that means it works.
But, if it still doesn't work when your edit your jpeg image, check the python path !!
my python path missed /usr/local/lib/python2.7/dist-packages/PIL-1.1.7-py2.7-linux-x86_64.egg/
, so I edit the ~/.bashrc
add the following code to this file:
Edit: export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python2.7/dist-packages/PIL-1.1.7-py2.7-linux-x86_64.egg/
then, finally, it works!!
According to the packages list in Ubuntu Wily Xenial Bionic there is a package named openjfx. This should be a candidate for what you're looking for:
JavaFX/OpenJFX 8 - Rich client application platform for Java
You can install it via:
sudo apt-get install openjfx
It provides the following JAR files to the OpenJDK installation on Ubuntu systems:
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/jfxrt.jar
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/jfxswt.jar
/usr/lib/jvm/java-8-openjdk-amd64/lib/ant-javafx.jar
/usr/lib/jvm/java-8-openjdk-amd64/lib/javafx-mx.jar
If you want to have sources available, for example for debugging, you can additionally install:
sudo apt-get install openjfx-source
You can do this either with multiple System.Net.Mail.MailAddress
objects or you can provide a single string containing all of the addresses separated by commas
Drop it in a cron job that runs every night (afternoon?) when you're sleeping.
I wrote a method for this sometime back. It deletes the specified directory and returns true if the directory deletion was successful.
/**
* Delets a dir recursively deleting anything inside it.
* @param dir The dir to delete
* @return true if the dir was successfully deleted
*/
public static boolean deleteDirectory(File dir) {
if(! dir.exists() || !dir.isDirectory()) {
return false;
}
String[] files = dir.list();
for(int i = 0, len = files.length; i < len; i++) {
File f = new File(dir, files[i]);
if(f.isDirectory()) {
deleteDirectory(f);
}else {
f.delete();
}
}
return dir.delete();
}
This is how you do if/else in Mustache (perfectly supported):
{{#repo}}
<b>{{name}}</b>
{{/repo}}
{{^repo}}
No repos :(
{{/repo}}
Or in your case:
{{#author}}
{{#avatar}}
<img src="{{avatar}}"/>
{{/avatar}}
{{^avatar}}
<img src="/images/default_avatar.png" height="75" width="75" />
{{/avatar}}
{{/author}}
Look for inverted sections in the docs: https://github.com/janl/mustache.js
Gets the value of the current TimeSpan structure expressed in whole and fractional minutes.
Assuming the following command works successfully:
mysql -u username -p -h remote.site.com
The syntax for mysqldump
is identical, and outputs the database dump to stdout
. Redirect the output to a local file on the computer:
mysqldump -u username -p -h remote.site.com DBNAME > backup.sql
Replace DBNAME
with the name of the database you'd like to download to your computer.
To reload a section of the page, you could use jquerys load
with the current url and specify the fragment you need, which would be the same element that load
is called on, in this case #here
:
function updateDiv()
{
$( "#here" ).load(window.location.href + " #here" );
}
+ " #here"
This function can be called within an interval, or attached to a click event
I ended up doing systemd service for WAR/JAR layout
I'm calling java -jar because its more flexible. Tried also putting the ExecStart=spring-mvc.war but even though is executable, I got 'Exec format error'
Anyway these days, systemd is present on all distros, and offers a nice solution to redirect logs(syserr is important when you service doesn't even start log4j file location will be empty :) ).
cat /etc/systemd/system/spring-mvc.service
[Unit]
Description=Spring MVC Java Service
[Service]
User=spring-mvc
# The configuration file application.properties should be here:
WorkingDirectory=/usr/local/spring-mvc
# Run ExecStartPre with root-permissions
PermissionsStartOnly=true
ExecStartPre=-/bin/mkdir -p /var/log/spring-mvc
ExecStartPre=/bin/chown -R spring-mvc:syslog /var/log/spring-mvc
ExecStartPre=/bin/chmod -R 775 /var/log/spring-mvc
#https://www.freedesktop.org/software/systemd/man/systemd.service.html#ExecStart=
ExecStart=/usr/bin/java \
-Dlog4j.configurationFile=log4j2-spring.xml \
-DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector \
-Dspring.profiles.active=dev \
-Denvironment-type=dev \
-XX:+UseConcMarkSweepGC \
-XX:CMSInitiatingOccupancyFraction=80 \
-XX:NewSize=756m \
-XX:MetaspaceSize=256m \
-Dsun.net.inetaddr.ttl=5 \
-Xloggc:/var/log/spring-mvc/gc.log \
-verbose:gc \
-verbosegc \
-XX:+DisableExplicitGC \
-XX:+PrintGCDetails \
-XX:+PrintGCDateStamps \
-XX:+PreserveFramePointer \
-XX:+StartAttachListener \
-Xms1024m \
-Xmx1024m \
-XX:+HeapDumpOnOutOfMemoryError \
-jar spring-mvc.war
SuccessExitStatus=143
StandardOutput=journal
StandardError=journal
KillSignal=SIGINT
TimeoutStopSec=20
Restart=always
RestartSec=5
StartLimitInterval=0
StartLimitBurst=10
LimitNOFILE=500000
LimitNPROC=500000
#https://www.freedesktop.org/software/systemd/man/systemd.exec.html#LimitCPU=
#LimitCPU=, LimitFSIZE=, LimitDATA=, LimitSTACK=, LimitCORE=, LimitRSS=, LimitNOFILE=, LimitAS=, LimitNPROC=, LimitMEMLOCK=, LimitLOCKS=, LimitSIGPENDING=, LimitMSGQUEUE=, LimitNICE=, LimitRTPRIO=, LimitRTTIME=¶
SyslogIdentifier=spring-mvc
[Install]
WantedBy=multi-user.target
# https://www.freedesktop.org/software/systemd/man/journalctl.html
#check logs --- journalctl -u spring-mvc -f -o cat
rsyslog - redirect syslog input from app to specific folder/file
cat /etc/rsyslog.d/30-spring-mvc.conf
if $programname == 'spring-mvc' then /var/log/spring-mvc/spring-mvc.log
& stop
logrotate
cat /etc/logrotate.d/spring-mvc.conf
/var/log/spring-mvc/spring-mvc.log
{
daily
rotate 30
maxage 30
copytruncate
missingok
notifempty
compress
dateext
dateformat _%Y-%m-%d_%H-%M
delaycompress
create 644 spring-mvc syslog
su spring-mvc syslog
}
logrotate gc
cat /etc/logrotate.d/spring-mvc-gc.conf
/var/log/spring-mvc/gc.log
{
daily
rotate 30
maxage 30
copytruncate
missingok
notifempty
compress
dateext
dateformat _%Y-%m-%d_%H-%M
delaycompress
create 644 spring-mvc syslog
su spring-mvc syslog
}
For SDK >= 23, please add setLargeIcon
notification = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(context.getResources(), R.drawable.lg_logo))
.setContentTitle(title)
.setStyle(new Notification.BigTextStyle().bigText(msg))
.setAutoCancel(true)
.setContentText(msg)
.setContentIntent(contentIntent)
.setSound(sound)
.build();
for (i in 1:names(DF){
DF[[i]] <- as.numeric(DF[[i]])
}
I solved this using double brackets [[]]
Any kind of wrapper is good.
With Java 8+, use either an AtomicInteger
:
AtomicInteger ordinal = new AtomicInteger(0);
list.forEach(s -> {
s.setOrdinal(ordinal.getAndIncrement());
});
... or an array:
int[] ordinal = { 0 };
list.forEach(s -> {
s.setOrdinal(ordinal[0]++);
});
With Java 10+:
var wrapper = new Object(){ int ordinal = 0; };
list.forEach(s -> {
s.setOrdinal(wrapper.ordinal++);
});
Note: be very careful if you use a parallel stream. You might not end up with the expected result. Other solutions like Stuart's might be more adapted for those cases.
int
Of course, this is still valid for types other than int
. You only need to change the wrapping type to an AtomicReference
or an array of that type. For instance, if you use a String
, just do the following:
AtomicReference<String> value = new AtomicReference<>();
list.forEach(s -> {
value.set("blah");
});
Use an array:
String[] value = { null };
list.forEach(s-> {
value[0] = "blah";
});
Or with Java 10+:
var wrapper = new Object(){ String value; };
list.forEach(s->{
wrapper.value = "blah";
});
This works using java.util.Scanner and will take multiple "enter" keystrokes:
Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();
while(readString!=null) {
System.out.println(readString);
if (readString.isEmpty()) {
System.out.println("Read Enter Key.");
}
if (scanner.hasNextLine()) {
readString = scanner.nextLine();
} else {
readString = null;
}
}
To break it down:
Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();
These lines initialize a new Scanner
that is reading from the standard input stream (the keyboard) and reads a single line from it.
while(readString!=null) {
System.out.println(readString);
While the scanner is still returning non-null data, print each line to the screen.
if (readString.isEmpty()) {
System.out.println("Read Enter Key.");
}
If the "enter" (or return, or whatever) key is supplied by the input, the nextLine()
method will return an empty string; by checking to see if the string is empty, we can determine whether that key was pressed. Here the text Read Enter Key is printed, but you could perform whatever action you want here.
if (scanner.hasNextLine()) {
readString = scanner.nextLine();
} else {
readString = null;
}
Finally, after printing the content and/or doing something when the "enter" key is pressed, we check to see if the scanner has another line; for the standard input stream, this method will "block" until either the stream is closed, the execution of the program ends, or further input is supplied.
http://msdn.microsoft.com/en-us/library/system.io.directory.getfiles.aspx
The System.IO namespace has loads of methods to help you with file operations. The
Directory.GetFiles()
method returns an array of strings which represent the files in the target directory.
I had the same problem, and I was using the following plugin for tests:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.9</version>
<configuration>
<useFile>true</useFile>
<includes>
<include>**/*Tests.java</include>
<include>**/*Test.java</include>
</includes>
<excludes>
<exclude>**/Abstract*.java</exclude>
</excludes>
<junitArtifactName>junit:junit</junitArtifactName>
<parallel>methods</parallel>
<threadCount>10</threadCount>
</configuration>
</plugin>
The test were running fine in the IDE (eclipse sts), but failed when using command mvn test.
After a lot of trial and error, I figured the solution was to remove parallel testing, the following two lines from the plugin configuration above:
<parallel>methods</parallel>
<threadCount>10</threadCount>
Hope that this helps someone out!
If we want to retrieve or update these attributes using existing, native JavaScript, then we can do so using the getAttribute and setAttribute methods as shown below:
Through JavaScript
<div id='strawberry-plant' data-fruit='12'></div>
<script>
// 'Getting' data-attributes using getAttribute
var plant = document.getElementById('strawberry-plant');
var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'
// 'Setting' data-attributes using setAttribute
plant.setAttribute('data-fruit','7'); // Pesky birds
</script>
Through jQuery
// Fetching data
var fruitCount = $(this).data('fruit');
OR
// If you updated the value, you will need to use below code to fetch new value
// otherwise above gives the old value which is intially set.
// And also above does not work in ***Firefox***, so use below code to fetch value
var fruitCount = $(this).attr('data-fruit');
// Assigning data
$(this).attr('data-fruit','7');
By using order separately each subset gets order, but not the whole set, which is what you would want uniting two tables.
You should use something like this to have one ordered set:
SELECT TOP (100) PERCENT field1, field2, field3, field4, field5 FROM
(SELECT table1.field1, table1.field2, table1.field3, table1.field4, table1.field5 FROM table1
UNION ALL
SELECT table2.field1, table2.field2, table2.field3, table2.field4, table2.field5 FROM table2)
AS unitedTables ORDER BY field5 DESC
echo date_format($date,"Y/m/d H:i:s");
Using file:///// just doesn't work if security settings are set to even a moderate level.
If you just want users to be able to download/view files* located on a network or share you can set up a Virtual Directory in IIS. On the Properties tab make sure the "A share located on another computer" is selected and the "Connect as..." is an account that can see the network location.
Link to the virtual directory from your webpage (e.g. http://yoursite/yourvirtualdir/) and this will open up a view of the directory in the web browser.
*You can allow write permissions on the virtual directory to allow users to add files but not tried it and assume network permissions would override this setting.
This is what worked for me. Tried everything else with no luck:
<html>
<head>
<title>Example: Change event on a select</title>
<script type="text/javascript">
function changeEventHandler(event) {
alert('You like ' + event.target.value + ' ice cream.');
}
</script>
</head>
<body>
<label>Choose an ice cream flavor: </label>
<select size="1" onchange="changeEventHandler(event);">
<option>chocolate</option>
<option>strawberry</option>
<option>vanilla</option>
</select>
</body>
</html>
Taken from Mozilla
Your code is very vague and not understandable, but I can provide you with an alternative.
First of all, if you want temp
to go through the whole string, you can do something like this:
char *temp;
for (temp = your_string; *temp; ++temp)
/* do something with *temp */
The term *temp
as the for
condition simply checks whether you have reached the end of the string or not. If you have, *temp
will be '\0'
(NUL
) and the for
ends.
Now, inside the for, you want to find the bits that compose *temp
. Let's say we print the bits:
for (as above)
{
int bit_index;
for (bit_index = 7; bit_index >= 0; --bit_index)
{
int bit = *temp >> bit_index & 1;
printf("%d", bit);
}
printf("\n");
}
To make it a bit more generic, that is to convert any type to bits, you can change the bit_index = 7
to bit_index = sizeof(*temp)*8-1
Even though, I have been using 400 to represent logical errors also, I have to say that returning 400 is wrong in this case because of the way the spec reads. Here is why i think so, the logical error could be that a relationship with another entity was failing or not satisfied and making changes to the other entity could cause the same exact to pass later. Like trying to (completely hypothetical) add an employee as a member of a department when that employee does not exist (logical error). Adding employee as member request could fail because employee does not exist. But the same exact request could pass after the employee has been added to the system.
Just my 2 cents ... We need lawyers & judges to interpret the language in the RFC these days :)
Thank You, Vish
I got this to work to scroll to the bottom of a ScrollView (with a TextView inside):
(I put this on a method that updates the TextView)
final ScrollView myScrollView = (ScrollView) findViewById(R.id.myScroller);
myScrollView.post(new Runnable() {
public void run() {
myScrollView.fullScroll(View.FOCUS_DOWN);
}
});
Well, why do you have %20
url-quoting escapes in a formatting string in first place? Ideally you'd do the interpolation formatting first:
formatting_template = 'Hello World%s'
text = '!'
full_string = formatting_template % text
Then you url quote it afterwards:
result = urllib.quote(full_string)
That is better because it would quote all url-quotable things in your string, including stuff that is in the text
part.
Elements that are not being rendered (be it through visibility: hidden
, display: none
, opacity: 0.0
, whatever) will not indicate focus. The browser will not draw a focus border around nothing.
If you want the text to be focusable, that's completely doable. You can wrap the whole thing in an element that can receive focus (for example, a hyperlink), or allow another tag to have focus using the tabindex
property:
<label tabindex="0" class="checkbox">
<input type="checkbox" value="valueofcheckbox" style="display:none" checked="checked" />Option Text
</label>
In this case, the <label>
tag above is actually receiving focus and everything within it will have a focus border when it's in focus.
I do question what your goal is. If you're using a hidden checkbox to internally track some sort of state, you might be better off using a <input type="hidden" />
tag instead.
You won't be able to check if char appears at all in some string without atleast going over the string once using loop / recursion ( the built-in methods like indexOf also use a loop )
If the no. of times you look up if a char is in string x is more way more than the length of the string than I would recommend using a Set data structure as that would be more efficient than simply using indexOf
String s = "abc";
// Build a set so we can check if character exists in constant time O(1)
Set<Character> set = new HashSet<>();
int len = s.length();
for(int i = 0; i < len; i++) set.add(s.charAt(i));
// Now we can check without the need of a loop
// contains method of set doesn't use a loop unlike string's contains method
set.contains('a') // true
set.contains('z') // false
Using set you will be able to check if character exists in a string in constant time O(1) but you will also use additional memory ( Space complexity will be O(n) ).
To parse the date string using String.replace with backreference:
var milli = "/Date(1245398693390)/".replace(/\/Date\((-?\d+)\)\//, '$1');
var d = new Date(parseInt(milli));
org.json.simple.JSONObject.escape()
escapes quotes,, /, \r, \n, \b, \f, \t and other control characters.
import org.json.simple.JSONValue;
JSONValue.escape("test string");
Add pom.xml when using maven
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<scope>test</scope>
</dependency>
You want to iterate through the list, sum all the numbers, and then divide the sum by the number of elements in the list. You can use a for loop to accomplish this.
average = 0
sum = 0
for n in numbers:
sum = sum + n
average = sum / len(numbers)
The for loop looks at each element in the list, and then adds it to the current sum. You then divide by the length of the list (or the number of elements in the list) to find the average.
I would recommend googling a python reference to find out how to use common programming concepts like loops and conditionals so that you feel comfortable when starting out. There are lots of great resources online that you could look up.
Good luck!
spinner.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
//add some code here
}
);
To add color to an input, Use the following css code:
input{
color: black;
}
So i have been struggling too on the same issue. The quick and easiest way to solve the problem is by just adding
modal-lg
on your modal DivExample <div class="modal-dialog modal-lg">
#more {
background:none;
border:none;
color:#FFF;
font-family:Verdana, Geneva, sans-serif;
cursor: pointer;
}
I think what you want ist
return value.toString();
and use the return value to display.
value.floatValue();
will always return 625.3 because its mainly used to calculate something.
There are two routes for get:
app.get('/', main.index);
todoRouter.get('/',todo.all);
Error: Route.get() requires callback functions but got a [object Undefined]
This exception is thrown when route.get
does not get a callback function. As you have defined todo.all in todo.js file, but it is unable to find main.index.
That's why it works once you define main.index file later on in the tutorial.
You could use RegEx:
Regex.IsMatch(hello, @"^[a-zA-Z]+$");
If you don't like that, you can use LINQ:
hello.All(Char.IsLetter);
Or, you can loop through the characters, and use isAlpha:
Char.IsLetter(character);
This examples shows how to realize the confirmed window close operation.
The window has a Window adapter which switches the default close operation to EXIT_ON_CLOSE
or DO_NOTHING_ON_CLOSE
dependent on your answer in the OptionDialog
.
The method closeWindow
of the ConfirmedCloseWindow
fires a close window event and can be used anywhere i.e. as an action of an menu item
public class WindowConfirmedCloseAdapter extends WindowAdapter {
public void windowClosing(WindowEvent e) {
Object options[] = {"Yes", "No"};
int close = JOptionPane.showOptionDialog(e.getComponent(),
"Really want to close this application?\n", "Attention",
JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE,
null,
options,
null);
if(close == JOptionPane.YES_OPTION) {
((JFrame)e.getSource()).setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
} else {
((JFrame)e.getSource()).setDefaultCloseOperation(
JFrame.DO_NOTHING_ON_CLOSE);
}
}
}
public class ConfirmedCloseWindow extends JFrame {
public ConfirmedCloseWindow() {
addWindowListener(new WindowConfirmedCloseAdapter());
}
private void closeWindow() {
processWindowEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
}
}
Try Collections.shuffle(list).If usage of this method is barred for solving the problem, then one can look at the actual implementation.
you can also use iloc:
df.iloc[[1,3],:]
This will not work if the indexes in your dataframe do not correspond to the order of the rows due to prior computations. In that case use:
df.index.isin([1,3])
... as suggested in other responses.
Another reason to the error may be if you are running a cron job that updates a subversion working copy and then has attempted to run a versioned script that was in a conflicted state after the update...
In my Home Activity I override the "onBackPressed" to:
@Override
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
so if the user is in the home activity and press back, he goes to the home screen.
I took the code from Going to home screen Programmatically
You need to create it. In most installations I've used it hasn't been created by default.
You usually create it as ~/.vimrc
.
There is an important technical difference between race conditions and data races. Most answers seem to make the assumption that these terms are equivalent, but they are not.
A data race occurs when 2 instructions access the same memory location, at least one of these accesses is a write and there is no happens before ordering among these accesses. Now what constitutes a happens before ordering is subject to a lot of debate, but in general ulock-lock pairs on the same lock variable and wait-signal pairs on the same condition variable induce a happens-before order.
A race condition is a semantic error. It is a flaw that occurs in the timing or the ordering of events that leads to erroneous program behavior.
Many race conditions can be (and in fact are) caused by data races, but this is not necessary. As a matter of fact, data races and race conditions are neither the necessary, nor the sufficient condition for one another. This blog post also explains the difference very well, with a simple bank transaction example. Here is another simple example that explains the difference.
Now that we nailed down the terminology, let us try to answer the original question.
Given that race conditions are semantic bugs, there is no general way of detecting them. This is because there is no way of having an automated oracle that can distinguish correct vs. incorrect program behavior in the general case. Race detection is an undecidable problem.
On the other hand, data races have a precise definition that does not necessarily relate to correctness, and therefore one can detect them. There are many flavors of data race detectors (static/dynamic data race detection, lockset-based data race detection, happens-before based data race detection, hybrid data race detection). A state of the art dynamic data race detector is ThreadSanitizer which works very well in practice.
Handling data races in general requires some programming discipline to induce happens-before edges between accesses to shared data (either during development, or once they are detected using the above mentioned tools). this can be done through locks, condition variables, semaphores, etc. However, one can also employ different programming paradigms like message passing (instead of shared memory) that avoid data races by construction.
Almost correctly.. Look at the joins, you are referring the wrong fields
SELECT student.firstname,
student.lastname,
exam.name,
exam.date,
grade.grade
FROM grade
INNER JOIN student ON student.studentId = grade.fk_studentId
INNER JOIN exam ON exam.examId = grade.fk_examId
ORDER BY exam.date
On mac, open the terminal and type:
cd /usr/local/mysql/bin
then type:
./mysql -u root -p
It will ask you for the mysql root password. Enter your password and use mysql database in the terminal.
An index friendly way of doing this is:
where (field is not null and field <> '')
If there aren't many rows or this field isn't indexed, you can use:
where isnull(field,'') <> ''
If you don't care about preserving the factors, and want to apply it to any column that can get converted to numeric, I used the script below. if df is your original dataframe, you can use the script below.
df[] <- lapply(df, as.character)
df <- data.frame(lapply(df, function(x) ifelse(!is.na(as.numeric(x)), as.numeric(x), x)))
Going to Window ? Devices and Simulators will give you a better idea of what's going on. In my case, I had to update the iPhone since Xcode updated overnight and stopped supporting my iPhone.
I met these warnings on mempcpy
function. Man page says this function is a GNU extension and synopsis shows:
#define _GNU_SOURCE
#include <string.h>
When #define
is added to my source before the #include
, declarations for the GNU extensions are made visible and warnings disappear.
Another alternative is to nest conditions
<ng-container *ngIf="foo === 1;else second"></ng-container>
<ng-template #second>
<ng-container *ngIf="foo === 2;else third"></ng-container>
</ng-template>
<ng-template #third></ng-template>
Maybe this is the answer you are looking for. It finds the last instance of <tr />
and appends the new row after it:
<script type="text/javascript">
$('a').click(function() {
$('#myTable tr:last').after('<tr class="child"><td>blahblah<\/td></tr>');
});
</script>
You're in luck bud...I had the same issue but had more tech knowledge on the matter and was able to determine that it was a mod_sec issue that hostgator has to fix/whitelist on their own. You cannot do it yourself. Simply ask the hostgator tech to check mod_sec settings on your server.
Enjoy your fixed issue ;D
I find using the pipe character with some top and bottom padding works well. Using a div with a border will require more CSS to vertically align it and get the horizontal spacing even with the other elements.
.divider-vertical {
padding-top: 14px;
padding-bottom: 14px;
}
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li class="divider-vertical">|</li>
<li><a href="#">Faq</a></li>
<li class="divider-vertical">|</li>
<li><a href="#">News</a></li>
<li class="divider-vertical">|</li>
<li><a href="#">Contact</a></li>
</ul>
I think that GNU GetOpt is not too immediate to use.
Qt and Boost could be a solution, but you need to download and compile a lot of code.
So I implemented a parser by myself that produces a std::map<std::string, std::string> of parameters.
For example, calling:
./myProgram -v -p 1234
map will be:
["-v"][""]
["-p"]["1234"]
Usage is:
int main(int argc, char *argv[]) {
MainOptions mo(argc, argv);
MainOptions::Option* opt = mo.getParamFromKey("-p");
const string type = opt ? (*opt).second : "";
cout << type << endl; /* Prints 1234 */
/* Your check code */
}
MainOptions.h
#ifndef MAINOPTIONS_H_
#define MAINOPTIONS_H_
#include <map>
#include <string>
class MainOptions {
public:
typedef std::pair<std::string, std::string> Option;
MainOptions(int argc, char *argv[]);
virtual ~MainOptions();
std::string getAppName() const;
bool hasKey(const std::string&) const;
Option* getParamFromKey(const std::string&) const;
void printOptions() const;
private:
typedef std::map<std::string, std::string> Options;
void parse();
const char* const *begin() const;
const char* const *end() const;
const char* const *last() const;
Options options_;
int argc_;
char** argv_;
std::string appName_;
};
MainOptions.cpp
#include "MainOptions.h"
#include <iostream>
using namespace std;
MainOptions::MainOptions(int argc, char* argv[]) :
argc_(argc),
argv_(argv) {
appName_ = argv_[0];
this->parse();
}
MainOptions::~MainOptions() {
}
std::string MainOptions::getAppName() const {
return appName_;
}
void MainOptions::parse() {
typedef pair<string, string> Option;
Option* option = new pair<string, string>();
for (const char* const * i = this->begin() + 1; i != this->end(); i++) {
const string p = *i;
if (option->first == "" && p[0] == '-') {
option->first = p;
if (i == this->last()) {
options_.insert(Option(option->first, option->second));
}
continue;
} else if (option->first != "" && p[0] == '-') {
option->second = "null"; /* or leave empty? */
options_.insert(Option(option->first, option->second));
option->first = p;
option->second = "";
if (i == this->last()) {
options_.insert(Option(option->first, option->second));
}
continue;
} else if (option->first != "") {
option->second = p;
options_.insert(Option(option->first, option->second));
option->first = "";
option->second = "";
continue;
}
}
}
void MainOptions::printOptions() const {
std::map<std::string, std::string>::const_iterator m = options_.begin();
int i = 0;
if (options_.empty()) {
cout << "No parameters\n";
}
for (; m != options_.end(); m++, ++i) {
cout << "Parameter [" << i << "] [" << (*m).first << " " << (*m).second
<< "]\n";
}
}
const char* const *MainOptions::begin() const {
return argv_;
}
const char* const *MainOptions::end() const {
return argv_ + argc_;
}
const char* const *MainOptions::last() const {
return argv_ + argc_ - 1;
}
bool MainOptions::hasKey(const std::string& key) const {
return options_.find(key) != options_.end();
}
MainOptions::Option* MainOptions::getParamFromKey(
const std::string& key) const {
const Options::const_iterator i = options_.find(key);
MainOptions::Option* o = 0;
if (i != options_.end()) {
o = new MainOptions::Option((*i).first, (*i).second);
}
return o;
}
I wouldn't bother looking for ASP.NET stuff specifically (probably won't find any anyways). Finding a good CSS theme easily can be used in ASP.NET.
Here's some sites that I love for CSS goodness:
http://www.freecsstemplates.org/
http://www.oswd.org/
http://www.openwebdesign.org/
http://www.styleshout.com/
http://www.freelayouts.com/
"UPDATE TableName SET TableField = TableField + 1 WHERE SomeFilterField = @ParameterID"
Here are the steps:
Step 1: Create services running in background.
Step 2: You require following permission in Manifest file too:
android.permission.ACCESS_FINE_LOCATION
Step 3: Write code:
final LocationManager manager = (LocationManager)context.getSystemService (Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) )
Toast.makeText(context, "GPS is disabled!", Toast.LENGTH_LONG).show();
else
Toast.makeText(context, "GPS is enabled!", Toast.LENGTH_LONG).show();
Step 4: Or simply you can check using:
LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE );
boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Step 5: Run your services continuously to monitor connection.
I have the same problem a few months ago. This solve my problem using Maven instead of a downloaded version of Spring and some changes in the web.xml.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>SpringWEB1</groupId>
<artifactId>SpringWEB1</artifactId>
<version>1</version>
<packaging>war</packaging>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
</project>
Controller.java
package com.jmtm.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@org.springframework.stereotype.Controller
public class Controller {
@RequestMapping("/hi")
public ModelAndView hi(){
return new ModelAndView("Hello", "msg", "Hello user.");
}
}
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">
<context:component-scan base-package="com.jmtm.controller"></context:component-scan>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
And the most important part of the solution, include the path of the servlet dispatcher (A.K.A. spring-servlet.xml) in the web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>SpringWEB1</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Something weird happen when I try to solve this. Any downloaded version of Spring from maven.springframework.org/release/org/springframework/spring gives me a lot of problems (Tomcat couldn't find servlet, Spring stops Tomcat, Eclipse couldn't start the server {weird}) so with many problems find many partial solutions. I hope this works for you.
As an extra help, in Eclipse, download from the Eclipse Marketplace the Spring STS Tool for Eclipse, this will help you to create configuration files (servlet.xml) and write code for the servlet in the web.xml file.
i know a Class is a bit the overkill
class Foo
{
private $sum = NULL;
public function __construct($array)
{
$this->sum[] = $array;
return $this;
}
public function getSum()
{
$sum = $this->sum;
for($i=0;$i<count($sum);$i++)
{
// get the last array index
$res[$i] = $sum[$i] + $sum[count($sum)-$i];
}
return $res;
}
}
$fo = new Foo($myarray)->getSum();
HashMap
is unordered per the second line of the documentation:
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
Perhaps you can do as aix suggests and use a LinkedHashMap
, or another ordered collection. This link can help you find the most appropriate collection to use.
Did you write return true
somewhere? You should have written it, otherwise function returns nothing and program may think that it's false, too.
function isValid(str) {
var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
for (var i = 0; i < str.length; i++) {
if (iChars.indexOf(str.charAt(i)) != -1) {
alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
return false;
}
}
return true;
}
I tried this in my chrome console and it worked well.
I prefer this :
<nav class="navbar">
<div class="hidden-xs hidden-sm" style="position: absolute;left: 50%;margin-left:-56px;width:112px" id="centered-div">
<!-- this element is on the center of the nav, visible only on -md and -lg -->
<a></a>
</div>
<div class="container-fluid">
<!-- ...things with your navbar... -->
<div class="visible-xs visible-sm">
<!-- this element will be hidden on -md and -lg -->
</div>
<!-- ...things with your navbar... -->
</div>
</nav>
The element is perfectly centered, and will be hidden on some screen sizes (there was no place left on -xs and -sm for me for example). I get the idea from Twitter's actual navbar
Assuming you don't store things like the '+', '()', '-', spaces and what-have-yous (and why would you, they are presentational concerns which would vary based on local customs and the network distributions anyways), the ITU-T recommendation E.164 for the international telephone network (which most national networks are connected via) specifies that the entire number (including country code, but not including prefixes such as the international calling prefix necessary for dialling out, which varies from country to country, nor including suffixes, such as PBX extension numbers) be at most 15 characters.
Call prefixes depend on the caller, not the callee, and thus shouldn't (in many circumstances) be stored with a phone number. If the database stores data for a personal address book (in which case storing the international call prefix makes sense), the longest international prefixes you'd have to deal with (according to Wikipedia) are currently 5 digits, in Finland.
As for suffixes, some PBXs support up to 11 digit extensions (again, according to Wikipedia). Since PBX extension numbers are part of a different dialing plan (PBXs are separate from phone companies' exchanges), extension numbers need to be distinguishable from phone numbers, either with a separator character or by storing them in a different column.
Dragon NaturallySpeaking seems to support MP3 input.
If you want an open source version (I think there are some Asterisk integration projects based on this one).
Sometimes the field is not recognized by crystal reports as DATE, so you can add a formula with function: Date({YourField}), And add it to the report, now when you open the format object dialog you will find the date formatting options.
Some versions of tar, for example, the default versions on HP-UX (I tested 11.11 and 11.31), do not include a command line option to specify a file list, so a decent work-around is to do this:
tar cvf allfiles.tar $(cat mylist.txt)
I came up with another solution, which I don't love but gets the job done.
Basically duplicate the child elements in such a way that the duplicates are not visible.
<div id="parent">
<div class="width-calc">
<div class="child1"></div>
<div class="child2"></div>
</div>
<div class="child1"></div>
<div class="child2"></div>
</div>
CSS:
.width-calc {
height: 0;
overflow: hidden;
}
If those child elements contain little markup, then the impact will be small.
As others have said, the minumum/maximum values the column can store and how much storage it takes in bytes is only defined by the type, not the length.
A lot of these answers are saying that the (11)
part only affects the display width which isn't exactly true, but mostly.
A definition of int(2)
with no zerofill specified will:
100
100
when output (not 0
or 00
)The only thing the (2)
will do is if zerofill is also specified:
1
will be shown 01
. The best way to see all the nuances is to run:
CREATE TABLE `mytable` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`int1` int(10) NOT NULL,
`int2` int(3) NOT NULL,
`zf1` int(10) ZEROFILL NOT NULL,
`zf2` int(3) ZEROFILL NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `mytable`
(`int1`, `int2`, `zf1`, `zf2`)
VALUES
(10000, 10000, 10000, 10000),
(100, 100, 100, 100);
select * from mytable;
which will output:
+----+-------+-------+------------+-------+
| id | int1 | int2 | zf1 | zf2 |
+----+-------+-------+------------+-------+
| 1 | 10000 | 10000 | 0000010000 | 10000 |
| 2 | 100 | 100 | 0000000100 | 100 |
+----+-------+-------+------------+-------+
This answer is tested against MySQL 5.7.12 for Linux and may or may not vary for other implementations.
You can use either "=" or "==" operators for string comparison in bash. The important factor is the spacing within the brackets. The proper method is for brackets to contain spacing within, and operators to contain spacing around. In some instances different combinations work; however, the following is intended to be a universal example.
if [ "$1" == "something" ]; then ## GOOD
if [ "$1" = "something" ]; then ## GOOD
if [ "$1"="something" ]; then ## BAD (operator spacing)
if ["$1" == "something"]; then ## BAD (bracket spacing)
Also, note double brackets are handled slightly differently compared to single brackets ...
if [[ $a == z* ]]; then # True if $a starts with a "z" (pattern matching).
if [[ $a == "z*" ]]; then # True if $a is equal to z* (literal matching).
if [ $a == z* ]; then # File globbing and word splitting take place.
if [ "$a" == "z*" ]; then # True if $a is equal to z* (literal matching).
I hope that helps!
There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.
Option Explicit
Public Numbers As Variant, Tens As Variant
Sub SetNums()
Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub
Function WordNum(MyNumber As Double) As String
Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
' This macro was written by Chris Mead - www.MeadInKent.co.uk
If Abs(MyNumber) > 999999999 Then
WordNum = "Value too large"
Exit Function
End If
SetNums
' String representation of amount (excl decimals)
NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
For n = 3 To 1 Step -1 'analyse the absolute number as 3 sets of 3 digits
StrNo = Format(ValNo(n), "000")
If ValNo(n) > 0 Then
Temp1 = GetTens(Val(Right(StrNo, 2)))
If Left(StrNo, 1) <> "0" Then
Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
If Temp1 <> "" Then Temp2 = Temp2 & " and "
Else
Temp2 = ""
End If
If n = 3 Then
If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
WordNum = Trim(Temp2 & Temp1)
End If
If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
End If
Next n
NumStr = Trim(Str(Abs(MyNumber)))
' Values after the decimal place
DecimalPosition = InStr(NumStr, ".")
Numbers(0) = "Zero"
If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
Temp1 = " point"
For n = DecimalPosition + 1 To Len(NumStr)
Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
Next n
WordNum = WordNum & Temp1
End If
If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
WordNum = "Zero" & WordNum
End If
End Function
Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
If TensNum <= 19 Then
GetTens = Numbers(TensNum)
Else
Dim MyNo As String
MyNo = Format(TensNum, "00")
GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
End If
End Function
After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)
It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.
Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)
you will see a Words equivalent of the numeric value.
This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel
In case any one stumbles upon this as I just have...
Find First blank cell in a column(I'm using column D but didn't want to include D1)
NextFree = Range("D2:D" & Rows.Count).Cells.SpecialCells(xlCellTypeBlanks).Row
Range("D" & NextFree).Select
NextFree is just a name, you could use sausages if you wanted.
I disagree, but the solution to increase the file size in php.ini
or .htaccess
won't work if the user sends a file larger than allowed by the server application.
I suggest validating this on the front end. For example:
$(document).ready(function() {
$ ('#your_input_file_id').bind('change', function() {
var fileSize = this.files[0].size/1024/1024;
if (fileSize > 2) { // 2M
alert('Your custom message for max file size exceeded');
$('#your_input_file_id').val('');
}
});
});
_x000D_
I'm passing to Django's template a function, which returns me some records
Why don't you pass to Django template the variable storing function's return value, instead of the function?
I've tried to set fuction's return value to a variable and iterate over variable, but there seems to be no way to set variable in Django template.
You should set variables in Django views instead of templates, and then pass them to the template.
Remove your script, and change the HTML:
<a id="closemodal" href="https://www.google.com" class="btn btn-primary close" data-dismiss="modal" target="_blank">Launch google.com</a>
EDIT: Please note that currently this will not work as this functionality does not yet exist in bootstrap. See issue here.
Question : What is the best practice of returning/storing variables of multiple threads? A global hash table?
This totally depends on what you want to return and how you would use it? If you want to return only status of the thread (say whether the thread completed what it intended to do) then just use pthread_exit or use a return statement to return the value from the thread function.
But, if you want some more information which will be used for further processing then you can use global data structure. But, in that case you need to handle concurrency issues by using appropriate synchronization primitives. Or you can allocate some dynamic memory (preferrably for the structure in which you want to store the data) and send it via pthread_exit and once the thread joins, you update it in another global structure. In this way only the one main thread will update the global structure and concurrency issues are resolved. But, you need to make sure to free all the memory allocated by different threads.
DECLARE @Database NVARCHAR(255)
DECLARE @Table NVARCHAR(255)
DECLARE @cmd NVARCHAR(1000)
DECLARE DatabaseCursor CURSOR READ_ONLY FOR
SELECT name FROM master.sys.databases
WHERE name NOT IN ('master','msdb','tempdb','model','distribution') -- databases to exclude
--WHERE name IN ('DB1', 'DB2') -- use this to select specific databases and comment out line above
AND state = 0 -- database is online
AND is_in_standby = 0 -- database is not read only for log shipping
ORDER BY 1
OPEN DatabaseCursor
FETCH NEXT FROM DatabaseCursor INTO @Database
WHILE @@FETCH_STATUS = 0
BEGIN
SET @cmd = 'DECLARE TableCursor CURSOR READ_ONLY FOR SELECT ''['' + table_catalog + ''].['' + table_schema + ''].['' +
table_name + '']'' as tableName FROM [' + @Database + '].INFORMATION_SCHEMA.TABLES WHERE table_type = ''BASE TABLE'''
-- create table cursor
EXEC (@cmd)
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @Table
WHILE @@FETCH_STATUS = 0
BEGIN
BEGIN TRY
SET @cmd = 'ALTER INDEX ALL ON ' + @Table + ' REBUILD'
--PRINT @cmd -- uncomment if you want to see commands
EXEC (@cmd)
END TRY
BEGIN CATCH
PRINT '---'
PRINT @cmd
PRINT ERROR_MESSAGE()
PRINT '---'
END CATCH
FETCH NEXT FROM TableCursor INTO @Table
END
CLOSE TableCursor
DEALLOCATE TableCursor
FETCH NEXT FROM DatabaseCursor INTO @Database
END
CLOSE DatabaseCursor
DEALLOCATE DatabaseCursor
I also got the same problem. When I try to add the opencv library
#include <opencv\cv.h>
I got not a warning but an error.
error C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. c:\program files (x86)\opencv\build\include\opencv2\flann\logger.h
I also used the preprocessor directives as mentioned. But that didn't solve the problem.
I solved it by doing as follows:
Some people do not have the luxury of using std::vector
, even with allocators. Some people need a dynamically sized array, so std::array
is out. And some people get their arrays from other code that is known to return an array; and that code isn't going to be rewritten to return a vector
or something.
By allowing unique_ptr<T[]>
, you service those needs.
In short, you use unique_ptr<T[]>
when you need to. When the alternatives simply aren't going to work for you. It's a tool of last resort.
-(void) viewWillAppear:(BOOL)animated
{
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
}
find -type f -print0 | xargs -0 ls -t
Drawback: Works only to a certain amount of files. If you have extremly large amounts of files you need something more complicated
The answer from JUnit.org FAQ page:
But if you must...
If you are using JDK 1.3 or higher, you can use reflection to subvert the access control mechanism with the aid of the PrivilegedAccessor. For details on how to use it, read this article.
If you are using JDK 1.6 or higher and you annotate your tests with @Test, you can use Dp4j to inject reflection in your test methods. For details on how to use it, see this test script.
P.S. I'm the main contributor to Dp4j, ask me if you need help. :)
You can assign default parameter values inline when you first create the mixin:
@mixin clearfix($width: 'auto') {
@if $width == 'auto' {
// if width is not passed, or empty do this
} @else {
display: inline-block;
width: $width;
}
}
My problem was with TIMEZONE
in emulator genymotion. Change TIMEZONE ANDROID EMULATOR
equal TIMEZONE SERVER
, solved problem.
I don't know whether there's a better answer out there as time goes by but this is simple and it works;
input[type='email'] {
background: white url(images/mail.svg) no-repeat ;
}
input[type='email']:focus {
background-image: none;
}
Style it up to suit.
There is already a command in the ssh suite to do this automatically for you. I.e log into a remote host and add the public key to that computers authorized_keys file.
ssh-copy-id -i /path/to/key/file [email protected]
If the key you are installing is ~/.ssh/id_rsa
then you can even drop the -i
flag completely.
Much better than manually doing it!
Sometimes scrollView.post doesn't work
scrollView.post(new Runnable() {
@Override
public void run() {
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
});
BUT if you use scrollView.postDelayed, it will definitely work
scrollView.postDelayed(new Runnable() {
@Override
public void run() {
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
},1000);
Tomcat can work in 2 modes:
Tomcat 7 is BIO by default, although consensus seems to be "don't use Bio because Nio is better in every way". You set this using the protocol
parameter in the server.xml
file.
HTTP/1.1
or org.apache.coyote.http11.Http11Protocol
org.apache.coyote.http11.Http11NioProtocol
If you're using BIO then I believe they should be more or less the same.
If you're using NIO then actually "maxConnections=1000" and "maxThreads=10" might even be reasonable. The defaults are maxConnections=10,000 and maxThreads=200. With NIO, each thread can serve any number of connections, switching back and forth but retaining the connection so you don't need to do all the usual handshaking which is especially time-consuming with HTTPS but even an issue with HTTP. You can adjust the "keepAlive" parameter to keep connections around for longer and this should speed everything up.
Existing answers point out that curl can post data from a file, and employ heredocs to avoid excessive quote escaping and clearly break the JSON out onto new lines. However there is no need to define a function or capture output from cat, because curl can post data from standard input. I find this form very readable:
curl -X POST -H 'Content-Type:application/json' --data '$@-' ${API_URL} << EOF
{
"account": {
"email": "$email",
"screenName": "$screenName",
"type": "$theType",
"passwordSettings": {
"password": "$password",
"passwordConfirm": "$password"
}
},
"firstName": "$firstName",
"lastName": "$lastName",
"middleName": "$middleName",
"locale": "$locale",
"registrationSiteId": "$registrationSiteId",
"receiveEmail": "$receiveEmail",
"dateOfBirth": "$dob",
"mobileNumber": "$mobileNumber",
"gender": "$gender",
"fuelActivationDate": "$fuelActivationDate",
"postalCode": "$postalCode",
"country": "$country",
"city": "$city",
"state": "$state",
"bio": "$bio",
"jpFirstNameKana": "$jpFirstNameKana",
"jpLastNameKana": "$jpLastNameKana",
"height": "$height",
"weight": "$weight",
"distanceUnit": "MILES",
"weightUnit": "POUNDS",
"heightUnit": "FT/INCHES"
}
EOF
You neglected to say which version of C you are concerned about. Let's assume it's this one:
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
As you can see by reading the specification, the standard definitions of true
and false
are 1 and 0, yes.
If your question is about a different version of C, or about non-standard definitions for true
and false
, then ask a more specific question.
By default Bootstrap javascript files are included just before the closing body tag
<script src="vendors/jquery-1.9.1.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="vendors/easypiechart/jquery.easy-pie-chart.js"></script>
<script src="assets/scripts.js"></script>
</body>
I took these javascript files into the head section right before the body tag and I wrote a small function to call the modal popup:
<script src="vendors/jquery-1.9.1.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="vendors/easypiechart/jquery.easy-pie-chart.js"></script>
<script src="assets/scripts.js"></script>
<script type="text/javascript">
function openModal() {
$('#myModal').modal('show');
}
</script>
</head>
<body>
then I could call the modal popup from code-behind with the following:
protected void lbEdit_Click(object sender, EventArgs e) {
ScriptManager.RegisterStartupScript(this,this.GetType(),"Pop", "openModal();", true);
}
no_of_lines = 5
lines = ""
for i in xrange(5):
lines+=input()+"\n"
a=raw_input("if u want to continue (Y/n)")
""
if(a=='y'):
continue
else:
break
print lines
That is a default behaviour of each browser; your browser seems to be Safari, in Google Chrome it is orange in color!
Use this to remove this effect:
button {
outline: none; // this one
}
I think a 32 bit JVM has a maximum of 2GB memory.This might be out of date though. If I understood correctly, you set the -Xmx on Eclipse launcher. If you want to increase the memory for the program you run from Eclipse, you should define -Xmx in the "Run->Run configurations..."(select your class and open the Arguments tab put it in the VM arguments area) menu, and NOT on Eclipse startup
Edit: details you asked for. in Eclipse 3.4
Run->Run Configurations...
if your class is not listed in the list on the left in the "Java Application" subtree, click on "New Launch configuration" in the upper left corner
on the right, "Main" tab make sure the project and the class are the right ones
select the "Arguments" tab on the right.
this one has two text areas. one is for the program arguments that get in to the args[] array supplied to your main method. the other one is for the VM arguments. put into the one with the VM arguments(lower one iirc) the following:
-Xmx2048m
I think that 1024m should more than enough for what you need though!
Click Apply, then Click Run
Should work :)
Updated 2018
The dropdown-submenu
has been removed in Bootstrap 3 RC. In the words of Bootstrap author Mark Otto..
"Submenus just don't have much of a place on the web right now, especially the mobile web. They will be removed with 3.0" - https://github.com/twbs/bootstrap/pull/6342
But, with a little extra CSS you can get the same functionality.
Bootstrap 4 (navbar submenu on hover)
.navbar-nav li:hover > ul.dropdown-menu {
display: block;
}
.dropdown-submenu {
position:relative;
}
.dropdown-submenu>.dropdown-menu {
top:0;
left:100%;
margin-top:-6px;
}
Navbar submenu dropdown hover
Navbar submenu dropdown hover (right aligned)
Navbar submenu dropdown click (right aligned)
Navbar dropdown hover (no submenu)
Bootstrap 3
Here is an example that uses 3.0 RC 1: http://bootply.com/71520
Here is an example that uses Bootstrap 3.0.0 (final): http://bootply.com/86684
CSS
.dropdown-submenu {
position:relative;
}
.dropdown-submenu>.dropdown-menu {
top:0;
left:100%;
margin-top:-6px;
margin-left:-1px;
-webkit-border-radius:0 6px 6px 6px;
-moz-border-radius:0 6px 6px 6px;
border-radius:0 6px 6px 6px;
}
.dropdown-submenu:hover>.dropdown-menu {
display:block;
}
.dropdown-submenu>a:after {
display:block;
content:" ";
float:right;
width:0;
height:0;
border-color:transparent;
border-style:solid;
border-width:5px 0 5px 5px;
border-left-color:#cccccc;
margin-top:5px;
margin-right:-10px;
}
.dropdown-submenu:hover>a:after {
border-left-color:#ffffff;
}
.dropdown-submenu.pull-left {
float:none;
}
.dropdown-submenu.pull-left>.dropdown-menu {
left:-100%;
margin-left:10px;
-webkit-border-radius:6px 0 6px 6px;
-moz-border-radius:6px 0 6px 6px;
border-radius:6px 0 6px 6px;
}
Sample Markup
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li class="menu-item dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Drop Down<b class="caret"></b></a>
<ul class="dropdown-menu">
<li class="menu-item dropdown dropdown-submenu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Level 1</a>
<ul class="dropdown-menu">
<li class="menu-item ">
<a href="#">Link 1</a>
</li>
<li class="menu-item dropdown dropdown-submenu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Level 2</a>
<ul class="dropdown-menu">
<li>
<a href="#">Link 3</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
P.S. - Example in navbar that adjusts left position: http://bootply.com/92442
We can use
Type.GetType()
to get class name and can also create object of it using Activator.CreateInstance(type);
using System;
using System.Reflection;
namespace MyApplication
{
class Application
{
static void Main()
{
Type type = Type.GetType("MyApplication.Action");
if (type == null)
{
throw new Exception("Type not found.");
}
var instance = Activator.CreateInstance(type);
//or
var newClass = System.Reflection.Assembly.GetAssembly(type).CreateInstance("MyApplication.Action");
}
}
public class Action
{
public string key { get; set; }
public string Value { get; set; }
}
}
API keys are just one way of authenticating users of web services.
Just use the clear method is works like a charm. ListView1.Items.Clear() i think if its not working it may be the position whereby you place this code. Also can try nullifying the datasource.
Make sure you don't include extension of the resource, nor path to it. It's only the resource file name.
PictureBoxName.Image = My.Resources.ResourceManager.GetObject("object_name")
$("#customFile").change(function() {
var fileName = $("#customFile").val();
if(fileName) { // returns true if the string is not empty
$('.picture-selected').addClass('disable-inputs');
$('#btn').removeClass('disabled');
} else { // no file was selected
$('.picture-selected').removeClass('disable-inputs');
$('#btn').addClass('disabled');
}
});
It's a linker error. ld
is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.
The error message tells you that none of the object files you're linking against contains a definition for avergecolumns
. The reason for that is that the function you've defined is called averagecolumns
(in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).
1) Why does the x-axis (frequency) end at 500? How do I know that there aren't more frequencies or are they just ignored?
It ends at 500Hz because that is the Nyquist frequency of the signal when sampled at 1000Hz. Look at this line in the Mathworks example:
f = Fs/2*linspace(0,1,NFFT/2+1);
The frequency axis of the second plot goes from 0 to Fs/2, or half the sampling frequency. The Nyquist frequency is always half the sampling frequency, because above that, aliasing occurs:
The signal would "fold" back on itself, and appear to be some frequency at or below 500Hz.
2) How do I know the frequencies are between 0 and 500? Shouldn't the FFT tell me, in which limits the frequencies are?
Due to "folding" described above (the Nyquist frequency is also commonly known as the "folding frequency"), it is physically impossible for frequencies above 500Hz to appear in the FFT; higher frequencies will "fold" back and appear as lower frequencies.
Does the FFT only return the amplitude value without the frequency?
Yes, the MATLAB FFT function only returns one vector of amplitudes. However, they map to the frequency points you pass to it.
Let me know what needs clarification so I can help you further.
Something like:
const char* strarr = {"ram","mohan","sita", 0L};
for(int i = 0; strarr[i]; ++i)
{
listbox.items.add(strarr[i]);
}
Also works for standard C. Not sure in C++ how to detect the end of the strarr without having a null element, but the above should work.
Verry Easy, change order of element:
Origin
<div style="">
My Text
<button type="button" style="float: right; margin:5px;">
My Button
</button>
</div>
Change to:
<div style="">
<button type="button" style="float: right; margin:5px;">
My Button
</button>
My Text
</div>
Just one comment about regexp. Every example provided here is wrong!. If you want to use regexp don't forget that compiling the pattern take a lot of time. This:
str.matches("^-?\\d+$")
and also this:
Pattern.matches("-?\\d+", input);
causes compile of pattern in every method call. To used it correctly follow:
import java.util.regex.Pattern;
/**
* @author Rastislav Komara
*/
public class NaturalNumberChecker {
public static final Pattern PATTERN = Pattern.compile("^\\d+$");
boolean isNaturalNumber(CharSequence input) {
return input != null && PATTERN.matcher(input).matches();
}
}
Previous answers don't account for the fact that you've overloaded the equals operator and are using that to test for the sought element. In that case, your code would look like this:
list.Find(x => x == objectToFind);
Or, if you don't like lambda syntax, and have overriden object.Equals(object) or have implemented IEquatable<T>, you could do this:
list.Find(objectToFind.Equals);
if you want to get an attribute of an HTML element with jQuery you can use .attr();
so $('html').attr('someAttribute');
will give you the value of someAttribute
of the element html
there is a jQuery plugin here: http://plugins.jquery.com/project/getAttributes
that allows you to get all attributes from an HTML element
I followed the instructions on BitBucket to move a repo with all its branches there. Here come the steps with explanations following the #
character:
cd path/to/local/repo
git remote remove origin # to get rid of the old setting, this was not in the BitBucket instructions
git remote add origin ssh://[email protected]/<username>/<newrepo> # modify URL as needed
git push -u origin --all # pushes _ALL_ branches in one go
git push -u origin --tags # pushes _ALL_ tags in one go
Worked nicely for me.
Edit: DTing's answer is more applicable to your question since it uses PIL, but I'll leave this up in case you want to know how to do it in numpy.
Here is a numpy/matplotlib solution that should work for N images (only color images) of any size/shape.
import numpy as np
import matplotlib.pyplot as plt
def concat_images(imga, imgb):
"""
Combines two color image ndarrays side-by-side.
"""
ha,wa = imga.shape[:2]
hb,wb = imgb.shape[:2]
max_height = np.max([ha, hb])
total_width = wa+wb
new_img = np.zeros(shape=(max_height, total_width, 3))
new_img[:ha,:wa]=imga
new_img[:hb,wa:wa+wb]=imgb
return new_img
def concat_n_images(image_path_list):
"""
Combines N color images from a list of image paths.
"""
output = None
for i, img_path in enumerate(image_path_list):
img = plt.imread(img_path)[:,:,:3]
if i==0:
output = img
else:
output = concat_images(output, img)
return output
Here is example use:
>>> images = ["ronda.jpeg", "rhod.jpeg", "ronda.jpeg", "rhod.jpeg"]
>>> output = concat_n_images(images)
>>> import matplotlib.pyplot as plt
>>> plt.imshow(output)
>>> plt.show()
With all zeroes:
static String hexToBin(String s) {
String preBin = new BigInteger(s, 16).toString(2);
Integer length = preBin.length();
if (length < 8) {
for (int i = 0; i < 8 - length; i++) {
preBin = "0" + preBin;
}
}
return preBin;
}
You can also choose to serialize your data and then visualize it in D3.js, as done here: Use Python & Pandas to Create a D3 Force Directed Network Diagram (It comes with a jupyter notebook as well!)
Here is the gist. You serialize your graph data in this format:
import json
json_data = {
"nodes":[
{"name":"Myriel","group":1},
{"name":"Napoleon","group":1},
{"name":"Mlle.Baptistine","group":1},
{"name":"Mme.Magloire","group":1},
{"name":"CountessdeLo","group":1},
],
"links":[
{"source":1,"target":0,"value":1},
{"source":2,"target":0,"value":8},
{"source":3,"target":0,"value":10},
{"source":3,"target":2,"value":6},
{"source":4,"target":0,"value":1},
{"source":5,"target":0,"value":1},
]
}
filename_out = 'graph_data.json'
json_out = open(filename_out,'w')
json_out.write(json_data)
json_out.close()
Then you load the data in with d3.js:
d3.json("pcap_export.json", drawGraph);
For the routine drawGraph
I refer you to the link, however.
You can't remove API functions without breaking the API. If you would, many applications would no longer compile or run at all.
This is the reason that one reference gives:
Reading a line that overflows the array pointed to by s results in undefined behavior. The use of fgets() is recommended.
I have also faced the same issue, The solution for it is : the file for which you are getting the error is probably a duplicated file of the actual file with another version. So just the removal of a particular file on which errors are thrown can resolve the issue.
The only way I can get this to work is to manually instantiate the section handler type, pass the raw XML to it, and cast the resulting object.
Seems pretty inefficient, but there you go.
I wrote an extension method to encapsulate this:
public static class ConfigurationSectionExtensions
{
public static T GetAs<T>(this ConfigurationSection section)
{
var sectionInformation = section.SectionInformation;
var sectionHandlerType = Type.GetType(sectionInformation.Type);
if (sectionHandlerType == null)
{
throw new InvalidOperationException(string.Format("Unable to find section handler type '{0}'.", sectionInformation.Type));
}
IConfigurationSectionHandler sectionHandler;
try
{
sectionHandler = (IConfigurationSectionHandler)Activator.CreateInstance(sectionHandlerType);
}
catch (InvalidCastException ex)
{
throw new InvalidOperationException(string.Format("Section handler type '{0}' does not implement IConfigurationSectionHandler.", sectionInformation.Type), ex);
}
var rawXml = sectionInformation.GetRawXml();
if (rawXml == null)
{
return default(T);
}
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(rawXml);
return (T)sectionHandler.Create(null, null, xmlDocument.DocumentElement);
}
}
The way you would call it in your example is:
var map = new ExeConfigurationFileMap
{
ExeConfigFilename = @"c:\\foo.config"
};
var configuration = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
var myParamsSection = configuration.GetSection("MyParams");
var myParamsCollection = myParamsSection.GetAs<NameValueCollection>();
Here's my solution:
# /initializers/string.rb
class String
IntegerRegex = /^(\d)+$/
def integer?
!!self.match(IntegerRegex)
end
end
# any_model_or_controller.rb
'12345'.integer? # true
'asd34'.integer? # false
And here's how it works:
/^(\d)+$/
is regex expression for finding digits in any string. You can test your regex expressions and results at http://rubular.com/.IntegerRegex
to avoid unnecessary memory allocation everytime we use it in the method.integer?
is an interrogative method which should return true
or false
.match
is a method on string which matches the occurrences as per the given regex expression in argument and return the matched values or nil
.!!
converts the result of match
method into equivalent boolean.String
class is monkey patching, which doesn't change anything in existing String functionalities, but just adds another method named integer?
on any String object. Use this Layout in your xml file
<LinearLayout
android:id="@+id/contacts_type"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone">
</LinearLayout>
Define your layout in .class file
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.contacts_type);
Now if you want to display this layout just write
linearLayout.setVisibility(View.VISIBLE);
and if you want to hide layout just write
linearLayout.setVisibility(View.INVISIBLE);
public static void setTextViewFromHtmlWithLinkClickable(TextView textView, String text) {
Spanned result;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
result = Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY);
} else {
result = Html.fromHtml(text);
}
textView.setText(result);
textView.setMovementMethod(LinkMovementMethod.getInstance());
}
I wanted a similar method for my project but in my case the input paths were either from local disk volumes or clustered storage volumes (CSVs). So DriveInfo class did not work for me. CSVs have a mount point under another drive, typically C:\ClusterStorage\Volume*. Note that C: will be a different Volume than C:\ClusterStorage\Volume1
This is what I finally came up with:
public static ulong GetFreeSpaceOfPathInBytes(string path)
{
if ((new Uri(path)).IsUnc)
{
throw new NotImplementedException("Cannot find free space for UNC path " + path);
}
ulong freeSpace = 0;
int prevVolumeNameLength = 0;
foreach (ManagementObject volume in
new ManagementObjectSearcher("Select * from Win32_Volume").Get())
{
if (UInt32.Parse(volume["DriveType"].ToString()) > 1 && // Is Volume monuted on host
volume["Name"] != null && // Volume has a root directory
path.StartsWith(volume["Name"].ToString(), StringComparison.OrdinalIgnoreCase) // Required Path is under Volume's root directory
)
{
// If multiple volumes have their root directory matching the required path,
// one with most nested (longest) Volume Name is given preference.
// Case: CSV volumes monuted under other drive volumes.
int currVolumeNameLength = volume["Name"].ToString().Length;
if ((prevVolumeNameLength == 0 || currVolumeNameLength > prevVolumeNameLength) &&
volume["FreeSpace"] != null
)
{
freeSpace = ulong.Parse(volume["FreeSpace"].ToString());
prevVolumeNameLength = volume["Name"].ToString().Length;
}
}
}
if (prevVolumeNameLength > 0)
{
return freeSpace;
}
throw new Exception("Could not find Volume Information for path " + path);
}
One possible way is to use .map()
method:
var all = $(".mbox").map(function() {
return this.innerHTML;
}).get();
console.log(all.join());
DEMO: http://jsfiddle.net/Y4bHh/
N.B. Please don't use document.write
. For testing purposes console.log
is the best way to go.
public static class ErrorCode
{
public const IDictionary<string , string > m_ErrorCodeDic;
public static ErrorCode()
{
m_ErrorCodeDic = new Dictionary<string, string>()
{ {"1","User name or password problem"} };
}
}
Probably initialise in the constructor.
Suppose you have a timedelta series:
import pandas as pd
from datetime import datetime
z = pd.DataFrame({'a':[datetime.strptime('20150101', '%Y%m%d')],'b':[datetime.strptime('20140601', '%Y%m%d')]})
td_series = (z['a'] - z['b'])
One way to convert this timedelta column or series is to cast it to a Timedelta object (pandas 0.15.0+) and then extract the days from the object:
td_series.astype(pd.Timedelta).apply(lambda l: l.days)
Another way is to cast the series as a timedelta64 in days, and then cast it as an int:
td_series.astype('timedelta64[D]').astype(int)
You can set a very small initial delay-time (e.g. 100) and set it to your desired delay-time within the function:
var delay = 100;_x000D_
_x000D_
function foo() {_x000D_
console.log("Change initial delay-time to what you want.");_x000D_
delay = 12000;_x000D_
setTimeout(foo, delay);_x000D_
}
_x000D_
Complementing the answer from @Nishant,the best way to return the activity result is:
Intent returnIntent = getIntent();
returnIntent.putExtra("result",result);
setResult(RESULT_OK,returnIntent);
finish();
I was having problem with
new Intent();
Then I found out that the correct way is using
getIntent();
to get the current intent
The easiest way it can be done is by reading mysql execution log file and you can do that in runtime.
There is a nice explanation here:
If you work with generics, use List instead of ArrayList. The List has exactly the GetEnumerator method you need.
List<MyObject> myList = new List<MyObject>();
Create a group object and call methods like below example:
grp = df.groupby(['col1', 'col2', 'col3'])
grp.max()
grp.mean()
grp.describe()
If you are looking for a specific container, you can run:
if [ "$( docker container inspect -f '{{.State.Running}}' $container_name )" == "true" ]; then ...
To avoid issues with a container that is in a crash loop and constantly restarting from showing that it's up, the above can be improved by checking the Status
field:
if [ "$( docker container inspect -f '{{.State.Status}}' $container_name )" == "running" ]; then ...
If you want to know if dockerd is running itself on the local machine and you have systemd installed, you can run:
systemctl show --property ActiveState docker
You can also connect to docker with docker info
or docker version
and they will error out if the daemon is unavailable.
With the introduction of lambda expression in Java 8 you can now have anonymous methods.
Say I have a class Alpha
and I want to filter Alpha
s on a specific condition. To do this you can use a Predicate<Alpha>
. This is a functional interface which has a method test
that accepts an Alpha
and returns a boolean
.
Assuming that the filter method has this signature:
List<Alpha> filter(Predicate<Alpha> filterPredicate)
With the old anonymous class solution you would need to something like:
filter(new Predicate<Alpha>() {
boolean test(Alpha alpha) {
return alpha.centauri > 1;
}
});
With the Java 8 lambdas you can do:
filter(alpha -> alpha.centauri > 1);
For more detailed information see the Lambda Expressions tutorial
Use the DATE function:
SELECT DATE(orders.date_purchased) AS date
Yet another option would be:
SELECT * FROM mytable
WHERE TRUNC(mydate, 'YEAR') = TRUNC(SYSDATE, 'YEAR');
You can use a StringWriter to write values to a string. It provides a stream-like syntax (though does not derive from Stream
) which works with an underlying StringBuilder
.
--for oracle
select tablespace_name, table_name from all_tables;
This link can provide much more information on this topic
The two alternative you gave are semantically identical, but using make([]int, 0)
will result in an internal call to runtime.makeslice (Go 1.14).
You also have the option to leave it with a nil
value:
var myslice []int
As written in the Golang.org blog:
a nil slice is functionally equivalent to a zero-length slice, even though it points to nothing. It has length zero and can be appended to, with allocation.
A nil
slice will however json.Marshal()
into "null"
whereas an empty slice will marshal into "[]"
, as pointed out by @farwayer.
None of the above options will cause any allocation, as pointed out by @ArmanOrdookhani.
Use percent-encoded form. Some (mainly old) computers running Windows XP for example do not support Unicode, but rather ISO encodings. That is the reason percent-encoded URLs were invented. Also, if you give a URL printed on paper to a user, containing characters that cannot be easily typed, that user may have a hard time typing it (or just ignore it). Percent-encoded form can even be used in many of the oldest machines that ever existed (although they don't support internet of course).
There is a downside though, as percent-encoded characters are longer than the original ones, thus possibly resulting in really long URLs. But just try to ignore it, or use a URL shortener (I would recommend goo.gl in this case, which makes a 13-character long URL). Also, if you don't want to register for a Google account, try bit.ly (bit.ly makes slightly longer URLs, with the length being 14 characters).
this is not possible in "mailto" function.
please go with server side coding(C#).make sure open vs in administrative permission.
Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
oMsg.Subject = "emailSubject";
oMsg.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML;
oMsg.BCC = "emailBcc";
oMsg.To = "emailRecipient";
string body = "emailMessage";
oMsg.HTMLBody = "body";
oMsg.Attachments.Add(Convert.ToString(@"/my_location_virtual_path/myfile.txt"), Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);
oMsg.Display(false); //In order to displ
u can check onCancelled() once then :
protected Object doInBackground(Object... x) {
while (/* condition */) {
if (isCancelled()) break;
}
return null;
}
I had a similar problem. GET requests worked and their (empty) request bodies got written to the the log file. POST requests failed with a 404. Experimenting a bit, I found that all POST requests were failing. I found a forum posting asking about POST requests and the solution there worked for me. That solution? Add a proxy_header
line right before the proxy_pass
line, exactly like the one in the example below.
server {
listen 192.168.0.1:45080;
server_name foo.example.org;
access_log /path/to/log/nginx/post_bodies.log post_bodies;
location / {
### add the following proxy_header line to get POSTs to work
proxy_set_header Host $http_host;
proxy_pass http://10.1.2.3;
}
}
(This is with nginx 1.2.1 for what it is worth.)
You might be better off using the Properties Service as you can use these as a kind of persistent global variable.
click 'file > project properties > project properties' to set a key value, or you can use
PropertiesService.getScriptProperties().setProperty('mykey', 'myvalue');
The data can be retrieved with
var myvalue = PropertiesService.getScriptProperties().getProperty('mykey');
public JSONObject makJsonObject(int id[], String name[], String year[],
String curriculum[], String birthday[], int numberof_students)
throws JSONException {
JSONObject obj = null;
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < numberof_students; i++) {
obj = new JSONObject();
try {
obj.put("id", id[i]);
obj.put("name", name[i]);
obj.put("year", year[i]);
obj.put("curriculum", curriculum[i]);
obj.put("birthday", birthday[i]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jsonArray.put(obj);
}
JSONObject finalobject = new JSONObject();
finalobject.put("student", jsonArray);
return finalobject;
}
I'm not sure if there's an absolute authoritative answer to this, but you may look upon it as a distinction of what happens when the request hits the webserver. The request may either be served by having the server return a file that's already been made (static content), or it can pass the request to an application that generates the respone sent back to the browser (dynamic content).
Both types will be called a website, but only the ones that have an application generate the contents will be called a web application.
How the application is written is of less concern. It may be ASP, PHP, Ruby, JavaScript or even C or C++.
The only solution worked for me is changing the following code
Mail::send('emails.activation', $data, function($message){
$message->from(env('MAIL_USERNAME'),'Test');
$message->to($email)->subject($subject);
});
You can use Array.Resize()
in .net 3.5 and higher. This method allocates a new array with the specified size, copies elements from the old array to the new one, and then replaces the old array with the new one.
(So you will need the memory available for both arrays as this probably uses Array.Copy
under the covers)
There is no such functionality in jQuery. Use JSON.stringify
or alternatively any jQuery plugin with similar functionality (e.g jquery-json).
dirname(rstudioapi::getActiveDocumentContext()$path)
works for me but if you don't want to use rstudioapi and you are not in a proyect, you can use the symbol ~ in your path. The symbol ~ refers to the default RStudio working directory (at least on Windows).
If your RStudio working directory is "D:/Documents", setwd("~/proyect1")
is the same as setwd("D:/Documents/proyect1").
Once you set that, you can navigate to a subdirectory: read.csv("DATA/mydata.csv")
. Is the same as read.csv("D:/Documents/proyect1/DATA/mydata.csv")
.
If you want to navigate to a parent folder, you can use "../"
.
For example: read.csv("../olddata/DATA/mydata.csv")
which is the same as read.csv("D:/Documents/oldata/DATA/mydata.csv")
This is the best way for me to code scripts, no matter what computer you are using.
Do you have a bean declared in your context file that has an id of "articleService"? I believe that autowiring matches the id of a bean in your context files with the variable name that you are attempting to Autowire.