I scanned the above answers and the proposed keydown
/keyup
approach works only under special circumstances. If the user alt-tabs away, or uses a key gesture to open a new browser window or tab, then a keydown
will be registered, which is fine, because at that point it's impossible to tell if the key is something the web app is monitoring, or is a standard browser or OS shortcut. Coming back to the browser page, it'll still think the key is held, though it was released in the meantime. Or some key is simply kept held, while the user is switching to another tab or application with the mouse, then released outside our page.
Modifier keys (Shift
etc.) can be monitored via mousemove
etc. assuming that there is at least one mouse interaction expected when tabbing back, which is frequently the case.
For most all other keys (except modifiers, Tab
, Delete
, but including Space
, Enter
), monitoring keypress
would work for most applications - a key held down will continue to fire. There's some latency in resetting the key though, due to the periodicity of keypress
firing. Basically, if keypress
doesn't keep firing, then it's possible to rule out most of the keys. This, combined with the modifiers is pretty airtight, though I haven't explored what to do with Tab
and Backspace
.
I'm sure there's some library out there that abstracts over this DOM weakness, or maybe some DOM standard change took care of it, since it's a rather old question.
BUT imagine a large table with changing columns. You have to compare every column and if the database changes you have to adjust the trigger. AND it doesn't "feel" good to compare every row hardcoded :)
Yeah, but that's the way to proceed.
As a side note, it's also good practice to pre-emptively check before updating:
UPDATE foo SET b = 3 WHERE a=3 and b <> 3;
In your example this would make it update (and thus overwrite) two rows instead of three.
Yes, it is. Just create files in the windows explorer and git automatically detects these files as currently untracked. Then add it with the command you already mentioned.
git add
does not create any files. See also http://gitref.org/basic/#add
Github probably creates the file with touch
and adds the file for tracking automatically. You can do this on the bash
as well.
You have to put a g
at the end, it stands for "global":
echo dog dog dos | sed -r 's:dog:log:g'
^
if
using(var db = new MyDbContext())
{
await db.Database.ExecuteSqlCommandAsync(@"TRUNCATE TABLE MyTable"););
}
causes
Cannot truncate table 'MyTable' because it is being referenced by a FOREIGN KEY constraint.
I use this :
using(var db = new MyDbContext())
{
await db.Database.ExecuteSqlCommandAsync(@"DELETE FROM MyTable WHERE ID != -1");
}
On macOs I manage to fix this by adding:
export ANDROID_HOME=$HOME/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/emulator
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH:$ANDROID_HOME/platform-tools
to ~/.zsh_profile file.
and than type to your terminal
source $HOME/.zsh_profile
The issue was caused by using iTerm2 shell so it's required to edit its own config instead of default $HOME/.bash_profile as described in the official documentation https://reactnative.dev/docs/environment-setup
To achieve the same programmatic you can use following
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
or adding following in layout also will perform the above task
android:keepScreenOn="true"
The details you can get from following url http://developer.android.com/training/scheduling/wakelock.html
I have used combination of following to wake my screen when keyguard locked and keep my screen on
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
Here is what I figured, and this happened recently on Windows 10 after an update was installed. From what I gathered, a Windows Defender update was installed which assumed my "Project.dll"(an asp.net core project) behaved like a virus so it was deleted.
So, one of the first things I suggest you do before you start installing/uninstalling stuffs is to check to confirm your "Project.dll" is where it should be.
Copy it back to the location if it is no longer there.
If you are having difficulty copying the file back add an exclusion to your project folder in windows defender. ( Learn how to do that here. )
This worked for me instantly, and I repeated it across application multiple servers.
use ArrayUtils.addAll(T[], T...):
import org.apache.commons.lang3.ArrayUtils;
AnyObject[] array1 = ...;
AnyObject[] array2 = ...;
AnyObject[] mergedArray = ArrayUtils.addAll(array1, array2);
Mark, this is already answered in your previous topic. But OK, here it is again:
Suppose ${list}
points to a List<Object>
, then the following
<c:forEach items="${list}" var="item">
${item}<br>
</c:forEach>
does basically the same as as following in "normal Java":
for (Object item : list) {
System.out.println(item);
}
If you have a List<Map<K, V>>
instead, then the following
<c:forEach items="${list}" var="map">
<c:forEach items="${map}" var="entry">
${entry.key}<br>
${entry.value}<br>
</c:forEach>
</c:forEach>
does basically the same as as following in "normal Java":
for (Map<K, V> map : list) {
for (Entry<K, V> entry : map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
The key
and value
are here not special methods or so. They are actually getter methods of Map.Entry
object (click at the blue Map.Entry
link to see the API doc). In EL (Expression Language) you can use the .
dot operator to access getter methods using "property name" (the getter method name without the get
prefix), all just according the Javabean specification.
That said, you really need to cleanup the "answers" in your previous topic as they adds noise to the question. Also read the comments I posted in your "answers".
Do this :
<script type="text/javascript"> function showDetails(username) { window.location = '/player_detail?username='+username; } </script> <input type="button" name="theButton" value="Detail" onclick="showDetails('username');">
You can modify the whole InfoWindow using jquery alone...
var popup = new google.maps.InfoWindow({
content:'<p id="hook">Hello World!</p>'
});
Here the <p> element will act as a hook into the actual InfoWindow. Once the domready fires, the element will become active and accessible using javascript/jquery, like $('#hook').parent().parent().parent().parent()
.
The below code just sets a 2 pixel border around the InfoWindow.
google.maps.event.addListener(popup, 'domready', function() {
var l = $('#hook').parent().parent().parent().siblings();
for (var i = 0; i < l.length; i++) {
if($(l[i]).css('z-index') == 'auto') {
$(l[i]).css('border-radius', '16px 16px 16px 16px');
$(l[i]).css('border', '2px solid red');
}
}
});
You can do anything like setting a new CSS class or just adding a new element.
Play around with the elements to get what you need...
To have the ultimate understanding of what is a case class:
let's assume the following case class definition:
case class Foo(foo:String, bar: Int)
and then do the following in the terminal:
$ scalac -print src/main/scala/Foo.scala
Scala 2.12.8 will output:
...
case class Foo extends Object with Product with Serializable {
<caseaccessor> <paramaccessor> private[this] val foo: String = _;
<stable> <caseaccessor> <accessor> <paramaccessor> def foo(): String = Foo.this.foo;
<caseaccessor> <paramaccessor> private[this] val bar: Int = _;
<stable> <caseaccessor> <accessor> <paramaccessor> def bar(): Int = Foo.this.bar;
<synthetic> def copy(foo: String, bar: Int): Foo = new Foo(foo, bar);
<synthetic> def copy$default$1(): String = Foo.this.foo();
<synthetic> def copy$default$2(): Int = Foo.this.bar();
override <synthetic> def productPrefix(): String = "Foo";
<synthetic> def productArity(): Int = 2;
<synthetic> def productElement(x$1: Int): Object = {
case <synthetic> val x1: Int = x$1;
(x1: Int) match {
case 0 => Foo.this.foo()
case 1 => scala.Int.box(Foo.this.bar())
case _ => throw new IndexOutOfBoundsException(scala.Int.box(x$1).toString())
}
};
override <synthetic> def productIterator(): Iterator = scala.runtime.ScalaRunTime.typedProductIterator(Foo.this);
<synthetic> def canEqual(x$1: Object): Boolean = x$1.$isInstanceOf[Foo]();
override <synthetic> def hashCode(): Int = {
<synthetic> var acc: Int = -889275714;
acc = scala.runtime.Statics.mix(acc, scala.runtime.Statics.anyHash(Foo.this.foo()));
acc = scala.runtime.Statics.mix(acc, Foo.this.bar());
scala.runtime.Statics.finalizeHash(acc, 2)
};
override <synthetic> def toString(): String = scala.runtime.ScalaRunTime._toString(Foo.this);
override <synthetic> def equals(x$1: Object): Boolean = Foo.this.eq(x$1).||({
case <synthetic> val x1: Object = x$1;
case5(){
if (x1.$isInstanceOf[Foo]())
matchEnd4(true)
else
case6()
};
case6(){
matchEnd4(false)
};
matchEnd4(x: Boolean){
x
}
}.&&({
<synthetic> val Foo$1: Foo = x$1.$asInstanceOf[Foo]();
Foo.this.foo().==(Foo$1.foo()).&&(Foo.this.bar().==(Foo$1.bar())).&&(Foo$1.canEqual(Foo.this))
}));
def <init>(foo: String, bar: Int): Foo = {
Foo.this.foo = foo;
Foo.this.bar = bar;
Foo.super.<init>();
Foo.super./*Product*/$init$();
()
}
};
<synthetic> object Foo extends scala.runtime.AbstractFunction2 with Serializable {
final override <synthetic> def toString(): String = "Foo";
case <synthetic> def apply(foo: String, bar: Int): Foo = new Foo(foo, bar);
case <synthetic> def unapply(x$0: Foo): Option =
if (x$0.==(null))
scala.None
else
new Some(new Tuple2(x$0.foo(), scala.Int.box(x$0.bar())));
<synthetic> private def readResolve(): Object = Foo;
case <synthetic> <bridge> <artifact> def apply(v1: Object, v2: Object): Object = Foo.this.apply(v1.$asInstanceOf[String](), scala.Int.unbox(v2));
def <init>(): Foo.type = {
Foo.super.<init>();
()
}
}
...
As we can see Scala compiler produces a regular class Foo
and companion-object Foo
.
Let's go through the compiled class and comment on what we have got:
Foo
class, immutable:val foo: String
val bar: Int
def foo(): String
def bar(): Int
def copy(foo: String, bar: Int): Foo
def copy$default$1(): String
def copy$default$2(): Int
scala.Product
trait: override def productPrefix(): String
def productArity(): Int
def productElement(x$1: Int): Object
override def productIterator(): Iterator
scala.Equals
trait for make case class instances comparable for equality by ==
:def canEqual(x$1: Object): Boolean
override def equals(x$1: Object): Boolean
java.lang.Object.hashCode
for obeying the equals-hashcode contract:override <synthetic> def hashCode(): Int
java.lang.Object.toString
: override def toString(): String
new
keyword:def <init>(foo: String, bar: Int): Foo
Object Foo:
- method apply
for instantiation without new
keyword:
case <synthetic> def apply(foo: String, bar: Int): Foo = new Foo(foo, bar);
unupply
for using case class Foo in pattern matching:case <synthetic> def unapply(x$0: Foo): Option
<synthetic> private def readResolve(): Object = Foo;
scala.runtime.AbstractFunction2
for doing such trick:scala> case class Foo(foo:String, bar: Int)
defined class Foo
scala> Foo.tupled
res1: ((String, Int)) => Foo = scala.Function2$$Lambda$224/1935637221@9ab310b
tupled
from object returns a funtion to create a new Foo by applying a tuple of 2 elements.
So case class is just syntactic sugar.
None of these worked for me, I have a message system inside a web app that's similar to Facebook messenger and wanted the messages to appear at the bottom of a div.
This worked a treat, basic Javascript.
window.onload=function () {
var objDiv = document.getElementById("MyDivElement");
objDiv.scrollTop = objDiv.scrollHeight;
}
Using the Windows FTP client you would want to use the -s:filename
option to specify a script for the FTP client to run. The documentation specifically points out that you should not try to pipe input into the FTP client with a <
character.
Execution of the script will start immediately, so it does work for username/password.
However, the security of this setup is questionable since you now have a username and password for the FTP server visible to anyone who decides to look at your batch file.
Either way, you can generate the script file on the fly from the batch file and then pass it to the FTP client like so:
@echo off
REM Generate the script. Will overwrite any existing temp.txt
echo open servername> temp.txt
echo username>> temp.txt
echo password>> temp.txt
echo get %1>> temp.txt
echo quit>> temp.txt
REM Launch FTP and pass it the script
ftp -s:temp.txt
REM Clean up.
del temp.txt
Replace servername, username, and password with your details and the batch file will generate the script as temp.txt launch ftp with the script and then delete the script.
If you are always getting the same file you can replace the %1
with the file name. If not you just launch the batchfile and provide the name of the file to get as an argument.
You could also turn on autoextend for the whole database using this command:
ALTER DATABASE DATAFILE 'C:\ORACLEXE\APP\ORACLE\ORADATA\XE\SYSTEM.DBF'
AUTOEXTEND ON NEXT 1M MAXSIZE 1024M;
Just change the filepath to point to your system.dbf file.
Credit Here
Try this
'''
This is a multiline
comment. I can type here whatever I want.
'''
Python does have a multiline string/comment syntax in the sense that unless used as docstrings, multiline strings generate no bytecode -- just like #-prepended comments. In effect, it acts exactly like a comment.
On the other hand, if you say this behavior must be documented in the official docs to be a true comment syntax, then yes, you would be right to say it is not guaranteed as part of the language specification.
In any case your editor should also be able to easily comment-out a selected region (by placing a # in front of each line individually). If not, switch to an editor that does.
Programming in Python without certain text editing features can be a painful experience. Finding the right editor (and knowing how to use it) can make a big difference in how the Python programming experience is perceived.
Not only should the editor be able to comment-out selected regions, it should also be able to shift blocks of code to the left and right easily, and should automatically place the cursor at the current indentation level when you press Enter. Code folding can also be useful.
From mere curiosity, I timed the two rivalling answers posted above.
And I had the following results:
dateutil.parser (valid str): 4.6732222699938575
dateutil.parser (invalid str): 1.7270505399937974
datetime.strptime (valid): 0.7822393209935399
datetime.strptime (invalid): 0.4394566189876059
And here's the code I used (Python 3.6)
from dateutil import parser as date_parser
from datetime import datetime
from timeit import timeit
def is_date_parsing(date_str):
try:
return bool(date_parser.parse(date_str))
except ValueError:
return False
def is_date_matching(date_str):
try:
return bool(datetime.strptime(date_str, '%Y-%m-%d'))
except ValueError:
return False
if __name__ == '__main__':
print("dateutil.parser (valid date):", end=' ')
print(timeit("is_date_parsing('2021-01-26')",
setup="from __main__ import is_date_parsing",
number=100000))
print("dateutil.parser (invalid date):", end=' ')
print(timeit("is_date_parsing('meh')",
setup="from __main__ import is_date_parsing",
number=100000))
print("datetime.strptime (valid date):", end=' ')
print(timeit("is_date_matching('2021-01-26')",
setup="from __main__ import is_date_matching",
number=100000))
print("datetime.strptime (invalid date):", end=' ')
print(timeit("is_date_matching('meh')",
setup="from __main__ import is_date_matching",
number=100000))
The report from SSLabs says:
This server's certificate chain is incomplete. Grade capped to B.
....
Chain Issues Incomplete
Desktop browsers often have chain certificates cached from previous connections or download them from the URL specified in the certificate. Mobile browsers and other applications usually don't.
Fix your chain by including the missing certificates and everything should be right.
Get key values from list of dictionaries in python?
Ex:
data =
[{'obj1':[{'cpu_percentage':'15%','ram':3,'memory_percentage':'66%'}]},
{'obj2': [{'cpu_percentage':'0','ram':4,'memory_percentage':'35%'}]}]
for d in data:
for key,value in d.items():
z ={key: {'cpu_percentage': d['cpu_percentage'],'memory_percentage': d['memory_percentage']} for d in value}
print(z)
Output:
{'obj1': {'cpu_percentage': '15%', 'memory_percentage': '66%'}}
{'obj2': {'cpu_percentage': '0', 'memory_percentage': '35%'}}
if you want to get the index values, you can simply do:
dataframe.index
this will output a pandas.core.index
Here is another alternative. It will of course give you a bad result if the input char is not ascii. I've not perf tested it but I think it would be pretty fast:
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GetAsciiVal(string s, int index) {
return GetAsciiVal(s[index]);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GetAsciiVal(char c) {
return unchecked(c & 0xFF);
}
I realize this question was about creating a plugin, but since the new Jenkins 2 Pipeline builds use Groovy, I found myself here while trying to figure out how to read a file from a workspace in a Pipeline build. So maybe I can help someone like me out in the future.
Turns out it's very easy, there is a readfile step, and I should have rtfm:
env.WORKSPACE = pwd()
def version = readFile "${env.WORKSPACE}/version.txt"
From the doc for path.resolve
:
The resulting path is normalized and trailing slashes are removed unless the path is resolved to the root directory.
But path.join
keeps trailing slashes
So
__dirname = '/';
path.resolve(__dirname, 'foo/'); // '/foo'
path.join(__dirname, 'foo/'); // '/foo/'
By using css you can add your icon via Unicode
content: '\f144';
font-family: FontAwesome;
This will work
You can't access non-static members from a static method. (Note that Main()
is static, which is a requirement of .Net). Just make siprimo and volteado static, by placing the static keyword in front of them. e.g.:
static private long volteado(long a)
I was having similar issue and I think if we simply ignore the ssl
verification will work like charm as it worked for me. So connecting to server with https
scheme but directing them not to verify the certificate.
Using requests
. Just mention verify=False
instead of None
requests.post(url, data=payload, headers=headers, verify=False)
Hoping this will work for those who needs :).
In appdelegate.m file write the follwing code in applicationDidEnterBackground to get the local notification
- (void)applicationDidEnterBackground:(UIApplication *)application
{
UILocalNotification *notification = [[UILocalNotification alloc]init];
notification.repeatInterval = NSDayCalendarUnit;
[notification setAlertBody:@"Hello world"];
[notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
[notification setTimeZone:[NSTimeZone defaultTimeZone]];
[application setScheduledLocalNotifications:[NSArray arrayWithObject:notification]];
}
Actually, you can do what you want. If you want to provide multiple interfaces or a class plus interfaces, you have to have your wildcard look something like this:
<T extends ClassA & InterfaceB>
See the Generics Tutorial at sun.com, specifically the Bounded Type Parameters section, at the bottom of the page. You can actually list more than one interface if you wish, using & InterfaceName
for each one that you need.
This can get arbitrarily complicated. To demonstrate, see the JavaDoc declaration of Collections#max
, which (wrapped onto two lines) is:
public static <T extends Object & Comparable<? super T>> T
max(Collection<? extends T> coll)
why so complicated? As said in the Java Generics FAQ: To preserve binary compatibility.
It looks like this doesn't work for variable declaration, but it does work when putting a generic boundary on a class. Thus, to do what you want, you may have to jump through a few hoops. But you can do it. You can do something like this, putting a generic boundary on your class and then:
class classB { }
interface interfaceC { }
public class MyClass<T extends classB & interfaceC> {
Class<T> variable;
}
to get variable
that has the restriction that you want. For more information and examples, check out page 3 of Generics in Java 5.0. Note, in <T extends B & C>
, the class name must come first, and interfaces follow. And of course you can only list a single class.
You forgot to set the width of the border! Change border: red;
to border:1px solid red;
Here the full code to get the circle:
.circle {_x000D_
background-color:#fff;_x000D_
border:1px solid red; _x000D_
height:100px;_x000D_
border-radius:50%;_x000D_
-moz-border-radius:50%;_x000D_
-webkit-border-radius:50%;_x000D_
width:100px;_x000D_
}
_x000D_
<div class="circle"></div>
_x000D_
Yes you can. Assume a process foo
is running...
ps -elf | grep foo look for the PID number gdb -a {PID number}
You can use in
operator in conjunction with lower
method of strings.
if "mandy" in line.lower():
If you are building 32bit then make sure you don't have _WIN64 defined for your project.
in HTML:
<a class="main-item" (click)="onNavigate()">Go to URL</a>
OR
<button class="main-item" (click)="onNavigate()">Go to URL</button>
in TS file:
onNavigate(){
// your logic here.... like set the url
const url = 'https://www.google.com';
window.open(url, '_blank');
}
DON'T FORGET - Use parseFloat();
if your dealing with decimals.
SWIFT 4 with extension
set:
// set button label for all states
extension UIButton {
public func setAllStatesTitle(_ newTitle: String){
self.setTitle(newTitle, for: .normal)
self.setTitle(newTitle, for: .selected)
self.setTitle(newTitle, for: .disabled)
}
}
and use:
yourBtn.setAllStatesTitle("btn title")
Why not try Ajax, check a code part 1 or part 2 (use comment).
$(document).ready(function(){ _x000D_
console.clear();_x000D_
/*_x000D_
// PART 1 ERROR_x000D_
// Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Sandbox access violation: Blocked a frame at "http://stacksnippets.net" from accessing a frame at "null". Both frames are sandboxed and lack the "allow-same-origin" flag._x000D_
console.log("PART 1:: ");_x000D_
console.log($('iframe#sandro').contents().find("html").html());_x000D_
*/_x000D_
// PART 2_x000D_
$.ajax({_x000D_
url: $("iframe#sandro").attr("src"),_x000D_
type: 'GET',_x000D_
dataType: 'html'_x000D_
}).done(function(html) {_x000D_
console.log("PART 2:: ");_x000D_
console.log(html);_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<html>_x000D_
<body>_x000D_
<iframe id="sandro" src="https://jsfiddle.net/robots.txt"></iframe>_x000D_
</body>_x000D_
</html>
_x000D_
Basically, I want to check if a particular string contains AT LEAST day(1 through 31 or 01 through 31),month(1 through 12 or 01 through 12) and year(yyyy or yy) in any order, with any date separator , what will be the solution? So, if the value includes any parts of time, it should return true too. I could NOT be able to define a array of format.
When I was in a similar situation, here is what I did:
This http://www.codeproject.com/Articles/13255/Validation-with-Regular-Expressions-Made-Simple was really helpful both for understanding as well as validation the syntax for each format.
My 2 cents if it helps....
Easiest, if you are using ES6
.
initialArray = [1, 2, 3];
newArray = [ ...initialArray, 4 ]; // --> [1,2,3,4]
New array will be [1,2,3,4]
to update your state in React
this.setState({
arrayvar:[...this.state.arrayvar, newelement]
});
I had to install MariaDB. I am using OpenSUSE LINUX Leap 15 and had to execute these commands:
sudo zypper update
sudo zypper install mariadb mariadb-client mariadb-tools
sudo systemctl start mysql
sudo systemctl enable mysql //enable auto start at boot time3
sudo mysql_secure_installation
Nevermind found an answer. Ty the same for anyone who was willing to reply.
WHERE DATEDIFF(mydata,'2008-11-20') >=0;
The minimal-ui viewport property is no longer supported in iOS 8. However, the minimal-ui itself is not gone. User can enter the minimal-ui with a "touch-drag down" gesture.
There are several pre-conditions and obstacles to manage the view state, e.g. for minimal-ui to work, there has to be enough content to enable user to scroll; for minimal-ui to persist, window scroll must be offset on page load and after orientation change. However, there is no way of calculating the dimensions of the minimal-ui using the screen
variable, and thus no way of telling when user is in the minimal-ui in advance.
These observations is a result of research as part of developing Brim – view manager for iOS 8. The end implementation works in the following way:
When page is loaded, Brim will create a treadmill element. Treadmill element is used to give user space to scroll. Presence of the treadmill element ensures that user can enter the minimal-ui view and that it continues to persist if user reloads the page or changes device orientation. It is invisible to the user the entire time. This element has ID
brim-treadmill
.Upon loading the page or after changing the orientation, Brim is using Scream to detect if page is in the minimal-ui view (page that has been previously in minimal-ui and has been reloaded will remain in the minimal-ui if content height is greater than the viewport height).
When page is in the minimal-ui, Brim will disable scrolling of the document (it does this in a safe way that does not affect the contents of the main element). Disabling document scrolling prevents accidentally leaving the minimal-ui when scrolling upwards. As per the original iOS 7.1 spec, tapping the top bar brings back the rest of the chrome.
The end result looks like this:
For the sake of documentation, and in case you prefer to write your own implementation, it is worth noting that you cannot use Scream to detect if device is in minimal-ui straight after the orientationchange event because window
dimensions do not reflect the new orientation until the rotation animation has ended. You have to attach a listener to the orientationchangeend event.
Scream and orientationchangeend have been developed as part of this project.
I know this is a pretty old topic, but I also had a same problem.
My solution:
how we fill the combobox:
foreach (KeyValuePair<int, string> item in listRegion)
{
combo.Items.Add(item.Value);
combo.ValueMember = item.Value.ToString();
combo.DisplayMember = item.Key.ToString();
combo.SelectedIndex = 0;
}
and that's how we get inside:
MessageBox.Show(combo_region.DisplayMember.ToString());
I hope it help someone
As it appears you have the values as text, and not the numeric True/False, then you can use either COUNTIF
or SUMPRODUCT
=IF(SUMPRODUCT(--(A2:D2="False")),"False","True")
=IF(COUNTIF(A3:D3,"False*"),"False","True")
To delete a folder even if it might not exist (avoiding the race condition in Charles Chow's answer) but still have errors when other things go wrong (e.g. permission problems, disk read error, the file isn't a directory)
For Python 3.x:
import shutil
def ignore_absent_file(func, path, exc_inf):
except_instance = exc_inf[1]
if isinstance(except_instance, FileNotFoundError):
return
raise except_instance
shutil.rmtree(dir_to_delete, onerror=ignore_absent_file)
The Python 2.7 code is almost the same:
import shutil
import errno
def ignore_absent_file(func, path, exc_inf):
except_instance = exc_inf[1]
if isinstance(except_instance, OSError) and \
except_instance.errno == errno.ENOENT:
return
raise except_instance
shutil.rmtree(dir_to_delete, onerror=ignore_absent_file)
Check this idea out. http://pastie.org/1096892
I think it's close. HTML 5 really needs to add the change event to the spec. The only problem is that the callback function evaluates if (before == $(this).html()) before the content is actually updated in $(this).html(). setTimeout don't work, and it's sad. Let me know what you think.
Another alternative solution:
cat ~/.ssh/id_rsa.pub | xsel -i -b
From man xsel
:
-i, --input
read standard input into the selection.
-b, --clipboard
operate on the CLIPBOARD selection.
For example if you navigate from viewControllerB to viewControllerA then in your viewControllerA below delegate will call and data will share.
@IBAction func unWindSeague (_ sender : UIStoryboardSegue) {
if sender.source is ViewControllerB {
if let _ = sender.source as? ViewControllerB {
self.textLabel.text = "Came from B = B->A , B exited"
}
}
}
A different point is that the first sentence is parsed as:
scala> List(1,2,3).++(List(4,5))
res0: List[Int] = List(1, 2, 3, 4, 5)
Whereas the second example is parsed as:
scala> List(4,5).:::(List(1,2,3))
res1: List[Int] = List(1, 2, 3, 4, 5)
So if you are using macros, you should take care.
Besides, ++
for two lists is calling :::
but with more overhead because it is asking for an implicit value to have a builder from List to List. But microbenchmarks did not prove anything useful in that sense, I guess that the compiler optimizes such calls.
Micro-Benchmarks after warming up.
scala>def time(a: => Unit): Long = { val t = System.currentTimeMillis; a; System.currentTimeMillis - t}
scala>def average(a: () => Long) = (for(i<-1 to 100) yield a()).sum/100
scala>average (() => time { (List[Int]() /: (1 to 1000)) { case (l, e) => l ++ List(e) } })
res1: Long = 46
scala>average (() => time { (List[Int]() /: (1 to 1000)) { case (l, e) => l ::: List(e ) } })
res2: Long = 46
As Daniel C. Sobrai said, you can append the content of any collection to a list using ++
, whereas with :::
you can only concatenate lists.
XMLStarlet or another XPath engine is the correct tool for this job.
For instance, with data.xml
containing the following:
<root>
<item>
<title>15:54:57 - George:</title>
<description>Diane DeConn? You saw Diane DeConn!</description>
</item>
<item>
<title>15:55:17 - Jerry:</title>
<description>Something huh?</description>
</item>
</root>
...you can extract only the first title with the following:
xmlstarlet sel -t -m '//title[1]' -v . -n <data.xml
Trying to use sed for this job is troublesome. For instance, the regex-based approaches won't work if the title has attributes; won't handle CDATA sections; won't correctly recognize namespace mappings; can't determine whether a portion of the XML documented is commented out; won't unescape attribute references (such as changing Brewster & Jobs
to Brewster & Jobs
), and so forth.
// app.js
let db = ...; // your db object initialized
const contextMiddleware = (req, res, next) => {
req.db=db;
next();
};
app.use(contextMiddleware);
// routes.js It's just a mapping.
exports.routes = [
['/', controllers.index],
['/posts', controllers.posts.index],
['/posts/:post', controllers.posts.show]
];
// app.js
var { routes } = require('./routes');
routes.forEach(route => app.get(...route));
// You can customize this according to your own needs, like adding post request
The final app.js:
// app.js
var express = require('express');
var app = express.createServer();
let db = ...; // your db object initialized
const contextMiddleware = (req, res, next) => {
req.db=db;
next();
};
app.use(contextMiddleware);
var { routes } = require('./routes');
routes.forEach(route => app.get(...route));
app.listen(3000, function() {
console.log('Application is listening on port 3000');
});
Another version: you can customize this according to your own needs, like adding post request
// routes.js It's just a mapping.
let get = ({path, callback}) => ({app})=>{
app.get(path, callback);
}
let post = ({path, callback}) => ({app})=>{
app.post(path, callback);
}
let someFn = ({path, callback}) => ({app})=>{
// ...custom logic
app.get(path, callback);
}
exports.routes = [
get({path: '/', callback: controllers.index}),
post({path: '/posts', callback: controllers.posts.index}),
someFn({path: '/posts/:post', callback: controllers.posts.show}),
];
// app.js
var { routes } = require('./routes');
routes.forEach(route => route({app}));
You failed to find an app that does this because it is not possible.
The documentation clearly states (here):
Note: You can play back the audio data only to the standard output device. Currently, that is the mobile device speaker or a Bluetooth headset. You cannot play sound files in the conversation audio during a call.
The reason behind this decision has probably something to do with security: there are several scenarios where this capability could be used for cons.
(the OP is highly similar to this, hence I'm basically giving the same answer)
In case you do not have the fragment tag, the following code works well for me.
Fragment currentFragment = getActivity().getFragmentManager().findFragmentById(R.id.fragment_container);
if (currentFragment instanceof "NAME OF YOUR FRAGMENT CLASS") {
FragmentTransaction fragTransaction = (getActivity()).getFragmentManager().beginTransaction();
fragTransaction.detach(currentFragment);
fragTransaction.attach(currentFragment);
fragTransaction.commit();}
}
I am using this:
if($("#element").length > 0){
//the element exists in the page, you can do the rest....
}
Its very simple and easy to find an element.
There's no particular single naming convention, but I've seen that for private members.
To add to the good answer by @Tomalak:
Here are some unmentioned and important differences:
xsl:apply-templates
is much richer and deeper than xsl:call-templates
and even from xsl:for-each
, simply because we don't know what code will be applied on the nodes of
the selection -- in the general case this code will be different for
different nodes of the node-list.
The code that will be applied
can be written way after the xsl:apply template
s was written and by
people that do not know the original author.
The FXSL library's implementation of higher-order functions (HOF) in XSLT wouldn't be possible if XSLT didn't have the <xsl:apply-templates>
instruction.
Summary: Templates and the <xsl:apply-templates>
instruction is how XSLT implements and deals with polymorphism.
Reference: See this whole thread: http://www.biglist.com/lists/lists.mulberrytech.com/xsl-list/archives/200411/msg00546.html
This should work as well.
#include <ctype.h>
#include <string.h>
template<typename T = unsigned int>
T Hex2Int(const char* const Hexstr, bool* Overflow)
{
if (!Hexstr)
return false;
if (Overflow)
*Overflow = false;
auto between = [](char val, char c1, char c2) { return val >= c1 && val <= c2; };
size_t len = strlen(Hexstr);
T result = 0;
for (size_t i = 0, offset = sizeof(T) << 3; i < len && (int)offset > 0; i++)
{
if (between(Hexstr[i], '0', '9'))
result = result << 4 ^ Hexstr[i] - '0';
else if (between(tolower(Hexstr[i]), 'a', 'f'))
result = result << 4 ^ tolower(Hexstr[i]) - ('a' - 10); // Remove the decimal part;
offset -= 4;
}
if (((len + ((len % 2) != 0)) << 2) > (sizeof(T) << 3) && Overflow)
*Overflow = true;
return result;
}
The 'Overflow' parameter is optional, so you can leave it NULL.
Example:
auto result = Hex2Int("C0ffee", NULL);
auto result2 = Hex2Int<long>("DeadC0ffe", NULL);
Other users commenting that the Content-Type
is plain/text
when encoding. You have to set the Content-Type
first w.Header().Set
, then the HTTP response code w.WriteHeader
.
If you call w.WriteHeader
first then call w.Header().Set
after you will get plain/text
.
An example handler might look like this;
func SomeHandler(w http.ResponseWriter, r *http.Request) {
data := SomeStruct{}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(data)
}
Not as concrete as the answer of Artefacto, but based in his suggestion of using array_slice(), I wrote the next function:
function arrayInsert($target, $byKey, $byOffset, $valuesToInsert, $afterKey) {
if (isset($byKey)) {
if (is_numeric($byKey)) $byKey = (int)floor($byKey);
$offset = 0;
foreach ($target as $key => $value) {
if ($key === $byKey) break;
$offset++;
}
if ($afterKey) $offset++;
} else {
$offset = $byOffset;
}
$targetLength = count($target);
$targetA = array_slice($target, 0, $offset, true);
$targetB = array_slice($target, $offset, $targetLength, true);
return array_merge($targetA, $valuesToInsert, $targetB);
}
Features:
Usage examples:
$target = [
'banana' => 12,
'potatoe' => 6,
'watermelon' => 8,
'apple' => 7,
2 => 21,
'pear' => 6
];
// Values must be nested in an array
$insertValues = [
'orange' => 0,
'lemon' => 3,
3
];
// By key
// Third parameter is not applicable
// Insert after 2 (before 'pear')
var_dump(arrayInsert($target, 2, null, $valuesToInsert, true));
// Insert before 'watermelon'
var_dump(arrayInsert($target, 'watermelon', null, $valuesToInsert, false));
// By offset
// Second and last parameter are not applicable
// Insert in position 2 (zero based i.e. before 'watermelon')
var_dump(arrayInsert($target, null, 2, $valuesToInsert, null));
In Typescript, one doesn't necessarily have to follow the new instance()
Singleton methodology. An imported, constructor-less static class can work equally as well.
Consider:
export class YourSingleton {
public static foo:bar;
public static initialise(_initVars:any):void {
YourSingleton.foo = _initvars.foo;
}
public static doThing():bar {
return YourSingleton.foo
}
}
You can import the class and refer to YourSingleton.doThing()
in any other class. But remember, because this is a static class, it has no constructor so I usually use an intialise()
method that is called from a class that imports the Singleton:
import {YourSingleton} from 'singleton.ts';
YourSingleton.initialise(params);
let _result:bar = YourSingleton.doThing();
Don't forget that in a static class, every method and variable needs to also be static so instead of this
you would use the full class name YourSingleton
.
Sounds like the "...and I jump line by line..." part is wrong. Do you StepOver or StepIn and are you sure you don't accidentally miss the relevant call?
That said, debugging frameworks can be tedious for exactly this reason. To alleviate the problem, you can enable the "Enable frameworks debugging support" experiment. Happy debugging! :)
Run into the same issue when i switch to ubuntu from windows 10.. the following worked for me.. this after googling and trying numerous suggestions for 2 hours...
sudo apt-get install libpq-dev, then pip3 install psycopg2
I hope this helps someone who has encountered the same problem especially when switching for windows OS to linux(ubuntu).
Assuming that "a" and "b" are bean properties
rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"
You may look at JSF EL operators
This works well for coping entire records.
UPDATE your_table
SET new_field = sourse_field
I tried using the 'WHERE' statement above, I thought its correct since nobody corrected it but I was wrong; after some searches I found out that this is the right formula for the WHERE statement so the code becomes like this:
SELECT COUNT(id)
FROM stats
WHERE YEAR(record_date) = 2009
GROUP BY MONTH(record_date)
Of course it is!
Give them both an id
and set up the CSS accordingly:
#table1
{
CSS for table1
}
#table2
{
CSS for table2
}
I've developed a small vagrant-address plugin for that. It's simple, cross-platform, cross-provider, and does not require scripting.
Multiple ways to do this :
var str1:String="\(23)"
var str2:String=String(format:"%d",234)
I think that what you have to check is:
if the target EXE is correctly configured in the project settings ("command", in the debugging tab). Since all individual projects run when you start debugging it's well possible that only the debugging target for the "ALL" solution is missing, check which project is currently active (you can also select the debugger target by changing the active project).
dependencies (DLLs) are also located at the target debugee directory or can be loaded (you can use the "depends.exe" tool for checking dependencies of an executable or DLL).
To update TechDo's answer for SQL server 2012. You need to change: 'FROM ' + @TableName + ' (NOLOCK) '
to FROM ' + @TableName + 'WITH (NOLOCK) ' +
Other wise you will get the following error: Deprecated feature 'Table hint without WITH' is not supported in this version of SQL Server.
Below is the complete updated stored procedure:
CREATE PROC SearchAllTables
(
@SearchStr nvarchar(100)
)
AS
BEGIN
CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
WHILE @TableName IS NOT NULL
BEGIN
SET @ColumnName = ''
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(
OBJECT_ID(
QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
), 'IsMSShipped'
) = 0
)
WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)
IF @ColumnName IS NOT NULL
BEGIN
INSERT INTO #Results
EXEC
(
'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + 'WITH (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
)
END
END
END
SELECT ColumnName, ColumnValue FROM #Results
END
We have this problem and to solve
Create a script file called to-utf8.sh
#!/bin/bash
TO="UTF-8"; FILE=$1
FROM=$(file -i $FILE | cut -d'=' -f2)
if [[ $FROM = "binary" ]]; then
echo "Skipping binary $FILE..."
exit 0
fi
iconv -f $FROM -t $TO -o $FILE.tmp $FILE; ERROR=$?
if [[ $ERROR -eq 0 ]]; then
echo "Converting $FILE..."
mv -f $FILE.tmp $FILE
else
echo "Error on $FILE"
fi
Set the executable bit
chmod +x to-utf8.sh
Do a conversion
./to-utf8.sh MyFile.txt
If you want to convert all files under a folder, do
find /your/folder/here | xargs -n 1 ./to-utf8.sh
Hope it's help.
I was recently shown this website for liquid layouts using CSS. http://matthewjamestaylor.com/blog/perfect-multi-column-liquid-layouts (Take a look at the demo pages in the links below).
The author now provides an example for fixed width layouts. Check out; http://matthewjamestaylor.com/blog/how-to-convert-a-liquid-layout-to-fixed-width.
This provides the following example(s), http://matthewjamestaylor.com/blog/ultimate-2-column-left-menu-pixels.htm (for two column layout like you are after I think)
http://matthewjamestaylor.com/blog/fixed-width-or-liquid-layout.htm (for three column layout).
Sorry for so many links to this guys site, but I think it is an AWESOME resource.
Thanks to Mike's comment, I've re-read the doc and I've realised that my current user (i.e. userA that already has the create privilege) wasn't a direct/indirect member of the new owning role...
So the solution was quite simple - I've just done this grant:
grant userB to userA;
That's all folks ;-)
Another requirement is that the object has to be owned by user userA before altering it...
You can use this method also it will act like that
thadari=[1,2,3,4,5,6]
#Front Two(Left)
print(thadari[:2])
[1,2]
#Last Two(Right)# edited
print(thadari[-2:])
[5,6]
#mid
mid = len(thadari) //2
lefthalf = thadari[:mid]
[1,2,3]
righthalf = thadari[mid:]
[4,5,6]
Hope it will help
Even if fileno(FILE *)
may return a file descriptor, be VERY careful not to bypass stdio's buffer. If there is buffer data (either read or unflushed write), reads/writes from the file descriptor might give you unexpected results.
To answer one of the side questions, to convert a file descriptor to a FILE pointer, use fdopen(3)
To add a rounded border in any button the best way is to add the border-radius
property. I belive this class is better because you can add-it at any button size. If you set the height and widht you will need to create a "rouding" class to each button size.
.btn-circle {_x000D_
border-radius: 50%;_x000D_
}
_x000D_
<button class='btn-circle'>Click Me!</button>_x000D_
<button class='btn-circle'>?</button>
_x000D_
You can use the binary instead, I ran into the issue in dockerizing the application when Django tried to install it as part of its dependencies, to resolve that, I used this setup for requirements.txt where the binary is installed first and then django does not try to install it again: psycopg2-binary django gunicorn
Declare it as a decimal
which uses the int
variable and divide this by 100
int number = 700
decimal correctNumber = (decimal)number / 100;
Edit: Bala was faster with his reaction
The problem was the notify filters. The program was trying to open a file that was still copying. I removed all of the notify filters except for LastWrite.
private void watch()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = path;
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Filter = "*.*";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
Google calendar is the "native" calendar app. As far as I know, all phones come with a version of it installed, and the default SDK provides a version.
You might check out this tutorial for working with it.
Add it to the session, not to the request.
HttpSession session = request.getSession();
session.setAttribute("object", object);
Also, don't use scriptlets in the JSP. Use EL instead; to access object
all you need is ${object}
.
A primary feature of JSP technology version 2.0 is its support for an expression language (EL). An expression language makes it possible to easily access application data stored in JavaBeans components. For example, the JSP expression language allows a page author to access a bean using simple syntax such as
${name}
for a simple variable or${name.foo.bar}
for a nested property.
Given
Required
Solution
let asyncFn = (item) => {
return new Promise((resolve, reject) => {
setTimeout( () => {console.log(item); resolve(true)}, 1000 )
})
}
// asyncFn('a')
// .then(()=>{return async('b')})
// .then(()=>{return async('c')})
// .then(()=>{return async('d')})
let a = ['a','b','c','d']
a.reduce((previous, current, index, array) => {
return previous // initiates the promise chain
.then(()=>{return asyncFn(array[index])}) //adds .then() promise for each item
}, Promise.resolve())
Mutable default arguments don't generally do what you want. Instead, try this:
class Node:
def __init__(self, wordList=None, adjacencyList=None):
if wordList is None:
self.wordList = []
else:
self.wordList = wordList
if adjacencyList is None:
self.adjacencyList = []
else:
self.adjacencyList = adjacencyList
You can use mouse events to control like hover. For example, the following code is making visible when you hover that element.
var foo = document.getElementById("foo");
foo.addEventListener('mouseover',function(){
foo.style.display="block";
})
foo.addEventListener('mouseleave',function(){
foo.style.display="none";
})
For those who will need to remove product key from Visual Studio 2015:
HKCR\Licenses\4D8CFBCB-2F6A-4AD2-BABF-10E28F6F2C8F
That's it, now you can change the product key if necessary.
"Just to hide" you can:
Change the output type from Console Application to Windows Application,
And Instead of Console.Readline/key
you can use new ManualResetEvent(false).WaitOne()
at the end to keep the app running.
The solution below uses a double loop to add data to the bottom of a 2x2 array in the Case 3. The inner loop pushes selected elements' values into a new row array. The outerloop then pushes the new row array to the bottom of an existing array (see Newbie: Add values to two-dimensional array with for loops, Google Apps Script).
In this example, I created a function that extracts a section from an existing array. The extracted section can be a row (full or partial), a column (full or partial), or a 2x2 section of the existing array. A new blank array (newArr) is filled by pushing the relevant section from the existing array (arr) into the new array.
function arraySection(arr, r1, c1, rLength, cLength) {
rowMax = arr.length;
if(isNaN(rowMax)){rowMax = 1};
colMax = arr[0].length;
if(isNaN(colMax)){colMax = 1};
var r2 = r1 + rLength - 1;
var c2 = c1 + cLength - 1;
if ((r1< 0 || r1 > r2 || r1 > rowMax || (r1 | 0) != r1) || (r2 < 0 ||
r2 > rowMax || (r2 | 0) != r2)|| (c1< 0 || c1 > c2 || c1 > colMax ||
(c1 | 0) != c1) ||(c2 < 0 || c2 > colMax || (c2 | 0) != c2)){
throw new Error(
'arraySection: invalid input')
return;
};
var newArr = [];
// Case 1: extracted section is a column array,
// all elements are in the same column
if (c1 == c2){
for (var i = r1; i <= r2; i++){
// Logger.log("arr[i][c1] for i = " + i);
// Logger.log(arr[i][c1]);
newArr.push([arr[i][c1]]);
};
};
// Case 2: extracted section is a row array,
// all elements are in the same row
if (r1 == r2 && c1 != c2){
for (var j = c1; j <= c2; j++){
newArr.push(arr[r1][j]);
};
};
// Case 3: extracted section is a 2x2 section
if (r1 != r2 && c1 != c2){
for (var i = r1; i <= r2; i++) {
rowi = [];
for (var j = c1; j <= c2; j++) {
rowi.push(arr[i][j]);
}
newArr.push(rowi)
};
};
return(newArr);
};
I think it's the best solution of fibonacci using recursion.
#include<bits/stdc++.h>
typedef unsigned long long ull;
typedef long long ll;
ull FIBO[100005];
using namespace std;
ull fibo(ull n)
{
if(n==1||n==0)
return n;
if(FIBO[n]!=0)
return FIBO[n];
FIBO[n] = (fibo(n-1)+fibo(n-2));
return FIBO[n];
}
int main()
{
for(long long i =34;i<=60;i++)
cout<<fibo(i)<<" " ;
return 0;
}
This javascript will add absolute positioned div's with pagenumbers on the right bottom corner and works in all browsers.
A4 height = 297mm = 1123px(96dpi)
<html>
<head>
<style type="text/css">
@page {
size: A4;
margin: 0;
}
body {
margin: 0;
}
</style>
</head>
<body>
<script type="text/javascript">
window.onload = addPageNumbers;
function addPageNumbers() {
var totalPages = Math.ceil(document.body.scrollHeight / 1123); //842px A4 pageheight for 72dpi, 1123px A4 pageheight for 96dpi,
for (var i = 1; i <= totalPages; i++) {
var pageNumberDiv = document.createElement("div");
var pageNumber = document.createTextNode("Page " + i + " of " + totalPages);
pageNumberDiv.style.position = "absolute";
pageNumberDiv.style.top = "calc((" + i + " * (297mm - 0.5px)) - 40px)"; //297mm A4 pageheight; 0,5px unknown needed necessary correction value; additional wanted 40px margin from bottom(own element height included)
pageNumberDiv.style.height = "16px";
pageNumberDiv.appendChild(pageNumber);
document.body.insertBefore(pageNumberDiv, document.getElementById("content"));
pageNumberDiv.style.left = "calc(100% - (" + pageNumberDiv.offsetWidth + "px + 20px))";
}
}
</script>
<div id="content">
Lorem ipsum....
</div>
</body>
</html>
Although I've used the accepted answer in the past, it seems with the current Build Tools it is possible to do:
<dimen name="listAvatarWidthPercent">0.19</dimen>
I'm using Build Tools major version 29.
Tim's method works perfectly for my case - selecting the text in a div for both IE and FF after I replaced the following statement:
range.moveToElementText(text);
with the following:
range.moveToElementText(el);
The text in the div is selected by clicking it with the following jQuery function:
$(function () {
$("#divFoo").click(function () {
selectElementText(document.getElementById("divFoo"));
})
});
Swift 3 | Xcode 10
If you want to make all tab bar items the same color (selected & unselected)...
Step 1
Make sure your image assets are setup to Render As = Template Image. This allows them to inherit color.
Step 2
Use the storyboard editor to change your tab bar settings as follows:
Step 3
Steps 1 & 2 will change the color for the selected icon. If you still want to change the color of the unselected items, you need to do it in code. I haven't found a way to do it via the storyboard editor.
Create a custom tab bar controller class...
// TabBarController.swift
class TabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
// make unselected icons white
self.tabBar.unselectedItemTintColor = UIColor.white
}
}
... and assign the custom class to your tab bar scene controller.
If you figure out how to change the unselected icon color via the storyboard editor please let me know. Thanks!
Nowadays, it is the most efficient and comfortable to use lubridate and dplyr libraries.
lubridate
contains a number of functions that make parsing dates into POSIXct
or Date
objects easy. Here we use dmy
which automatically parses dates in Day, Month, Year
formats. Once your data is in a date format, you can sort it with dplyr::arrange
(or any other ordering function) as desired:
d$V3 <- lubridate::dmy(d$V3)
dplyr::arrange(d, V3)
It is XOR operator. It is use to do bit operations on numbers. It has the behavior such that when you do a xor operation on same bits say 0 XOR 0 / 1 XOR 1 the result is 0. But if any of the bits is different then result is 1. So when you did 5^3 then you can look at these numbers 5, 6 in their binary forms and thus the expression becomes (101) XOR (110) which gives the result (011) whose decimal representation is 3.
FWIW be very careful with storing something like a userid in a cookie unencrypted. Doing this makes your site very prone to cookie poisoning where users can easily impersonate another user. If you are considering something like this I would highly recommend using the forms authentication cookie directly.
bool persist = true;
var cookie = FormsAuthentication.GetAuthCookie(loginUser.ContactId, persist);
cookie.Expires = DateTime.Now.AddMonths(3);
var ticket = FormsAuthentication.Decrypt(cookie.Value);
var userData = "store any string values you want inside the ticket
extra than user id that will be encrypted"
var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name,
ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userData);
cookie.Value = FormsAuthentication.Encrypt(newTicket);
Response.Cookies.Add(cookie);
Then you can read this at any time from an ASP.NET page by doing
string userId = null;
if (this.Context.User.Identity.IsAuthenticated)
{
userId = this.Context.User.Identity.Name;
}
If you ignore the characteristics of both languages, how do you define "SPEED"? Which features should be in your benchmark and which do you want to omit?
For example:
Conclusion: Your question has no answer because it isn't defined what you want. Even if you made it more clear, the question will probably become academic since you will measure something that doesn't count in real life. For all of my projects, both Java and Python have always been fast enough. Of course, I would prefer one language over the other for a specific problem in a certain context.
You can use Mockito.isA()
for that:
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.verify;
verify(bar).doStuff(isA(Foo[].class));
http://site.mockito.org/mockito/docs/current/org/mockito/Matchers.html#isA(java.lang.Class)
In Android Studio resolved it by
ISO-8859-1
UTF-8
and the same case to Default encoding for properties files.@echo off
set countfiles=10
:loop
set /a countfiles -= 1
echo hi
if %countfiles% GTR 0 goto loop
pause
on the first "set countfiles" the 10 you see is the amount it will loop the echo hi is the thing you want to loop
...i'm 5 years late
You could use a regular expression replace:
str = str.replace(/ +(?= )/g,'');
Credit: The above regex was taken from Regex to replace multiple spaces with a single space
This is a warning for usual. You can either disable it by
#pragma warning(disable:4996)
or simply use fopen_s like Microsoft has intended.
But be sure to use the pragma before other headers.
Please note that PrimeFaces supports the standard JSF 2.0+ keywords:
@this
Current component.@all
Whole view.@form
Closest ancestor form of current component.@none
No component.and the standard JSF 2.3+ keywords:
@child(n)
nth child.@composite
Closest composite component ancestor.@id(id)
Used to search components by their id ignoring the component tree structure and naming containers.@namingcontainer
Closest ancestor naming container of current component.@parent
Parent of the current component.@previous
Previous sibling.@next
Next sibling.@root
UIViewRoot instance of the view, can be used to start searching from the root instead the current component.But, it also comes with some PrimeFaces specific keywords:
@row(n)
nth row.@widgetVar(name)
Component with given widgetVar.And you can even use something called "PrimeFaces Selectors" which allows you to use jQuery Selector API. For example to process all inputs in a element with the CSS class myClass
:
process="@(.myClass :input)"
See:
I have no idea what linux distribution "ubuntu centOS" is. Ubuntu and CentOS are two different distributions.
To answer the question in the header: To install make in ubuntu you have to install build-essentials
sudo apt-get install build-essential
one-to-many has parent class contains n number of childrens so it is a collection mapping.
many-to-one has n number of childrens contains one parent so it is a object mapping
In addition to the accepted answer you can use this if you want to group by multiple columns:
<ul ng-repeat="(key, value) in players | groupBy: '[team,name]'">
You can have just one ng-view
.
You can change its content in several ways: ng-include
, ng-switch
or mapping different controllers and templates through the routeProvider.
As pointed out by others, Python 3's int
does not have a maximum size, but if you just need something that's guaranteed to be higher than any other int
value, then you can use the float value for Infinity, which you can get with float("inf")
.
System.currentTimeMillis()
does give you the number of milliseconds since January 1, 1970 00:00:00 UTC. The reason you see local times might be because you convert a Date
instance to a string before using it. You can use DateFormat
s to convert Date
s to String
s in any timezone:
DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("gmt"));
String gmtTime = df.format(new Date());
Shared libraries are .so (or in Windows .dll, or in OS X .dylib) files. All the code relating to the library is in this file, and it is referenced by programs using it at run-time. A program using a shared library only makes reference to the code that it uses in the shared library.
Static libraries are .a (or in Windows .lib) files. All the code relating to the library is in this file, and it is directly linked into the program at compile time. A program using a static library takes copies of the code that it uses from the static library and makes it part of the program. [Windows also has .lib files which are used to reference .dll files, but they act the same way as the first one].
There are advantages and disadvantages in each method:
Shared libraries reduce the amount of code that is duplicated in each program that makes use of the library, keeping the binaries small. It also allows you to replace the shared object with one that is functionally equivalent, but may have added performance benefits without needing to recompile the program that makes use of it. Shared libraries will, however have a small additional cost for the execution of the functions as well as a run-time loading cost as all the symbols in the library need to be connected to the things they use. Additionally, shared libraries can be loaded into an application at run-time, which is the general mechanism for implementing binary plug-in systems.
Static libraries increase the overall size of the binary, but it means that you don't need to carry along a copy of the library that is being used. As the code is connected at compile time there are not any additional run-time loading costs. The code is simply there.
Personally, I prefer shared libraries, but use static libraries when needing to ensure that the binary does not have many external dependencies that may be difficult to meet, such as specific versions of the C++ standard library or specific versions of the Boost C++ library.
You could use a List<T>
and when T
is a value type it will be allocated in contiguous memory which would not be the case if T
is a reference type.
Example:
List<int> integers = new List<int>();
integers.Add(1);
integers.Add(4);
integers.Add(7);
int someElement = integers[1];
You need to update currentTime video element and then draw the frame in canvas. Don't init play() event on the video.
You can also use for ex. this plugin https://github.com/tstabla/stVideo
For me when I created a file and saved it as python file, I was getting this error during importing. I had to create a filename with the type ".py" , like filename.py and then save it as a python file. post trying to import the file worked for me.
None of the examples above create 8-bit (8bpp) bitmap images. Some software, such as image processing, only supports 8bpp. Unfortunately the MS .NET libraries do not have a solution. The PixelFormat.Format8bppIndexed format looks promising but after a lot of attempts I couldn't get it working.
To create a true 8-bit bitmap file you need to create the proper headers. Ultimately I found the Grayscale library solution for creating 8-bit bitmap (BMP) files. The code is very simple:
Image image = Image.FromFile("c:/path/to/image.jpg");
GrayBMP_File.CreateGrayBitmapFile(image, "c:/path/to/8bpp/image.bmp");
The code for this project is far from pretty but it works, with one little simple-to-fix problem. The author hard-coded the image resolution to 10x10. Image processing programs do not like this. The fix is open GrayBMP_File.cs (yeah, funky file naming, I know) and replace lines 50 and 51 with the code below. The example sets the resolution to 200x200 but you should change it to the proper number.
int resX = 200;
int resY = 200;
// horizontal resolution
Copy_to_Index(DIB_header, BitConverter.GetBytes(resX * 100), 24);
// vertical resolution
Copy_to_Index(DIB_header, BitConverter.GetBytes(resY * 100), 28);
Possibly:
select lpad(column, 8, 0) from table;
Edited in response to question from mylesg, in comments below:
ok, seems to make the change on the query- but how do I make it stick (change it) permanently in the table? I tried an UPDATE instead of SELECT
I'm assuming that you used a query similar to:
UPDATE table SET columnName=lpad(nums,8,0);
If that was successful, but the table's values are still without leading-zeroes, then I'd suggest you probably set the column as a numeric type? If that's the case then you'd need to alter the table so that the column is of a text/varchar() type in order to preserve the leading zeroes:
First:
ALTER TABLE `table` CHANGE `numberColumn` `numberColumn` CHAR(8);
Second, run the update:
UPDATE table SET `numberColumn`=LPAD(`numberColum`, 8, '0');
This should, then, preserve the leading-zeroes; the down-side is that the column is no longer strictly of a numeric type; so you may have to enforce more strict validation (depending on your use-case) to ensure that non-numerals aren't entered into that column.
References:
Use window.URL
:
> s = 'http://www.example.com/index.html?1111342=Adam%20Franco&348572=Bob%20Jones'
> u = new URL(s)
> Array.from(u.searchParams.entries())
[["1111342", "Adam Franco"], ["348572", "Bob Jones"]]
Something like this might work for you:
"UPDATE myTable SET ... ;
UPDATE myTable SET ... ;
UPDATE myTable SET ... ;
UPDATE myTable SET ... ;"
If any of the posX or posY values are the same, then they could be combined into one query
UPDATE myTable SET posX='39' WHERE id IN('2','3','40');
@RequestParam
annotated parameters get linked to specific Servlet request parameters. Parameter values are converted to the declared method argument type.
This annotation indicates that a method parameter should be bound to a web request parameter.
For example Angular request for Spring RequestParam(s) would look like that:
$http.post('http://localhost:7777/scan/l/register?username="Johny"&password="123123"&auth=true')
.success(function (data, status, headers, config) {
...
})
Endpoint with RequestParam:
@RequestMapping(method = RequestMethod.POST, value = "/register")
public Map<String, String> register(Model uiModel,
@RequestParam String username,
@RequestParam String password,
@RequestParam boolean auth,
HttpServletRequest httpServletRequest) {...
@RequestBody
annotated parameters get linked to the HTTP request body. Parameter values are converted to the declared method argument type using HttpMessageConverters.
This annotation indicates a method parameter should be bound to the body of the web request.
For example Angular request for Spring RequestBody would look like that:
$scope.user = {
username: "foo",
auth: true,
password: "bar"
};
$http.post('http://localhost:7777/scan/l/register', $scope.user).
success(function (data, status, headers, config) {
...
})
Endpoint with RequestBody:
@RequestMapping(method = RequestMethod.POST, produces = "application/json",
value = "/register")
public Map<String, String> register(Model uiModel,
@RequestBody User user,
HttpServletRequest httpServletRequest) {...
Hope this helps.
ALTER PROCEDURE [dbo].[spConvertir_CampoACadena]( @nomb_tabla varchar(30),
@campo_tabla varchar(30),
@delimitador varchar(5),
@respuesta varchar(max) OUTPUT
)
AS
DECLARE @query varchar(1000),
@cadena varchar(500)
BEGIN
SET @query = 'SELECT @cadena = COALESCE(@cadena + '''+ @delimitador +''', '+ '''''' +') + '+ @campo_tabla + ' FROM '+@nomb_tabla
--select @query
EXEC(@query)
SET @respuesta = @cadena
END
...for now
If you need async: false
in your ajax, you should use success
instead of .done
. Else you better to use .done
.
This is from jQuery official site:
As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done().
jQlite (angular's "jQuery" port) doesn't support lookup by classes.
One solution would be to include jQuery in your app.
Another is using QuerySelector
or QuerySelectorAll
:
link: function(scope, element, attrs) {
console.log(element[0].querySelector('.list-scrollable'))
}
We use the first item in the element
array, which is the HTML element. element.eq(0)
would yield the same.
Here are some easy way to get you up and running with the XlsxWriter module.The first step is to install the XlsxWriter module.The pip installer is the preferred method for installing Python modules from PyPI, the Python Package Index:
sudo pip install xlsxwriter
Note
Windows users can omit sudo at the start of the command.
For Mac Users
I am using Mac and I was facing same problem while I was trying to push a project from Android Studio. The reason for that other user had previously logged into Github and his credentials were saved in Keychain Access.
You need to remove those credentials from Keychain Access and then try to push.
Hope it help to Mac users.
I'm currently experimenting with canvas and pixels... I'm finding this logic works out for me better.
add to offset the 'tint' value
var grey = (r + g + b) / 3;
var grey2 = (new_r + new_g + new_b) / 3;
var dr = grey - grey2 * 1;
var dg = grey - grey2 * 1
var db = grey - grey2 * 1;
tint_r = new_r + dr;
tint_g = new_g + dg;
tint_b = new_b _ db;
or something like that...
Maybe using Where() before First() can help you, as my problem has been solved in this case.
var documentRow = _dsACL.Documents.Where(o => o.ID == id).FirstOrDefault();
If your app is in background, Firebase will not trigger onMessageReceived(). Why.....? I have no idea. In this situation, I do not see any point in implementing FirebaseMessagingService.
According to docs, if you want to process background message arrival, you have to send 'click_action' with your message. But it is not possible if you send message from Firebase console, only via Firebase API. It means you will have to build your own "console" in order to enable marketing people to use it. So, this makes Firebase console also quite useless!
There is really good, promising, idea behind this new tool, but executed badly.
I suppose we will have to wait for new versions and improvements/fixes!
Bash job control involves multiple processes, not multiple threads.
You can execute a command in background with the &
suffix.
You can wait for completion of a background command with the wait
command.
You can execute multiple commands in parallel by separating them with |
. This provides also a synchronization mechanism, since stdout of a command at left of |
is connected to stdin of command at right.
I'm using the following method based on @Watki02's answer:
That way you can keep your visual studio instance as your own user whilst debugging from the other.
You may want to look at the Simple XML Serialization project. It is the closest thing I've found to the System.Xml.Serialization in .Net.
First of all, thank you all for your inputs. I tweak my Query - 1
and got my desired result. Gordon Linoff is right, PRINT
was messing up my query so I modified it as following:
Modified Query - 1:
SET ROWCOUNT 5
WHILE (1 = 1)
BEGIN
BEGIN TRANSACTION
UPDATE TableName
SET Value = 'abc1'
WHERE Parameter1 = 'abc' AND Parameter2 = 123
IF @@ROWCOUNT = 0
BEGIN
COMMIT TRANSACTION
BREAK
END
COMMIT TRANSACTION
END
SET ROWCOUNT 0
Output:
(5 row(s) affected)
(5 row(s) affected)
(4 row(s) affected)
(0 row(s) affected)
Redirect the output to DEVNULL:
import os
import subprocess
FNULL = open(os.devnull, 'w')
retcode = subprocess.call(['echo', 'foo'],
stdout=FNULL,
stderr=subprocess.STDOUT)
It is effectively the same as running this shell command:
retcode = os.system("echo 'foo' &> /dev/null")
Update: This answer applies to the original question relating to python 2.7. As of python >= 3.3 an official subprocess.DEVNULL
symbol was added.
retcode = subprocess.call(['echo', 'foo'],
stdout=subprocess.DEVNULL,
stderr=subprocess.STDOUT)
If you want the overflow to wrap: flex-flow: row wrap
(function($) {
var triggers = [];
$.fn.floatingFixed = function(options) {
options = $.extend({}, $.floatingFixed.defaults, options);
var r = $(this).each(function() {
var $this = $(this), pos = $this.position();
pos.position = $this.css("position");
$this.data("floatingFixedOrig", pos);
$this.data("floatingFixedOptions", options);
triggers.push($this);
});
windowScroll();
return r;
};
$.floatingFixed = $.fn.floatingFixed;
$.floatingFixed.defaults = {
padding: 0
};
var $window = $(window);
var windowScroll = function() {
if(triggers.length === 0) { return; }
var scrollY = $window.scrollTop();
for(var i = 0; i < triggers.length; i++) {
var t = triggers[i], opt = t.data("floatingFixedOptions");
if(!t.data("isFloating")) {
var off = t.offset();
t.data("floatingFixedTop", off.top);
t.data("floatingFixedLeft", off.left);
}
var top = top = t.data("floatingFixedTop");
if(top < scrollY + opt.padding && !t.data("isFloating")) {
t.css({position: 'fixed', top: opt.padding, left: t.data("floatingFixedLeft"), width: t.width() }).data("isFloating", true);
} else if(top >= scrollY + opt.padding && t.data("isFloating")) {
var pos = t.data("floatingFixedOrig");
t.css(pos).data("isFloating", false);
}
}
};
$window.scroll(windowScroll).resize(windowScroll);
})(jQuery);
and then make any div as floating fixed by calling
$('#id of the div').floatingFixed();
Good list. The Angry Ninjas Starter Kit will have a Cocos2d-X update soon.
It means you don't have privileges to create the trigger with root@localhost user..
try removing definer from the trigger command:
CREATE DEFINER = root
@localhost
FUNCTION fnc_calcWalkedDistance
If you don't want indention in your list and also don't care about or don't want bullets, there is the CSS-free option of using a "definition list" (HTML 4.01) or "description list" (HTML 5). Use only the non-indenting definition <dt>
tags, but not the indenting description <dd>
tags, neither of which produces a bullet.
<dl>
<dt>Item 1</dt>
<dt>Item 2</dt>
<dt>Item 3</dt>
</dl>
The output looks like this:
Item 1
Item 2
Item 3
you can copy the export file for e.g dump.sql using docker cp into the container and then import the db. if you need full instructions, let me know and I will provide
What you need is the svn 'export' command. With this you can put a file or entire directory tree in the state of another revision in another branch.
So something like
rm file #without 'svn' in front!
svn export myrepo/path/to/file@<revision> .
svn commit
RenderPartial()
is a void method that writes to the response stream. A void method, in C#, needs a ;
and hence must be enclosed by { }
.
Partial()
is a method that returns an MvcHtmlString. In Razor, You can call a property or a method that returns such a string with just a @
prefix to distinguish it from plain HTML you have on the page.
I'll try and break it down (example from documention)
/*
* The cellForRowAtIndexPath takes for argument the tableView (so if the same object
* is delegate for several tableViews it can identify which one is asking for a cell),
* and an indexPath which determines which row and section the cell is returned for.
*/
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
/*
* This is an important bit, it asks the table view if it has any available cells
* already created which it is not using (if they are offScreen), so that it can
* reuse them (saving the time of alloc/init/load from xib a new cell ).
* The identifier is there to differentiate between different types of cells
* (you can display different types of cells in the same table view)
*/
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];
/*
* If the cell is nil it means no cell was available for reuse and that we should
* create a new one.
*/
if (cell == nil) {
/*
* Actually create a new cell (with an identifier so that it can be dequeued).
*/
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
/*
* Now that we have a cell we can configure it to display the data corresponding to
* this row/section
*/
NSDictionary *item = (NSDictionary *)[self.content objectAtIndex:indexPath.row];
cell.textLabel.text = [item objectForKey:@"mainTitleKey"];
cell.detailTextLabel.text = [item objectForKey:@"secondaryTitleKey"];
NSString *path = [[NSBundle mainBundle] pathForResource:[item objectForKey:@"imageKey"] ofType:@"png"];
UIImage *theImage = [UIImage imageWithContentsOfFile:path];
cell.imageView.image = theImage;
/* Now that the cell is configured we return it to the table view so that it can display it */
return cell;
}
This is a DataSource
method so it will be called on whichever object has declared itself as the DataSource
of the UITableView
. It is called when the table view actually needs to display the cell onscreen, based on the number of rows and sections (which you specify in other DataSource methods).
You can achieve this with the background-size
property, which is now supported by most browsers.
To scale the background image to fit inside the div:
background-size: contain;
To scale the background image to cover the whole div:
background-size: cover;
There also exists a filter for IE 5.5+ support, as well as vendor prefixes for some older browsers.
As an additional note, there is no need for the for loop because of R's vectorization.
This:
P <- 243.51
t <- 31 / 365
n <- 365
for (r in seq(0.15, 0.22, by = 0.01))
A <- P * ((1 + (r/ n))^ (n * t))
interest <- A - P
}
is equivalent to:
P <- 243.51
t <- 31 / 365
n <- 365
r <- seq(0.15, 0.22, by = 0.01)
A <- P * ((1 + (r/ n))^ (n * t))
interest <- A - P
Because r
is a vector, the expression above containing it is performed for all values of the vector.
Anyone can define "token_type" as an OAuth 2.0 extension, but currently "bearer" token type is the most common one.
https://tools.ietf.org/html/rfc6750
Basically that's what Facebook is using. Their implementation is a bit behind from the latest spec though.
If you want to be more secure than Facebook (or as secure as OAuth 1.0 which has "signature"), you can use "mac" token type.
However, it will be hard way since the mac spec is still changing rapidly.
Try using the code after you active the sheet:
Dim J as integer
J = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row
If you use Cells.SpecialCells(xlCellTypeLastCell).Row
only, the problem will be that the xlCellTypeLastCell
information will not be updated unless one do a "Save file" action. But use UsedRange
will always update the information in realtime.
There is an assertNotEquals
in JUnit 4.11: https://github.com/junit-team/junit/blob/master/doc/ReleaseNotes4.11.md#improvements-to-assert-and-assume
import static org.junit.Assert.assertNotEquals;
This should also work:
ArrayList<String> orig = new ArrayList<String>();
ArrayList<String> copy = (ArrayList<String>) orig.clone()
I'm not actually suggesting that you do this, as the UNIQUE
index as suggested by Piskvor and others is a far better way to do it, but you can actually do what you were attempting:
CREATE TABLE `table_listnames` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(255) NOT NULL,
`address` varchar(255) NOT NULL,
`tele` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
Insert a record:
INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'Rupert', 'Somewhere', '022') AS tmp
WHERE NOT EXISTS (
SELECT name FROM table_listnames WHERE name = 'Rupert'
) LIMIT 1;
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0
SELECT * FROM `table_listnames`;
+----+--------+-----------+------+
| id | name | address | tele |
+----+--------+-----------+------+
| 1 | Rupert | Somewhere | 022 |
+----+--------+-----------+------+
Try to insert the same record again:
INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'Rupert', 'Somewhere', '022') AS tmp
WHERE NOT EXISTS (
SELECT name FROM table_listnames WHERE name = 'Rupert'
) LIMIT 1;
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
+----+--------+-----------+------+
| id | name | address | tele |
+----+--------+-----------+------+
| 1 | Rupert | Somewhere | 022 |
+----+--------+-----------+------+
Insert a different record:
INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'John', 'Doe', '022') AS tmp
WHERE NOT EXISTS (
SELECT name FROM table_listnames WHERE name = 'John'
) LIMIT 1;
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0
SELECT * FROM `table_listnames`;
+----+--------+-----------+------+
| id | name | address | tele |
+----+--------+-----------+------+
| 1 | Rupert | Somewhere | 022 |
| 2 | John | Doe | 022 |
+----+--------+-----------+------+
And so on...
Update:
To prevent #1060 - Duplicate column name
error in case two values may equal, you must name the columns of the inner SELECT:
INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'Unknown' AS name, 'Unknown' AS address, '022' AS tele) AS tmp
WHERE NOT EXISTS (
SELECT name FROM table_listnames WHERE name = 'Rupert'
) LIMIT 1;
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0
SELECT * FROM `table_listnames`;
+----+---------+-----------+------+
| id | name | address | tele |
+----+---------+-----------+------+
| 1 | Rupert | Somewhere | 022 |
| 2 | John | Doe | 022 |
| 3 | Unknown | Unknown | 022 |
+----+---------+-----------+------+
This can be done very easily using a PostBackUrl and a regular button.
<asp:Button ID="Button1" runat="server" Text="Name of web location" PostBackUrl="web address" />
Swift 4 :
Store
UserDefaults.standard.set(object/value, forKey: "key_name")
Retrive
var returnValue: [datatype]? = UserDefaults.standard.object(forKey: "key_name") as? [datatype]
Remove
UserDefaults.standard.removeObject(forKey:"key_name")
For the length of 6, recursiveness doesn't matter a lot.
function random(len) {_x000D_
let result = Math.floor(Math.random() * Math.pow(10, len));_x000D_
_x000D_
return (result.toString().length < len) ? random(len) : result;_x000D_
}_x000D_
_x000D_
console.log(random(6));
_x000D_
A bit late to the party, but I had to solve this for myself recently, though slightly different, it might still help someone with similar circumstances to my own.
I'm using xampp on a laptop to run a purely local website app on windows. (A very specific environment I know). In this instance, I use a html link to a php file and run:
shell_exec('cd C:\path\to\file');
shell_exec('start .');
This opens a local Windows explorer window.
For me the problem was I had to use /usr/bin/php-cgi
command instead of just /usr/bin/php
php-cgi is the command run when accessed thru web browser.
php is the CLI command line command.
Not sure why php cli is not working, but running with php-cgi instead fixed the problem for me.
I encountered this error and it turned out the issue was FxCop was running against my project. I closed FxCop and then I could compile again.
Try going to "Manage Jenkins"->"Manage Users" go to the specific user, edit his/her configuration "My Views section" default view.
Try this. Works well in my Oracle 10g,
CREATE TABLE new_table
AS (SELECT * FROM old_table);
this works for me:
myTuple= tuple(myList)
sql="select fooid from foo where bar in "+str(myTuple)
cursor.execute(sql)
Update Use Eirik's solution using .live()
instead as it is a bit more robust.
Even though you wanted a solution that wasn't using jQuery, I thought I'd add one in for anyone finding this page via Google and looking for a jQuery-esque solution:
$(function() {
// Get all textareas that have a "maxlength" property.
$('textarea[maxlength]').each(function() {
// Store the jQuery object to be more efficient...
var $textarea = $(this);
// Store the maxlength and value of the field.
var maxlength = $textarea.attr('maxlength');
var val = $textarea.val();
// Trim the field if it has content over the maxlength.
$textarea.val(val.slice(0, maxlength));
// Bind the trimming behavior to the "keyup" event.
$textarea.bind('keyup', function() {
$textarea.val($textarea.val().slice(0, maxlength));
});
});
});
Hope that is useful to you Googlers out there...
If you really want to scale an image, do it, but you should resize it before using it. Resizing it at run time will just lose CPU cycles.
This is the category I'm using to scale an image :
UIImage+Extra.h
@interface UIImage (Extras)
- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize;
@end;
UIImage+Extra.m
@implementation UIImage (Extras)
- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize {
UIImage *sourceImage = self;
UIImage *newImage = nil;
CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;
CGFloat scaleFactor = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;
CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
if (!CGSizeEqualToSize(imageSize, targetSize)) {
CGFloat widthFactor = targetWidth / width;
CGFloat heightFactor = targetHeight / height;
if (widthFactor < heightFactor)
scaleFactor = widthFactor;
else
scaleFactor = heightFactor;
scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;
// center the image
if (widthFactor < heightFactor) {
thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
} else if (widthFactor > heightFactor) {
thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
}
}
// this is actually the interesting part:
UIGraphicsBeginImageContextWithOptions(targetSize, NO, 0);
CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width = scaledWidth;
thumbnailRect.size.height = scaledHeight;
[sourceImage drawInRect:thumbnailRect];
newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
if(newImage == nil) NSLog(@"could not scale image");
return newImage ;
}
@end
You can use it to the size you want. Like :
[self.itemImageButton setImage:[stretchImage imageByScalingProportionallyToSize:CGSizeMake(20,20)]];
Nice solution! Included in my library of auxiliary functions, now it looks like this:
Object.isDate = function(obj) {
/// <summary>
/// Determines if the passed object is an instance of Date.
/// </summary>
/// <param name="obj">The object to test.</param>
return Object.prototype.toString.call(obj) === '[object Date]';
}
Object.isValidDate = function(obj) {
/// <summary>
/// Determines if the passed object is a Date object, containing an actual date.
/// </summary>
/// <param name="obj">The object to test.</param>
return Object.isDate(obj) && !isNaN(obj.getTime());
}
Here is an example which might help someone:
Grid test = new Grid();
test.ColumnDefinitions.Add(new ColumnDefinition());
test.ColumnDefinitions.Add(new ColumnDefinition());
test.RowDefinitions.Add(new RowDefinition());
test.RowDefinitions.Add(new RowDefinition());
test.RowDefinitions.Add(new RowDefinition());
Label t1 = new Label();
t1.Content = "Test1";
Label t2 = new Label();
t2.Content = "Test2";
Label t3 = new Label();
t3.Content = "Test3";
Label t4 = new Label();
t4.Content = "Test4";
Label t5 = new Label();
t5.Content = "Test5";
Label t6 = new Label();
t6.Content = "Test6";
Grid.SetColumn(t1, 0);
Grid.SetRow(t1, 0);
test.Children.Add(t1);
Grid.SetColumn(t2, 1);
Grid.SetRow(t2, 0);
test.Children.Add(t2);
Grid.SetColumn(t3, 0);
Grid.SetRow(t3, 1);
test.Children.Add(t3);
Grid.SetColumn(t4, 1);
Grid.SetRow(t4, 1);
test.Children.Add(t4);
Grid.SetColumn(t5, 0);
Grid.SetRow(t5, 2);
test.Children.Add(t5);
Grid.SetColumn(t6, 1);
Grid.SetRow(t6, 2);
test.Children.Add(t6);
One option would be combining use of CASE..WHEN
statement is redundant within an aggregation for MySQL Database, and considering the needed query generation dynamically along with getting proper column title for the result set as in the following code block :
SET @sql = NULL;
SELECT GROUP_CONCAT(
CONCAT('SUM( `action` = ''', action, '''',pc0,' ) AS ',action,pc1)
)
INTO @sql
FROM
(
SELECT DISTINCT `action`,
IF(`pagecount` IS NULL,'',CONCAT('page',`pagecount`)) AS pc1,
IF(`pagecount` IS NULL,'',CONCAT(' AND `pagecount` = ', pagecount, '')) AS pc0
FROM `tab`
ORDER BY CONCAT(action,pc0)
) t;
SET @sql = CONCAT('SELECT company_name,',@sql,' FROM `tab` GROUP BY company_name');
SELECT @sql;
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
You need to have a 'static' folder setup (for css/js files) unless you specifically override it during Flask initialization. I am assuming you did not override it.
Your directory structure for css should be like:
/app
- app_runner.py
/services
- app.py
/templates
- mainpage.html
/static
/styles
- mainpage.css
Notice that your /styles directory should be under /static
Then, do this
<link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='styles/mainpage.css') }}">
Flask will now look for the css file under static/styles/mainpage.css
First rollback your previous migration
php artisan migrate:rollback
After that, you can modify your existing migration file (add new , rename or delete columns) then Re-Run your migration file
php artisan migrate
Jenkins: Multiple SCM - deprecated. GIT Plugin - doesn't work for multiple repos.
Scripting / pipeline as code - is the way to go.
In my case I didn't needed start adb.exe. I only started the BlueStacks before android studio.
After that when I press "Run" in android studio, bluestacks is detected as a new emulator.
Regards.
I ran into this same problem when I was converting my MVC 2 app to MVC 3 and just to give another (clean) solution to this problem I want to post what I did...
IEnumerable<SelectListItem> producers = new SelectList(Services.GetProducers(),
"ID", "Name", model.ProducerID);
GetProducers() simply returns an entity collection of Producers. P.S. The SqlFunctions.StringConvert didn't work for me.
One of the approaches may be like this:
1) Create a CSS file with name "style.css" and define an id selector in it:
#pane{ -fx-background-image: url("background_image.jpg"); -fx-background-repeat: stretch; -fx-background-size: 900 506; -fx-background-position: center center; -fx-effect: dropshadow(three-pass-box, black, 30, 0.5, 0, 0); }
2) Set the id of the most top control (or any control) in the scene with value defined in CSS and load this CSS file into the scene:
public class Test extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
StackPane root = new StackPane();
root.setId("pane");
Scene scene = new Scene(root, 300, 250);
scene.getStylesheets().addAll(this.getClass().getResource("style.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
}
}
You can also give an id to the control in a FXML file:
<StackPane id="pane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml" fx:controller="demo.Sample">
<children>
</children>
</StackPane>
For more info about JavaFX CSS Styling refer to this guide.
my approach works without a library and with cropped maps. Means it works with just parts from a Mercator image. Maybe it helps somebody: https://stackoverflow.com/a/10401734/730823
I solved the problem updating all packages from Android SDK Manager and also, I had to install Extras -> Android Support Repository
.
This should do the trick:
pw_bytes.decode("utf-8")
Just run
docker restart $(docker ps -q)
Update
For Docker 1.13.1
use docker restart $(docker ps -a -q)
as in answer lower.
Angular's own ng-Router takes URLs
into consideration while routing, UI-Router takes states
in addition to URLs.
States are bound to named, nested and parallel views, allowing you to powerfully manage your application's interface.
While in ng-router, you have to be very careful about URLs when providing links via <a href="">
tag, in UI-Router you have to only keep state
in mind. You provide links like <a ui-sref="">
. Note that even if you use <a href="">
in UI-Router, just like you would do in ng-router, it will still work.
So, even if you decide to change your URL some day, your state
will remain same and you need to change URL only at .config
.
While ngRouter can be used to make simple apps, UI-Router makes development much easier for complex apps. Here its wiki.
Unfortunately an ajax request gets the entire file, but you can filter the content once it's retrieved:
$.ajax({
url:href,
type:'GET',
success: function(data) {
var content = $('<div>').append(data).find('#content');
$('#content').html( content );
}
});
Note the use of a dummy element as find()
only works with descendants, and won't find root elements.
or let jQuery filter it for you:
$('#content').load(href + ' #IDofDivToFind');
I'm assuming this isn't a cross domain request, as that won't work, only pages on the same domain.
I think you are intended to contain ALL YOUR LOGIC under your if
statement. Basically:
' PRINTS EVERYTHING EXCEPT 4
For i = 0 To 10
' you want to say
' If i = 4 CONTINUE but VBScript has no continue
If i <> 4 Then ' just invert the logic
WSH.Echo( i )
End If
Next
This can make the code a bit longer, but some people don't like break
or continue
anyway.
One thing that is really important to understand considering you have an XML file as :
<customer id="100">
<Age>29</Age>
<NAME>mkyong</NAME>
</customer>
I am sorry to inform you but :
@XmlElement
public void setAge(int age) {
this.age = age;
}
will not help you, as it tries to look for "age" instead of "Age" element name from the XML.
I encourage you to manually specify the element name matching the one in the XML file :
@XmlElement(name="Age")
public void setAge(int age) {
this.age = age;
}
And if you have for example :
@XmlRootElement
@XmlAccessorType (XmlAccessType.FIELD)
public class Customer {
...
It means it will use java beans by default, and at this time if you specify that you must not set another
@XmlElement(name="NAME")
annotation above a setter method for an element <NAME>..</NAME>
it will fail saying that there cannot be two elements on one single variables.
I hope that it helps.
It seems that the most accurate (and seamless) method of adding the padding for iPhone X/8 using env()...
padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);
Here's a link describing this:
The easiest way to configure your system to use single ssh sessions by default with multiplexing.
This can be done by creating a folder for the sockets:
mkdir ~/.ssh/controlmasters
And then adding the following to your .ssh configuration:
Host *
ControlMaster auto
ControlPath ~/.ssh/controlmasters/%r@%h:%p.socket
ControlMaster auto
ControlPersist 10m
Now, you do not need to modify any of your code. This allows multiple calls to ssh and scp without creating multiple sessions, which is useful when there needs to be more interaction between your local and remote machines.
Thanks to @terminus's answer, http://www.cyberciti.biz/faq/linux-unix-osx-bsd-ssh-multiplexing-to-speed-up-ssh-connections/ and https://en.wikibooks.org/wiki/OpenSSH/Cookbook/Multiplexing.
Once you have got the words from the string it is easy. From Java 10 onwards you can try the following code:
import java.util.Arrays;
import java.util.stream.Collectors;
public class StringFrequencyMap {
public static void main(String... args) {
String[] wordArray = {"House", "House", "House", "Dog", "Dog", "Dog", "Dog"};
var freq = Arrays.stream(wordArray)
.collect(Collectors.groupingBy(x -> x, Collectors.counting()));
System.out.println(freq);
}
}
Output:
{House=3, Dog=4}
You probably need to do something like :
Paint red = new Paint();
red.setColor(android.graphics.Color.RED);
red.setStyle(Paint.Style.FILL);
And use this color for your path, instead of your ARGB. Make sure the last point of your path ends on the first one, it makes sense also.
Tell me if it works please !
If there is a null
in an array and you want to avoid it:
db.test.find({"contain" : {$ne :[] }}).pretty()
In C, character constant expressions such as '\n'
or 'a'
have type int
(thus sizeof '\n' == sizeof (int)
), whereas in C++ they have type char
.
The statement printf("%d", '\0');
should simply print 0; the type of the expression '\0'
is int
, and its value is 0.
The statement printf("%d", ch);
should print the integer encoding for the value in ch
(for ASCII, 'a'
== 97).
{JAVA_1_4_HOME}/bin/javacyou can try also...
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
<showDeprecation>true</showDeprecation>
<showWarnings>true</showWarnings>
<executable>{JAVA_HOME_1_7}/bin/javac</executable>
<fork>true</fork>
</configuration>
</plugin>
Let us make it simple if you're using Python 3
mydict = {'a':'apple','b':'boy','c':'cat'}
check = 'c' in mydict
if check:
print('c key is present')
If you need else condition
mydict = {'a':'apple','b':'boy','c':'cat'}
if 'c' in mydict:
print('key present')
else:
print('key not found')
For the dynamic key value, you can also handle through try-exception block
mydict = {'a':'apple','b':'boy','c':'cat'}
try:
print(mydict['c'])
except KeyError:
print('key value not found')mydict = {'a':'apple','b':'boy','c':'cat'}
I faced similar problem. I solved it without using onload handler.I was working on AngularJs project so i used $interval and $ timeout. U can also use setTimeout and setInterval.Here's the code:
var stopPolling;
var doIframePolling;
$scope.showIframe = true;
doIframePolling = $interval(function () {
if(document.getElementById('UrlIframe') && document.getElementById('UrlIframe').contentDocument.head && document.getElementById('UrlIframe').contentDocument.head.innerHTML != ''){
$interval.cancel(doIframePolling);
doIframePolling = undefined;
$timeout.cancel(stopPolling);
stopPolling = undefined;
$scope.showIframe = true;
}
},400);
stopPolling = $timeout(function () {
$interval.cancel(doIframePolling);
doIframePolling = undefined;
$timeout.cancel(stopPolling);
stopPolling = undefined;
$scope.showIframe = false;
},5000);
$scope.$on("$destroy",function() {
$timeout.cancel(stopPolling);
$interval.cancel(doIframePolling);
});
Every 0.4 Seconds keep checking the head of iFrame Document. I somthing is present.Loading was not stopped by CORS as CORS error shows blank page. If nothing is present after 5 seconds there was some error (Cors policy) etc.. Show suitable message.Thanks. I hope it solves your problem.
We experienced the SecurityError: The operation is insecure when a user disabled their cookies prior to visiting our site, any subsequent XHR requests trying to use the session would obviously fail and cause this error.
Just for the sake of completeness, appending values to a vector in a for loop is not really the philosophy in R. R works better by operating on vectors as a whole, as @BrodieG pointed out. See if your code can't be rewritten as:
ouput <- sapply(values, function(v) return(2*v))
Output will be a vector of return values. You can also use lapply
if values is a list instead of a vector.
Func - When you want a delegate for a function that may or may not take parameters and returns a value. The most common example would be Select from LINQ:
var result = someCollection.Select( x => new { x.Name, x.Address });
Action - When you want a delegate for a function that may or may not take parameters and does not return a value. I use these often for anonymous event handlers:
button1.Click += (sender, e) => { /* Do Some Work */ }
Predicate - When you want a specialized version of a Func that evaluates a value against a set of criteria and returns a boolean result (true for a match, false otherwise). Again, these are used in LINQ quite frequently for things like Where:
var filteredResults =
someCollection.Where(x => x.someCriteriaHolder == someCriteria);
I just double checked and it turns out that LINQ doesn't use Predicates. Not sure why they made that decision...but theoretically it is still a situation where a Predicate would fit.
I had an issue that even when I did overwrite "height" to "unset" or "initial", it behaved differently from when I removed the previous setting.
It turned out I needed to remove the min-height property too!
height: unset;
min-height: none
Edit: I tested on IE 7 and it doesn't recognize "unset", so "auto" works better".
Did you try RedirectView where you can provide the contextRelative parameter?
Found a nice solution by Laurent Bugnion, it can look something like this:
<UserControl xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:comment="Tag to add comments"
mc:Ignorable="d comment" d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Button Width="100"
comment:Width="example comment on Width, will be ignored......">
</Button>
</Grid>
</UserControl>
Here's the link: http://blog.galasoft.ch/posts/2010/02/quick-tip-commenting-out-properties-in-xaml/
A commenter on the link provided extra characters for the ignore prefix in lieu of highlighting:
mc:Ignorable=”ØignoreØ”
It is more appropriate to approach this problem with the mentality that a form will have a default action tied to one submit button, and then an alternative action bound to a plain button. The difference here is that whichever one goes under the submit will be the one used when a user submits the form by pressing enter, while the other one will only be fired when a user explicitly clicks on the button.
Anyhow, with that in mind, this should do it:
<form id='myform' action='jquery.php' method='GET'>
<input type='submit' id='btn1' value='Normal Submit'>
<input type='button' id='btn2' value='New Window'>
</form>
With this javascript:
var form = document.getElementById('myform');
form.onsubmit = function() {
form.target = '_self';
};
document.getElementById('btn2').onclick = function() {
form.target = '_blank';
form.submit();
}
Approaches that bind code to the submit button's click event will not work on IE.
Here is the combined Join/Linq approach I settled on after looking at the other answers and the issues addressed in a similar question (namely that Aggregate and Concatenate fail with 0 elements).
string Result = String.Join(",", split.Select(s => s.Name));
or (if s
is not a string)
string Result = String.Join(",", split.Select(s => s.ToString()));
StringBuilder
) to implementAnd of course Join takes care of the pesky final comma that sometimes sneaks into other approaches (for
, foreach
), which is why I was looking for a Linq solution in the first place.
Make your Activity like this.
public class MainActivity extends Activity {
WebView browser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// find the WebView by name in the main.xml of step 2
browser=(WebView)findViewById(R.id.wvwMain);
// Enable javascript
browser.getSettings().setJavaScriptEnabled(true);
// Set WebView client
browser.setWebChromeClient(new WebChromeClient());
browser.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
// Load the webpage
browser.loadUrl("http://google.com/");
}
}
I'm going to expand your question a bit and also include the compile function.
compile function - use for template DOM manipulation (i.e., manipulation of tElement = template element), hence manipulations that apply to all DOM clones of the template associated with the directive. (If you also need a link function (or pre and post link functions), and you defined a compile function, the compile function must return the link function(s) because the 'link'
attribute is ignored if the 'compile'
attribute is defined.)
link function - normally use for registering listener callbacks (i.e., $watch
expressions on the scope) as well as updating the DOM (i.e., manipulation of iElement = individual instance element). It is executed after the template has been cloned. E.g., inside an <li ng-repeat...>
, the link function is executed after the <li>
template (tElement) has been cloned (into an iElement) for that particular <li>
element. A $watch
allows a directive to be notified of scope property changes (a scope is associated with each instance), which allows the directive to render an updated instance value to the DOM.
controller function - must be used when another directive needs to interact with this directive. E.g., on the AngularJS home page, the pane directive needs to add itself to the scope maintained by the tabs directive, hence the tabs directive needs to define a controller method (think API) that the pane directive can access/call.
For a more in-depth explanation of the tabs and pane directives, and why the tabs directive creates a function on its controller using this
(rather than on $scope
), please see 'this' vs $scope in AngularJS controllers.
In general, you can put methods, $watches
, etc. into either the directive's controller or link function. The controller will run first, which sometimes matters (see this fiddle which logs when the ctrl and link functions run with two nested directives). As Josh mentioned in a comment, you may want to put scope-manipulation functions inside a controller just for consistency with the rest of the framework.
A little intro to dictionary
d={'a':'apple','b':'ball'}
d.keys() # displays all keys in list
['a','b']
d.values() # displays your values in list
['apple','ball']
d.items() # displays your pair tuple of key and value
[('a','apple'),('b','ball')
Print keys,values method one
for x in d.keys():
print x +" => " + d[x]
Another method
for key,value in d.items():
print key + " => " + value
You can get keys using iter
>>> list(iter(d))
['a', 'b']
You can get value of key of dictionary using get(key, [value])
:
d.get('a')
'apple'
If key is not present in dictionary,when default value given, will return value.
d.get('c', 'Cat')
'Cat'
This error occurred to me when I made changes to my Model and did not make migration for the changes to update the database.
If you have ever made changes to your model in Code First Migration Schema
Don't forget to add migration
add-migration UpdatesToModelProperites
The above command will read all the changes you have made in the model and will write it in the Up() and Down() methods.
Then simply update your database using the below command.
update-database
This what worked for me.
The most effective solution that I found is to define the parent element with display:flex
and align-items:center
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
.myclass{
display:flex;
align-items:center;
background-color:grey;
color:#fff;
height:50px;
}
</style>
</head>
<body>
<div class="myclass">
<input type="checkbox">
<label>do you love Ananas?
</label>
</div>
</body>
</html>
OUTPUT:
I have craeted a little script for read directory and write a console name new file (example: 'name.txt' ) and text into file.
const readline = require('readline');
const fs = require('fs');
const pathFile = fs.readdirSync('.');
const file = readline.createInterface({
input: process.stdin,
output: process.stdout
});
file.question('Insert name of your file? ', (f) => {
console.log('File is: ',f.toString().trim());
try{
file.question('Insert text of your file? ', (d) => {
console.log('Text is: ',d.toString().trim());
try {
if(f != ''){
if (fs.existsSync(f)) {
//file exists
console.log('file exist');
return file.close();
}else{
//save file
fs.writeFile(f, d, (err) => {
if (err) throw err;
console.log('The file has been saved!');
file.close();
});
}
}else{
//file empty
console.log('Not file is created!');
console.log(pathFile);
file.close();
}
} catch(err) {
console.error(err);
file.close();
}
});
}catch(err){
console.log(err);
file.close();
}
});