Hey I found a permanent solution that should work in every case!
For normal webdevelopment
<script type="text/javascript">
$("video").each(function(){jQuery(this).append('controlsList="nodownload"')});
</script>
HTML5 videos that has preload on false
$( document ).ready(function() {
$("video").each(function(){
$(this).attr('controlsList','nodownload');
$(this).load();
});
});
$ undevinded? --> Debug modus!
<script type="text/javascript">
jQuery("video").each(function(){jQuery(this).append('controlsList="nodownload"')});
</script>
HTML5 videos that has preload on false
jQuery( document ).ready(function() {
jQuery("video").each(function(){
jQuery(this).attr('controlsList','nodownload');
jQuery(this).load();
});
});
Let me know if it helped you out!
After trying all the solutions, none of them where working for me.
In my case I had the Android Studio and the adb was correctly working but the Android Studio was not capable to detect the adb. These was because I installed it with homebrew in another directory, not the /Users/$USER/Library/Android/sdk but Usr/Library blabla
Apparently AS needed to have it in his route /Users/$USER/Library/Android/sdk (same place as in preferences SDK installation route)
So I deleted all the adb from my computer (I installed several) and executed these terminal commands:
echo 'export ANDROID_HOME=/Users/$USER/Library/Android/sdk' >> ~/.bash_profile
echo 'export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools' >> ~/.bash_profile
source ~/.bash_profile
adb devices
Well, after that, still wasn't working, because for some reason the route for the adb was /Users/$USER/Library/Android/sdk/platform-tools/platform-tools (yes, repeated) so I just copied the last platform-tools into the first directory with all the license files and started working.
Weird but true
You can also pass the init parameters to the instance variables by position
# Abstract struct class
class Struct:
def __init__ (self, *argv, **argd):
if len(argd):
# Update by dictionary
self.__dict__.update (argd)
else:
# Update by position
attrs = filter (lambda x: x[0:2] != "__", dir(self))
for n in range(len(argv)):
setattr(self, attrs[n], argv[n])
# Specific class
class Point3dStruct (Struct):
x = 0
y = 0
z = 0
pt1 = Point3dStruct()
pt1.x = 10
print pt1.x
print "-"*10
pt2 = Point3dStruct(5, 6)
print pt2.x, pt2.y
print "-"*10
pt3 = Point3dStruct (x=1, y=2, z=3)
print pt3.x, pt3.y, pt3.z
print "-"*10
This will unstage all files you might have staged with git add
:
git reset
This will revert all local uncommitted changes (should be executed in repo root):
git checkout .
You can also revert uncommitted changes only to particular file or directory:
git checkout [some_dir|file.txt]
Yet another way to revert all uncommitted changes (longer to type, but works from any subdirectory):
git reset --hard HEAD
This will remove all local untracked files, so only git tracked files remain:
git clean -fdx
WARNING:
-x
will also remove all ignored files, including ones specified by.gitignore
! You may want to use-n
for preview of files to be deleted.
To sum it up: executing commands below is basically equivalent to fresh git clone
from original source (but it does not re-download anything, so is much faster):
git reset
git checkout .
git clean -fdx
Typical usage for this would be in build scripts, when you must make sure that your tree is absolutely clean - does not have any modifications or locally created object files or build artefacts, and you want to make it work very fast and to not re-clone whole repository every single time.
This error message comes specifically from the XDebug extension. PHP itself does not have a function nesting limit. Change the setting in your php.ini:
xdebug.max_nesting_level = 200
or in your PHP code:
ini_set('xdebug.max_nesting_level', 200);
As for if you really need to change it (i.e.: if there's a alternative solution to a recursive function), I can't tell without the code.
date must be insert with two apostrophes' As example if the date is 2018/10/20. It can insert from these query
Query -
insert into run(id,name,dob)values(&id,'&name','2018-10-20')
I have just tested this and works fine.
string test = "Testing 1-2-3";
// convert string to stream
byte[] byteArray = Encoding.ASCII.GetBytes(test);
MemoryStream stream = new MemoryStream(byteArray);
// convert stream to string
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
If stream
has already been written to, you might want to seek to the beginning before first before reading out the text: stream.Seek(0, SeekOrigin.Begin);
My resolution to this issue was to Close the damn chrome browser which was choking my computer's memory
In some cases you can pipe after the command a Out-Null
command | Out-Null
In my case, I've lost all private keys in my keychain, new ones were imported correctly, but doesn't show the private key as well. The only thing that helped was generating new CertificateSigningRequest
If you need the variable set before you're starting the notebook, the only solution which worked for me was env VARIABLE=$VARIABLE jupyter notebook
with export VARIABLE=value
in .bashrc
.
In my case tensorflow needs the exported variable for successful importing it in a notebook.
You don't need to use anything but plain React and ES6 to achieve what you want. As per Jim's answer, just define the constant in the right place. I like the idea of keeping the constant local to the component if not needed externally. The below is an example of possible usage.
import React from "react";
const sizeToLetterMap = {
small_square: 's',
large_square: 'q',
thumbnail: 't',
small_240: 'm',
small_320: 'n',
medium_640: 'z',
medium_800: 'c',
large_1024: 'b',
large_1600: 'h',
large_2048: 'k',
original: 'o'
};
class PhotoComponent extends React.Component {
constructor(args) {
super(args);
}
photoUrl(image, size_text) {
return (<span>
Image: {image}, Size Letter: {sizeToLetterMap[size_text]}
</span>);
}
render() {
return (
<div className="photo-wrapper">
The url is: {this.photoUrl(this.props.image, this.props.size_text)}
</div>
)
}
}
export default PhotoComponent;
// Call this with <PhotoComponent image="abc.png" size_text="thumbnail" />
// Of course the component must first be imported where used, example:
// import PhotoComponent from "./photo_component.jsx";
This warning also could be raised due to
new HashMap() or new ArrayList() that is generic type has to be specific otherwise the compiler will generate warning.
Please make sure that if you code contains the following you have to change accordingly
new HashMap() => Map map = new HashMap() new HashMap() => Map map = new HashMap<>()
new ArrayList() => List map = new ArrayList() new ArrayList() => List map = new ArrayList<>()
A good method which is a favorite of mine and for many I'm sure, is to make use of foreach
which will output each color you chose, and appear on screen one underneath each other.
When it comes to using checkboxes, you kind of do not have a choice but to use foreach
, and that's why you only get one value returned from your array.
Here is an example using $_GET
. You can however use $_POST
and would need to make both directives match in both files in order to work properly.
###HTML FORM
<form action="third.php" method="get">
Red<input type="checkbox" name="color[]" value="red">
Green<input type="checkbox" name="color[]" value="green">
Blue<input type="checkbox" name="color[]" value="blue">
Cyan<input type="checkbox" name="color[]" value="cyan">
Magenta<input type="checkbox" name="color[]" value="Magenta">
Yellow<input type="checkbox" name="color[]" value="yellow">
Black<input type="checkbox" name="color[]" value="black">
<input type="submit" value="submit">
</form>
###PHP (using $_GET) using third.php
as your handler
<?php
$name = $_GET['color'];
// optional
// echo "You chose the following color(s): <br>";
foreach ($name as $color){
echo $color."<br />";
}
?>
Assuming having chosen red, green, blue and cyan as colors, will appear like this:
red
green
blue
cyan
##OPTION #2
You can also check if a color was chosen. If none are chosen, then a seperate message will appear.
<?php
$name = $_GET['color'];
if (isset($_GET['color'])) {
echo "You chose the following color(s): <br>";
foreach ($name as $color){
echo $color."<br />";
}
} else {
echo "You did not choose a color.";
}
?>
##Additional options:
To appear as a list: (<ul></ul>
can be replaced by <ol></ol>
)
<?php
$name = $_GET['color'];
if (isset($_GET['color'])) {
echo "You chose the following color(s): <br>";
echo "<ul>";
foreach ($name as $color){
echo "<li>" .$color."</li>";
}
echo "</ul>";
} else {
echo "You did not choose a color.";
}
?>
You can use the string formatting operator as so:
num = 49
x = "%.2f" % num # x is now the string "49.00"
I'm not sure what you mean by "efficient" -- this is almost certainly not the bottleneck of your application. If your program is running slowly, profile it first to find the hot spots, and then optimize those.
Using dummies::dummy():
library(dummies)
# example data
df1 <- data.frame(id = 1:4, year = 1991:1994)
df1 <- cbind(df1, dummy(df1$year, sep = "_"))
df1
# id year df1_1991 df1_1992 df1_1993 df1_1994
# 1 1 1991 1 0 0 0
# 2 2 1992 0 1 0 0
# 3 3 1993 0 0 1 0
# 4 4 1994 0 0 0 1
IF EXISTS (SELECT * FROM [Table] WHERE ID = rowID)
UPDATE [Table] SET propertyOne = propOne, property2 . . .
ELSE
INSERT INTO [Table] (propOne, propTwo . . .)
Edit:
Alas, even to my own detriment, I must admit the solutions that do this without a select seem to be better since they accomplish the task with one less step.
While you can use a virtualenv
, you don't need to. The trick is passing the PEP370 --user
argument to the setup.py
script. With the latest version of pip
, one way to do it is:
pip install --user mercurial
This should result in the hg
script being installed in $HOME/.local/bin/hg
and the rest of the hg package in $HOME/.local/lib/pythonx.y/site-packages/
.
Note, that the above is true for Python 2.6. There has been a bit of controversy among the Python core developers about what is the appropriate directory location on Mac OS X for PEP370-style user
installations. In Python 2.7 and 3.2, the location on Mac OS X was changed from $HOME/.local
to $HOME/Library/Python
. This might change in a future release. But, for now, on 2.7 (and 3.2, if hg
were supported on Python 3), the above locations will be $HOME/Library/Python/x.y/bin/hg
and $HOME/Library/Python/x.y/lib/python/site-packages
.
it is safe to delete the inetpub it is only a cache.
For add environment variable please add \ after bin like below
C:\Program Files\MongoDB\Server\3.2\bin\
Then try below code in command prompt to run mongo server from parent folder of data folder.
mongod -dbpath ./data
For my case I am unable to run mongo from command prompt(normal mode). You should run as administrator. It also works on git bash.
Whould this help? (Most confusion of 'this' in javascript is coming from the fact that it generally is not linked to your object, but to the current executing scope -- that might not be exactly how it works but is always feels like that to me -- see the article for a complete explanation)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
int a = 543210 ;
char arr[10] ="" ;
itoa(a,arr,10) ; // itoa() is a function of stdlib.h file that convert integer
// int to array itoa( integer, targated array, base u want to
//convert like decimal have 10
for( int i= 0 ; i < strlen(arr); i++) // strlen() function in string file thar return string length
printf("%c",arr[i]);
}
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String A=sc.next();
char[] array = A.toCharArray();
String str = "";
for(int i=A.length()-1;i>=0;i--){
str = str + array[i];
}
if(A.equalsIgnoreCase(str))System.out.println("Yes");
else System.out.println("No");
}
}
You can escape the apostrophe with a \
character as well:
mystring.replace('\'', '')
Solution without using loops and recursion.
Use the required pattern in compile method and enter the desired occurrence in variable 'n' and the last statement will print the starting index of the nth occurrence of the pattern in the given string. Here the result of finditer i.e. iterator is being converted to list and directly accessing the nth index.
import re
n=2
sampleString="this is history"
pattern=re.compile("is")
matches=pattern.finditer(sampleString)
print(list(matches)[n].span()[0])
The one-liner solution is more useful as a shibboleth than good code; good Perl coders will know it and understand it, but it's much less transparent and readable than the two-line copy-and-modify couplet you're starting with.
In other words, a good way to do this is the way you're already doing it. Unnecessary concision at the cost of readability isn't a win.
I had a scenario, and this one helped me
JObject
objParserd = JObject
.Parse(jsonString);
JObject
arrayObject1 = (JObject
)objParserd["d"];
D
myOutput= JsonConvert
.DeserializeObject<D>
(arrayObject1.ToString());
You can parameterise it and pass gradle clean build -Pprokey=goodbye
task choiceMyMainClass(type: JavaExec) {
group = "Execution"
description = "Run Option main class with JavaExecTask"
classpath = sourceSets.main.runtimeClasspath
if (project.hasProperty('prokey')){
if (prokey == 'hello'){
main = 'com.sam.home.HelloWorld'
}
else if (prokey == 'goodbye'){
main = 'com.sam.home.GoodBye'
}
} else {
println 'Invalid value is enterrd';
// println 'Invalid value is enterrd'+ project.prokey;
}
Adding to @Dima's answer, if you're using maven
to build your package, you can tell it to set your WAR file name to ROOT
in pom.xml
:
<build>
<finalName>ROOT</finalName>
</build>
By default, tomcat
will deploy ROOT.war
webapp into root context (/
).
You can do:
super.alphaMethod1();
Note, that super
is a reference to the parent, but super() is it's constructor.
Short answer:
Neither
Longer answer:
using Argument*Exception (except in a library that is a product on its on, such as component library) is a smell. Exceptions are to handle exceptional situation, not bugs, and not user's (i.e. API consumer) shortfalls.
Longest answer:
Throwing exceptions for invalid arguments is rude, unless you write a library.
I prefer using assertions, for two (or more) reasons:
Here is what handling of null exception looks like (being sarcastic, obviously):
try {
library.Method(null);
}
catch (ArgumentNullException e) {
// retry with real argument this time
library.Method(realArgument);
}
Exceptions shall be used when situation is expected but exceptional (things happen that are outside of consumer's control, such as IO failure). Argument*Exception is an indication of a bug and shall be (my opinion) handled with tests and assisted with Debug.Assert
BTW: In this particular case, you could have used Month type, instead of int. C# falls short when it comes to type safety (Aspect# rulez!) but sometimes you can prevent (or catch at compile time) those bugs all together.
And yes, MicroSoft is wrong about that.
I don't have experience with ksh, but I have used both bash and zsh. I prefer zsh over bash because of its support for very powerful file globbing, variable expansion modifiers, and faster tab completion.
Here's a quick intro: http://friedcpu.wordpress.com/2007/07/24/zsh-the-last-shell-youll-ever-need/
I have passed through that error today and did everything described above but didn't work for me. So I decided to view the core problem and logged onto the MySQL root folder in Windows 7 and did this solution:
Go to folder:
C:\AppServ\MySQL
Right click and Run as Administrator these files:
mysql_servicefix.bat
mysql_serviceinstall.bat
mysql_servicestart.bat
Then close the entire explorer window and reopen it or clear cache then login to phpMyAdmin again.
If you don't care what groups the users were in, and just want a big ol' list of users - this does the job:
$Groups = Get-ADGroup -Filter {Name -like "AB*"}
$rtn = @(); ForEach ($Group in $Groups) {
$rtn += (Get-ADGroupMember -Identity "$($Group.Name)" -Recursive)
}
Then the results:
$rtn | ft -autosize
It is good practice when you start creating website to reset all the margins and paddings. So I recommend on start just to simple do:
* { margin: 0, padding: 0 }
This will make margins and paddings of all elements to be 0, and then you can style them as you wish, because each browser has a different default margin and padding of the elements.
First of all, from __future__ import print_function
needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print
as a function now. That's the whole point of from __future__ import print_function
; to bring the print
function from Python 3 into Python 2.6+.
from __future__ import print_function
import sys, os, time
for x in range(0,10):
print(x, sep=' ', end='') # No need for sep here, but okay :)
time.sleep(1)
__future__
statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:
A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.
The documentation also mentions that the only things that can precede a __future__
statement are the module docstring, comments, blank lines, and other future statements.
Your usage is correct. I bet that your external program, flow.exe, needs to be executed in its directory, because it accesses some external files stored there.
So you might try:
import sys, string, os, arcgisscripting
os.chdir('c:\\documents and settings\\flow_model')
os.system('"C:\\Documents and Settings\\flow_model\\flow.exe"')
(Beware of the double quotes inside the single quotes...)
I created the following Method to create reusable One Liner:
public void oneMethodToCloseThemAll(ResultSet resultSet, Statement statement, Connection connection) {
if (resultSet != null) {
try {
if (!resultSet.isClosed()) {
resultSet.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
if (!statement.isClosed()) {
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
if (!connection.isClosed()) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
I use this Code in a parent Class thats inherited to all my classes that send DB Queries. I can use the Oneliner on all Queries, even if i do not have a resultSet.The Method takes care of closing the ResultSet, Statement, Connection in the correct order. This is what my finally block looks like.
finally {
oneMethodToCloseThemAll(resultSet, preStatement, sqlConnection);
}
To answer "why" someone might use it, I was tempted to use it since I had the $_POST values stored after the page refresh or while going from one page to another. My sense tells me this is not a good practice, but it works nevertheless.
Setting a min-width on child elements will also create a breakpoint. For example breaking every 3 elements,
flex-grow: 1;
min-width: 33%;
If there are 4 elements, this will have the 4th element wrap taking the full 100%. If there are 5 elements, the 4th and 5th elements will wrap and take each 50%.
Make sure to have parent element with,
flex-wrap: wrap
So to have a specific column come first, then the rest alphabetically, I'd propose this solution:
test[, c("myFirstColumn", sort(setdiff(names(test), "myFirstColumn")))]
try using the css pseudoclass :focus
input[type="button"], input[type="button"]:focus {
/* your style goes here */
}
edit as for links and onclick events use (you shouldn’t use inline javascript eventhandlers, but for the sake of simplicity i will use them here):
<a href="some/page.php" title="perform some js action" onclick="callFunction(this.href);return false;">watch and learn</a>
with this.href you can even access the target of the link in your function. return false
will just prevent browsers from following the link when clicked.
if javascript is disabled the link will work as a normal link and just load some/page.php
—if you want your link to be dead when js is disabled use href="#"
I've just tested the following in Chrome (79), Firefox (71) and Edge (44) and it works fine. It applies the script solution as others noted above.
Just add a "Logout" link and when clicked return the following html
<div>You have been logged out. Redirecting to home...</div>
<script>
var XHR = new XMLHttpRequest();
XHR.open("GET", "/Home/MyProtectedPage", true, "no user", "no password");
XHR.send();
setTimeout(function () {
window.location.href = "/";
}, 3000);
</script>
I had same problem. Try the following command. This solved my problem.
sudo apt-get install libapache2-mod-php5
I would use the built-in ngInclude
directive. In the example below, you don't even need to write any javascript. The templates can just as easily live at a remote url.
Here's a working demo: http://plnkr.co/edit/5ImqWj65YllaCYD5kX5E?p=preview
<p>Select page content template via dropdown</p>
<select ng-model="template">
<option value="page1">Page 1</option>
<option value="page2">Page 2</option>
</select>
<p>Set page content template via button click</p>
<button ng-click="template='page2'">Show Page 2 Content</button>
<ng-include src="template"></ng-include>
<script type="text/ng-template" id="page1">
<h1 style="color: blue;">This is the page 1 content</h1>
</script>
<script type="text/ng-template" id="page2">
<h1 style="color:green;">This is the page 2 content</h1>
</script>
You could use the setTimeout()
function:
// Your delay in milliseconds
var delay = 1000;
setTimeout(function(){ window.location = URL; }, delay);
The &nKByte
creates a temporary value, which cannot be bound to a reference to non-const.
You could change void test(float *&x)
to void test(float * const &x)
or you could just drop the pointer altogether and use void test(float &x); /*...*/ test(nKByte);
.
To clarify for anyone who is looking for what is the difference between the 3 on a simpler level. You can expose your service with minimal ClusterIp (within k8s cluster) or larger exposure with NodePort (within cluster external to k8s cluster) or LoadBalancer (external world or whatever you defined in your LB).
ClusterIp exposure < NodePort exposure < LoadBalancer exposure
ip/name:port
ip/name:port
@qbzenker provided the most idiomatic method IMO
Here are a few alternatives:
In [28]: df.query('Col2 != Col2') # Using the fact that: np.nan != np.nan
Out[28]:
Col1 Col2 Col3
1 0 NaN 0.0
In [29]: df[np.isnan(df.Col2)]
Out[29]:
Col1 Col2 Col3
1 0 NaN 0.0
Make sure you didn't skip all jars in
tomcat.util.scan.StandardJarScanFilter.jarsToSkip
in Tomcat catalina.properties.
Since vim 8 right click enables visual mode by default. This prevents the "normal" copy & paste (call it a "defect by design" https://github.com/vim/vim/issues/1326). Fix it by doing:
echo "set mouse-=a" >> ~/.vimrc
.
Exit and restart vim.
TL;DR
What does an exclamation mark mean in the Swift language?
The exclamation mark effectively says, “I know that this optional definitely has a value; please use it.” This is known as forced unwrapping of the optional’s value:
Example
let possibleString: String? = "An optional string."
print(possibleString!) // requires an exclamation mark to access its value
// prints "An optional string."
let assumedString: String! = "An implicitly unwrapped optional string."
print(assumedString) // no exclamation mark is needed to access its value
// prints "An implicitly unwrapped optional string."
After some tries, these are the samples I am using in order to connect:
Specifying the username and the password:
sqlcmd -S 211.11.111.111 -U NotSA -P NotTheSaPassword
Specifying the DB as well:
sqlcmd -S 211.11.111.111 -d SomeSpecificDatabase -U NotSA -P NotTheSaPassword
Based on @dave1010 answer but with updated https
links.
Numbered marker:
https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=7|FF0000|000000
Text marker:
https://chart.googleapis.com/chart?chst=d_map_spin&chld=1|0|FF0000|12|_|Marker
pm2 start npm --name "custom_pm2_name" -- run prod
"scripts": {
"prod": "nodemon --exec babel-node ./src/index.js"
}
This worked for me when the others didnt
For better understanding why wait() and notify() method belongs to Object class, I'll give you a real life example: Suppose a gas station has a single toilet, the key for which is kept at the service desk. The toilet is a shared resource for passing motorists. To use this shared resource the prospective user must acquire a key to the lock on the toilet. The user goes to the service desk and acquires the key, opens the door, locks it from the inside and uses the facilities.
Meanwhile, if a second prospective user arrives at the gas station he finds the toilet locked and therefore unavailable to him. He goes to the service desk but the key is not there because it is in the hands of the current user. When the current user finishes, he unlocks the door and returns the key to the service desk. He does not bother about waiting customers. The service desk gives the key to the waiting customer. If more than one prospective user turns up while the toilet is locked, they must form a queue waiting for the key to the lock. Each thread has no idea who is in the toilet.
Obviously in applying this analogy to Java, a Java thread is a user and the toilet is a block of code which the thread wishes to execute. Java provides a way to lock the code for a thread which is currently executing it using the synchronized keyword, and making other threads that wish to use it wait until the first thread is finished. These other threads are placed in the waiting state. Java is NOT AS FAIR as the service station because there is no queue for waiting threads. Any one of the waiting threads may get the monitor next, regardless of the order they asked for it. The only guarantee is that all threads will get to use the monitored code sooner or later.
Finally the answer to your question: the lock could be the key object or the service desk. None of which is a Thread.
However, these are the objects that currently decide whether the toilet is locked or open. These are the objects that are in a position to notify that the bathroom is open (“notify”) or ask people to wait when it is locked wait.
If your table is MyISAM
:
SELECT *
FROM pages
WHERE MATCH(title, content) AGAINST ('keyword' IN BOOLEAN MODE)
This will be much faster if you create a FULLTEXT
index on your columns:
CREATE FULLTEXT INDEX fx_pages_title_content ON pages (title, content)
, but will work even without the index.
if you get this issue while running certbot while creating or renewing certificate, Please use the following method
grep -r -P '[^\x00-\x7f]' /etc/apache2 /etc/letsencrypt /etc/nginx
That command found the offending character "´" in one .conf file in the comment. After removing it (you can edit comments as you wish) and reloading nginx, everything worked again.
This usage has been deprected: https://developer.mozilla.org/en-US/docs/Web/HTML/Using_the_application_cache
This answer is only 6 years late, but I don't see this answer in many places... HTML5 has introduced Application Cache which is used to solve this problem. I was finding that new server code I was writing was crashing old javascript stored in people's browsers, so I wanted to find a way to expire their javascript. Use a manifest file that looks like this:
CACHE MANIFEST
# Aug 14, 2014
/mycode.js
NETWORK:
*
and generate this file with a new time stamp every time you want users to update their cache. As a side note, if you add this, the browser will not reload (even when a user refreshes the page) until the manifest tells it to.
I started Task Manager, made sure adb.exe is closed (it locks some files)
Create the folder C:\Android Moved folder + all files from C:\Program Files\android-sdk to C:\Android
Edited C:\Documents and Settings\All Users\Start Menu\Programs\Android SDK Tools shortcuts.
I considered uninstalling the SDK and re-installing, but for the life of me, where does it store the temp files?? I don't
want to re-download the platforms, samples and doco that I have added to the SDK.
Here is the configuration for those trying to accomplish the original goal (wildcards all pointing to same codebase -- install nothing, dev environment ie, XAMPP)
file: /etc/hosts (non-windows)
127.0.0.1 example.local
file: /XAMPP/etc/httpd.conf
# Virtual hosts
Include etc/extra/httpd-vhosts.conf
file: XAMPP/etc/extra/httpd-vhosts.conf
<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "/path_to_XAMPP/htdocs"
ServerName example.local
ServerAlias *.example.local
# SetEnv APP_ENVIRONMENT development
# ErrorLog "logs/example.local-error_log"
# CustomLog "logs/example.local-access_log" common
</VirtualHost>
restart apache
save as whatever.pac wherever you want to and then load the file in the browser's network>proxy>auto_configuration settings (reload if you alter this)
function FindProxyForURL(url, host) {
if (shExpMatch(host, "*example.local")) {
return "PROXY example.local";
}
return "DIRECT";
}
SELECT
hat,
shoe,
boat,
0 as placeholder -- for column having 0 value
FROM
objects
--OR '' as Placeholder -- for blank column
--OR NULL as Placeholder -- for column having null value
Hit Ctrl+Alt+Del to open the Windows Task manager and switch to the processes tab.
32-bit programs should be marked with *32
.
the easiest way to do this is to wrap your sockets in ObjectInput/OutputStreams and send serialized java objects. you can create classes which contain the relevant data, and then you don't need to worry about the nitty gritty details of handling binary protocols. just make sure that you flush your object streams after you write each object "message".
Below are the options:
echo $this->Registration->id;
echo $this->Registration->getInsertID();
echo $this->Registration->getLastInsertId();
Here, you can replace Registration
with your model name.
Thanks
It's the only solution to map a ManyToMany association : you need a join table between the two entities tables to map the association.
It's also used for OneToMany (usually unidirectional) associations when you don't want to add a foreign key in the table of the many side and thus keep it independent of the one side.
Search for @JoinTable in the hibernate documentation for explanations and examples.
In your manifest file package
attribute is set to com.test.helloworld
however your activity class is under different package. Change your MyActivity class package to com.example.helloworld
Add this in your Xml - android:background="@android:color/transparent"
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Button"
android:background="@android:color/transparent"
android:textStyle="bold"/>
I couldn't find a type that worked best for me in all situations: I needed to default to numeric entry (entry of "7.5" for example) but also at certain times allow text ("pass" for example). Users wanted a numeric keypad (entry of 7.5 for example) but occasional text entry was required ("pass" for example).
Rather what I did was to add a checkbox to the form and allow the user to toggle my input (id="inputSresult") between type="number" and type="text".
<input type="number" id="result"... >
<label><input id="cbAllowTextResults" type="checkbox" ...>Allow entry of text results.</label>
Then I wired a click handler to the checkbox that toggles the type between text and number based on whether the checkbox above is checked:
$(document).ready(function () {
var cb = document.getElementById('cbAllowTextResults');
cb.onclick = function (event) {
if ($("#cbAllowTextResults").is(":checked"))
$("#result").attr("type", "text");
else
$("#result").attr("type", "number");
}
});
This worked out well for us.
You should use options.addAll(allPoints);
instead of options.add(point);
I liked this question and some answers was helpful to me, but i need to convert the xml to one domination array, so i will post my solution maybe someone need it later:
<?php
$xml = json_decode(json_encode((array)simplexml_load_string($xml)),1);
$finalItem = getChild($xml);
var_dump($finalItem);
function getChild($xml, $finalItem = []){
foreach($xml as $key=>$value){
if(!is_array($value)){
$finalItem[$key] = $value;
}else{
$finalItem = getChild($value, $finalItem);
}
}
return $finalItem;
}
?>
sample = ("Python 3.2 is very easy") #sample string
letters = 0 # initiating the count of letters to 0
numeric = 0 # initiating the count of numbers to 0
for i in sample:
if i.isdigit():
numeric +=1
elif i.isalpha():
letters +=1
else:
pass
letters
numeric
I did some benchmarking for speed on these answers and was surprised to see percent
in the scales
package so touted, given its sluggishness. I imagine the advantage is its automatic detector for for proper formatting, but if you know what your data looks like it seems clear to be avoided.
Here are the results from trying to format a list of 100,000 percentages in (0,1) to a percentage in 2 digits:
library(microbenchmark)
x = runif(1e5)
microbenchmark(times = 100L, andrie1(), andrie2(), richie(), krlmlr())
# Unit: milliseconds
# expr min lq mean median uq max
# 1 andrie1() 91.08811 95.51952 99.54368 97.39548 102.75665 126.54918 #paste(round())
# 2 andrie2() 43.75678 45.56284 49.20919 47.42042 51.23483 69.10444 #sprintf()
# 3 richie() 79.35606 82.30379 87.29905 84.47743 90.38425 112.22889 #paste(formatC())
# 4 krlmlr() 243.19699 267.74435 304.16202 280.28878 311.41978 534.55904 #scales::percent()
So sprintf
emerges as a clear winner when we want to add a percent sign. On the other hand, if we only want to multiply the number and round (go from proportion to percent without "%", then round()
is fastest:
# Unit: milliseconds
# expr min lq mean median uq max
# 1 andrie1() 4.43576 4.514349 4.583014 4.547911 4.640199 4.939159 # round()
# 2 andrie2() 42.26545 42.462963 43.229595 42.960719 43.642912 47.344517 # sprintf()
# 3 richie() 64.99420 65.872592 67.480730 66.731730 67.950658 96.722691 # formatC()
something is not right
Well, you are using jQuery to check for the presence of jQuery. If jQuery isn't loaded then $()
won't even run at all and your callback won't execute, unless you're using another library and that library happens to share the same $()
syntax.
Remove your $(document).ready()
(use something like window.onload
instead):
window.onload = function() {
if (window.jQuery) {
// jQuery is loaded
alert("Yeah!");
} else {
// jQuery is not loaded
alert("Doesn't Work");
}
}
zoom is a css3 spec for the @viewport descriptor, as described here
http://dev.w3.org/csswg/css-device-adapt/#zoom-desc
used to zoom the entire viewport ('screen'). it also happens to zoom individuals elements in a lot of browsers, but not all. css3 specifies transform:scale should be used to achieve such an effect:
http://www.w3.org/TR/css3-transforms/#transform-functions
but it works a little different than the 'element zoom' in those browsers that support it.
To create a comma separated list from an IList<string>
or IEnumerable<string>
, besides using string.Join()
you can use the StringBuilder.AppendJoin
method:
new StringBuilder().AppendJoin(", ", itemList).ToString();
or
$"{new StringBuilder().AppendJoin(", ", itemList)}";
Assuming you want to add this path for all users on the system, add the following line to your /etc/profile.d/play.sh
(and possibly play.csh
, etc):
PATH=$PATH:/home/me/play
export PATH
You can also use pageMethods in asp.net. So that you can call javascript functions from asp.net functions. E.g.
[WebMethod]_x000D_
public static string showTxtbox(string name)_x000D_
{_x000D_
return showResult(name);_x000D_
}_x000D_
_x000D_
public static string showResult(string name)_x000D_
{_x000D_
Database databaseObj = new Database();_x000D_
DataTable dtObj = databaseObj.getMatches(name);_x000D_
_x000D_
string result = "<table border='1' cellspacing='2' cellpadding='2' >" +_x000D_
"<tr>" +_x000D_
"<td><b>Name</b></td>" +_x000D_
"<td><b>Company Name</b></td>" +_x000D_
"<td><b>Phone</b></td>"+_x000D_
"</tr>";_x000D_
_x000D_
for (int i = 0; i < dtObj.Rows.Count; i++)_x000D_
{_x000D_
result += "<tr> <td><a href=\"javascript:link('" + dtObj.Rows[i][0].ToString().Trim() + "','" +_x000D_
dtObj.Rows[i][1].ToString().Trim() +"','"+dtObj.Rows[i][2]+ "');\">" + Convert.ToString(dtObj.Rows[i]["name"]) + "</td>" +_x000D_
"<td>" + Convert.ToString(dtObj.Rows[i]["customerCompany"]) + "</td>" +_x000D_
"<td>"+Convert.ToString(dtObj.Rows[i]["Phone"])+"</td>"+_x000D_
"</tr>";_x000D_
}_x000D_
_x000D_
result += "</table>";_x000D_
return result;_x000D_
}
_x000D_
Here above code is written in .aspx.cs page. Database is another class. In showResult() function I've called javascript's link() function. Result is displayed in the form of table.
No, a view consists of a single SELECT
statement. You cannot create or drop tables in a view.
Maybe a common table expression (CTE) can solve your problem. CTEs are temporary result sets that are defined within the execution scope of a single statement and they can be used in views.
Example (taken from here) - you can think of the SalesBySalesPerson
CTE as a temporary table:
CREATE VIEW vSalesStaffQuickStats
AS
WITH SalesBySalesPerson (SalesPersonID, NumberOfOrders, MostRecentOrderDate)
AS
(
SELECT SalesPersonID, COUNT(*), MAX(OrderDate)
FROM Sales.SalesOrderHeader
GROUP BY SalesPersonID
)
SELECT E.EmployeeID,
EmployeeOrders = OS.NumberOfOrders,
EmployeeLastOrderDate = OS.MostRecentOrderDate,
E.ManagerID,
ManagerOrders = OM.NumberOfOrders,
ManagerLastOrderDate = OM.MostRecentOrderDate
FROM HumanResources.Employee AS E
INNER JOIN SalesBySalesPerson AS OS ON E.EmployeeID = OS.SalesPersonID
LEFT JOIN SalesBySalesPerson AS OM ON E.ManagerID = OM.SalesPersonID
GO
Obligatory: SHA1 is broken, you can compute SHA1 collisions for 45,000 USD. You should use sha256
:
var getSHA256ofJSON = function(input){
return crypto.createHash('sha256').update(JSON.stringify(input)).digest('hex')
}
To answer your question and make a SHA1 hash:
const INSECURE_ALGORITHM = 'sha1'
var getInsecureSHA1ofJSON = function(input){
return crypto.createHash(INSECURE_ALGORITHM).update(JSON.stringify(input)).digest('hex')
}
Then:
getSHA256ofJSON('whatever')
or
getSHA256ofJSON(['whatever'])
or
getSHA256ofJSON({'this':'too'})
According to the json.org specification, your return is invalid. The names are always quoted, so you should be returning
{ "title": "One", "key": "1" }
and
[ { "title": "One", "key": "1" }, { "title": "Two", "key": "2" } ]
This may not be the problem with your setup, since you say one of them works now, but it should be fixed for correctness in case you need to switch to another JSON parser in the future.
There is an example how to achieve it, when the card is at the very bottom of the screen. If someone has this kind of problem just do something like that:
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="-5dp"
card_view:cardCornerRadius="4dp">
<SomeView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp">
</SomeView>
</android.support.v7.widget.CardView>
Card View has a negative bottom margin. The view inside a Card View has the same, but positive bottom margin. This way rounded parts are hidden below the screen, but everything looks exactly the same, because the inner view has a counter margin.
For a simple and semantic solution i prefer to define the initial value in HTML, example:
<select name="myfield" data-placeholder="Select an option">
<option value="initial-value" selected>Initial text</option>
</select>
So when i call $('select').select2({ ajax: {...}});
the initial value is initial-value
and its option text is Initial text
.
My current Select2 version is 4.0.3, but i think it has a great compatibility with other versions.
For startswith, you can use indexOf:
if(str.indexOf('Hello') == 0) {
...
and you can do the maths based on string length to determine 'endswith'.
if(str.lastIndexOf('Hello') == str.length - 'Hello'.length) {
I struggled while working MS OCR Read API which returns back angle of rotation in range (-180, 180]. So I have to do an extra step of converting negative angles to positive. I hope someone struggling with point rotation with negative or positive angles can use the following.
def rotate(origin, point, angle):
"""
Rotate a point counter-clockwise by a given angle around a given origin.
"""
# Convert negative angles to positive
angle = normalise_angle(angle)
# Convert to radians
angle = math.radians(angle)
# Convert to radians
ox, oy = origin
px, py = point
# Move point 'p' to origin (0,0)
_px = px - ox
_py = py - oy
# Rotate the point 'p'
qx = (math.cos(angle) * _px) - (math.sin(angle) * _py)
qy = (math.sin(angle) * _px) + (math.cos(angle) * _py)
# Move point 'p' back to origin (ox, oy)
qx = ox + qx
qy = oy + qy
return [qx, qy]
def normalise_angle(angle):
""" If angle is negative then convert it to positive. """
if (angle != 0) & (abs(angle) == (angle * -1)):
angle = 360 + angle
return angle
As has already been mention in various answers here, the Thread
class currently (4.7.2) provides several constructors and a Start
method with overloads.
These relevant constructors for this question are:
public Thread(ThreadStart start);
and
public Thread(ParameterizedThreadStart start);
which either take a ThreadStart
delegate or a ParameterizedThreadStart
delegate.
The corresponding delegates look like this:
public delegate void ThreadStart();
public delegate void ParameterizedThreadStart(object obj);
So as can be seen, the correct constructor to use seems to be the one taking a ParameterizedThreadStart
delegate so that some method conform to the specified signature of the delegate can be started by the thread.
A simple example for instanciating the Thread
class would be
Thread thread = new Thread(new ParameterizedThreadStart(Work));
or just
Thread thread = new Thread(Work);
The signature of the corresponding method (called Work
in this example) looks like this:
private void Work(object data)
{
...
}
What is left is to start the thread. This is done by using either
public void Start();
or
public void Start(object parameter);
While Start()
would start the thread and pass null
as data to the method, Start(...)
can be used to pass anything into the Work
method of the thread.
There is however one big problem with this approach:
Everything passed into the Work
method is cast into an object. That means within the Work
method it has to be cast to the original type again like in the following example:
public static void Main(string[] args)
{
Thread thread = new Thread(Work);
thread.Start("I've got some text");
Console.ReadLine();
}
private static void Work(object data)
{
string message = (string)data; // Wow, this is ugly
Console.WriteLine($"I, the thread write: {message}");
}
Casting is something you typically do not want to do.
What if someone passes something else which is not a string? As this seems not possible at first (because It is my method, I know what I do or The method is private, how should someone ever be able to pass anything to it?) you may possibly end up with exactly that case for various reasons. As some cases may not be a problem, others are. In such cases you will probably end up with an InvalidCastException
which you probably will not notice because it simply terminates the thread.
As a solution you would expect to get a generic ParameterizedThreadStart
delegate like ParameterizedThreadStart<T>
where T
would be the type of data you want to pass into the Work
method. Unfortunately something like this does not exist (yet?).
There is however a suggested solution to this issue. It involves creating a class which contains both, the data to be passed to the thread as well as the method that represents the worker method like this:
public class ThreadWithState
{
private string message;
public ThreadWithState(string message)
{
this.message = message;
}
public void Work()
{
Console.WriteLine($"I, the thread write: {this.message}");
}
}
With this approach you would start the thread like this:
ThreadWithState tws = new ThreadWithState("I've got some text");
Thread thread = new Thread(tws.Work);
thread.Start();
So in this way you simply avoid casting around and have a typesafe way of providing data to a thread ;-)
Add this line at the top:
"xmlns:app="http://schemas.android.com/apk/res-auto"
and then use:
app:showasaction="ifroom"
Actually your command line arguments are practically like an array already. At least, you can treat the $@
variable much like an array. That said, you can convert it into an actual array like this:
myArray=( "$@" )
If you just want to type some arguments and feed them into the $@
value, use set
:
$ set -- apple banana "kiwi fruit"
$ echo "$#"
3
$ echo "$@"
apple banana kiwi fruit
Understanding how to use the argument structure is particularly useful in POSIX sh, which has nothing else like an array.
Are you sure you're using the correct proxy as system properties?
Also if you are using 1.5 or 1.6 you could pass a java.net.Proxy instance to the openConnection() method. This is more elegant imo:
//Proxy instance, proxy ip = 10.0.0.1 with port 8080
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080));
conn = new URL(urlString).openConnection(proxy);
From the same page
Note: To avoid conflicts between parallel Python 2 and Python 3 installations, only the versioned pip3 and pip3.4 commands are bootstrapped by default when ensurepip is invoked directly - the --default-pip option is needed to also request the unversioned pip command. pyvenv and the Windows installer ensure that the unqualified pip command is made available in those environments, and pip can always be invoked via the -m switch rather than directly to avoid ambiguity on systems with multiple Python installations.
So try pip3
or pip3.4
in Command Prompt.
Also, ensure that environment variable are set for pip command, if you missed to opt-in for automatic PATH
configuration.
Your Gemfile has a line reading
ruby '2.2.5'
Change it to
ruby '2.3.0'
Then run
bundle install
If the <i>
tag isn't displayed as a block and causing the probelm then this should work:
<td style="white-space:nowrap;"><i class="flag-bfh-ES"></i> +34 666 66 66 66</td>
select *
into #TempTable
from SomeTale
select *
from #TempTable
I've had some issues with parser that are based on string parsing particularly with large files I found it would run out of memory and fail to parse binary data.
To cope with these issues I've open sourced my own attempt at a C# multipart/form-data parser here
Features:
Restrictions:
Just use the MultipartFormDataParser class like so:
Stream data = GetTheStream();
// Boundary is auto-detected but can also be specified.
var parser = new MultipartFormDataParser(data, Encoding.UTF8);
// The stream is parsed, if it failed it will throw an exception. Now we can use
// your data!
// The key of these maps corresponds to the name field in your
// form
string username = parser.Parameters["username"].Data;
string password = parser.Parameters["password"].Data
// Single file access:
var file = parser.Files.First();
string filename = file.FileName;
Stream data = file.Data;
// Multi-file access
foreach(var f in parser.Files)
{
// Do stuff with each file.
}
In the context of a WCF service you could use it like this:
public ResponseClass MyMethod(Stream multipartData)
{
// First we need to get the boundary from the header, this is sent
// with the HTTP request. We can do that in WCF using the WebOperationConext:
var type = WebOperationContext.Current.IncomingRequest.Headers["Content-Type"];
// Now we want to strip the boundary out of the Content-Type, currently the string
// looks like: "multipart/form-data; boundary=---------------------124123qase124"
var boundary = type.Substring(type.IndexOf('=')+1);
// Now that we've got the boundary we can parse our multipart and use it as normal
var parser = new MultipartFormDataParser(data, boundary, Encoding.UTF8);
...
}
Or like this (slightly slower but more code friendly):
public ResponseClass MyMethod(Stream multipartData)
{
var parser = new MultipartFormDataParser(data, Encoding.UTF8);
}
Documentation is also available, when you clone the repository simply navigate to HttpMultipartParserDocumentation/Help/index.html
Below code might help you.. Don't forget to add permissions..
public String getLocalIpAddress(){
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress();
}
}
}
} catch (Exception ex) {
Log.e("IP Address", ex.toString());
}
return null;
}
Add below permission in the manifest file.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
happy coding!!
I did following steps to downgrade Gradle back to the original version:
Probably last step is enough as in my case the path to the new Gradle distribution was hardcoded there under 'Gradle home' option.
em
is basically CSS property for font sizes.
The em and ex units depend on the font and may be different for each element in the document. The em is simply the font size. In an element with a 2in font, 1em thus means 2in. Expressing sizes, such as margins and paddings, in em means they are related to the font size, and if the user has a big font (e.g., on a big screen) or a small font (e.g., on a handheld device), the sizes will be in proportion. Declarations such as text-indent: 1.5em and margin: 1em are extremely common in CSS.
You need to allow gmail to install the service handler for mailto protocol:
1) go to gmail
2) click the small rhombus icon at the end of address bar (screenshot)
3) enjoy
This is not a matter of accuracy, nor is it a matter of precision. It is a matter of meeting the expectations of humans who use base 10 for calculations instead of base 2. For example, using doubles for financial calculations does not produce answers that are "wrong" in a mathematical sense, but it can produce answers that are not what is expected in a financial sense.
Even if you round off your results at the last minute before output, you can still occasionally get a result using doubles that does not match expectations.
Using a calculator, or calculating results by hand, 1.40 * 165 = 231 exactly. However, internally using doubles, on my compiler / operating system environment, it is stored as a binary number close to 230.99999... so if you truncate the number, you get 230 instead of 231. You may reason that rounding instead of truncating would have given the desired result of 231. That is true, but rounding always involves truncation. Whatever rounding technique you use, there are still boundary conditions like this one that will round down when you expect it to round up. They are rare enough that they often will not be found through casual testing or observation. You may have to write some code to search for examples that illustrate outcomes that do not behave as expected.
Assume you want to round something to the nearest penny. So you take your final result, multiply by 100, add 0.5, truncate, then divide the result by 100 to get back to pennies. If the internal number you stored was 3.46499999.... instead of 3.465, you are going to get 3.46 instead 3.47 when you round the number to the nearest penny. But your base 10 calculations may have indicated that the answer should be 3.465 exactly, which clearly should round up to 3.47, not down to 3.46. These kinds of things happen occasionally in real life when you use doubles for financial calculations. It is rare, so it often goes unnoticed as an issue, but it happens.
If you use base 10 for your internal calculations instead of doubles, the answers are always exactly what is expected by humans, assuming no other bugs in your code.
... Could not load file or assembly 'X' or one of its dependencies ...
Most likely it fails to load another dependency.
you could try to check the dependencies with a dependency walker.
I.e: https://www.dependencywalker.com/
Also check your build configuration (x86 / 64)
Edit: I also had this problem once when I was copying dlls in zip from a "untrusted" network share. The file was locked by Windows and the FileNotFoundException was raised.
See here: Detected DLLs that are from the internet and "blocked" by CASPOL
Most of the time we login to remote server using ssh. If you start a shell script and you logout then the process is killed. Nohup helps to continue running the script in background even after you log out from shell.
Nohup command name &
eg: nohup sh script.sh &
Nohup catches the HUP signals. Nohup doesn't put the job automatically in the background. We need to tell that explicitly using &
When the left part is an object instance, you use ->
. Otherwise, you use ::
.
This means that ->
is mostly used to access instance members (though it can also be used to access static members, such usage is discouraged), while ::
is usually used to access static members (though in a few special cases, it's used to access instance members).
In general, ::
is used for scope resolution, and it may have either a class name, parent
, self
, or (in PHP 5.3) static
to its left. parent
refers to the scope of the superclass of the class where it's used; self
refers to the scope of the class where it's used; static
refers to the "called scope" (see late static bindings).
The rule is that a call with ::
is an instance call if and only if:
$this
exists and$this
is either the class of the method being called or a subclass of it.Example:
class A {
public function func_instance() {
echo "in ", __METHOD__, "\n";
}
public function callDynamic() {
echo "in ", __METHOD__, "\n";
B::dyn();
}
}
class B extends A {
public static $prop_static = 'B::$prop_static value';
public $prop_instance = 'B::$prop_instance value';
public function func_instance() {
echo "in ", __METHOD__, "\n";
/* this is one exception where :: is required to access an
* instance member.
* The super implementation of func_instance is being
* accessed here */
parent::func_instance();
A::func_instance(); //same as the statement above
}
public static function func_static() {
echo "in ", __METHOD__, "\n";
}
public function __call($name, $arguments) {
echo "in dynamic $name (__call)", "\n";
}
public static function __callStatic($name, $arguments) {
echo "in dynamic $name (__callStatic)", "\n";
}
}
echo 'B::$prop_static: ', B::$prop_static, "\n";
echo 'B::func_static(): ', B::func_static(), "\n";
$a = new A;
$b = new B;
echo '$b->prop_instance: ', $b->prop_instance, "\n";
//not recommended (static method called as instance method):
echo '$b->func_static(): ', $b->func_static(), "\n";
echo '$b->func_instance():', "\n", $b->func_instance(), "\n";
/* This is more tricky
* in the first case, a static call is made because $this is an
* instance of A, so B::dyn() is a method of an incompatible class
*/
echo '$a->dyn():', "\n", $a->callDynamic(), "\n";
/* in this case, an instance call is made because $this is an
* instance of B (despite the fact we are in a method of A), so
* B::dyn() is a method of a compatible class (namely, it's the
* same class as the object's)
*/
echo '$b->dyn():', "\n", $b->callDynamic(), "\n";
Output:
B::$prop_static: B::$prop_static value B::func_static(): in B::func_static $b->prop_instance: B::$prop_instance value $b->func_static(): in B::func_static $b->func_instance(): in B::func_instance in A::func_instance in A::func_instance $a->dyn(): in A::callDynamic in dynamic dyn (__callStatic) $b->dyn(): in A::callDynamic in dynamic dyn (__call)
I had this problem recently where apt install wget
does not find anything. As it turns out apt update
was never run.
apt update
apt install wget
After discussing this with a coworker we mused that apt update
is likely not run in order to save both time and space in the docker image.
I think the problem is that you want one result for each p.id?
But you are getting "duplicate" results for some p.id's, is that right?
The DISTINCT keyword applies to the entire result set, so applies to pl.nm, pl.val, pl.txt_val, not just p.id.
You need something like
SELECT TOP 10 p.id, max( p1.nm ), max (p1.val), ...
FROM ...
GROUP BY p.id
Won't need the distinct keyword then.
If you are using XIB for tableView's main headerView you can set XIB as a freeform set the Height as you want and unclick Autoresizing's top,bottom blocks and upper,lower arrows.Only horizontal pieces will be selected.Vertical will be unselected as I mentioned above.
Include <tchar.h>
which has the line:
#define _tWinMain wWinMain
Probably you are looking for something like this:
Accept "2.0 or 2.0 as an INT but reject 2.1 and "2.1"
num = 2.0
if num.is_a? String num = Float(num) rescue false end
new_num = Integer(num) rescue false
puts num
puts new_num
puts num == new_num
n = 2
a=dataframe['name'].value_counts()[:n].index.tolist()
dataframe["name"].value_counts()[a]
In my case just run the command and worked like charm.
php artisan route:clear
Issues arise among before and after versions of Android 4.0 (API level 14).
from here I created my own solution.
@SuppressLint("NewApi")
@Override
protected void onResume()
{
super.onResume();
if (Build.VERSION.SDK_INT < 16)
{
// Hide the status bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
// Hide the action bar
getSupportActionBar().hide();
}
else
{
// Hide the status bar
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
/ Hide the action bar
getActionBar().hide();
}
}
I write this code in onResume() method because if you exit from your app and then you reopen it, the action bar remains active! (and so this fix the problem)
I hope it was helpful ;)
Simple and easy trick:
$host = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$path = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$baseurl = "http://" . $host . $path . "/";
URL looks like this: http://example.com/folder/
I'm late to the party, but hopefully this is a useful addition to the other answers here...
I need to know how I can determine what "too much work" my application may be doing as all my processing is done in AsyncTasks.
The following are all candidates:
Uri
's on ImageView
's all constitute IO on the main thread)View
hierarchiesView
hierarchyonDraw
methods in custom View
'sAsyncTask
's are "background" by default, java.lang.Thread
is not)To actually determine the specific cause you'll need to profile your app.
I've been trying to understand Choreographer by experimenting and looking at the code.
The documentation of Choreographer opens with "Coordinates the timing of animations, input and drawing." which is actually a good description, but the rest goes on to over-emphasize animations.
The Choreographer is actually responsible for executing 3 types of callbacks, which run in this order:
The aim is to match the rate at which invalidated views are re-drawn (and animations tweened) with the screen vsync - typically 60fps.
The warning about skipped frames looks like an afterthought: The message is logged if a single pass through the 3 steps takes more than 30x the expected frame duration, so the smallest number you can expect to see in the log messages is "skipped 30 frames"; If each pass takes 50% longer than it should you will still skip 30 frames (naughty!) but you won't be warned about it.
From the 3 steps involved its clear that it isn't only animations that can trigger the warning: Invalidating a significant portion of a large View
hierarchy or a View
with a complicated onDraw method might be enough.
For example this will trigger the warning repeatedly:
public class AnnoyTheChoreographerActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_linear_layout);
ViewGroup root = (ViewGroup) findViewById(R.id.root);
root.addView(new TextView(this){
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
long sleep = (long)(Math.random() * 1000L);
setText("" + sleep);
try {
Thread.sleep(sleep);
} catch (Exception exc) {}
}
});
}
}
... which produces logging like this:
11-06 09:35:15.865 13721-13721/example I/Choreographer? Skipped 42 frames! The application may be doing too much work on its main thread.
11-06 09:35:17.395 13721-13721/example I/Choreographer? Skipped 59 frames! The application may be doing too much work on its main thread.
11-06 09:35:18.030 13721-13721/example I/Choreographer? Skipped 37 frames! The application may be doing too much work on its main thread.
You can see from the stack during onDraw
that the choreographer is involved regardless of whether you are animating:
at example.AnnoyTheChoreographerActivity$1.onDraw(AnnoyTheChoreographerActivity.java:25) at android.view.View.draw(View.java:13759)
... quite a bit of repetition ...
at android.view.ViewGroup.drawChild(ViewGroup.java:3169) at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3039) at android.view.View.draw(View.java:13762) at android.widget.FrameLayout.draw(FrameLayout.java:467) at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:2396) at android.view.View.getDisplayList(View.java:12710) at android.view.View.getDisplayList(View.java:12754) at android.view.HardwareRenderer$GlRenderer.draw(HardwareRenderer.java:1144) at android.view.ViewRootImpl.draw(ViewRootImpl.java:2273) at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2145) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1956) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1112) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4472) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725) at android.view.Choreographer.doCallbacks(Choreographer.java:555) at android.view.Choreographer.doFrame(Choreographer.java:525) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711) at android.os.Handler.handleCallback(Handler.java:615) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4898)
Finally, if there is contention from other threads that reduce the amount of work the main thread can get done, the chance of skipping frames increases dramatically even though you aren't actually doing the work on the main thread.
In this situation it might be considered misleading to suggest that the app is doing too much on the main thread, but Android really wants worker threads to run at low priority so that they are prevented from starving the main thread. If your worker threads are low priority the only way to trigger the Choreographer warning really is to do too much on the main thread.
It's easy, do this way
private static final int REQUEST_READ_PHONE_STATE = 110 , REQUEST_ACCESS_FINE_LOCATION = 111, REQUEST_WRITE_STORAGE = 112;
In your onCreate
//request permission
boolean hasPermissionPhoneState = (ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED);
if (!hasPermissionPhoneState) {
ActivityCompat.requestPermissions(LoginActivity.this,
new String[]{Manifest.permission.READ_PHONE_STATE},
REQUEST_READ_PHONE_STATE);
}
boolean hasPermissionLocation = (ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED);
if (!hasPermissionLocation) {
ActivityCompat.requestPermissions(LoginActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_ACCESS_FINE_LOCATION);
}
boolean hasPermissionWrite = (ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
if (!hasPermissionWrite) {
ActivityCompat.requestPermissions(LoginActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_WRITE_STORAGE);
}
Then check result
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case REQUEST_READ_PHONE_STATE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(LoginActivity.this, "Permission granted.", Toast.LENGTH_SHORT).show();
//reload my activity with permission granted or use the features what required the permission
finish();
startActivity(getIntent());
} else
{
Toast.makeText(LoginActivity.this, "The app was not allowed to get your phone state. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
case REQUEST_ACCESS_FINE_LOCATION: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(LoginActivity.this, "Permission granted.", Toast.LENGTH_SHORT).show();
//reload my activity with permission granted or use the features what required the permission
finish();
startActivity(getIntent());
} else
{
Toast.makeText(LoginActivity.this, "The app was not allowed to get your location. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
case REQUEST_WRITE_STORAGE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(LoginActivity.this, "Permission granted.", Toast.LENGTH_SHORT).show();
//reload my activity with permission granted or use the features what required the permission
finish();
startActivity(getIntent());
} else
{
Toast.makeText(LoginActivity.this, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
}
}
Where are you configuring your authenticated URL pattern(s)? I only see one uri in your code.
Do you have multiple configure(HttpSecurity) methods or just one? It looks like you need all your URIs in the one method.
I have a site which requires authentication to access everything so I want to protect /*. However in order to authenticate I obviously want to not protect /login. I also have static assets I'd like to allow access to (so I can make the login page pretty) and a healthcheck page that shouldn't require auth.
In addition I have a resource, /admin, which requires higher privledges than the rest of the site.
The following is working for me.
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login**").permitAll()
.antMatchers("/healthcheck**").permitAll()
.antMatchers("/static/**").permitAll()
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
.antMatchers("/**").access("hasRole('ROLE_USER')")
.and()
.formLogin().loginPage("/login").failureUrl("/login?error")
.usernameParameter("username").passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/login?logout")
.and()
.exceptionHandling().accessDeniedPage("/403")
.and()
.csrf();
}
NOTE: This is a first match wins so you may need to play with the order. For example, I originally had /** first:
.antMatchers("/**").access("hasRole('ROLE_USER')")
.antMatchers("/login**").permitAll()
.antMatchers("/healthcheck**").permitAll()
Which caused the site to continually redirect all requests for /login back to /login. Likewise I had /admin/** last:
.antMatchers("/**").access("hasRole('ROLE_USER')")
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
Which resulted in my unprivledged test user "guest" having access to the admin interface (yikes!)
It may be a permission issue,
Please try the following command /etc/init.d/mysqld start
as root user.
Use JOIN to join the subqueries and use ON to say where the rows from each subquery must match:
SELECT T1.col_a, T1.col_b, T2.col_c
FROM (SELECT col_a, col_b, ...etc...) AS T1
JOIN (SELECT col_a, col_c, ...etc...) AS T2
ON T1.col_a = T2.col_a
If there are some values of col_a that are in T1 but not in T2, you can use a LEFT OUTER JOIN instead.
If anyone cares, for NTEXT
, use the following format:
SELECT CAST(REPLACE(CAST([ColumnValue] AS NVARCHAR(MAX)),'find','replace') AS NTEXT)
FROM [DataTable]
For all built-in Python objects (like strings, lists, dicts, functions, etc.), if x is y, then x==y is also True.
Not always. NaN is a counterexample. But usually, identity (is
) implies equality (==
). The converse is not true: Two distinct objects can have the same value.
Also, is it generally considered better to just use '==' by default, even when comparing int or Boolean values?
You use ==
when comparing values and is
when comparing identities.
When comparing ints (or immutable types in general), you pretty much always want the former. There's an optimization that allows small integers to be compared with is
, but don't rely on it.
For boolean values, you shouldn't be doing comparisons at all. Instead of:
if x == True:
# do something
write:
if x:
# do something
For comparing against None
, is None
is preferred over == None
.
I've always liked to use 'is' because I find it more aesthetically pleasing and pythonic (which is how I fell into this trap...), but I wonder if it's intended to just be reserved for when you care about finding two objects with the same id.
Yes, that's exactly what it's for.
Download and install LINQPad, it works for SQL Server, MySQL, SQLite and also SDF (SQL CE 4.0).
Steps for open SDF Files:
Click Add Connection
Select Build data context automatically and Default (LINQ to SQL), then Next.
Under Provider choose SQL CE 4.0.
Under Database with Attach database file selected, choose Browse to select your .sdf file.
Click OK.
Since you're using ToFileTime
, you'll want to use FromFileTime to go the other way. But note:
Ordinarily, the FromFileTime method restores a DateTime value that was saved by the ToFileTime method. However, the two values may differ under the following conditions:
If the serialization and deserialization of the DateTime value occur in different time zones. For example, if a DateTime value with a time of 12:30 P.M. in the U.S. Eastern Time zone is serialized, and then deserialized in the U.S. Pacific Time zone, the original value of 12:30 P.M. is adjusted to 9:30 A.M. to reflect the difference between the two time zones.
If the DateTime value that is serialized represents an invalid time in the local time zone. In this case, the ToFileTime method adjusts the restored DateTime value so that it represents a valid time in the local time zone.
If you don't care which long
representation of a DateTime is stored, you can use Ticks
as others have suggested (Ticks is probably preferable, depending on your requirements, since the value returned by ToFileTime
seems to be in the context of the Windows filesystem API).
Policykit is a system daemon and policykit authentication agent is used to verify identity of the user before executing actions. The messages logged in /var/log/secure
show that an authentication agent is registered when user logs in and it gets unregistered when user logs out. These messages are harmless and can be safely ignored.
You can use array_count_values function
$array = array('apple', 'orange', 'pear', 'banana', 'apple',
'pear', 'kiwi', 'kiwi', 'kiwi');
print_r(array_count_values($array));
will output
Array
(
[apple] => 2
[orange] => 1
[pear] => 2
etc...
)
I use :
int convertToInt(char a[1000]){
int i = 0;
int num = 0;
while (a[i] != 0)
{
num = (a[i] - '0') + (num * 10);
i++;
}
return num;;
}
On Windows 10 install Python from Python.org Once installed add these two paths to PATH env variable C:\Users<your user>\AppData\Local\Programs\Python\Python38 C:\Users<your user>\AppData\Local\Programs\Python\Python38\Scripts
Open command prompt and following command should be working python --version pip --version
This is actually trickier than it looks, because you can't call strlen
unless the string is actually nul terminated. In fact, without some
additional constraints, the problem practically requires inventing a new
function, a version of strlen
which never goes beyond the a certain
length. However:
If the buffer containing the c-style string is guaranteed to be at least
max_length
char's (although perhaps with a '\0'
before the end),
then you can use the address-length constructor of std::string
, and
trim afterwards:
std::string result( c_string, max_length );
result.erase( std::find( result.begin(), result.end(), '\0' ), result.end() );
and if you know that c_string
is a nul terminated string (but perhaps
longer than max_length
, you can use strlen
:
std::string result( c_string, std::min( strlen( c_string ), max_length ) );
Here's a list : http://delphi.about.com/od/devutilities/a/decompiling_3.htm (and this page mentions some more : http://www.program-transformation.org/Transform/DelphiDecompilers )
I've used DeDe on occasion, but it's not really all that powerfull, and it's not up-to-date with current Delphi versions (latest version it supports is Delphi 7 I believe)
You just need this simple code:
Code:
private void updateAdapter() {
if (adapterViewPager != null) {
int from = vpMyViewPager.getCurrentItem() - vpMyViewPager.getOffscreenPageLimit();
int to = vpMyViewPager.getCurrentItem() + vpMyViewPager.getOffscreenPageLimit();
vpMyViewPager.removeAllViews();
for (int i = from; i <= to; i++) {
if (i < 0) {
continue;
}
adapterViewPager.instantiateItem(vpMyViewPager, i);
}
}
}
Explanation:
If you haven't changed offscreenPageLimit
of the ViewPager
, it always has 3 to 4 children depending on which direction you are going. And in order to show the correct content inside its children, it uses the adapter to get the right content.
now when you call removeAllViews()
on your ViewPager
, only 3 to 4 View
s are actually being removed from the Window
's hierarchy, and by calling instantiateItem(ViewGroup viewPager, int index)
, you are only recreating 3 to 4 View
s. Then everything is back to normal, you swipe and scroll, the ViewPager
shows contents using its adapter. The number of its children is not the same on all devices in all situations, for example if you set the offscreenPageLimit
to 5, it will probably have around 11 to 12 children, but that's all, it's not much. it's fast.
It looks like you are trying to read an object from JSON that actually describes an array. Java objects are mapped to JSON objects with curly braces {}
but your JSON actually starts with square brackets []
designating an array.
What you actually have is a List<product>
To describe generic types, due to Java's type erasure, you must use a TypeReference
. Your deserialization could read: myProduct = objectMapper.readValue(productJson, new TypeReference<List<product>>() {});
A couple of other notes: your classes should always be PascalCased. Your main method can just be public static void main(String[] args) throws Exception
which saves you all the useless catch
blocks.
(returnValue != "1" ? false : true);
to take output in MySQL you can use if statement SYNTAX:
if(condition,if_true,if_false)
the if_true and if_false can be used to verify and to show output as there is no print statement in the MySQL
From MSDN:
Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This is the code to use if you are have called Application.Run (WinForms applications), this method stops all running message loops on all threads and closes all windows of the application.
Terminates this process and gives the underlying operating system the specified exit code. This is the code to call when you are using console application.
This article, Application.Exit vs. Environment.Exit, points towards a good tip:
You can determine if System.Windows.Forms.Application.Run
has been called by checking the System.Windows.Forms.Application.MessageLoop
property. If true, then Run has been called and you can assume that a WinForms application is executing as follows.
if (System.Windows.Forms.Application.MessageLoop)
{
// WinForms app
System.Windows.Forms.Application.Exit();
}
else
{
// Console app
System.Environment.Exit(1);
}
Reference: Why would Application.Exit fail to work?
It's a 32-bit signed integer type on most legacy platforms. However, that causes your code to suffer from the year 2038 bug. So modern C libraries should be defining it to be a signed 64-bit int instead, which is safe for a few billion years.
Now I see what you are doing. You cannot send output to the screen then change the headers. If you are trying to create an XML file of map marker and download them to display, they should be in separate files.
Take this
<?php
require("database.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
?>
and place it in phpsqlajax_genxml.php
so your javascript can download the XML file. You are trying to do too many things in the same file.
This is how I got it to finally go to the proper place when you click on the navigation. I added an event handler for the navigation clicks. Then you can just use "scrollBy" to move up on the offset.
var offset = 90;
$('.navbar li a').click(function(event) {
event.preventDefault();
$($(this).attr('href'))[0].scrollIntoView();
scrollBy(0, -offset);
});
Google is my friend and it showed me this page:
I have added below line and its working fine.
-vm C:/Program Files/Java/jdk1.6.0_16/bin/javax.exe
-Xmx512m
-Dosgi.requiredJavaVersion=1.6
I just had the same problem the solution is easy.
You are trying to add an id in the child table that does not exist in the parent table.
check well, because InnoDB has the bug that sometimes increases the auto_increment column without adding values, for example, INSERT ... ON DUPLICATE KEY
Lombok Issue #78 references this page https://www.donneo.de/2015/09/16/lomboks-builder-annotation-and-inheritance/ with this lovely explanation:
@AllArgsConstructor public class Parent { private String a; } public class Child extends Parent { private String b; @Builder public Child(String a, String b){ super(a); this.b = b; } }
As a result you can then use the generated builder like this:
Child.builder().a("testA").b("testB").build();
The official documentation explains this, but it doesn’t explicitly point out that you can facilitate it in this way.
I also found this works nicely with Spring Data JPA.
getDerivedStateFromProps is used whenever you want to update state before render and update with the condition of props
GetDerivedStateFromPropd updating the stats value with the help of props value
If you don't have to support IE, you can use selectionStart
and selectionEnd
attributes of textarea
.
To get caret position just use selectionStart
:
function getCaretPosition(textarea) {
return textarea.selectionStart
}
To get the strings surrounding the selection, use following code:
function getSurroundingSelection(textarea) {
return [textarea.value.substring(0, textarea.selectionStart)
,textarea.value.substring(textarea.selectionStart, textarea.selectionEnd)
,textarea.value.substring(textarea.selectionEnd, textarea.value.length)]
}
See also HTMLTextAreaElement docs.
just follow below steps:
//Start Excel and get Application object.
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = false;
list1 = (x[0] for x in source_list)
list2 = (x[1] for x in source_list)
Oracle SQL Developer 4.0.1.14 surely does support connections to PostgreSQL.
Tools ? Preferences
, Database ? Third Party JDBC Drivers
and add the jar file (see http://www.oracle.com/technetwork/products/migration/jdbc-migration-1923524.html for step by step example)Database Connection
and instead of Oracle
, select PostgreSQL
tabEdit:
If you have different user name and database name, one should specify in hostname: hostname/database?
(do not forget ?
) or hostname:port/database?
.
(thanks to @kinkajou and @Kloe2378231; more details on https://stackoverflow.com/a/28671213/565525).
goobox()
will take the URL of your image file, and change it to be used directly as an image source.cconst goobox = (url)=>{
let dropbox_regex = /(http(s)*:\/\/)*(www\.)*(dropbox.com)/;
let drive_regex =/(http(s)*:\/\/)*(www\.)*(drive.google.com\/file\/d\/)/;
if(url.match(dropbox_regex)){
return url.replace(/(http(s)*:\/\/)*(www\.)*/, "https://dl.");
}
if(url.match(drive_regex)){
return `https://drive.google.com/uc?id=${url.replace(drive_regex, "").match(/[\w]*\//)[0].replace(/\//,"")}`;
}
return console.error('Wrong URL, not a vlid drobox or google drive url');
}
let url = 'https://drive.google.com/file/d/1PiCWHIwyQWrn4YxatPZDkB8EfegRIkIV/view'
goobox(URL); // https://drive.google.com/uc?id=1PiCWHIwyQWrn4YxatPZDkB8EfegRIkIV
The androidmanifest.xml and policies.xml files on the sample page are invisible in my browser due to it trying to format the XML files as HTML. I'm only posting this for reference for the convenience of others, this is sourced from the sample page.
Thanks all for this helpful question!
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kns"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".LockScreenActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyAdmin"
android:permission="android.permission.BIND_DEVICE_ADMIN">
<meta-data android:name="android.app.device_admin"
android:resource="@xml/policies" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
</intent-filter>
</receiver>
</application>
</manifest>
policies.xml
<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
<uses-policies>
<limit-password />
<watch-login />
<reset-password />
<force-lock />
<wipe-data />
</uses-policies>
</device-admin>
I had the same problem, on Windows7.
I was getting error 2147942667 and a report of being unable to run c:\windows\system32\CMD.EXE. I tried with and without double quotes in the Script and Start-in and it made no difference. Then I tried replacing all path references to mapped network drives and with UNC references (\Server1\Sharexx\my_scripts\run_this.cmd) and that fixed it for me. Pat.
I've merged some solutions together:
public static int getStatusBarHeight(final Context context) {
final Resources resources = context.getResources();
final int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0)
return resources.getDimensionPixelSize(resourceId);
else
return (int) Math.ceil((VERSION.SDK_INT >= VERSION_CODES.M ? 24 : 25) * resources.getDisplayMetrics().density);
}
another alternative:
final View view = findViewById(android.R.id.content);
runJustBeforeBeingDrawn(view, new Runnable() {
@Override
public void run() {
int statusBarHeight = getResources().getDisplayMetrics().heightPixels - view.getMeasuredHeight();
}
});
EDIT: Alternative to runJustBeforeBeingDrawn: https://stackoverflow.com/a/28136027/878126
Common practice for handling currency is to use decimal type. Here is a simple example from "Agile Web Development with Rails"
add_column :products, :price, :decimal, :precision => 8, :scale => 2
This will allow you to handle prices from -999,999.99 to 999,999.99
You may also want to include a validation in your items like
def validate
errors.add(:price, "should be at least 0.01") if price.nil? || price < 0.01
end
to sanity-check your values.
Add hide
class to alert-message
. Then put the following code after your jQuery script import:
$(document).ready( function(){
$(".alert-message").animate({ 'height':'toggle','opacity':'toggle'});
window.setTimeout( function(){
$(".alert-message").slideUp();
}, 2500);
});
If you want handle multiple messages, this code will hide them in ascending order:
$(document).ready( function(){
var hide_delay = 2500; // starting timeout before first message is hidden
var hide_next = 800; // time in mS to wait before hiding next message
$(".alert-message").slideDown().each( function(index,el) {
window.setTimeout( function(){
$(el).slideUp(); // hide the message
}, hide_delay + hide_next*index);
});
});
For Each row As DataGridViewRow In yourDGV.SelectedRows
yourDGV.Rows.Remove(row)
Next
This will delete all rows that had been selected.
You can use lftp interactively in a shell script so the password not saved in .bash_history or similar by doing the following:
vi test_script.sh
Add the following to your file:
#!/bin/sh
HOST=<yourhostname>
USER=<someusername>
PASSWD=<yourpasswd>
cd <base directory for your put file>
lftp<<END_SCRIPT
open sftp://$HOST
user $USER $PASSWD
put local-file.name
bye
END_SCRIPT
And write/quit the vi editor after you edit the host, user, pass, and directory for your put file typing :wq
.Then make your script executable chmod +x test_script.sh
and execute it ./test_script.sh
.
This is now supported (since ScalaTest 2.1.3) within interactive mode:
testOnly *MySuite -- -z foo
to run only the tests whose name includes the substring "foo".
For exact match rather than substring, use -t
instead of -z
.
In my case, I want to add a column to a Primary key (column4). I used this script to add column4
ALTER TABLE TableA
DROP CONSTRAINT [PK_TableA]
ALTER TABLE TableA
ADD CONSTRAINT [PK_TableA] PRIMARY KEY (
[column1] ASC,
[column2] ASC,
[column3] ASC,
[column4] ASC
)
This error is also at times deceiving. It says file is not found even though the files is indeed present. It could be because of invalid unreadable special characters present in the files that could be caused by the editor you are using. This link might help you in such cases.
-bash: ./my_script: /bin/bash^M: bad interpreter: No such file or directory
The best way to find out if it is this issue is to simple place an echo statement in the entire file and verify if the same error is thrown.
Here is a pure-java implementation of background image repeating:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.bg_image);
BitmapDrawable bitmapDrawable = new BitmapDrawable(bmp);
bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
LinearLayout layout = new LinearLayout(this);
layout.setBackgroundDrawable(bitmapDrawable);
}
In this case, our background image would have to be stored in res/drawable/bg_image.png.
There are all sorts of things which can do this. One possiblity is "Traffic Shaping". This is commonly done in office environments to reserve bandwidth for business critical activities. It may also be done by the web hosting company, or by your ISP, for very similar reasons.
You can also set it up at home very simply.
For example there may be a rule reserving minimum bandwidth for FTP, while SFTP might be falling under an "everything else" rule. Or there might be a rule capping bandwidth for SFTP, but someone else is also using SFTP at the same time as you.
So: Where are you tranferring the file from and to?
For anyone looking to do this dynamically then setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom)
on the buttons object will assist.
Sample
Button search = (Button) findViewById(R.id.yoursearchbutton);
search.setCompoundDrawables('your_drawable',null,null,null);
in fact, you can, but not that way.
Sub MySub( Optional Byval Counter as Long=1 , Optional Byval Events as Boolean= True)
'code...
End Sub
And you can set the variables differently when calling the sub, or let them at their default values.
As for me, it's a bad and quick solution for your problem :
android {
lintOptions {
abortOnError false
}
}
Better solution is solving problem in your code, because lint tool checks your Android project source files for potential bugs and optimization improvements for correctness, security, performance, usability, accessibility, and internationalization.
This problem most frequently occurring when:
Find your bugs by Inspect Code
in Android Studio: Improve Your Code with Lint
All the previous posts bring valid points, but some don't answer the question precisely.
The question is: Why would someone prefer money when we already know it is a less precise data type and can cause errors if used in complex calculations?
You use money when you won't make complex calculations and can trade this precision for other needs.
For example, when you don't have to make those calculations, and need to import data from valid currency text strings. This automatic conversion works only with MONEY data type:
SELECT CONVERT(MONEY, '$1,000.68')
I know you can make your own import routine. But sometimes you don't want to recreate a import routine with worldwide specific locale formats.
Another example, when you don't have to make those calculations (you need just to store a value) and need to save 1 byte (money takes 8 bytes and decimal(19,4) takes 9 bytes). In some applications (fast CPU, big RAM, slow IO), like just reading huge amount of data, this can be faster too.
From the links the others have posted, I'm not seeing an option. -- I just use powershell to kill it -- you can save this to a Stop-IisExpress.ps1 file:
get-process | where { $_.ProcessName -like "IISExpress" } | stop-process
There's no harm in it -- Visual Studio will just pop a new one up when it wants one.
Boolean
wraps the boolean primitive type. In JDK 5 and upwards, Oracle (or Sun before Oracle bought them) introduced autoboxing/unboxing, which essentially allows you to do this
boolean result = Boolean.TRUE;
or
Boolean result = true;
Which essentially the compiler does,
Boolean result = Boolean.valueOf(true);
So, for your answer, it's YES.
I like Imagemagick. http://www.imagemagick.org/script/api.php
This is slighly more OS independent way:
# do this init somewhere
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
font = pygame.font.Font(pygame.font.get_default_font(), 36)
# now print the text
text_surface = font.render('Hello world', antialias=True, color=(0, 0, 0))
screen.blit(text_surface, dest=(0,0))
You can use unirest, It provides easy method to post request. `
import unirest
def callback(response):
print "code:"+ str(response.code)
print "******************"
print "headers:"+ str(response.headers)
print "******************"
print "body:"+ str(response.body)
print "******************"
print "raw_body:"+ str(response.raw_body)
# consume async post request
def consumePOSTRequestASync():
params = {'test1':'param1','test2':'param2'}
# we need to pass a dummy variable which is open method
# actually unirest does not provide variable to shift between
# application-x-www-form-urlencoded and
# multipart/form-data
params['dummy'] = open('dummy.txt', 'r')
url = 'http://httpbin.org/post'
headers = {"Accept": "application/json"}
# call get service with headers and params
unirest.post(url, headers = headers,params = params, callback = callback)
# post async request multipart/form-data
consumePOSTRequestASync()
The .spec.ts files are for unit tests for individual components.
You can run Karma task runner through ng test
. In order to see code coverage of unit test cases for particular components run ng test --code-coverage
Using functions with the ellipses is not very safe. If performance is not critical for log function consider using operator overloading as in boost::format. You could write something like this:
#include <sstream>
#include <boost/format.hpp>
#include <iostream>
using namespace std;
class formatted_log_t {
public:
formatted_log_t(const char* msg ) : fmt(msg) {}
~formatted_log_t() { cout << fmt << endl; }
template <typename T>
formatted_log_t& operator %(T value) {
fmt % value;
return *this;
}
protected:
boost::format fmt;
};
formatted_log_t log(const char* msg) { return formatted_log_t( msg ); }
// use
int main ()
{
log("hello %s in %d-th time") % "world" % 10000000;
return 0;
}
The following sample demonstrates possible errors with ellipses:
int x = SOME_VALUE;
double y = SOME_MORE_VALUE;
printf( "some var = %f, other one %f", y, x ); // no errors at compile time, but error at runtime. compiler do not know types you wanted
log( "some var = %f, other one %f" ) % y % x; // no errors. %f only for compatibility. you could write %1% instead.
You can use pub_image context (holder.pub_image.getContext()
) :
@Override
public void onBindViewHolder(ViewHolder ViewHolder, int position) {
holder.txtHeader.setText(mDataset.get(position).getPost_text());
Picasso.with(holder.pub_image.getContext()).load("http://i.imgur.com/DvpvklR.png").into(holder.pub_image);
}
Use ORACLE equivalent of getdate()
which is sysdate
. Read about here.
Getdate() belongs to SQL Server , will not work on Oracle.
Other option is current_date
df.groupby(df.columns.tolist()).size().reset_index().\
rename(columns={0:'records'})
one two records
0 1 1 2
1 1 2 1
I had the same issue in C# using 64-bit Windows and the 64-bit Firefox browser which doesn't seem to work on Selenium. If you are using the 64-bit browser, try the 32-bit one.
Surprisingly, the 32-bit Firefox browser runs on 64-bit Windows just fine.
Edited to clarify the intent of my post.
you can check the type. s3 has a special application/x-directory
bucket.objects({:delimiter=>"/", :prefix=>"f1/"}).each { |obj| p obj.object.content_type }
In addition to @Emilia Apostolova answer to get the ground truth labels, from
generator = train_datagen.flow_from_directory("train", batch_size=batch_size)
just call
y_true_labels = generator.classes
Not pretty good solution, but you can try the hjson tool. It allows you to write text multi-lined in editor and then converts it to the proper valid JSON format.
Note: it adds '\n' characters for the new lines, but you can simply delete them in any text editor with the "Replace all.." function.
This also works:
REPLACE(ISNULL(CONVERT(DATE, @date), ''), '1900-01-01', '') AS 'Your Date Field'
There are many ways to list all containers.
You can find using 3 Aliases
ls, ps, list
like this.
sudo docker container ls
sudo docker container ps
sudo docker container list
sudo docker ps
sudo docker ps -a
You can also use give option[option]
.
Options -:
-a, --all Show all containers (default shows just running)
-f, --filter filter Filter output based on conditions provided
--format string Pretty-print containers using a Go template
-n, --last int Show last created containers (includes all states) (default -1)
-l, --latest Show the latest created container (includes all states)
--no-trunc Don't truncate output
-q, --quiet Only display numeric IDs
-s, --size Display total file sizes
You can use an option like this:
sudo docker ps //Showing only running containers
sudo docker ps -a //All container (running + stopped)
sudo docker pa -l // latest
sudo docker ps -n <int valuse 1,2,3 etc>// latest number of created containers
sudo docker ps -s // Display container with size
sudo docker ps -q // Only display numeric IDs for containers
docker docker ps -a | tail -n 1 //oldest container
You can use the Random generator to generate a random index and return the element at that index:
//initialization
Random generator = new Random();
int randomIndex = generator.nextInt(myArray.length);
return myArray[randomIndex];
I had a similar problem with ASP with my pages. I've resolved so:
1) Inserted at the begin of the ASP file called by Jquery ajax method the instruction:
Response.Charset = "windows-1252"
In My asp page before the charset wasn't defined and i had saved my file with ANSI encoding (with a text editor as notepad++)
2) In the html file that calls the ASP file with the jquery ajax method i've inserted the parameter content-type that you see below:
$.ajax({
data: parameters,
type: "POST",
url: ajax_url,
datatype: 'html',
contentType: "text/html;charset=windows-1252",
Briefly, it's important to define in your ASP file called the charset. Strangely, I see that my jquery works with windows-1252 but doesn't work with ISO-8859-1 charset: in this case jquery ajax method give an exception.
Unlike the C#/.NET class library (and most other sensible languages), when you pass a String
in as the string-to-match argument to the string.replace
method, it doesn't do a string replace. It converts the string to a RegExp
and does a regex substitution. As Gumbo explains, a regex substitution requires the g
?lobal flag, which is not on by default, to replace all matches in one go.
If you want a real string-based replace — for example because the match-string is dynamic and might contain characters that have a special meaning in regexen — the JavaScript idiom for that is:
var id= 'c_'+date.split('/').join('');
To be able to access the form in your controller, you have to add it to a dummy scope object.
Something like $scope.dummy = {}
For your situation this would mean something like:
<form name="dummy.customerForm">
In your controller you will be able to access the form by:
$scope.dummy.customerForm
and you will be able to do stuff like
$scope.dummy.customerForm.$setPristine()
Having a '.' in your models will ensure that prototypal inheritance is in play. So, use
<input type="text" ng-model="someObj.prop1">
rather than<input type="text" ng-model="prop1">
If you really want/need to use a primitive, there are two workarounds:
1.Use $parent.parentScopeProperty in the child scope. This will prevent the child scope from creating its own property. 2.Define a function on the parent scope, and call it from the child, passing the primitive value up to the parent (not always possible)
As mentioned in the earlier comment, stacked bar chart does the trick, though the data needs to be setup differently.(See image below)
Duration column = End - Start
Here is an alternative method using ls
:
(ls x.txt && echo yes) || echo no
If you want to hide any output from ls
so you only see yes or no, redirect stdout
and stderr
to /dev/null
:
(ls x.txt >> /dev/null 2>&1 && echo yes) || echo no
This can also be achieved with the CSS "Order" property and a media query.
Something like this:
@media only screen and (max-width: 768px) {
#first {
order: 2;
}
#second {
order: 4;
}
#third {
order: 1;
}
#fourth {
order: 3;
}
}
CodePen Link: https://codepen.io/preston206/pen/EwrXqm
Shared hosting no ssh or shell access?
Here is how i did it;
Most of the time, if you are very sure you imported the library in question, Visual Studio will guide you with IntelliSense.
Here is what worked for me:
Make sure that #include "stdafx.h"
is declared first, that is, at the top of all of your includes.
Ansible remote_src does not support recursive copying.See remote_src description in Ansible copy docs
To recursively copy the contents of a folder and to make sure the task stays idempotent I usually do it this way:
- name: get file names to copy
command: "find /home/vagrant/dist -type f"
register: files_to_copy
- name: copy files
copy:
src: "{{ item }}"
dest: "/usr/share/nginx/html"
owner: nginx
group: nginx
remote_src: True
mode: 0644
with_items:
- "{{ files_to_copy.stdout_lines }}"
Downside is that the find command still shows up as 'changed'
TLDR; The formula is n(n-1)/2
where n
is the number of items in the set.
To find the number of unique pairs in a set, where the pairs are subject to the commutative property (AB = BA)
, you can calculate the summation of 1 + 2 + ... + (n-1)
where n
is the number of items in the set.
The reasoning is as follows, say you have 4 items:
A
B
C
D
The number of items that can be paired with A
is 3, or n-1
:
AB
AC
AD
It follows that the number of items that can be paired with B
is n-2
(because B
has already been paired with A
):
BC
BD
and so on...
(n-1) + (n-2) + ... + (n-(n-1))
which is the same as
1 + 2 + ... + (n-1)
or
n(n-1)/2
Did you try using t.Text
?
You can change the passphrase for your private key by doing:
ssh-keygen -f ~/.ssh/id_rsa -p
Try Like This: For SQL SERVER 2008+
SELECT c.name AS ColName, t.name AS TableName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%MyColumnaName%'
Or
SELECT COLUMN_NAME, TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%MyName%'
Or Something Like This:
SELECT name
FROM sys.tables
WHERE OBJECT_ID IN ( SELECT id
FROM syscolumns
WHERE name like '%COlName%' )
You can use @UtilityClass annotation from lombok https://projectlombok.org/features/experimental/UtilityClass
in your server side the code looks like:
var request = require('request');
app.post('/add', function(req, res){
console.log(req.body);
request.post(
{
url:'http://localhost:6001/add',
json: {
unit_name:req.body.unit_name,
unit_price:req.body.unit_price
},
headers: {
'Content-Type': 'application/json'
}
},
function(error, response, body){
// console.log(error);
// console.log(response);
console.log(body);
res.send(body);
});
// res.send("body");
});
in receiving end server code looks like:
app.post('/add', function(req, res){
console.log('received request')
console.log(req.body);
let adunit = new AdUnit(req.body);
adunit.save()
.then(game => {
res.status(200).json({'adUnit':'AdUnit is added successfully'})
})
.catch(err => {
res.status(400).send('unable to save to database');
})
});
Schema is just two properties unit_name and unit_price.
Simply place normal button indide Ajax.BeginForm and on click find parent form and normal submit. Ajax form in Razor:
@using (Ajax.BeginForm("AjaxPost", "Home", ajaxOptions))
{
<div class="form-group">
<div class="col-md-12">
<button class="btn btn-primary" role="button" type="button" onclick="submitParentForm($(this))">Submit parent from Jquery</button>
</div>
</div>
}
and Javascript:
function submitParentForm(sender) {
var $formToSubmit = $(sender).closest('form');
$formToSubmit.submit();
}
I was asked to build a java system that will have the ability to load new code while running
You might want to base your system on OSGi (or at least take a lot at it), which was made for exactly this situation.
Messing with classloaders is really tricky business, mostly because of how class visibility works, and you do not want to run into hard-to-debug problems later on. For example, Class.forName(), which is widely used in many libraries does not work too well on a fragmented classloader space.
I was looking for this:
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
Based on @Peter Baley answer, I created a more generic function:
@objectId: HTML object ID
@values: can be a string or an array. String is less "secure" (should not contain repeated value).
function checkMultiValues(objectId, values){
selectMultiObject=document.getElementById(objectId);
for ( var i = 0, l = selectMultiObject.options.length, o; i < l; i++ )
{
o = selectMultiObject.options[i];
if ( values.indexOf( o.value ) != -1 )
{
o.selected = true;
} else {
o.selected = false;
}
}
}
Example: checkMultiValues('thisMultiHTMLObject','a,b,c,d');
In order to hide the exception:
For Hibernate 5.2 (and Spring Boot 2.0), you can either use the use_jdbc_metadata_defaults property that the others pointed out:
# Meant to hide HHH000424: Disabling contextual LOB creation as createClob() method threw error
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults: false
Or, if you want to not have any side effects from the above setting (there's a comment warning us about some Oracle side effects, I don't know if it's valid or not), you can just disable the logging of the exception like this:
logging:
level:
# Hides HHH000424: Disabling contextual LOB creation as createClob() method threw error
org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl: WARN
The top-scoring answer has the right idea, but the API seems to have evolved so that it no longer works as when it was first written, in 2015.
In place of this:
from OpenSSL import SSL
context = SSL.Context(SSL.PROTOCOL_TLSv1_2)
context.use_privatekey_file('server.key')
context.use_certificate_file('server.crt')
I used this, with Python 3.7.5:
import ssl
context = ssl.SSLContext()
context.load_cert_chain('fullchain.pem', 'privkey.pem')
and then supplied the SSL context in the Flask.run
call as it said:
app.run(…, ssl_context=context)
(My server.crt
file is called fullchain.pem
and my server.key
is called privkey.pem
. These files were supplied to me by my LetsEncrypt Certbot.)