See my comment above asking for clarification on what you really want. Hopefully this is it:
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
System.Diagnostics.FileVersionInfo fvi = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location);
string version = fvi.FileVersion;
Use the tee
command:
echo "hello" | tee logfile.txt
You can simply use JavaScripts join()
function for that. This would simply look like a.value.join(',')
. The output would be a string though.
check for this by calling the library jquery after the noconflict.js or that this calling more than once jquery library after the noconflict.js
My code was out of void setup() or void loop() in Arduino.
The equals method on List will do this, Lists are ordered, so to be equal two Lists must have the same elements in the same order.
return list1.equals(list2);
In this sample, I created a JavaScript progress bar (with percentage display), you can control it and hide it with JavaScript.
In this sample, the progress bar advances every 100ms. You can see it in JSFiddle
var elapsedTime = 0;
var interval = setInterval(function() {
timer()
}, 100);
function progressbar(percent) {
document.getElementById("prgsbarcolor").style.width = percent + '%';
document.getElementById("prgsbartext").innerHTML = percent + '%';
}
function timer() {
if (elapsedTime > 100) {
document.getElementById("prgsbartext").style.color = "#FFF";
document.getElementById("prgsbartext").innerHTML = "Completed.";
if (elapsedTime >= 107) {
clearInterval(interval);
history.go(-1);
}
} else {
progressbar(elapsedTime);
}
elapsedTime++;
}
You can delete documents from type with following query:
POST /index/type/_delete_by_query
{
"query" : {
"match_all" : {}
}
}
I tested this query in Kibana and Elastic 5.5.2
Why not just display it in the user's web browser?
Are there any libraries to do this in numpy/SciPy
Sure. You can do this without OpenCV, scikit-image or PIL.
Image resizing is basically mapping the coordinates of each pixel from the original image to its resized position.
Since the coordinates of an image must be integers (think of it as a matrix), if the mapped coordinate has decimal values, you should interpolate the pixel value to approximate it to the integer position (e.g. getting the nearest pixel to that position is known as Nearest neighbor interpolation).
All you need is a function that does this interpolation for you. SciPy has interpolate.interp2d
.
You can use it to resize an image in numpy array, say arr
, as follows:
W, H = arr.shape[:2]
new_W, new_H = (600,300)
xrange = lambda x: np.linspace(0, 1, x)
f = interp2d(xrange(W), xrange(H), arr, kind="linear")
new_arr = f(xrange(new_W), xrange(new_H))
Of course, if your image is RGB, you have to perform the interpolation for each channel.
If you would like to understand more, I suggest watching Resizing Images - Computerphile.
Not with a regular statement, no.
What you can do is wrap the functionality in a PL/pgsql function (or another language, but PL/pgsql seems to be the most appropriate for this), and then just call that function. That means it'll still be a single statement to your app.
I have added a helper da()
to Laravel which in fact works as an alias for dd($object->toArray())
Here is the Gist: https://gist.github.com/TommyZG/0505eb331f240a6324b0527bc588769c
If you're gonna use B2 for styling purposes you can try this "hack"
#B { overflow: hidden;}
#B2 {padding-bottom: 9999px; margin-bottom: -9999px}
This works for me when disabling finish Activity animation.
@Override
protected void onPause() {
super.onPause();
overridePendingTransition(0, 0);
}
If you are using Eclipse, for an existing project (which has a build.gradle
file) you can simply type gradle eclipse
which will create all the Eclipse files and folders for this project.
It takes care of all the dependencies for you and adds them to the project resource path in Eclipse as well.
Try to run below example in order to feel how the magical variables work.
@echo off
SETLOCAL EnableDelayedExpansion
echo Full path and filename: %~f0
echo Drive: %~d0
echo Path: %~p0
echo Drive and path: %~dp0
echo Filename without extension: %~n0
echo Filename with extension: %~nx0
echo Extension: %~x0
echo date time : %~t0
echo file size: %~z0
ENDLOCAL
The related rules are following.
%~I - expands %I removing any surrounding quotes ("")
%~fI - expands %I to a fully qualified path name
%~dI - expands %I to a drive letter only
%~pI - expands %I to a path only
%~nI - expands %I to a file name only
%~xI - expands %I to a file extension only
%~sI - expanded path contains short names only
%~aI - expands %I to file attributes of file
%~tI - expands %I to date/time of file
%~zI - expands %I to size of file
%~$PATH:I - searches the directories listed in the PATH
environment variable and expands %I to the
fully qualified name of the first one found.
If the environment variable name is not
defined or the file is not found by the
search, then this modifier expands to the
empty string
As a C++ Developer here's some simply guidelines:
As for the detection of memory leaks personally I've always used Visual Leak Detector and find it to be very useful.
Just in case, don't forget to guard range size before applying it to the string. Otherwise, you will get crash if the user will do this:
Type maximum length text Insert something (Nothing will be inserted due to length limitation, but iOS doesn't know about it) Undo insertion (You get crash, cause range will be greater than actual string size)
Also, using iOS 13 users can accidentally trigger this by gestures
I suggest you add to your project this
extension String {
func replace(with text: String, in range: NSRange) -> String? {
guard range.location + range.length <= self.count else { return nil }
return (self as NSString).replacingCharacters(in: range, with: text)
}
}
And use it like this:
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
guard let newText = textView.text.replace(with: text, in: range) else { return false }
return newText.count < maxNumberOfCharacters
}
Otherwise, you will constantly be getting crashed in your app
As others have pointed out, listeners have to be registered in order to read these streams. Also note that Debug.Write
will only function if the DEBUG
build flag is set, while Trace.Write
will only function if the TRACE
build flag is set.
Setting the DEBUG
and/or TRACE
flags is easily done in the project properties in Visual Studio or by supplying the following arguments to csc.exe
/define:DEBUG;TRACE
Use both. In fact refer a guide like the OWASP XSS Prevention cheat sheet, on the possible cases for usage of output encoding and input validation.
Input validation helps when you cannot rely on output encoding in certain cases. For instance, you're better off validating inputs appearing in URLs rather than encoding the URLs themselves (Apache will not serve a URL that is url-encoded). Or for that matter, validate inputs that appear in JavaScript expressions.
Ultimately, a simple thumb rule will help - if you do not trust user input enough or if you suspect that certain sources can result in XSS attacks despite output encoding, validate it against a whitelist.
Do take a look at the OWASP ESAPI source code on how the output encoders and input validators are written in a security library.
you can use jquery validator for that but you need to add jquery.validate.js and jquery.form.js file for that. after including validator file define your validation something like this.
<script type="text/javascript">
$(document).ready(function(){
$("#formID").validate({
rules :{
"data[User][name]" : {
required : true
}
},
messages :{
"data[User][name]" : {
required : 'Enter username'
}
}
});
});
</script>
You can see required : true
same there is many more property like for email you can define email : true
for number number : true
This started taking me down a huge rabbit hole of fixing glitches with Eclipse, however I just deleted the project from Eclipse and reimported it to fix it.
Fill in the service layer with the model and then send it to the view. For example: ViewItem=ModelItem.ToString().Substring(0,100);
chartr
is also convenient for these types of substitutions:
chartr("_", "-", data1$c)
# [1] "A-B" "A-B" "A-B" "A-B" "A-C" "A-C" "A-C" "A-C" "A-C" "A-C"
Thus, you can just do:
data1$c <- chartr("_", "-", data1$c)
So I had a problem I needed solved. I had an array object with values. One of those values I needed to update if the value == X.I needed X value to be updated to the Y value. Looking over examples here none of them worked for what I needed or wanted. I finally figured out a simple solution to the problem and was actually surprised it worked. Now normally I like to put the full code solution into these answers but due to its complexity I wont do that here. If anyone finds they cant make this solution work or need more code let me know and I will attempt to update this at some later date to help. For the most part if the array object has named values this solution should work.
$scope.model.ticketsArr.forEach(function (Ticket) {
if (Ticket.AppointmentType == 'CRASH_TECH_SUPPORT') {
Ticket.AppointmentType = '360_SUPPORT'
}
});
Full example below _____________________________________________________
var Students = [
{ ID: 1, FName: "Ajay", LName: "Test1", Age: 20 },
{ ID: 2, FName: "Jack", LName: "Test2", Age: 21 },
{ ID: 3, FName: "John", LName: "Test3", age: 22 },
{ ID: 4, FName: "Steve", LName: "Test4", Age: 22 }
]
Students.forEach(function (Student) {
if (Student.LName == 'Test1') {
Student.LName = 'Smith'
}
if (Student.LName == 'Test2') {
Student.LName = 'Black'
}
});
Students.forEach(function (Student) {
document.write(Student.FName + " " + Student.LName + "<BR>");
});
When you log in to your developer account, you can find a link at the bottom of the download section for Xcode that says "Looking for an older version of Xcode?". In there you can find download links to older versions of Xcode and other developer tools
/**
* Get the method name for a depth in call stack. <br />
* Utility function
* @param depth depth in the call stack (0 means current method, 1 means call method, ...)
* @return method name
*/
public static String getMethodName(final int depth)
{
final StackTraceElement[] ste = new Throwable().getStackTrace();
//System. out.println(ste[ste.length-depth].getClassName()+"#"+ste[ste.length-depth].getMethodName());
return ste[ste.length - depth].getMethodName();
}
For example, if you try to get the calling method line for debug purpose, you need to get past the Utility class in which you code those static methods:
(old java1.4 code, just to illustrate a potential StackTraceElement usage)
/**
* Returns the first "[class#method(line)]: " of the first class not equal to "StackTraceUtils". <br />
* From the Stack Trace.
* @return "[class#method(line)]: " (never empty, first class past StackTraceUtils)
*/
public static String getClassMethodLine()
{
return getClassMethodLine(null);
}
/**
* Returns the first "[class#method(line)]: " of the first class not equal to "StackTraceUtils" and aclass. <br />
* Allows to get past a certain class.
* @param aclass class to get pass in the stack trace. If null, only try to get past StackTraceUtils.
* @return "[class#method(line)]: " (never empty, because if aclass is not found, returns first class past StackTraceUtils)
*/
public static String getClassMethodLine(final Class aclass)
{
final StackTraceElement st = getCallingStackTraceElement(aclass);
final String amsg = "[" + st.getClassName() + "#" + st.getMethodName() + "(" + st.getLineNumber()
+")] <" + Thread.currentThread().getName() + ">: ";
return amsg;
}
/**
* Returns the first stack trace element of the first class not equal to "StackTraceUtils" or "LogUtils" and aClass. <br />
* Stored in array of the callstack. <br />
* Allows to get past a certain class.
* @param aclass class to get pass in the stack trace. If null, only try to get past StackTraceUtils.
* @return stackTraceElement (never null, because if aClass is not found, returns first class past StackTraceUtils)
* @throws AssertionFailedException if resulting statckTrace is null (RuntimeException)
*/
public static StackTraceElement getCallingStackTraceElement(final Class aclass)
{
final Throwable t = new Throwable();
final StackTraceElement[] ste = t.getStackTrace();
int index = 1;
final int limit = ste.length;
StackTraceElement st = ste[index];
String className = st.getClassName();
boolean aclassfound = false;
if(aclass == null)
{
aclassfound = true;
}
StackTraceElement resst = null;
while(index < limit)
{
if(shouldExamine(className, aclass) == true)
{
if(resst == null)
{
resst = st;
}
if(aclassfound == true)
{
final StackTraceElement ast = onClassfound(aclass, className, st);
if(ast != null)
{
resst = ast;
break;
}
}
else
{
if(aclass != null && aclass.getName().equals(className) == true)
{
aclassfound = true;
}
}
}
index = index + 1;
st = ste[index];
className = st.getClassName();
}
if(resst == null)
{
//Assert.isNotNull(resst, "stack trace should null"); //NO OTHERWISE circular dependencies
throw new AssertionFailedException(StackTraceUtils.getClassMethodLine() + " null argument:" + "stack trace should null"); //$NON-NLS-1$
}
return resst;
}
static private boolean shouldExamine(String className, Class aclass)
{
final boolean res = StackTraceUtils.class.getName().equals(className) == false && (className.endsWith("LogUtils"
) == false || (aclass !=null && aclass.getName().endsWith("LogUtils")));
return res;
}
static private StackTraceElement onClassfound(Class aclass, String className, StackTraceElement st)
{
StackTraceElement resst = null;
if(aclass != null && aclass.getName().equals(className) == false)
{
resst = st;
}
if(aclass == null)
{
resst = st;
}
return resst;
}
Instead of giving localhost give the IP.
IMO, the provider is telling you to change the service endpoint (i.e. where to reach the web service), not the client endpoint (I don't understand what this could be). To change the service endpoint, you basically have two options.
The first option is to change the BindingProvider.ENDPOINT_ADDRESS_PROPERTY
property value of the BindingProvider
(every proxy implements javax.xml.ws.BindingProvider
interface):
...
EchoService service = new EchoService();
Echo port = service.getEchoPort();
/* Set NEW Endpoint Location */
String endpointURL = "http://NEW_ENDPOINT_URL";
BindingProvider bp = (BindingProvider)port;
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointURL);
System.out.println("Server said: " + echo.echo(args[0]));
...
The drawback is that this only works when the original WSDL is still accessible. Not recommended.
The second option is to get the endpoint URL from the WSDL.
...
URL newEndpoint = new URL("NEW_ENDPOINT_URL");
QName qname = new QName("http://ws.mycompany.tld","EchoService");
EchoService service = new EchoService(newEndpoint, qname);
Echo port = service.getEchoPort();
System.out.println("Server said: " + echo.echo(args[0]));
...
You can stop the image from overlapping it's edges by clipping the image and applying a wrapper element which sets the blur effect to 0 pixels. This is how it looks like:
HTML
<div id="wrapper">
<div id="image"></div>
</div>
CSS
#wrapper {
width: 1024px;
height: 768px;
border: 1px solid black;
// 'blur(0px)' will prevent the wrapped image
// from overlapping the border
-webkit-filter: blur(0px);
-moz-filter: blur(0px);
-ms-filter: blur(0px);
filter: blur(0px);
}
#wrapper #image {
width: 1024px;
height: 768px;
background-image: url("../images/cats.jpg");
background-size: cover;
-webkit-filter: blur(10px);
-moz-filter: blur(10px);
-ms-filter: blur(10px);
filter: blur(10px);
// Position 'absolute' is needed for clipping
position: absolute;
clip: rect(0px, 1024px, 768px, 0px);
}
Space char is hexadecimal 0x20, decimal 32 and octal \040.
>>> SPACE = 0x20
>>> a = chr(SPACE)
>>> type(a)
<class 'str'>
>>> print(f"'{a}'")
' '
You would write a comparator class, for example:
struct CompareAge {
bool operator()(Person const & p1, Person const & p2) {
// return "true" if "p1" is ordered before "p2", for example:
return p1.age < p2.age;
}
};
and use that as the comparator argument:
priority_queue<Person, vector<Person>, CompareAge>
Using greater
gives the opposite ordering to the default less
, meaning that the queue will give you the lowest value rather than the highest.
Seems like you posted a new question after you realized that you were dealing with a simpler problem related to size_t
. I am glad that you did.
Anyways, You have a .c
source file, and most of the code looks as per C standards, except that #include <iostream>
and using namespace std;
C equivalent for the built-in functions of C++ standard #include<iostream>
can be availed through #include<stdio.h>
#include <iostream>
with #include <stdio.h>
, delete using namespace std;
With #include <iostream>
taken off, you would need a C standard alternative for cout << endl;
, which can be done by printf("\n");
or putchar('\n');
Out of the two options, printf("\n");
works the faster as I observed.
When used printf("\n");
in the code above in place of cout<<endl;
$ time ./thread.exe
1 2 3 4 5 6 7 8 9 10
real 0m0.031s
user 0m0.030s
sys 0m0.030s
When used putchar('\n');
in the code above in place of cout<<endl;
$ time ./thread.exe
1 2 3 4 5 6 7 8 9 10
real 0m0.047s
user 0m0.030s
sys 0m0.030s
Compiled with Cygwin gcc (GCC) 4.8.3
version. results averaged over 10 samples. (Took me 15 mins)
Calling pip
command inside a virtualenv should list the packages visible/available in the isolated environment. Make sure to use a recent version of virtualenv that uses option --no-site-packages
by default. This way the purpose of using virtualenv is to create a python environment without access to packages installed in system python.
Next, make sure you use pip
command provided inside the virtualenv (YOUR_ENV/bin/pip
). Or just activate the virtualenv (source YOUR_ENV/bin/activate
) as a convenient way to call the proper commands for python interpreter or pip
~/Projects$ virtualenv --version
1.9.1
~/Projects$ virtualenv -p /usr/bin/python2.7 demoenv2.7
Running virtualenv with interpreter /usr/bin/python2.7
New python executable in demoenv2.7/bin/python2.7
Also creating executable in demoenv2.7/bin/python
Installing setuptools............................done.
Installing pip...............done.
~/Projects$ cd demoenv2.7/
~/Projects/demoenv2.7$ bin/pip freeze
wsgiref==0.1.2
~/Projects/demoenv2.7$ bin/pip install commandlineapp
Downloading/unpacking commandlineapp
Downloading CommandLineApp-3.0.7.tar.gz (142kB): 142kB downloaded
Running setup.py egg_info for package commandlineapp
Installing collected packages: commandlineapp
Running setup.py install for commandlineapp
Successfully installed commandlineapp
Cleaning up...
~/Projects/demoenv2.7$ bin/pip freeze
CommandLineApp==3.0.7
wsgiref==0.1.2
What's strange in my answer is that package 'wsgiref' is visible inside the virtualenv. Its from my system python. Currently I do not know why, but maybe it is different on your system.
you should change
@Test
public static void testmethod(){}
to
@Test
public void testmethod(){}
the @Test is unsupport static method
A call to EntityManager.flush();
will force the data to be persist in the database immediately as EntityManager.persist()
will not (depending on how the EntityManager is configured : FlushModeType (AUTO or COMMIT) by default it's set to AUTO and a flush will be done automatically by if it's set to COMMIT the persitence of the data to the underlying database will be delayed when the transaction is commited).
A simple thing to do is to use a HashSet with an incorrect (or non-existent) hashCode()
or equals()
, and then keep adding "duplicates". Instead of ignoring duplicates as it should, the set will only ever grow and you won't be able to remove them.
If you want these bad keys/elements to hang around you can use a static field like
class BadKey {
// no hashCode or equals();
public final String key;
public BadKey(String key) { this.key = key; }
}
Map map = System.getProperties();
map.put(new BadKey("key"), "value"); // Memory leak even if your threads die.
In case anyone arrives here via the same root I did - I hit this problem because I was building a single JAR with all dependencies, including Spring JARs. As a result the spring.schemas file in some of the META-INF directories of Spring JARs was overwritten.
I found suggested solutions here: How to create spring-based executable jar with maven?
Both C# and Java don't have plain functions only member functions (aka methods). And the methods are not first-class citizens. First-class functions allow us to create beautiful and powerful code, as seen in F# or Clojure languages. (For instance, first-class functions can be passed as parameters and can return functions.) Java and C# ameliorate this somewhat with interfaces/delegates.
Func<int, int, int> randInt = (n1, n2) => new Random().Next(n1, n2);
So, Func
is a built-in delegate which brings some functional programming features and helps reduce code verbosity.
One way is to wrap the array in java.nio.ByteBuffer
, use the absolute put/get functions, and slice the buffer to work on a subarray.
For instance:
doSomething(ByteBuffer twoBytes) {
byte b1 = twoBytes.get(0);
byte b2 = twoBytes.get(1);
...
}
void someMethod(byte[] bigArray) {
int offset = 4;
int length = 2;
doSomething(ByteBuffer.wrap(bigArray, offset, length).slice());
}
Note that you have to call both wrap()
and slice()
, since wrap()
by itself only affects the relative put/get functions, not the absolute ones.
ByteBuffer
can be a bit tricky to understand, but is most likely efficiently implemented, and well worth learning.
Visual select the text, then U for uppercase or u for lowercase. To swap all casing in a visual selection, press ~ (tilde).
Without using a visual selection, gU<motion>
will make the characters in motion
uppercase, or use gu<motion>
for lowercase.
For more of these, see Section 3 in Vim's change.txt help file.
For from / to date, here is how I implemented restricting the dates based on the date entered in the other datepicker. Works pretty good:
function activateDatePickers() {
$("#aDateFrom").datepicker({
onClose: function() {
$("#aDateTo").datepicker(
"change",
{ minDate: new Date($('#aDateFrom').val()) }
);
}
});
$("#aDateTo").datepicker({
onClose: function() {
$("#aDateFrom").datepicker(
"change",
{ maxDate: new Date($('#aDateTo').val()) }
);
}
});
}
Assuming popup
is the ID of your "description box":
HTML
<div id="parent"> <!-- This is the main container, to mouse over -->
<div id="popup" style="display: none">description text here</div>
</div>
JavaScript
var e = document.getElementById('parent');
e.onmouseover = function() {
document.getElementById('popup').style.display = 'block';
}
e.onmouseout = function() {
document.getElementById('popup').style.display = 'none';
}
Alternatively you can get rid of JavaScript entirely and do it just with CSS:
CSS
#parent #popup {
display: none;
}
#parent:hover #popup {
display: block;
}
I know this thread is about EditPad Pro, but I came here because I had the same need with a javascript regexp.
For the people who are here needing the same tip, you can use a function or lambda as the replace argument.
I use the function below to convert css names with -
to the javascript equivalent, for example, "border-top"
will be transformed into "borderTop"
:
s = s.replace(/\-[a-z]/g, x => x[1].toUpperCase());
First of all I can highly recommend reading the Nexus book. It will explain the benefits of using a Maven repository manager.
There is a section on how to configure your Maven build to use Nexus:
This leads me to question why you altering your POM file? I suspect what you really want to do is setup Nexus as a remote repository mirror. This is done in your Maven settings file.
The following tells Maven use Nexus as your default repository (Instead of Maven Central)
<settings>
..
..
<mirrors>
<mirror>
<id>nexus</id>
<url>http://localhost:8081/nexus/content/groups/public</url>
<mirrorOf>central</mirrorOf>
</mirror>
</mirrors>
This is desired behaviour since your Nexus repository is configured to cache artifacts retrieved from Central (which is good for build performance).
Note:
It didn't work, because QuerySets are not JSON serializable.
1) In case of json.dumps
you have to explicitely convert your QuerySet to JSON serializable objects:
class Model(model.Model):
def as_dict(self):
return {
"id": self.id,
# other stuff
}
And the serialization:
dictionaries = [ obj.as_dict() for obj in self.get_queryset() ]
return HttpResponse(json.dumps({"data": dictionaries}), content_type='application/json')
2) In case of serializers. Serializers accept either JSON serializable object or QuerySet, but a dictionary containing a QuerySet is neither. Try this:
serializers.serialize("json", self.get_queryset())
Read more about it here:
As of now (NOV-2019), graph.api V5.0
graph API says, refer graph api
A link to the person's Timeline. The link will only resolve if the person clicking the link is logged into Facebook and is a friend of the person whose profile is being viewed.
You do not need to use substring at all since your format
doesn't hold that info.
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String fechaStr = "2013-10-10 10:49:29.10000";
Date fechaNueva = format.parse(fechaStr);
System.out.println(format.format(fechaNueva)); // Prints 2013-10-10 10:49:29
This is one of the best suggestion in which is done using query. Good for those who has a lot of databases just like me. Can run it using a script.
USE DatabaseName;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE DatabaseName
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (DatabaseName_Log, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE DatabaseName
SET RECOVERY FULL;
GO
If your path to view is true first try to config:cache
and route:cache
if nothing changed check your resource path permission are true.
example: your can do it in ubuntu with :
sudo chgrp -R www-data resources/views
sudo usermod -a -G www-data $USER
Yes, it is possible since lists are mutable.
Look at the built-in enumerate()
function to get an idea how to iterate over the list and find each entry's index (which you can then use to assign to the specific list item).
In addition to already posted examples, here is another approach using express-async-wrap and asynchronous functions (ES2017).
Router
router.put('/:id/settings/profile', wrap(async function (request, response, next) {
const username = request.body.username
const email = request.body.email
const userWithEmail = await userService.findUserByEmail(email)
if (userWithEmail) {
return response.status(409).send({message: 'Email is already taken.'})
}
const userWithUsername = await userService.findUserByUsername(username)
if (userWithUsername) {
return response.status(409).send({message: 'Username is already taken.'})
}
const user = await userService.updateProfileSettings(userId, username, email)
return response.status(200).json({user: user})
}))
UserService
async function updateProfileSettings (userId, username, email) {
try {
return User.findOneAndUpdate({'_id': userId}, {
$set: {
'username': username,
'auth.email': email
}
}, {new: true})
} catch (error) {
throw new Error(`Unable to update user with id "${userId}".`)
}
}
async function findUserByEmail (email) {
try {
return User.findOne({'auth.email': email.toLowerCase()})
} catch (error) {
throw new Error(`Unable to connect to the database.`)
}
}
async function findUserByUsername (username) {
try {
return User.findOne({'username': username})
} catch (error) {
throw new Error(`Unable to connect to the database.`)
}
}
// other methods
export default {
updateProfileSettings,
findUserByEmail,
findUserByUsername,
}
Resources
The best way (actually the only way*) to simulate an actual click event using only CSS (rather than just hovering on an element or making an element active, where you don't have mouseUp) is to use the checkbox hack. It works by attaching a label
to an <input type="checkbox">
element via the label's for=""
attribute.
This feature has broad browser support (the :checked
pseudo-class is IE9+).
Apply the same value to an <input>
's ID attribute and an accompanying <label>
's for=""
attribute, and you can tell the browser to re-style the label on click with the :checked
pseudo-class, thanks to the fact that clicking a label will check and uncheck the "associated" <input type="checkbox">
.
* You can simulate a "selected" event via the :active
or :focus
pseudo-class in IE7+ (e.g. for a button that's normally 50px
wide, you can change its width while active
: #btnControl:active { width: 75px; }
), but those are not true "click" events. They are "live" the entire time the element is selected (such as by Tabbing with your keyboard), which is a little different from a true click event, which fires an action on - typically - mouseUp
.
label {
display: block;
background: lightgrey;
width: 100px;
height: 100px;
}
#demo:checked + label {
background: blue;
color: white;
}
_x000D_
<input type="checkbox" id="demo"/>
<label for="demo">I'm a square. Click me.</label>
_x000D_
Here I've positioned the label right after the input in my markup. This is so that I can use the adjacent sibling selector (the + key) to select only the label that immediately follows my #demo
checkbox. Since the :checked
pseudo-class applies to the checkbox, #demo:checked + label
will only apply when the checkbox is checked.
#btnControl {
display: none;
}
#btnControl:checked + label > img {
width: 70px;
height: 74px;
}
_x000D_
<input type="checkbox" id="btnControl"/>
<label class="btn" for="btnControl"><img src="https://placekitten.com/200/140" id="btnLeft" /></label>
_x000D_
With that being said, there is some bad news. Because a label can only be associated with one form control at a time, that means you can't just drop a button inside the <label></label>
tags and call it a day. However, we can use some CSS to make the label look and behave fairly close to how an HTML button looks and behaves.
#btnControl {
display: none;
}
.btn {
width: 60px;
height: 20px;
background: silver;
border-radius: 5px;
padding: 1px 3px;
box-shadow: 1px 1px 1px #000;
display: block;
text-align: center;
background-image: linear-gradient(to bottom, #f4f5f5, #dfdddd);
font-family: arial;
font-size: 12px;
line-height:20px;
}
.btn:hover {
background-image: linear-gradient(to bottom, #c3e3fa, #a5defb);
}
.btn:active {
margin-left: 1px 1px 0;
box-shadow: -1px -1px 1px #000;
outline: 1px solid black;
-moz-outline-radius: 5px;
background-image: linear-gradient(to top, #f4f5f5, #dfdddd);
}
#btnControl:checked + label {
width: 70px;
height: 74px;
line-height: 74px;
}
_x000D_
<input type="checkbox" id="btnControl"/>
<label class="btn" for="btnControl">Click me!</label>
_x000D_
Most of the CSS in this demo is just for styling the label element. If you don't actually need a button, and any old element will suffice, then you can remove almost all of the styles in this demo, similar to my second demo above.
You'll also notice I have one prefixed property in there, -moz-outline-radius
. A while back, Mozilla added this awesome non-spec property to Firefox, but the folks at WebKit decided they aren't going to add it, unfortunately. So consider that line of CSS just a progressive enhancement for people who use Firefox.
You can also register your keystore :
private void registerKeyStore(String keyStoreName) {
try {
ClassLoader classLoader = this.getClass().getClassLoader();
InputStream keyStoreInputStream = classLoader.getResourceAsStream(keyStoreName);
if (keyStoreInputStream == null) {
throw new FileNotFoundException("Could not find file named '" + keyStoreName + "' in the CLASSPATH");
}
//load the keystore
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(keyStoreInputStream, null);
//add to known keystore
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keystore);
//default SSL connections are initialized with the keystore above
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustManagers, null);
SSLContext.setDefault(sc);
} catch (IOException | GeneralSecurityException e) {
throw new RuntimeException(e);
}
}
span::before { content: "\A"; white-space: pre; }
Thread.interrupt()
sets the interrupted status/flag of the target thread to true which when checked using Thread.interrupted()
can help in stopping the endless thread. Refer http://www.yegor256.com/2015/10/20/interrupted-exception.html
It's simple. On the sender side, use Intent.putExtra
:
Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("intVariableName", intValue);
startActivity(myIntent);
On the receiver side, use Intent.getIntExtra
:
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0);
I don't recommend this method... but if you want to go wacky and strange:
EXEC sp_MSForEachDB 'SELECT ''?'' AS DatabaseName'
or
EXEC sp_MSForEachDB 'Print ''?'''
$('#message').html('');
You can use this method too. Because everything between the open and close tag of textarea is html code.
jQuery has made this a lot easier with the introduction of the Widget Factory.
Example:
$.widget( "myNamespace.myPlugin", {
options: {
// Default options
},
_create: function() {
// Initialization logic here
},
// Create a public method.
myPublicMethod: function( argument ) {
// ...
},
// Create a private method.
_myPrivateMethod: function( argument ) {
// ...
}
});
Initialization:
$('#my-element').myPlugin();
$('#my-element').myPlugin( {defaultValue:10} );
Method calling:
$('#my-element').myPlugin('myPublicMethod', 20);
(This is how the jQuery UI library is built.)
sometimes mysql_upgrade -u root -p --force
is not realy enough,
please refer to this question : Table 'performance_schema.session_variables' doesn't exist
according to it:
cd [installation_path]\eds-binaries\dbserver\mysql5711x86x160420141510\bin
mysql_upgrade -u root -p --force
There is a simple shell command "ascii",
if you use Ubuntu,just
sudo apt install ascii
then:
ascii 0x5a
will output:
ASCII 5/10 is decimal 090, hex 5a, octal 132, bits 01011010: prints as `Z'
Official name: Majuscule Z
Other names: Capital Z, Uppercase Z
A way to make it work is the following:
Rotate the parent div 180 degrees using
-moz-transform:rotate(180deg);
-webkit-transform:rotate(180deg);
-o-transform:rotate(180deg);
-ms-transform:rotate(180deg);
filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=2);
JSfiddle: http://jsfiddle.net/wcneY/
Now rotate all the elements that float left (give them a class) 180 degrees to put them straight again. Voila! they float to the bottom.
As others have already mentioned you are required to provide a default constructor public Employee(){}
in your Employee
class.
What happens is that the compiler automatically provides a no-argument, default constructor for any class without constructors. If your class has no explicit superclass, then it has an implicit superclass of Object
, which does have a no-argument constructor. In this case you are declaring a constructor in your class Employee
therefore you must provide also the no-argument constructor.
Having said that Employee
class should look like this:
Your class Employee
import java.util.Date;
public class Employee
{
private String name, number;
private Date date;
public Employee(){} // No-argument Constructor
public Employee(String name, String number, Date date)
{
setName(name);
setNumber(number);
setDate(date);
}
public void setName(String n)
{
name = n;
}
public void setNumber(String n)
{
number = n;
// you can check the format here for correctness
}
public void setDate(Date d)
{
date = d;
}
public String getName()
{
return name;
}
public String getNumber()
{
return number;
}
public Date getDate()
{
return date;
}
}
Here is the Java Oracle tutorial - Providing Constructors for Your Classes chapter. Go through it and you will have a clearer idea of what is going on.
PDFBox contains tools for text extraction.
iText has more low-level support for text manipulation, but you'd have to write a considerable amount of code to get text extraction.
iText in Action contains a good overview of the limitations of text extraction from PDF, regardless of the library used (Section 18.2: Extracting and editing text), and a convincing explanation why the library does not have text extraction support. In short, it's relatively easy to write a code that will handle simple cases, but it's basically impossible to extract text from PDF in general.
Thanks to everyone who posted in this thread. I created a module that includes the Defer() object described earlier as well as a few other objects built upon it. They all leverage Promises and the neat Promise call-back syntax to implement communication/event handling within a program.
rp = require("openpromise")
https://github.com/CABrouwers/openpromise https://www.npmjs.com/package/openpromise
I solved this problem using the split npm module. Pipe your stream into split, and it will "Break up a stream and reassemble it so that each line is a chunk".
Sample code:
var fs = require('fs')
, split = require('split')
;
var stream = fs.createReadStream(filePath, {flags: 'r', encoding: 'utf-8'});
var lineStream = stream.pipe(split());
linestream.on('data', function(chunk) {
var json = JSON.parse(chunk);
// ...
});
Here is a dplyr/tidyverse solution using the na_if() function:
dat %>% mutate_if(is.numeric, list(~na_if(., Inf)))
Note that this only replaces positive infinity with NA. Need to repeat if negative infinity values also need to be replaced.
dat %>% mutate_if(is.numeric, list(~na_if(., Inf))) %>%
mutate_if(is.numeric, list(~na_if(., -Inf)))
Use the constructor for appending material to the file:
FileOutputStream(File file, boolean append)
Creates a file output stream to write to the file represented by the specified File object.
So to append to a file say "abc.txt" use
FileOutputStream fos=new FileOutputStream(new File("abc.txt"),true);
Just another clean way:
function validateIp($var_ip){
$ip = trim($var_ip);
return (!empty($ip) &&
$ip != '::1' &&
$ip != '127.0.0.1' &&
filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false)
? $ip : false;
}
function getClientIp() {
$ip = @$this->validateIp($_SERVER['HTTP_CLIENT_IP']) ?:
@$this->validateIp($_SERVER['HTTP_X_FORWARDED_FOR']) ?:
@$this->validateIp($_SERVER['HTTP_X_FORWARDED']) ?:
@$this->validateIp($_SERVER['HTTP_FORWARDED_FOR']) ?:
@$this->validateIp($_SERVER['HTTP_FORWARDED']) ?:
@$this->validateIp($_SERVER['REMOTE_ADDR']) ?:
'LOCAL OR UNKNOWN ACCESS';
return $ip;
}
A dictionary can be automatically cast to boolean which evaluates to False
for empty dictionary and True
for non-empty dictionary.
if myDictionary: non_empty_clause()
else: empty_clause()
If this looks too idiomatic, you can also test len(myDictionary)
for zero, or set(myDictionary.keys())
for an empty set, or simply test for equality with {}
.
The isEmpty function is not only unnecessary but also your implementation has multiple issues that I can spot prima-facie.
return False
statement is indented one level too deep. It should be outside the for loop and at the same level as the for
statement. As a result, your code will process only one, arbitrarily selected key, if a key exists. If a key does not exist, the function will return None
, which will be cast to boolean False. Ouch! All the empty dictionaries will be classified as false-nagatives. return False
statement and bring it outside the for
loop. Then what you get is the boolean OR of all the keys, or False
if the dictionary empty. Still you will have false positives and false negatives. Do the correction and test against the following dictionary for an evidence.myDictionary={0:'zero', '':'Empty string', None:'None value', False:'Boolean False value', ():'Empty tuple'}
For anybody still interested:
http://wiki.phonegap.com/w/page/16494815/Preventing-Scrolling-on-iPhone-Phonegap-Applications
From the page:
<meta name="viewport" content="user-scalable=no,width=device-width" />
This instructs Safari to prevent the user from zooming into the page with the "pinch" gesture and fixes the width of the view port to the width of the screen, which ever orientation the iPhone is in.
string name= "abc";
IList<string> strList = new List<string>() { "abc", "def", "ghi", "jkl", "mno" };
if (strList.Contains(name))
{
Console.WriteLine("Got It");
}
///////////////// OR ////////////////////////
IList<int> num = new List<int>();
num.Add(10);
num.Add(20);
num.Add(30);
num.Add(40);
Console.WriteLine(num.Count); // to count the total numbers in the list
if(num.Contains(20)) {
Console.WriteLine("Got It"); // if condition to find the number from list
}
I am not experiented .But i think XmlReader is unnecessary.
It is very hard to use.
XElement is very easy to use.
If you need performance ( faster ) you must change file format and use StreamReader and StreamWriter classes.
That's still a constant. See the JLS for more information regarding the naming convention for constants. But in reality, it's all a matter of preference.
The names of constants in interface types should be, and
final
variables of class types may conventionally be, a sequence of one or more words, acronyms, or abbreviations, all uppercase, with components separated by underscore"_"
characters. Constant names should be descriptive and not unnecessarily abbreviated. Conventionally they may be any appropriate part of speech. Examples of names for constants includeMIN_VALUE
,MAX_VALUE
,MIN_RADIX
, andMAX_RADIX
of the classCharacter
.A group of constants that represent alternative values of a set, or, less frequently, masking bits in an integer value, are sometimes usefully specified with a common acronym as a name prefix, as in:
interface ProcessStates { int PS_RUNNING = 0; int PS_SUSPENDED = 1; }
Obscuring involving constant names is rare:
- Constant names normally have no lowercase letters, so they will not normally obscure names of packages or types, nor will they normally shadow fields, whose names typically contain at least one lowercase letter.
- Constant names cannot obscure method names, because they are distinguished syntactically.
In Python-3.6
I can see the suggestion in the traceback. That's quite helpful.
Hence I will say you guys to pay attention to the error you got, most of the time answers are within that problem ;).
And then as suggested by other folks here either using python terminal or using a command like python -c "import nltk; nltk.download('wordnet')"
we can install them on the fly.
You just need to run that command once and then it will save the data locally in your home directory.
install sqlescapy package:
pip install sqlescapy
then you can escape variables in you raw query
from sqlescapy import sqlescape
query = """
SELECT * FROM "bar_table" WHERE id='%s'
""" % sqlescape(user_input)
userType = (user.Type == 0) ? "Admin" : (user.type == 1) ? "User" : "Admin";
should do the trick.
In the modern browsers you can use the fetch to download resource (Mozilla docs) and then eval to execute it.
For example to download Angular1 you need to type:
fetch('https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js')
.then(response => response.text())
.then(text => eval(text))
.then(() => { /* now you can use your library */ })
DELETE FROM blob
WHERE NOT EXISTS (
SELECT *
FROM files
WHERE id=blob.id
)
String s=t.getText().trim();
int l=s.length();
char c=Character.toUpperCase(s.charAt(0));
s=c+s.substring(1);
for(int i=1; i<l; i++)
{
if(s.charAt(i)==' ')
{
c=Character.toUpperCase(s.charAt(i+1));
s=s.substring(0, i) + c + s.substring(i+2);
}
}
t.setText(s);
This is an old question but I recently stumbled upon it.
git commit --date='2021-01-01 12:12:00' -m "message"
worked properly and verified it on GitHub
.
I think $PsHome has the information you're after?
PS .> $PsHome C:\Windows\System32\WindowsPowerShell\v1.0 PS .> Get-Help about_automatic_variables TOPIC about_Automatic_Variables ...
To get any sort of file path use this :
/*
* Copyright (C) 2007-2008 OpenIntents.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yourpackage;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.webkit.MimeTypeMap;
import java.io.File;
import java.io.FileFilter;
import java.text.DecimalFormat;
import java.util.Comparator;
import java.util.List;
/**
* @author Peli
* @author paulburke (ipaulpro)
* @version 2013-12-11
*/
public class FileUtils {
private FileUtils() {
} //private constructor to enforce Singleton pattern
/**
* TAG for log messages.
*/
static final String TAG = "FileUtils";
private static final boolean DEBUG = true; // Set to true to enable logging
public static final String MIME_TYPE_AUDIO = "audio/*";
public static final String MIME_TYPE_TEXT = "text/*";
public static final String MIME_TYPE_IMAGE = "image/*";
public static final String MIME_TYPE_VIDEO = "video/*";
public static final String MIME_TYPE_APP = "application/*";
public static final String HIDDEN_PREFIX = ".";
/**
* Gets the extension of a file name, like ".png" or ".jpg".
*
* @param uri
* @return Extension including the dot("."); "" if there is no extension;
* null if uri was null.
*/
public static String getExtension(String uri) {
if (uri == null) {
return null;
}
int dot = uri.lastIndexOf(".");
if (dot >= 0) {
return uri.substring(dot);
} else {
// No extension.
return "";
}
}
/**
* @return Whether the URI is a local one.
*/
public static boolean isLocal(String url) {
if (url != null && !url.startsWith("http://") && !url.startsWith("https://")) {
return true;
}
return false;
}
/**
* @return True if Uri is a MediaStore Uri.
* @author paulburke
*/
public static boolean isMediaUri(Uri uri) {
return "media".equalsIgnoreCase(uri.getAuthority());
}
/**
* Convert File into Uri.
*
* @param file
* @return uri
*/
public static Uri getUri(File file) {
if (file != null) {
return Uri.fromFile(file);
}
return null;
}
/**
* Returns the path only (without file name).
*
* @param file
* @return
*/
public static File getPathWithoutFilename(File file) {
if (file != null) {
if (file.isDirectory()) {
// no file to be split off. Return everything
return file;
} else {
String filename = file.getName();
String filepath = file.getAbsolutePath();
// Construct path without file name.
String pathwithoutname = filepath.substring(0,
filepath.length() - filename.length());
if (pathwithoutname.endsWith("/")) {
pathwithoutname = pathwithoutname.substring(0, pathwithoutname.length() - 1);
}
return new File(pathwithoutname);
}
}
return null;
}
/**
* @return The MIME type for the given file.
*/
public static String getMimeType(File file) {
String extension = getExtension(file.getName());
if (extension.length() > 0)
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.substring(1));
return "application/octet-stream";
}
/**
* @return The MIME type for the give Uri.
*/
public static String getMimeType(Context context, Uri uri) {
File file = new File(getPath(context, uri));
return getMimeType(file);
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is {@link LocalStorageProvider}.
* @author paulburke
*/
public static boolean isLocalStorageDocument(Uri uri) {
return LocalStorageProvider.AUTHORITY.equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
* @author paulburke
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
* @author paulburke
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
* @author paulburke
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
* @author paulburke
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
if (DEBUG)
DatabaseUtils.dumpCursor(cursor);
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* Get a file path from a Uri. This will quickGet the the path for Storage Access
* Framework Documents, as well as the _data field for the MediaStore and
* other file-based ContentProviders.<br>
* <br>
* Callers should check whether the path is local before assuming it
* represents a local file.
*
* @param context The context.
* @param uri The Uri to query.
* @author paulburke
* @see #isLocal(String)
* @see #getFile(Context, Uri)
*/
public static String getPath(final Context context, final Uri uri) {
if (DEBUG)
Log.d(TAG + " File -",
"Authority: " + uri.getAuthority() +
", Fragment: " + uri.getFragment() +
", Port: " + uri.getPort() +
", Query: " + uri.getQuery() +
", Scheme: " + uri.getScheme() +
", Host: " + uri.getHost() +
", Segments: " + uri.getPathSegments().toString()
);
// DocumentProvider
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, uri)) {
// LocalStorageProvider
if (isLocalStorageDocument(uri)) {
// The path is the id
return DocumentsContract.getDocumentId(uri);
}
// ExternalStorageProvider
else if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
// if ("primary".equalsIgnoreCase(type)) {
// return Environment.getExternalStorageDirectory() + "/" + split[1];
// }
return Environment.getExternalStorageDirectory() + "/" + split[1];
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
try {
final String id = DocumentsContract.getDocumentId(uri);
Log.d(TAG, "getPath: id= " + id);
final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}catch (Exception e){
e.printStackTrace();
List<String> segments = uri.getPathSegments();
if(segments.size() > 1) {
String rawPath = segments.get(1);
if(!rawPath.startsWith("/")){
return rawPath.substring(rawPath.indexOf("/"));
}else {
return rawPath;
}
}
}
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Convert Uri into File, if possible.
*
* @return file A local file that the Uri was pointing to, or null if the
* Uri is unsupported or pointed to a remote resource.
* @author paulburke
* @see #getPath(Context, Uri)
*/
public static File getFile(Context context, Uri uri) {
if (uri != null) {
String path = getPath(context, uri);
if (path != null && isLocal(path)) {
return new File(path);
}
}
return null;
}
/**
* Get the file size in a human-readable string.
*
* @param size
* @return
* @author paulburke
*/
public static String getReadableFileSize(int size) {
final int BYTES_IN_KILOBYTES = 1024;
final DecimalFormat dec = new DecimalFormat("###.#");
final String KILOBYTES = " KB";
final String MEGABYTES = " MB";
final String GIGABYTES = " GB";
float fileSize = 0;
String suffix = KILOBYTES;
if (size > BYTES_IN_KILOBYTES) {
fileSize = size / BYTES_IN_KILOBYTES;
if (fileSize > BYTES_IN_KILOBYTES) {
fileSize = fileSize / BYTES_IN_KILOBYTES;
if (fileSize > BYTES_IN_KILOBYTES) {
fileSize = fileSize / BYTES_IN_KILOBYTES;
suffix = GIGABYTES;
} else {
suffix = MEGABYTES;
}
}
}
return String.valueOf(dec.format(fileSize) + suffix);
}
/**
* Attempt to retrieve the thumbnail of given File from the MediaStore. This
* should not be called on the UI thread.
*
* @param context
* @param file
* @return
* @author paulburke
*/
public static Bitmap getThumbnail(Context context, File file) {
return getThumbnail(context, getUri(file), getMimeType(file));
}
/**
* Attempt to retrieve the thumbnail of given Uri from the MediaStore. This
* should not be called on the UI thread.
*
* @param context
* @param uri
* @return
* @author paulburke
*/
public static Bitmap getThumbnail(Context context, Uri uri) {
return getThumbnail(context, uri, getMimeType(context, uri));
}
/**
* Attempt to retrieve the thumbnail of given Uri from the MediaStore. This
* should not be called on the UI thread.
*
* @param context
* @param uri
* @param mimeType
* @return
* @author paulburke
*/
public static Bitmap getThumbnail(Context context, Uri uri, String mimeType) {
if (DEBUG)
Log.d(TAG, "Attempting to quickGet thumbnail");
if (!isMediaUri(uri)) {
Log.e(TAG, "You can only retrieve thumbnails for images and videos.");
return null;
}
Bitmap bm = null;
if (uri != null) {
final ContentResolver resolver = context.getContentResolver();
Cursor cursor = null;
try {
cursor = resolver.query(uri, null, null, null, null);
if (cursor.moveToFirst()) {
final int id = cursor.getInt(0);
if (DEBUG)
Log.d(TAG, "Got thumb ID: " + id);
if (mimeType.contains("video")) {
bm = MediaStore.Video.Thumbnails.getThumbnail(
resolver,
id,
MediaStore.Video.Thumbnails.MINI_KIND,
null);
} else if (mimeType.contains(FileUtils.MIME_TYPE_IMAGE)) {
bm = MediaStore.Images.Thumbnails.getThumbnail(
resolver,
id,
MediaStore.Images.Thumbnails.MINI_KIND,
null);
}
}
} catch (Exception e) {
if (DEBUG)
Log.e(TAG, "getThumbnail", e);
} finally {
if (cursor != null)
cursor.close();
}
}
return bm;
}
/**
* File and folder comparator. TODO Expose sorting option method
*
* @author paulburke
*/
public static Comparator<File> sComparator = new Comparator<File>() {
@Override
public int compare(File f1, File f2) {
// Sort alphabetically by lower case, which is much cleaner
return f1.getName().toLowerCase().compareTo(
f2.getName().toLowerCase());
}
};
/**
* File (not directories) filter.
*
* @author paulburke
*/
public static FileFilter sFileFilter = new FileFilter() {
@Override
public boolean accept(File file) {
final String fileName = file.getName();
// Return files only (not directories) and skip hidden files
return file.isFile() && !fileName.startsWith(HIDDEN_PREFIX);
}
};
/**
* Folder (directories) filter.
*
* @author paulburke
*/
public static FileFilter sDirFilter = new FileFilter() {
@Override
public boolean accept(File file) {
final String fileName = file.getName();
// Return directories only and skip hidden directories
return file.isDirectory() && !fileName.startsWith(HIDDEN_PREFIX);
}
};
/**
* Get the Intent for selecting content to be used in an Intent Chooser.
*
* @return The intent for opening a file with Intent.createChooser()
* @author paulburke
*/
public static Intent createGetContentIntent() {
// Implicitly allow the user to select a particular kind of data
final Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// The MIME data type filter
intent.setType("*/*");
// Only return URIs that can be opened with ContentResolver
intent.addCategory(Intent.CATEGORY_OPENABLE);
return intent;
}
}
I like the solution of Javier. I did not try it, but it sounds cool!
For reading through a arbitary large text and wanting to know it a string exists, replace it, you can use Flashtext, which is faster than Regex with very large files.
Edit:
From the developer page:
>>> from flashtext import KeywordProcessor
>>> keyword_processor = KeywordProcessor()
>>> # keyword_processor.add_keyword(<unclean name>, <standardised name>)
>>> keyword_processor.add_keyword('Big Apple', 'New York')
>>> keyword_processor.add_keyword('Bay Area')
>>> keywords_found = keyword_processor.extract_keywords('I love Big Apple and Bay Area.')
>>> keywords_found
>>> # ['New York', 'Bay Area']
Or when extracting the offset:
>>> from flashtext import KeywordProcessor
>>> keyword_processor = KeywordProcessor()
>>> keyword_processor.add_keyword('Big Apple', 'New York')
>>> keyword_processor.add_keyword('Bay Area')
>>> keywords_found = keyword_processor.extract_keywords('I love big Apple and Bay Area.', span_info=True)
>>> keywords_found
>>> # [('New York', 7, 16), ('Bay Area', 21, 29)]
using System;
using System.Collections.Generic; (???????? ?????????? ?? ?? ?????
using System.Linq; ?????? PlayerScript.health =
using System.Text; 999999; ??? ?? ???? ??????)
using System.Threading.Tasks;
using UnityEngine;
namespace OneHack
{
public class One
{
public Rect RT_MainMenu = new Rect(0f, 100f, 120f, 100f); //Rect ??? ????????????????? ???? ?? x,y ? ??????, ??????.
public int ID_RTMainMenu = 1;
private bool MainMenu = true;
private void Menu_MainMenu(int id) //??????? ????
{
if (GUILayout.Button("???????? ????? ??????", new GUILayoutOption[0]))
{
if (GUILayout.Button("??????????", new GUILayoutOption[0]))
{
PlayerScript.health = 999999;//??? ??????? ?? ?????? ? ?????? ??????????????? ???????? 999999 //????? ???, ??????? ????? ??????????? ??? ??????? ?? ??? ??????
}
}
}
private void OnGUI()
{
if (this.MainMenu)
{
this.RT_MainMenu = GUILayout.Window(this.ID_RTMainMenu, this.RT_MainMenu, new GUI.WindowFunction(this.Menu_MainMenu), "MainMenu", new GUILayoutOption[0]);
}
}
private void Update() //????????? ??????????? ?????, ??? ??? ????? ????? ????????? ????? ??????????? ??????????
{
if (Input.GetKeyDown(KeyCode.Insert)) //?????? ?? ??????? ????? ??????????? ? ??????????? ????, ????? ????????? ??????
{
this.MainMenu = !this.MainMenu;
}
}
}
}
In your git dir, suppose you have sync all changes.
rm -rf .git
rm -rf .gitmodules
Then do:
git init
git submodule add url_to_repo projectfolder
I've made a function which allows you to move multiple selected options up or down
$('#your_select_box').move_selected_options('down');
$('#your_select_boxt').move_selected_options('up');
Dependencies:
$.fn.reverse = [].reverse;
function swapWith() (Paolo Bergantino)
First it checks whether the first/last selected option is able to move up/down. Then it loops through all the elements and calls
swapWith(element.next() or element.prev())
jQuery.fn.move_selected_options = function(up_or_down) {
if(up_or_down == 'up'){
var first_can_move_up = $("#" + this.attr('id') + ' option:selected:first').prev().size();
if(first_can_move_up){
$.each($("#" + this.attr('id') + ' option:selected'), function(index, option){
$(option).swapWith($(option).prev());
});
}
} else {
var last_can_move_down = $("#" + this.attr('id') + ' option:selected:last').next().size();
if(last_can_move_down){
$.each($("#" + this.attr('id') + ' option:selected').reverse(), function(index, option){
$(option).swapWith($(option).next());
});
}
}
return $(this);
}
Answer below the dotted line below is the original that's now outdated.
Here is the latest information ( Thank you @deadfish ):
add &hl=<language>
like &hl=pl
or &hl=en
example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl
All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en
......................................................................
To change the actual local market:
Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html
To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720
You can use a deadlock graph
and gather the information you require from the log file.
The only other way I could suggest is digging through the information by using EXEC SP_LOCK
(Soon to be deprecated), EXEC SP_WHO2
or the sys.dm_tran_locks
table.
SELECT L.request_session_id AS SPID,
DB_NAME(L.resource_database_id) AS DatabaseName,
O.Name AS LockedObjectName,
P.object_id AS LockedObjectId,
L.resource_type AS LockedResource,
L.request_mode AS LockType,
ST.text AS SqlStatementText,
ES.login_name AS LoginName,
ES.host_name AS HostName,
TST.is_user_transaction as IsUserTransaction,
AT.name as TransactionName,
CN.auth_scheme as AuthenticationMethod
FROM sys.dm_tran_locks L
JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
JOIN sys.objects O ON O.object_id = P.object_id
JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE resource_database_id = db_id()
ORDER BY L.request_session_id
http://www.sqlmag.com/article/sql-server-profiler/gathering-deadlock-information-with-deadlock-graph
It does work in Firefox (including 2.0.0.20
). See http://jsbin.com/akili (add /edit
to the url to edit):
<p id="one">One</p>
<a href="#" onclick="document.getElementById('one').id = 'two'; return false">Link2</a>
The first click changes the id
to "two"
, the second click errors because the element with id="one"
now can't be found!
Perhaps you have another element already with id="two"
(FYI you can't have more than one element with the same id
).
You could write a function that takes a filename and an environment name, checks to see if the file has been loaded into the environment and uses sys.source
to source the file if not.
Here's a quick and untested function (improvements welcome!):
include <- function(file, env) {
# ensure file and env are provided
if(missing(file) || missing(env))
stop("'file' and 'env' must be provided")
# ensure env is character
if(!is.character(file) || !is.character(env))
stop("'file' and 'env' must be a character")
# see if env is attached to the search path
if(env %in% search()) {
ENV <- get(env)
files <- get(".files",ENV)
# if the file hasn't been loaded
if(!(file %in% files)) {
sys.source(file, ENV) # load the file
assign(".files", c(file, files), envir=ENV) # set the flag
}
} else {
ENV <- attach(NULL, name=env) # create/attach new environment
sys.source(file, ENV) # load the file
assign(".files", file, envir=ENV) # set the flag
}
}
FOR SWIFT 3.1
func convertDateStringToDate(longDate: String) -> String{
/* INPUT: longDate = "2017-01-27T05:00:00.000Z"
* OUTPUT: "1/26/17"
* date_format_you_want_in_string from
* http://userguide.icu-project.org/formatparse/datetime
*/
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = dateFormatter.date(from: longDate)
if date != nil {
let formatter = DateFormatter()
formatter.dateStyle = .short
let dateShort = formatter.string(from: date!)
return dateShort
} else {
return longDate
}
}
NOTE: THIS WILL RETURN THE ORIGINAL STRING IF ERROR
For PHP you can set
window > preferences > PHP > editor > mark occurrences
Please check first checkbox (Mark occurrences of selected element in the current file)
And also check
Preferences > General > Editors > Text Editors > Annotations
'Occurrences' and 'Write Occurrences' with different style and color
just make sure how you are using image through css background use backgroud image position like background: url(your image path) no-repeat center center; automatically it wil align center to the screen.
Inside a code block (eg, @foreach
), you need to mark the markup (or, in this case, Javascript) with @:
or the <text>
tag.
Inside the markup contexts, you need to surround code with code blocks (@{ ... }
or @if
, ...)
Or you might be looking at this question because you happened to make a silly typo like I did and have the =~ reversed to ~=
One scenario where your git repo will get seriously bigger with each commit is one where you are committing binary files that you generate regularly. Their storage won't be as efficient than text file.
Another is one where you have a huge number of files within one repo (which is a limit of git) instead of several subrepos (managed as submodules).
In this article on git space, AlBlue mentions:
Note that Git (and Hg, and other DVCSs) do suffer from a problem where (large) binaries are checked in, then deleted, as they'll still show up in the repository and take up space, even if they're not current.
If you have large binaries stored in your git repo, you may consider:
git filter-branch
(warning: this will rewrite the history, which is bad if you have already pushed your repo and if other have pulled from it)As I mentioned in "What are the file limits in Git (number and size)?", the more recent (2015, 5 years after this answer) Git LFS from GitHub is a way to manage those large files (by storing them outside the Git repository).
raw.github.com
is not truely raw access to file asset,
but a view rendered by Rails.
So accessing raw.github.com
is much heavier than needed.
I don't know why raw.github.com
is implemented as a Rails view.
Instead of fix this route issue, GitHub added a X-Content-Type-Options: nosniff
header.
Workaround:
user.github.io/repo
You can use the opacity value appended to the hexadecimal value:
background-color: #11ffeeaa;
In this example aa
is the opacity. An opacity of 00
means transparent and ff
means solid color.
The opacity is optional, so you can use the hexadecimal value as always:
background-color: #11ffee;
You can also use the old way with rgba()
:
background-color: rgba(117, 190, 218, 0.5);
And the background
shorthand if you want to make sure that the background has no other styles, like images or gradients:
background: #11ffeeaa;
From the Mozilla's specification (https://developer.mozilla.org/en-US/docs/Web/CSS/background-color):
/* Keyword values */
background-color: red;
background-color: indigo;
/* Hexadecimal value */
background-color: #bbff00; /* Fully opaque */
background-color: #bf0; /* Fully opaque shorthand */
background-color: #11ffee00; /* Fully transparent */
background-color: #1fe0; /* Fully transparent shorthand */
background-color: #11ffeeff; /* Fully opaque */
background-color: #1fef; /* Fully opaque shorthand */
/* RGB value */
background-color: rgb(255, 255, 128); /* Fully opaque */
background-color: rgba(117, 190, 218, 0.5); /* 50% transparent */
/* HSL value */
background-color: hsl(50, 33%, 25%); /* Fully opaque */
background-color: hsla(50, 33%, 25%, 0.75); /* 75% transparent */
/* Special keyword values */
background-color: currentcolor;
background-color: transparent;
/* Global values */
background-color: inherit;
background-color: initial;
background-color: unset;
You can create 2 wrapper methods for saving and retrieving object from session storage.
function saveSession(obj) {
sessionStorage.setItem("myObj", JSON.stringify(obj));
return true;
}
function getSession() {
var obj = {};
if (typeof sessionStorage.myObj !== "undefined") {
obj = JSON.parse(sessionStorage.myObj);
}
return obj;
}
Use it like this:- Get object, modify some data, and save back.
var obj = getSession();
obj.newProperty = "Prod"
saveSession(obj);
I would consider to refactor the service to return your domain object rather than JSON strings and let Spring handle the serialization (via the MappingJacksonHttpMessageConverter
as you write). As of Spring 3.1, the implementation looks quite neat:
@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE,
method = RequestMethod.GET
value = "/foo/bar")
@ResponseBody
public Bar fooBar(){
return myService.getBar();
}
Comments:
First, the <mvc:annotation-driven />
or the @EnableWebMvc
must be added to your application config.
Next, the produces attribute of the @RequestMapping
annotation is used to specify the content type of the response. Consequently, it should be set to MediaType.APPLICATION_JSON_VALUE (or "application/json"
).
Lastly, Jackson must be added so that any serialization and de-serialization between Java and JSON will be handled automatically by Spring (the Jackson dependency is detected by Spring and the MappingJacksonHttpMessageConverter
will be under the hood).
In the spirit of @Chris W, just try to replicate the exact error you are getting. An example would have helped but maybe you're doing:
x <- c(1,2)
y <- c("a","b","c")
names(x) <- y
Error in names(x) <- y :
'names' attribute [3] must be the same length as the vector [2]
I suspect you're trying to give names to a vector (x
) that is shorter than your vector of names (y
).
If I understand your issue this should work
&emsp—the em space; this should be a very wide space, typically as much as four real spaces. &ensp—the en space; this should be a somewhat wide space, roughly two regular spaces. &thinsp—this will be a narrow space, even more narrow than a regular space.
Sources: http://hea-www.harvard.edu/~fine/Tech/html-sentences.html
with ggplot2:
library(ggplot2)
Animals <- read.table(
header=TRUE, text='Category Reason Species
1 Decline Genuine 24
2 Improved Genuine 16
3 Improved Misclassified 85
4 Decline Misclassified 41
5 Decline Taxonomic 2
6 Improved Taxonomic 7
7 Decline Unclear 41
8 Improved Unclear 117')
ggplot(Animals, aes(factor(Reason), Species, fill = Category)) +
geom_bar(stat="identity", position = "dodge") +
scale_fill_brewer(palette = "Set1")
If your are in Visual Studio 2012 or later this has an additional setting 'SDL checks' Under Property Pages -> C/C++ -> General
Additional Security Development Lifecycle (SDL) recommended checks; includes enabling additional secure code generation features and extra security-relevant warnings as errors.
It defaults to YES - For a reason, I.E you should use the secure version of the strncpy. If you change this to NO you will not get a error when using the insecure version.
The size member function.
myList.size();
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html
I done this way:
$scope.printDiv = function (div) {
var docHead = document.head.outerHTML;
var printContents = document.getElementById(div).outerHTML;
var winAttr = "location=yes, statusbar=no, menubar=no, titlebar=no, toolbar=no,dependent=no, width=865, height=600, resizable=yes, screenX=200, screenY=200, personalbar=no, scrollbars=yes";
var newWin = window.open("", "_blank", winAttr);
var writeDoc = newWin.document;
writeDoc.open();
writeDoc.write('<!doctype html><html>' + docHead + '<body onLoad="window.print()">' + printContents + '</body></html>');
writeDoc.close();
newWin.focus();
}
The accepted answer worked for me using a CollapsingToolbarLayout. It's important to note though, that setSytstemUiVisibility()
overrides any previous calls to that function. So if you're using that function somewhere else for the same view, you need to include the View.SYSTEM_UI_FLAG_LAYOUT_STABLE
and View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
flags, or they will be overridden with the new call.
This was the case for me, and once I added the two flags to the other place I was making a call to setSystemUiVisibility()
, the accepted answer worked perfectly.
Using str_replace()
to remove the dots is not overkill.
$string_number = '1.512.523,55';
// NOTE: You don't really have to use floatval() here, it's just to prove that it's a legitimate float value.
$number = floatval(str_replace(',', '.', str_replace('.', '', $string_number)));
// At this point, $number is a "natural" float.
print $number;
This is almost certainly the least CPU-intensive way you can do this, and odds are that even if you use some fancy function to do it, that this is what it does under the hood.
I need to do this frequently, so I use this:
var loadJS = function(url, implementationCode, location){
//url is URL of external file, implementationCode is the code
//to be called from the file, location is the location to
//insert the <script> element
var scriptTag = document.createElement('script');
scriptTag.src = url;
scriptTag.onload = implementationCode;
scriptTag.onreadystatechange = implementationCode;
location.appendChild(scriptTag);
};
var yourCodeToBeCalled = function(){
//your code goes here
}
loadJS('yourcode.js', yourCodeToBeCalled, document.body);
For more information, see this site How do I include a JavaScript file in another JavaScript file?, which is the source of my function idea.
(x > 0 for x in list)
in that function call creates a generator expression eg.
>>> nums = [1, 2, -1, 9, -5]
>>> genexp = (x > 0 for x in nums)
>>> for x in genexp:
print x
True
True
False
True
False
Which any
uses, and shortcircuits on encountering the first object that evaluates True
I ran into a very similar problem with my Xamarin Windows Phone 8.1 app. The reason JObject.Parse(json) would not work for me was because my Json had a beginning "[" and an ending "]". In order to make it work, I had to remove those two characters. From your example, it looks like you might have the same issue.
jsonResult = jsonResult.TrimStart(new char[] { '[' }).TrimEnd(new char[] { ']' });
I was then able to use the JObject.Parse(jsonResult) and everything worked.
It is also possible to add more important properties:
inputObj.attr('style', 'color:black !important; background-color:#428bca !important;');
Not all formats store their frame count or total duration - and even if they do, the file might be incomplete - so ffmpeg doesn't detect either of them accurately by default.
Instead, try seeking to the end of the file and read the time, then count the current time while you go.
Alternatively, you can try AVFormatContext->nb_index_entries
or the detected duration, which should work on fine at least undamaged AVI/MOV, or the library FFMS2, which is probably too slow to bother with for a progress bar.
String
s in java are objects, so when comparing with ==
, you are comparing references, rather than values. The correct way is to use equals()
.
However, there is a way. If you want to compare String
objects using the ==
operator, you can make use of the way the JVM copes with strings. For example:
String a = "aaa";
String b = "aaa";
boolean b = a == b;
b
would be true
. Why?
Because the JVM has a table of String
constants. So whenever you use string literals (quotes "
), the virtual machine returns the same objects, and therefore ==
returns true
.
You can use the same "table" even with non-literal strings by using the intern()
method. It returns the object that corresponds to the current string value from that table (or puts it there, if it is not). So:
String a = new String("aa");
String b = new String("aa");
boolean check1 = a == b; // false
boolean check1 = a.intern() == b.intern(); // true
It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.
This is not perfect but it does the job.
convert -density 1200 -resize 200x200 source.svg target.png
Basically it increases the DPI high enough (just use an educated/safe guess) that resizing is done with adequate quality. I was trying to find a proper solution to this but after a while decided this was good enough for my current need.
Note: Use 200x200! to force the given resolution
If you're having troubles accessing your Flask server, deployed using PyCharm, take the following into account:
PyCharm doesn't run your main .py file directly, so any code in if __name__ == '__main__':
won't be executed, and any changes (like app.run(host='0.0.0.0', port=5000)
) won't take effect.
Instead, you should configure the Flask server using Run Configurations, in particular, placing --host 0.0.0.0 --port 5000
into Additional options field.
More about configuring Flask server in PyCharm
In Oracle 12c, you can now specify the CURRVAL and NEXTVAL sequence pseudocolumns as default values for a column. Alternatively, you can use Identity columns; see:
E.g.,
CREATE SEQUENCE t1_seq;
CREATE TABLE t1 (
id NUMBER DEFAULT t1_seq.NEXTVAL,
description VARCHAR2(30)
);
string::c.str()
returns a string of type const char *
as seen here
A quick fix: try casting printfunc(num,addr,(char *)data.str().c_str())
;
While the above may work, it is undefined behaviour, and unsafe.
Here's a nicer solution using templates:
char * my_argument = const_cast<char*> ( ...c_str() );
As others have said, you can't do that either using alert()
or confirm()
.
You can, however, create an external HTML document containing your error message and an OK
button, set its <title>
element to whatever you want, then display it in a modal dialog box using showModalDialog().
You can use the getText() method anywhere in your code it is instancely called by your object, So you can use the method anywhere within a calass
Where does it fail?
I agree that your issue is probably that your dataset of 600,000 rows is probably just too large. I see that you are then adding it to Session. If you are using Sql session state, it will have to serialize that data as well.
Even if you dispose of your objects properly, you will always have at least 2 copies of this dataset in memory if you run it twice, once in session, once in procedural code. This will never scale in a web application.
Do the math, 600,000 rows, at even 1-128 bit guid per row would yield 9.6 megabytes (600k * 128 / 8) of just data, not to mention the dataset overhead.
Trim down your results.
You can use cross platform solution https://www.npmjs.com/package/cross-env
$ cross-env PORT=1234
Here is solution for Hibernate 4.3.7.Final.
pacakge-info.java contains
@TypeDefs(
{
@TypeDef(
name = "javaUtilDateType",
defaultForType = java.util.Date.class,
typeClass = JavaUtilDateType.class
)
})
package some.pack;
import org.hibernate.annotations.TypeDef;
import org.hibernate.annotations.TypeDefs;
And JavaUtilDateType:
package some.other.or.same.pack;
import java.sql.Timestamp;
import java.util.Comparator;
import java.util.Date;
import org.hibernate.HibernateException;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.type.AbstractSingleColumnStandardBasicType;
import org.hibernate.type.LiteralType;
import org.hibernate.type.StringType;
import org.hibernate.type.TimestampType;
import org.hibernate.type.VersionType;
import org.hibernate.type.descriptor.WrapperOptions;
import org.hibernate.type.descriptor.java.JdbcTimestampTypeDescriptor;
import org.hibernate.type.descriptor.sql.TimestampTypeDescriptor;
/**
* Note: Depends on hibernate implementation details hibernate-core-4.3.7.Final.
*
* @see
* <a href="http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch06.html#types-custom">Hibernate
* Documentation</a>
* @see TimestampType
*/
public class JavaUtilDateType
extends AbstractSingleColumnStandardBasicType<Date>
implements VersionType<Date>, LiteralType<Date> {
public static final TimestampType INSTANCE = new TimestampType();
public JavaUtilDateType() {
super(
TimestampTypeDescriptor.INSTANCE,
new JdbcTimestampTypeDescriptor() {
@Override
public Date fromString(String string) {
return new Date(super.fromString(string).getTime());
}
@Override
public <X> Date wrap(X value, WrapperOptions options) {
return new Date(super.wrap(value, options).getTime());
}
}
);
}
@Override
public String getName() {
return "timestamp";
}
@Override
public String[] getRegistrationKeys() {
return new String[]{getName(), Timestamp.class.getName(), java.util.Date.class.getName()};
}
@Override
public Date next(Date current, SessionImplementor session) {
return seed(session);
}
@Override
public Date seed(SessionImplementor session) {
return new Timestamp(System.currentTimeMillis());
}
@Override
public Comparator<Date> getComparator() {
return getJavaTypeDescriptor().getComparator();
}
@Override
public String objectToSQLString(Date value, Dialect dialect) throws Exception {
final Timestamp ts = Timestamp.class.isInstance(value)
? (Timestamp) value
: new Timestamp(value.getTime());
// TODO : use JDBC date literal escape syntax? -> {d 'date-string'} in yyyy-mm-dd hh:mm:ss[.f...] format
return StringType.INSTANCE.objectToSQLString(ts.toString(), dialect);
}
@Override
public Date fromStringValue(String xml) throws HibernateException {
return fromString(xml);
}
}
This solution mostly relies on TimestampType implementation with adding additional behaviour through anonymous class of type JdbcTimestampTypeDescriptor.
You could use something like this
var el = document.createElement("svg");
el.style.width="600px";
el.style.height="100px";
....
iElement[0].appendChild(el)
file = open("filename.txt", newline='')
for row in self.data:
print(row)
Save data to a variable(file
), so you need a with
.
For your case solution is :
php artisan cache:clear
php artisan route:cache
Optimizing Route Loading is a must on production :
If you are building a large application with many routes, you should make sure that you are running the route:cache Artisan command during your deployment process:
php artisan route:cache
This command reduces all of your route registrations into a single method call within a cached file, improving the performance of route registration when registering hundreds of routes.
Since this feature uses PHP serialization, you may only cache the routes for applications that exclusively use controller based routes. PHP is not able to serialize Closures.
Laravel 5 clear cache from route, view, config and all cache data from application
I would like to share my experience and solution. when i was working on my laravel e commerce website with gitlab. I was fetching one issue suddenly my view cache with error during development. i did try lot to refresh and something other but i can't see any more change in my view, but at last I did resolve my problem using laravel command so, let's see i added several command for clear cache from view, route, config etc.
Reoptimized class loader:
php artisan optimize
Clear Cache facade value:
php artisan cache:clear
Clear Route cache:
php artisan route:cache
Clear View cache:
php artisan view:clear
Clear Config cache:
php artisan config:cache
Google Chrome released the storage API: http://developer.chrome.com/extensions/storage.html
It is pretty easy to use like the other Chrome APIs and you can use it from any page context within Chrome.
// Save it using the Chrome extension storage API.
chrome.storage.sync.set({'foo': 'hello', 'bar': 'hi'}, function() {
console.log('Settings saved');
});
// Read it using the storage API
chrome.storage.sync.get(['foo', 'bar'], function(items) {
message('Settings retrieved', items);
});
To use it, make sure you define it in the manifest:
"permissions": [
"storage"
],
There are methods to "remove", "clear", "getBytesInUse", and an event listener to listen for changed storage "onChanged"
Content scripts run in the context of webpages, not extension pages. Therefore, if you're accessing localStorage from your contentscript, it will be the storage from that webpage, not the extension page storage.
Now, to let your content script to read your extension storage (where you set them from your options page), you need to use extension message passing.
The first thing you do is tell your content script to send a request to your extension to fetch some data, and that data can be your extension localStorage:
contentscript.js
chrome.runtime.sendMessage({method: "getStatus"}, function(response) {
console.log(response.status);
});
background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getStatus")
sendResponse({status: localStorage['status']});
else
sendResponse({}); // snub them.
});
You can do an API around that to get generic localStorage data to your content script, or perhaps, get the whole localStorage array.
I hope that helped solve your problem.
To be fancy and generic ...
contentscript.js
chrome.runtime.sendMessage({method: "getLocalStorage", key: "status"}, function(response) {
console.log(response.data);
});
background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getLocalStorage")
sendResponse({data: localStorage[request.key]});
else
sendResponse({}); // snub them.
});
Use encodeURIComponent()
in JS and in PHP you should receive the correct values.
Note: When you access $_GET
, $_POST
or $_REQUEST
in PHP, you are retrieving values that have already been decoded.
Example:
In your JS:
// url encode your string
var string = encodeURIComponent('+'); // "%2B"
// send it to your server
window.location = 'http://example.com/?string='+string; // http://example.com/?string=%2B
On your server:
echo $_GET['string']; // "+"
It is only the raw HTTP request that contains the url encoded data.
For a GET request you can retrieve this from the URI. $_SERVER['REQUEST_URI']
or $_SERVER['QUERY_STRING']
. For a urlencoded POST, file_get_contents('php://stdin')
NB:
decode()
only works for single byte encoded characters. It will not work for the full UTF-8 range.
eg:
text = "\u0100"; // A
// incorrect
escape(text); // %u0100
// correct
encodeURIComponent(text); // "%C4%80"
Note: "%C4%80"
is equivalent to: escape('\xc4\x80')
Which is the byte sequence (\xc4\x80
) that represents A
in UTF-8. So if you use encodeURIComponent()
your server side must know that it is receiving UTF-8. Otherwise PHP will mangle the encoding.
If you are using
<mvc:annotation-driven/>
make sure your spring-servlet.xml has correct
<context:component-scan base-package="com.....controller" /> tag.
Basically, you need to include all the packages where you have used the annotation in your java code.
Also, please ensure you do not have duplication of component-scan (for a discovery of beans). If your config XML already contains the element, then any of your Controller classes that are annotated with @ComponentScan(basePackages=... needs to be stripped of the said annotation.
Gradle 6.3, Java library. The code from "jar task" adds the dependencies to the "build/libs/xyz.jar" when running "gradle build" task.
plugins {
id 'java-library'
}
jar {
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
}
}
In Russ answer he binds the focus event. I don't think it is necessary.
You can store the old value in the change event.
<script>
$(document).ready(function(){
var newValue = $('#myInputElement').val();
var oldValue;
$('#myInputElement').change(function(){
oldValue = newValue;
newValue = $(this).val();
});
});
</script>
<input id="myInputElement" type="text">
I worked around this by using UriBuilder instead.
UriBuilder builder = new UriBuilder(slct.Text);
if (DeleteFileOnServer(builder.Uri))
{
...
}
I had this problem on production with Heroku and locally while debugging on my macbook pro this morning.
After an hour of debugging, this resolved on its own both locally and on production. I'm not sure what fixed it, so that's a bit annoying. It happened right when I thought I did something, but reverting my supposed fix didn't bring the problem back :(
Interestingly enough, it appears my database service, MongoDb has been having server problems since this morning, so there's a good chance this was related to it.
Method to call the About&support dialog
public void setupAboutSupport() {
try {
// The About&Support AlertDialog is active
activeAboutSupport=true;
View messageView;
int orientation=this.getResources().getConfiguration().orientation;
// Inflate the about message contents
messageView = getLayoutInflater().inflate(R.layout.about_support, null, false);
ContextThemeWrapper ctw = new ContextThemeWrapper(this, R.style.MyCustomTheme_AlertDialog1);
AlertDialog.Builder builder = new AlertDialog.Builder(ctw);
builder.setIcon(R.mipmap.ic_launcher);
builder.setTitle(R.string.action_aboutSupport);
builder.setView(messageView);
TouchImageView imgDisplay = (TouchImageView) messageView.findViewById(R.id.action_infolinks_about_support);
imgDisplay.setMaxZoom(3f);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.myinfolinks_about_support);
int imageWidth = bitmap.getWidth();
int imageHeight = bitmap.getHeight();
int newWidth;
// Calculate the new About_Support image width
if(orientation==Configuration.ORIENTATION_PORTRAIT ) {
// For 7" up to 10" tablets
//if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
if (SingletonMyInfoLinks.isTablet) {
// newWidth = widthScreen - (two borders of about_support layout and 20% of width Screen)
newWidth = widthScreen - ((2 * toPixels(8)) + (int)(widthScreen*0.2));
} else newWidth = widthScreen - ((2 * toPixels(8)) + (int)(widthScreen*0.1));
} else {
// For 7" up to 10" tablets
//if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
if (SingletonMyInfoLinks.isTablet) {
newWidth = widthScreen - ((2 * toPixels(8)) + (int)(widthScreen*0.5));
} else newWidth = widthScreen - ((2 * toPixels(8)) + (int)(widthScreen*0.3));
}
// Get the scale factor
float scaleFactor = (float)newWidth/(float)imageWidth;
// Calculate the new About_Support image height
int newHeight = (int)(imageHeight * scaleFactor);
// Set the new bitmap corresponding the adjusted About_Support image
bitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
// Rescale the image
imgDisplay.setImageBitmap(bitmap);
dialogAboutSupport = builder.show();
TextView textViewVersion = (TextView) dialogAboutSupport.findViewById(R.id.action_strVersion);
textViewVersion.setText(Html.fromHtml(getString(R.string.aboutSupport_text1)+" <b>"+versionName+"</b>"));
TextView textViewDeveloperName = (TextView) dialogAboutSupport.findViewById(R.id.action_strDeveloperName);
textViewDeveloperName.setText(Html.fromHtml(getString(R.string.aboutSupport_text2)+" <b>"+SingletonMyInfoLinks.developerName+"</b>"));
TextView textViewSupportEmail = (TextView) dialogAboutSupport.findViewById(R.id.action_strSupportEmail);
textViewSupportEmail.setText(Html.fromHtml(getString(R.string.aboutSupport_text3)+" "+SingletonMyInfoLinks.developerEmail));
TextView textViewCompanyName = (TextView) dialogAboutSupport.findViewById(R.id.action_strCompanyName);
textViewCompanyName.setText(Html.fromHtml(getString(R.string.aboutSupport_text4)+" "+SingletonMyInfoLinks.companyName));
Button btnOk = (Button) dialogAboutSupport.findViewById(R.id.btnOK);
btnOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialogAboutSupport.dismiss();
}
});
dialogAboutSupport.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(final DialogInterface dialog) {
// the About & Support AlertDialog is closed
activeAboutSupport=false;
}
});
dialogAboutSupport.getWindow().setBackgroundDrawable(new ColorDrawable(SingletonMyInfoLinks.atualBackgroundColor));
/* Effect that image appear slower */
// Only the fade_in matters
AlphaAnimation fade_out = new AlphaAnimation(1.0f, 0.0f);
AlphaAnimation fade_in = new AlphaAnimation(0.0f, 1.0f);
AlphaAnimation a = false ? fade_out : fade_in;
a.setDuration(2000); // 2 sec
a.setFillAfter(true); // Maintain the visibility at the end of animation
// Animation start
ImageView img = (ImageView) messageView.findViewById(R.id.action_infolinks_about_support);
img.startAnimation(a);
} catch (Exception e) {
//Log.e(SingletonMyInfoLinks.appNameText +"-" + getLocalClassName() + ": ", e.getMessage());
}
}
SELECT table1.col,table2.col,table3.col
FROM table1
INNER JOIN
(table2 INNER JOIN table3
ON table3.id=table2.id)
ON table1.id(f-key)=table2.id
AND //add any additional filters HERE
Go to this link and download ODBC Driver for 64 bits OS.
http://www.microsoft.com/en-us/download/details.aspx?id=13255
This https://github.com/rails/strong_parameters seems like the relevant section of the docs:
The permitted scalar types are String, Symbol, NilClass, Numeric, TrueClass, FalseClass, Date, Time, DateTime, StringIO, IO, ActionDispatch::Http::UploadedFile and Rack::Test::UploadedFile.
To declare that the value in params must be an array of permitted scalar values map the key to an empty array:
params.permit(:id => [])
In my app, the category_ids are passed to the create action in an array
"category_ids"=>["", "2"],
Therefore, when declaring strong parameters, I explicitly set category_ids to be an array
params.require(:question).permit(:question_details, :question_content, :user_id, :accepted_answer_id, :province_id, :city, :category_ids => [])
Works perfectly now!
(IMPORTANT: As @Lenart notes in the comments, the array declarations must be at the end of the attributes list, otherwise you'll get a syntax error.)
The answer is on the example link you provided:
http://getbootstrap.com/javascript/#modals-usage
i.e.
Call a modal with id myModal with a single line of JavaScript:
$('#myModal').modal('show');
If you're on Windows, this might work:
There's also a whitepaper of a PDF creation and editing framework in Python. It's a little dated, but maybe can give you some useful info:
It's worth subscribing to the Google Tech Talk YouTube channel. It's a video podcast with a bunch of really interesting, wide-ranging talks given to Google but (usually) outside speakers.
Past presenters include Linus Torvals, Guido van Rossum, Merlin Mann and Larry Wall. The video is usually just the slides so (depending on the speaker) you might not need to watch.
If you don't want to group your result, use a window function.
You didn't state your DBMS, but this is ANSI SQL:
SELECT AccountNumber,
Bill,
BillDate,
SUM(Bill) over (partition by accountNumber) as account_total
FROM Table1
order by AccountNumber, BillDate;
Here is an SQLFiddle: http://sqlfiddle.com/#!15/2c35e/1
You can even add a running sum, by adding:
sum(bill) over (partition by account_number order by bill_date) as sum_to_date
which will give you the total up to the current's row date.
You can use the Class XmlAttribute.
Eg:
XmlAttribute attr = xmlDoc.CreateAttribute("userName");
attr.Value = "Tushar";
node.Attributes.Append(attr);
Another method if you're stuck on <2.6, you don't have numpy, and you don't have IEEE 754 support:
def isNaN(x):
return str(x) == str(1e400*0)
var linkGo = function(item) {_x000D_
$(item).on('click', function() {_x000D_
var _$this = $(this);_x000D_
var _urlBlank = _$this.attr("data-link");_x000D_
var _urlTemp = _$this.attr("data-url");_x000D_
if (_urlBlank === "_blank") {_x000D_
window.open(_urlTemp, '_blank');_x000D_
} else {_x000D_
// cross-origin_x000D_
location.href = _urlTemp;_x000D_
}_x000D_
});_x000D_
};_x000D_
_x000D_
linkGo(".button__main[data-link]");
_x000D_
.button{cursor:pointer;}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<span class="button button__main" data-link="" data-url="https://stackoverflow.com/">go stackoverflow</span>
_x000D_
var jsonData = [{"person":"me","age":"30"},{"person":"you","age":"25"}];
for(var i in jsonData){
var key = i;
var val = jsonData[i];
for(var j in val){
var sub_key = j;
var sub_val = val[j];
console.log(sub_key);
}
}
EDIT
var jsonObj = {"person":"me","age":"30"};
Object.keys(jsonObj); // returns ["person", "age"]
Object
has a property
keys
, returns an Array
of keys from that Object
Chrome, FF & Safari supports Object.keys
try this:
#outer {
width:500px;
height:200px;
background:#FFCCCC;
margin:50px auto 0 auto;
display:table;
}
#inner {
background:#FFCC33;
margin:50px 50px 50px 50px;
padding:10px;
display:block;
}?
Good luck
With reference to Cori's answer, I modified it and used below command, which is working. Without exit
, remaining command was actually logging to remote machine, which I didn't want in script
ssh -o StrictHostKeyChecking=no user@ip_of_remote_machine "exit"
Try this:
>>> import time
>>> time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(1347517119))
'2012-09-12 23:18:39'
Also in MySQL, you can FROM_UNIXTIME
like:
INSERT INTO tblname VALUES (FROM_UNIXTIME(1347517119))
For your 2nd question, it is probably because getbbb_class.end_time
is a string. You can convert it to numeric like: float(getbbb_class.end_time)
A "floating point number" is how computers usually represent numbers that are not integers -- basically, a number with a decimal point. In C++ you declare them with float
instead of int
. A floating point exception is an error that occurs when you try to do something impossible with a floating point number, such as divide by zero.
String[] args = new String[]{"firstarg", "secondarg", "thirdarg"};
I have made a query for you. This will give you Recursive Category with a Single Query:
SELECT id,NAME,'' AS subName,'' AS subsubName,'' AS subsubsubName FROM Table1 WHERE prent is NULL
UNION
SELECT b.id,a.name,b.name AS subName,'' AS subsubName,'' AS subsubsubName FROM Table1 AS a LEFT JOIN Table1 AS b ON b.prent=a.id WHERE a.prent is NULL AND b.name IS NOT NULL
UNION
SELECT c.id,a.name,b.name AS subName,c.name AS subsubName,'' AS subsubsubName FROM Table1 AS a LEFT JOIN Table1 AS b ON b.prent=a.id LEFT JOIN Table1 AS c ON c.prent=b.id WHERE a.prent is NULL AND c.name IS NOT NULL
UNION
SELECT d.id,a.name,b.name AS subName,c.name AS subsubName,d.name AS subsubsubName FROM Table1 AS a LEFT JOIN Table1 AS b ON b.prent=a.id LEFT JOIN Table1 AS c ON c.prent=b.id LEFT JOIN Table1 AS d ON d.prent=c.id WHERE a.prent is NULL AND d.name IS NOT NULL
ORDER BY NAME,subName,subsubName,subsubsubName
Here is a fiddle.
catch
ing in this fashion, in my experience, is dangerous. Any error thrown in the entire stack will be caught, not just an error from this promise (which is probably not what you want).
The second argument to a promise is already a rejection/failure callback. It's better and safer to use that instead.
Here's a typescript typesafe one-liner I wrote to handle this:
function wait<R, E>(promise: Promise<R>): [R | null, E | null] {
return (promise.then((data: R) => [data, null], (err: E) => [null, err]) as any) as [R, E];
}
// Usage
const [currUser, currUserError] = await wait<GetCurrentUser_user, GetCurrentUser_errors>(
apiClient.getCurrentUser()
);
After a few futile hours battling with a 'SyntaxError: missing : after property id' message I can now expand on this topic:
border-width is a valid css property but it is not included in the jQuery css oject definition, so .css({border-width: '2px'}) will cause an error, but it's quite happy with .css({'border-width': '2px'}), presumably property names in quotes are just passed on as received.
Try adding a pair of class attributes, say 'even' and 'odd', to alternating list elements, e.g.
<ul>
<li class="even"><a href="link">Link 1</a></li>
<li class="odd"><a href="link">Link 2</a></li>
<li class="even"><a href="link">Link 3</a></li>
<li class="odd"><a href="link">Link 4</a></li>
<li class="even"><a href="link">Link 5</a></li>
</ul>
In a <style> section of the HTML page, or in a linked stylesheet, you would define those same classes, specifying your desired background colours:
li.even { background-color: red; }
li.odd { background-color: blue; }
You might want to use a template library as your needs evolve to provide you with greater flexibility and to cut down on the typing. Why type all those list elements by hand?
There's another way to do it that I've always found to be more readable.
Say that you want to start rabbitmq and mongodb when you run it then your CMD
would look something like this:
CMD /etc/init.d/rabbitmq-server start && \
/etc/init.d/mongod start
Since you can have only one CMD
per Dockerfile
the trick is to concatenate all instructions with &&
and then use \
for each command to start a new line.
If you end up adding to many of those I suggest you put all your commands in a script file and start it like @larry-cai suggested:
CMD /start.sh
It should also be noted there is an alternative Proxy pattern for maintaining a reference to the original this
in a callback if you dislike the var self = this
idiom.
As a function can be called with a given context by using function.apply
or function.call
, you can write a wrapper that returns a function that calls your function with apply
or call
using the given context. See jQuery's proxy
function for an implementation of this pattern. Here is an example of using it:
var wrappedFunc = $.proxy(this.myFunc, this);
wrappedFunc
can then be called and will have your version of this
as the context.
Based on the previous answers, and cobbled together from various places in stack overflow, here is the solution I came up with which handles the case when you actually want to submit your changes:
window.thisPage = window.thisPage || {};
window.thisPage.isDirty = false;
window.thisPage.closeEditorWarning = function (event) {
if (window.thisPage.isDirty)
return 'It looks like you have been editing something' +
' - if you leave before saving, then your changes will be lost.'
else
return undefined;
};
$("form").on('keyup', 'textarea', // You can use input[type=text] here as well.
function () {
window.thisPage.isDirty = true;
});
$("form").submit(function () {
QC.thisPage.isDirty = false;
});
window.onbeforeunload = window.thisPage.closeEditorWarning;
It's worth noting that IE11 seems to require that the closeEditorWarning
function returns undefined
for it not to show an alert.
Download and install Miniconda first from this link and later on download and install Anaconda. Then you will be able to see the navigator in your all programs list in the start menu. I hope this will help you. Let me know in case of any concerns.
While the others answers are correct in so far as they show what a mere +
usually does (namely, leave the number as it is, if it is one), they are incomplete in so far as they don't explain what happens.
To be exact, +x
evaluates to x.__pos__()
and ++x
to x.__pos__().__pos__()
.
I could imagine a VERY weird class structure (Children, don't do this at home!) like this:
class ValueKeeper(object):
def __init__(self, value): self.value = value
def __str__(self): return str(self.value)
class A(ValueKeeper):
def __pos__(self):
print 'called A.__pos__'
return B(self.value - 3)
class B(ValueKeeper):
def __pos__(self):
print 'called B.__pos__'
return A(self.value + 19)
x = A(430)
print x, type(x)
print +x, type(+x)
print ++x, type(++x)
print +++x, type(+++x)
Your code is correct. Just put them inside the <VirtualHost *:443>
Example:
<VirtualHost *:443>
SSLEnable
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}
</VirtualHost>
NUMBER (precision, scale)
means precision
number of total digits, of which scale
digits are right of the decimal point.
NUMBER(2,2)
in other words means a number with 2 digits, both of which are decimals. You may mean to use NUMBER(4,2)
to get 4 digits, of which 2 are decimals. Currently you can just insert values with a zero integer part.
jQuery processes the data
attribute and converts the values into strings.
Adding processData: false
to your options object fixes the error, but I'm not sure if it fixes the problem.
I recently came up with the following convention for naming my tests, their classes and containing projects in order to maximize their descriptivenes:
Lets say I am testing the Settings
class in a project in the MyApp.Serialization
namespace.
First I will create a test project with the MyApp.Serialization.Tests
namespace.
Within this project and of course the namespace I will create a class called IfSettings
(saved as IfSettings.cs).
Lets say I am testing the SaveStrings()
method. -> I will name the test CanSaveStrings()
.
When I run this test it will show the following heading:
MyApp.Serialization.Tests.IfSettings.CanSaveStrings
I think this tells me very well, what it is testing.
Of course it is usefull that in English the noun "Tests" is the same as the verb "tests".
There is no limit to your creativity in naming the tests, so that we get full sentence headings for them.
Usually the Test names will have to start with a verb.
Examples include:
DetectsInvalidUserInput
)ThrowsOnNotFound
)WillCloseTheDatabaseAfterTheTransaction
)etc.
Another option is to use "that" instead of "if".
The latter saves me keystrokes though and describes more exactly what I am doing, since I don't know, that the tested behavior is present, but am testing if it is.
[Edit]
After using above naming convention for a little longer now, I have found, that the If prefix can be confusing, when working with interfaces. It just so happens, that the testing class IfSerializer.cs looks very similar to the interface ISerializer.cs in the "Open Files Tab". This can get very annoying when switching back and forth between the tests, the class being tested and its interface. As a result I would now choose That over If as a prefix.
Additionally I now use - only for methods in my test classes as it is not considered best practice anywhere else - the "_" to separate words in my test method names as in:
[Test] public void detects_invalid_User_Input()
I find this to be easier to read.
[End Edit]
I hope this spawns some more ideas, since I consider naming tests of great importance as it can save you a lot of time that would otherwise have been spent trying to understand what the tests are doing (e.g. after resuming a project after an extended hiatus).
By invoking its toString()
method.
Returns a string containing the characters in this sequence in the same order as this sequence. The length of the string will be the length of this sequence.
Checkout the following article
on MSDN about examples of the N
format. This is also covered in the Standard Numeric Format Strings
article.
Relevant excerpts:
// Formatting of 1054.32179:
// N: 1,054.32
// N0: 1,054
// N1: 1,054.3
// N2: 1,054.32
// N3: 1,054.322
When precision specifier controls the number of fractional digits in the result string, the result string reflects a number that is rounded to a representable result nearest to the infinitely precise result. If there are two equally near representable results:
- On the .NET Framework and .NET Core up to .NET Core 2.0, the runtime selects the result with the greater least significant digit (that is, using MidpointRounding.AwayFromZero).
- On .NET Core 2.1 and later, the runtime selects the result with an even least significant digit (that is, using MidpointRounding.ToEven).
If you launch your program with -enableassertions
(or -ea
for short) then this statement
assert cond;
is equivalent to
if (!cond)
throw new AssertionError();
If you launch your program without this option, the assert statement will have no effect.
For example, assert d >= 0 && d <= s.length();
, as posted in your question, is equivalent to
if (!(d >= 0 && d <= s.length()))
throw new AssertionError();
(If you launched with -enableassertions
that is.)
Formally, the Java Language Specification: 14.10. The assert
Statement says the following:
14.10. The
assert
Statement
An assertion is anassert
statement containing a boolean expression. An assertion is either enabled or disabled. If the assertion is enabled, execution of the assertion causes evaluation of the boolean expression and an error is reported if the expression evaluates tofalse
. If the assertion is disabled, execution of the assertion has no effect whatsoever.
Where "enabled or disabled" is controlled with the -ea
switch and "An error is reported" means that an AssertionError
is thrown.
assert
:You can append : "Error message"
like this:
assert d != null : "d is null";
to specify what the error message of the thrown AssertionError should be.
This post has been rewritten as an article here.
I had this same exact error all of a sudden the other day. I did a "Clean Project" and a "Rebuild Project" and never saw the error again.
I've only got a few months of Android development under my belt. But whenever I get an unexplained error like this, "Clean Project" and/or "Rebuild Project" are the first things I try.
Your code as given (after the edit) compiles fine, so something else is wrong that isn't in what you posted.
Some things to check, is everything public? That includes both the class and the method.
Overload with different parameters?
Are you sure that Base
is the class you think it is? I.e. is there another class by the same name that it's actually referencing?
Edit:
To answer the question in your comment, you can't override a method with different parameters, nor is there a need to. You can create a new method (with the new parameter) without the override
keyword and it will work just fine.
If your intention is to prohibit calling of the base method without the parameter you can mark the method as protected
instead of public
. That way it can only be called from classes that inherit from Base
For Mac OS X with blanks in target directory (follow up to @pheon). Add extra pair of double quotes around $(...) in line 2 thus. See: https://stackoverflow.com/a/1308838 (Sean Bright)
#!/bin/bash
cd "$(dirname "$0")" && pwd
ipython notebook
*************Resolved - #1214 - The used table type doesn't support FULLTEXT indexes***************
Its Very Simple to resolve this issue. People are answering here in very difficult words which are not easily understandable by the people who are not technical.
So i am mentioning here steps in very simple words will resolve your issue.
1.) Open your .sql file with Notepad by right clicking on file>Edit Or Simply open a Notepad file and drag and drop the file on Notepad and the file will be opened. (Note: Please don't change the extention .sql of file as its still your sql database. Also to keep a copy of your sql file to save yourself from any mishappening)
2.) Click on Notepad Menu Edit > Replace (A Window will be pop us with Find What & Replace With Fields)
3.) In Find What Field Enter ENGINE=InnoDB & In Replace With Field Enter ENGINE=MyISAM
4.) Now Click on Replace All Button
5.) Click CTRL+S or File>Save
6.) Now Upload This File and I am Sure your issue will be resolved....
cmd (command):
netdom renamecomputer %COMPUTERNAME% /Newname "NEW-NAME"
powershell (windows 2008/2012):
netdom renamecomputer "$env:COMPUTERNAME" /Newname "NEW-NAME"
after that, you need to reboot your computer.
You can do it like this,
$('.ads_Checkbox:checked')
You can iterate through them with each()
and fill the array with checkedbox values.
To get the values of selected checkboxes in array
var i = 0;
$('#save_value').click(function () {
var arr = [];
$('.ads_Checkbox:checked').each(function () {
arr[i++] = $(this).val();
});
});
Edit, using .map()
You can also use jQuery.map with get()
to get the array of selected checkboxe values.
As a side note using this.value
instead of $(this).val()
would give better performance.
$('#save_value').click(function(){
var arr = $('.ads_Checkbox:checked').map(function(){
return this.value;
}).get();
});
You could try to extract columns as list, massage this as you want, and reindex your dataframe:
>>> cols = df.columns.tolist()
>>> cols = [cols[-1]]+cols[:-1] # or whatever change you need
>>> df.reindex(columns=cols)
n l v
0 0 a 1
1 0 b 2
2 0 c 1
3 0 d 2
EDIT: this can be done in one line ; however, this looks a bit ugly. Maybe some cleaner proposal may come...
>>> df.reindex(columns=['n']+df.columns[:-1].tolist())
n l v
0 0 a 1
1 0 b 2
2 0 c 1
3 0 d 2
This worked for me
<div style="display: flex; position: absolute; width: 100%;">
<div style="white-space: nowrap; overflow: hidden;text-overflow: ellipsis;">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi.
</div>
</div>
Adding position:absolute
to the parent container made it work.
PS: This is for anyone looking for a solution to dynamically truncating text.
EDIT: This was meant to be an answer for this question but since they are related and it could help someone on this question I shall also leave it here instead of deleting it.
The web server is prompting you for a SPNEGO (Simple and Protected GSSAPI Negotiation Mechanism) token.
This is a Microsoft invention for negotiating a type of authentication to use for Web SSO (single-sign-on):
See:
Number one difference for me: if HAVING
was removed from the SQL language then life would go on more or less as before. Certainly, a minority queries would need to be rewritten using a derived table, CTE, etc but they would arguably be easier to understand and maintain as a result. Maybe vendors' optimizer code would need to be rewritten to account for this, again an opportunity for improvement within the industry.
Now consider for a moment removing WHERE
from the language. This time the majority of queries in existence would need to be rewritten without an obvious alternative construct. Coders would have to get creative e.g. inner join to a table known to contain exactly one row (e.g. DUAL
in Oracle) using the ON
clause to simulate the prior WHERE
clause. Such constructions would be contrived; it would be obvious there was something was missing from the language and the situation would be worse as a result.
TL;DR we could lose HAVING
tomorrow and things would be no worse, possibly better, but the same cannot be said of WHERE
.
From the answers here, it seems that many folk don't realize that a HAVING
clause may be used without a GROUP BY
clause. In this case, the HAVING
clause is applied to the entire table expression and requires that only constants appear in the SELECT
clause. Typically the HAVING
clause will involve aggregates.
This is more useful than it sounds. For example, consider this query to test whether the name
column is unique for all values in T
:
SELECT 1 AS result
FROM T
HAVING COUNT( DISTINCT name ) = COUNT( name );
There are only two possible results: if the HAVING
clause is true then the result with be a single row containing the value 1
, otherwise the result will be the empty set.
CREATE TEMPORARY TABLE IF NOT EXISTS to_table_name AS (SELECT * FROM from_table_name)
The parseInt
function converts strings to numbers, and it takes a second argument specifying the base in which the string representation is:
var digit = parseInt(binary, 2);
To check with current branch:
git diff -- projects/components/some.component.ts ... origin
git diff -- projects/components/some.component.html ... origin
To check with some other branch say staging:
git diff -- projects/components/some.component.ts ... origin/staging
git diff -- projects/components/some.component.html ... origin/staging
Whenever there are issues of mismatched axis limits, the right tool in base
graphics is to use matplot
. The key is to leverage the from
and to
arguments to density.default
. It's a bit hackish, but fairly straightforward to roll yourself:
set.seed(102349)
x1 = rnorm(1000, mean = 5, sd = 3)
x2 = rnorm(5000, mean = 2, sd = 8)
xrng = range(x1, x2)
#force the x values at which density is
# evaluated to be the same between 'density'
# calls by specifying 'from' and 'to'
# (and possibly 'n', if you'd like)
kde1 = density(x1, from = xrng[1L], to = xrng[2L])
kde2 = density(x2, from = xrng[1L], to = xrng[2L])
matplot(kde1$x, cbind(kde1$y, kde2$y))
Add bells and whistles as desired (matplot
accepts all the standard plot
/par
arguments, e.g. lty
, type
, col
, lwd
, ...).
If you add height in .wrapper
class then your scroll is working, without height
scroll is not working.
Try this http://jsfiddle.net/ZcrFr/3/
CSS:
.wrapper {
position: relative;
overflow: scroll;
width: 1000px;
height: 800px;
}
It should be sufficient to use
git ls-files --others -i --exclude-standard
as that covers everything covered by
git ls-files --others -i --exclude-from=.git/info/exclude
therefore the latter is redundant.
~/.gitconfig
file:
git config --global alias.ignored "ls-files --others -i --exclude-standard"
Now you can just type git ignored
to see the list. Much easier to remember, and faster to type.
If you prefer the more succinct display of Jason Geng's solution, you can add an alias for that like this:
git config --global alias.ignored "status --ignored -s"
However the more verbose output is more useful for troubleshooting problems with your .gitignore files, as it lists every single cotton-pickin' file that is ignored. You would normally pipe the results through grep
to see if a file you expect to be ignored is in there, or if a file you don't want to be ignore is in there.
git ignored | grep some-file-that-isnt-being-ignored-properly
Then, when you just want to see a short display, it's easy enough to remember and type
git status --ignored
(The -s
can normally be left off.)
simple and easier solution:
select extract(hour from systimestamp) from dual;
EXTRACT(HOURFROMSYSTIMESTAMP)
-----------------------------
16
As soon as they view your page that includes the picture or video, the item is downloaded into the temporary folder of their browser. So if you don't want it downloaded, don't post it.
Assuming MySQL (EDIT: posted before the SQL variant was supplied):
ALTER TABLE myTable ADD myNewColumn VARCHAR(255) AFTER myOtherColumn
The AFTER keyword tells MySQL where to place the new column. You can also use FIRST to flag the new column as the first column in the table.
Just copy war file to standalone/deployments/ folder, it should deploy it automatically. It'll also create your_app_name.deployed file, when your application is deployed. Also be sure that you start server with bin/standalone.sh script.
Maybe it is not what you are looking for, but I had a similar problem and i solved it including JSON 2 to my application:
https://github.com/douglascrockford/JSON-js
Other browsers natively implements JSON but IE < 8 (also IE 8 compatibility mode) does not, that's why you need to include it.
Here is a related question: JSON on IE6 (IE7)
UPDATE
the JSON parser has been updated so you should use the new one: http://bestiejs.github.io/json3/
In [6]: os.listdir?
Type: builtin_function_or_method
String Form:<built-in function listdir>
Docstring:
listdir(path) -> list_of_strings
Return a list containing the names of the entries in the directory.
path: path of directory to list
The list is in **arbitrary order**. It does not include the special
entries '.' and '..' even if they are present in the directory.
You can't install Integration Services with it. Express does not support Integration Services. So if you want build say SSIS-packages you'll need at least Standard Edition.
See more here.
You can also use rsync
rsync -rv --size-only --dry-run /my/source/ /my/dest/ > diff.out
You're getting that error because the default value current_time
is not valid for the type DATETIME
. That's what it says, and that's whats going on.
The only field you can use current_time
on is a timestamp.