The first step is figuring out what the error actually is. In order to do this expand your MsBuild output to be diagnostic. This will reveal the actual command executed and hopefully the full error message as well
You can mark it as @JsonIgnore
.
With 1.9, you can add @JsonIgnore
for getter, @JsonProperty
for setter, to make it deserialize but not serialize.
Reserved.objects.filter(client=client_id).order_by('-check_in')
A hyphen "-" in front of "check_in" indicates descending order. Ascending order is implied.
We don't have to add an all() before filter(). That would still work, but you only need to add all() when you want all objects from the root QuerySet.
More on this here: https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters
To get the content of a url:
try: # Try importing requests first.
import requests
except ImportError:
try: # Try importing Python3 urllib
import urllib.request
except AttributeError: # Now importing Python2 urllib
import urllib
def get_content(url):
try: # Using requests.
return requests.get(url).content # Returns requests.models.Response.
except NameError:
try: # Using Python3 urllib.
with urllib.request.urlopen(index_url) as response:
return response.read() # Returns http.client.HTTPResponse.
except AttributeError: # Using Python3 urllib.
return urllib.urlopen(url).read() # Returns an instance.
It's hard to write Python2 and Python3 and request
dependencies code for the responses because they urlopen()
functions and requests.get()
function return different types:
urllib.request.urlopen()
returns a http.client.HTTPResponse
urllib.urlopen(url)
returns an instance
request.get(url)
returns a requests.models.Response
As for ERRORCODE 39, you can definately just delete the physical table files on the disk. the location depends on your OS distribution and setup. On Debian its typically under /var/lib/mysql/database_name/ So do a:
rm -f /var/lib/mysql/<database_name>/
And then drop the database from your tool of choice or using the command:
DROP DATABASE <database_name>
I am also having This Error!
Then i change this
$("#from").datepicker('disable');
to This
$("#from").datepicker("disable");
mistake : single and double quotes..
Now its Work fine for me..
I had the same issue when my server free disk space available was 0
You can use the command (there must be ample space for the mysql files)
REPAIR TABLE `<table name>`;
for repairing individual tables
world !
No need to do execute batch command. With the current version, just run BLUESTACKS before ANDROID STUDIO
This goes back to the basic difference between & and &&, | and ||
BTW you perform the same tasks many times. Not sure if efficiency is an issue. You could remove some of the duplication.
Z z2 = partialHits.get(req_nr).get(z); // assuming a value cannout be null.
Z z3 = tmpmap.get(z); // assuming z3 cannot be null.
if(z2 == null || z2 < z3){
partialHits.get(z).put(z, z3);
}
Use the following:
getActivity().setTitle("YOUR_TITLE");
var result = from x in entity
join y in entity2 on new { x.field1, x.field2 } equals new { y.field1, y.field2 }
jQuery.i18n is a lightweight jQuery plugin for enabling internationalization in your web pages. It allows you to package custom resource strings in ‘.properties’ files, just like in Java Resource Bundles. It loads and parses resource bundles (.properties) based on provided language or language reported by browser.
to know more about this take a look at the How to internationalize your pages using JQuery?
Instead of "returning true", you can also use the "noop" or null utility (as referred in the POSIX specs) :
and just "do nothing". You'll save a few letters. :)
#!/usr/bin/env bash
set -e
man nonexistentghing || :
echo "It's ok.."
Call the pd.DataFrame
constructor directly:
df = pd.DataFrame(table, columns=headers)
df
Heading1 Heading2
0 1 2
1 3 4
If you move from iframes, you may get lost in your page, best way to execute some jquery without issue (with selenimum/python/gecko):
# 1) Get back to the main body page
driver.switch_to.default_content()
# 2) Download jquery lib file to your current folder manually & set path here
with open('./_lib/jquery-3.3.1.min.js', 'r') as jquery_js:
# 3) Read the jquery from a file
jquery = jquery_js.read()
# 4) Load jquery lib
driver.execute_script(jquery)
# 5) Execute your command
driver.execute_script('$("#myId").click()')
You could use the old ways. And use a table. In the table you define 3 columns. You set the width of your whole table and define the width of every colum. that way you can horizantaly space 2 objects. You put object one inside cell1 (colum1, row1) and object2 in cell3 (colum 3, row 1) and you leave cell 2 empty. Given it has a width, you will see empty spaces. example
<table width="500">
<tr>
<td width="40%">
Object 1
</td>
<td width="20%">
</td>
<td width="40%">
Object 2
</td>
</tr>
</table>
Or you could go the better way with div's. Just put your objects inside divs. Add a middle div and put these 3 divs inside another div. At the css style to the upper div: overflow: auto and define a width. Add css style to the 3 divs to define their width and add float: left example
<div style="overflow: auto;width: 100%;">
<div style="width:200px;float: left;">
Object 1
</div>
<div style="width:200px;float: left;">
</div>
<div style="width:200px;float: left;">
Object 2
</div>
</div>
You can also plot the timestamp, value pairs using pyplot.plot (after parsing them from their string representation). (Tested with matplotlib versions 1.2.0 and 1.3.1.)
Example:
import datetime
import random
import matplotlib.pyplot as plt
# make up some data
x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(12)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]
# plot
plt.plot(x,y)
# beautify the x-labels
plt.gcf().autofmt_xdate()
plt.show()
Resulting image:
Here's the same as a scatter plot:
import datetime
import random
import matplotlib.pyplot as plt
# make up some data
x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(12)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]
# plot
plt.scatter(x,y)
# beautify the x-labels
plt.gcf().autofmt_xdate()
plt.show()
Produces an image similar to this:
declare @temp as varchar
set @temp='Measure'
if(@temp = 'Measure')
Select Measure from Measuretable
else
Select OtherMeasure from Measuretable
I assume you want to clear the Images drawn via PictureBox.
This you would be achieved via a Bitmap object and using Graphics object. you might be doing something like
Graphics graphic = Graphics.FromImage(pictbox.Image);
graphic.Clear(Color.Red) //Color to fill the background and reset the box
Is this what you were looking out?
EDIT
Since you are using the paint method this would cause it to be redrawn every time, I would suggest you to set a flag at the formlevel indicating whether it should or not paint the Picturebox
private bool _shouldDraw = true;
public bool ShouldDraw
{
get { return _shouldDraw; }
set { _shouldDraw = value; }
}
In your paint just use
if(ShouldDraw)
//do your stuff
When you click the button set this property to false and you should be fine.
There is a new instance method called String::formatted(Object... args)
as of Java 15.
The internal implementation is same to String::format(String format, Object... args)
.
Formats using this string as the format string, and the supplied arguments.
String step1 = "one";
String step2 = "two";
// results in "Step one of two"
String string = "Step %s of %s".formatted(step1, step2);
Advantage: The difference is that the method is not static
and the formatting pattern is a string itself from which a new one is created based on the args
. This allows chaining to build the format itself first.
Disadvantage: There is no overloaded method with Locale
, therefore uses the default one. If you need to use a custom Locale
, you have to stick with String::format(Locale l,String format,Object... args)
.
You probably want to add "static" to the declaration of con2.
In Java, things (both variables and methods) can be properties of the class (which means they're shared by all objects of that type), or they can be properties of the object (a different one in each object of the same class). The keyword "static" is used to indicate that something is a property of the class.
"Static" stuff exists all the time. The other stuff only exists after you've created an object, and even then each individual object has its own copy of the thing. And the flip side of this is key in this case: static stuff can't access non-static stuff, because it doesn't know which object to look in. If you pass it an object reference, it can do stuff like "thingie.con2", but simply saying "con2" is not allowed, because you haven't said which object's con2 is meant.
The fastest way is to do a*a
or a**2
or np.square(a)
whereas np.power(a, 2)
showed to be considerably slower.
np.power()
allows you to use different exponents for each element if instead of 2
you pass another array of exponents. From the comments of @GarethRees I just learned that this function will give you different results than a**2
or a*a
, which become important in cases where you have small tolerances.
I've timed some examples using NumPy 1.9.0 MKL 64 bit, and the results are shown below:
In [29]: a = np.random.random((1000, 1000))
In [30]: timeit a*a
100 loops, best of 3: 2.78 ms per loop
In [31]: timeit a**2
100 loops, best of 3: 2.77 ms per loop
In [32]: timeit np.power(a, 2)
10 loops, best of 3: 71.3 ms per loop
The following snippet of WebDriver Java code should work to launch IE. The code will ignore the setup of Protected mode settings for all zone in the IE browser.
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
File file = new File("D:\\Ripon Al Wasim\\IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
WebDriver driver = new InternetExplorerDriver(capabilities);
driver.get("https://www.google.com/");
Download IEDriverServer and extract it into your desired location and set the absolute path (In my above example it was "D:\Ripon Al Wasim\IEDriverServer.exe")
You don't mention what language you want to track these in, but I found two for javascript:
change your code to this
$start_date = new DateTime( "@" . $dbResult->db_timestamp );
and it will work fine
If you load a page in your browser using HTTPS, the browser will refuse to load any resources over HTTP. As you've tried, changing the API URL to have HTTPS instead of HTTP typically resolves this issue. However, your API must not allow for HTTPS connections. Because of this, you must either force HTTP on the main page or request that they allow HTTPS connections.
Note on this: The request will still work if you go to the API URL instead of attempting to load it with AJAX. This is because the browser is not loading a resource from within a secured page, instead it's loading an insecure page and it's accepting that. In order for it to be available through AJAX, though, the protocols should match.
I had the same issue with setting StatusCode
and then Response.End
in HandleUnauthorizedRequest
method of AuthorizeAttribute
var ctx = filterContext.HttpContext;
ctx.Response.StatusCode = (int)HttpStatusCode.Forbidden;
ctx.Response.End();
If you are using .NET 4.5+, add this line before Response.StatusCode
filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
If you are using .NET 4.0, try SuppressFormsAuthenticationRedirectModule.
If you are only concerned with the constant True
, a simple sum
is fine. However, keep in mind that in Python other values evaluate as True
as well. A more robust solution would be to use the bool
builtin:
>>> l = [1, 2, True, False]
>>> sum(bool(x) for x in l)
3
UPDATE: Here's another similarly robust solution that has the advantage of being more transparent:
>>> sum(1 for x in l if x)
3
P.S. Python trivia: True
could be true without being 1. Warning: do not try this at work!
>>> True = 2
>>> if True: print('true')
...
true
>>> l = [True, True, False, True]
>>> sum(l)
6
>>> sum(bool(x) for x in l)
3
>>> sum(1 for x in l if x)
3
Much more evil:
True = False
There are 3 access specifiers
for a class/struct/Union in C++. These access specifiers define how the members of the class can be accessed. Of course, any member of a class is accessible within that class(Inside any member function of that same class). Moving ahead to type of access specifiers, they are:
Public - The members declared as Public are accessible from outside the Class through an object of the class.
Protected - The members declared as Protected are accessible from outside the class BUT only in a class derived from it.
Private - These members are only accessible from within the class. No outside Access is allowed.
An Source Code Example:
class MyClass
{
public:
int a;
protected:
int b;
private:
int c;
};
int main()
{
MyClass obj;
obj.a = 10; //Allowed
obj.b = 20; //Not Allowed, gives compiler error
obj.c = 30; //Not Allowed, gives compiler error
}
Inheritance in C++ can be one of the following types:
Private
Inheritance Public
Inheritance Protected
inheritance Here are the member access rules with respect to each of these:
First and most important rule
Private
members of a class are never accessible from anywhere except the members of the same class.
All
Public
members of the Base Class becomePublic
Members of the derived class &
AllProtected
members of the Base Class becomeProtected
Members of the Derived Class.
i.e. No change in the Access of the members. The access rules we discussed before are further then applied to these members.
Code Example:
Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived:public Base
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};
int main()
{
Derived obj;
obj.a = 10; //Allowed
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
}
All
Public
members of the Base Class becomePrivate
Members of the Derived class &
AllProtected
members of the Base Class becomePrivate
Members of the Derived Class.
An code Example:
Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived:private Base //Not mentioning private is OK because for classes it defaults to private
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};
class Derived2:public Derived
{
void doSomethingMore()
{
a = 10; //Not Allowed, Compiler Error, a is private member of Derived now
b = 20; //Not Allowed, Compiler Error, b is private member of Derived now
c = 30; //Not Allowed, Compiler Error
}
};
int main()
{
Derived obj;
obj.a = 10; //Not Allowed, Compiler Error
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
}
All
Public
members of the Base Class becomeProtected
Members of the derived class &
AllProtected
members of the Base Class becomeProtected
Members of the Derived Class.
A Code Example:
Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived:protected Base
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};
class Derived2:public Derived
{
void doSomethingMore()
{
a = 10; //Allowed, a is protected member inside Derived & Derived2 is public derivation from Derived, a is now protected member of Derived2
b = 20; //Allowed, b is protected member inside Derived & Derived2 is public derivation from Derived, b is now protected member of Derived2
c = 30; //Not Allowed, Compiler Error
}
};
int main()
{
Derived obj;
obj.a = 10; //Not Allowed, Compiler Error
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
}
Remember the same access rules apply to the classes and members down the inheritance hierarchy.
- Access Specification is per-Class not per-Object
Note that the access specification C++ work on per-Class basis and not per-object basis.
A good example of this is that in a copy constructor or Copy Assignment operator function, all the members of the object being passed can be accessed.
- A Derived class can only access members of its own Base class
Consider the following code example:
class Myclass
{
protected:
int x;
};
class derived : public Myclass
{
public:
void f( Myclass& obj )
{
obj.x = 5;
}
};
int main()
{
return 0;
}
It gives an compilation error:
prog.cpp:4: error: ‘int Myclass::x’ is protected
Because the derived class can only access members of its own Base Class. Note that the object obj
being passed here is no way related to the derived
class function in which it is being accessed, it is an altogether different object and hence derived
member function cannot access its members.
friend
? How does friend
affect access specification rules?You can declare a function or class as friend
of another class. When you do so the access specification rules do not apply to the friend
ed class/function. The class or function can access all the members of that particular class.
So do
friend
s break Encapsulation?
No they don't, On the contrary they enhance Encapsulation!
friend
ship is used to indicate a intentional strong coupling between two entities.
If there exists a special relationship between two entities such that one needs access to others private
or protected
members but You do not want everyone to have access by using the public
access specifier then you should use friend
ship.
With PHP 5.4, you can turn Matthew's answer into a one-liner:
$date = sprintf('%d-%d-01', $year, date_parse('may')['month']);
One major difference that is important to know is that ActiveX controls show up as objects that you can use in your code- try inserting an ActiveX control into a worksheet, bring up the VBA editor (ALT + F11) and you will be able to access the control programatically. You can't do this with form controls (macros must instead be explicitly assigned to each control), but form controls are a little easier to use. If you are just doing something simple, it doesn't matter which you use but for more advanced scripts ActiveX has better possibilities.
ActiveX is also more customizable.
Using the below line
SELECT LEFT(subject , 10) FROM tbl
Here you are trying to execute IQueryable object on inactive DBContext. your DBcontext is already disposed of. you can only execute IQueryable object before DBContext is disposed of. Means you need to write users.Select(x => x.ToInfo()).ToList()
statement inside using scope
It is also worth noting the sorted()
function:
for x in sorted(list):
print x
This returns a new, sorted version of a list without changing the original list.
Using a thread pool is a good option, and will make this fairly easy. Unfortunately, python doesn't have a standard library that makes thread pools ultra easy. But here is a decent library that should get you started: http://www.chrisarndt.de/projects/threadpool/
Code example from their site:
pool = ThreadPool(poolsize)
requests = makeRequests(some_callable, list_of_args, callback)
[pool.putRequest(req) for req in requests]
pool.wait()
Hope this helps.
Here is an (untested) implementation of a ReverseIterable
. When iterator()
is called it creates and returns a private ReverseIterator
implementation, which simply maps calls to hasNext()
to hasPrevious()
and calls to next()
are mapped to previous()
. It means you could iterate over an ArrayList
in reverse as follows:
ArrayList<String> l = ...
for (String s : new ReverseIterable(l)) {
System.err.println(s);
}
Class Definition
public class ReverseIterable<T> implements Iterable<T> {
private static class ReverseIterator<T> implements Iterator {
private final ListIterator<T> it;
public boolean hasNext() {
return it.hasPrevious();
}
public T next() {
return it.previous();
}
public void remove() {
it.remove();
}
}
private final ArrayList<T> l;
public ReverseIterable(ArrayList<T> l) {
this.l = l;
}
public Iterator<T> iterator() {
return new ReverseIterator(l.listIterator(l.size()));
}
}
Use insertAdjacentHTML
if it's available, otherwise use some sort of fallback. insertAdjacentHTML is supported in all current browsers.
div.insertAdjacentHTML( 'beforeend', str );
Live demo: http://jsfiddle.net/euQ5n/
Starting from C# 6.0, when $ - string interpolation has been introduced, there is one more way:
var array = new[] { "A", "B", "C" };
Console.WriteLine($"{string.Join(", ", array}");
//output
A, B, C
Concatenation could be archived using the System.Linq
, convert the string[]
to char[]
and print as a string
var array = new[] { "A", "B", "C" };
Console.WriteLine($"{new String(array.SelectMany(_ => _).ToArray())}");
//output
ABC
Put .gitignore in the working directory. It doesn't work if you put it in the .git (repository) directory.
$ ls -1d .git*
.git
.gitignore
This solved the problem for me (Ubuntu 16.04):
sudo apt-get install build-essential libssl-dev libffi-dev python-dev python3-dev
and then it was working like this:
pip install cryptography
pip install pyopenssl ndg-httpsclient pyasn1
You can easily build a dictionary style collection...
function getQueryStrings() {
var assoc = {};
var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
var queryString = location.search.substring(1);
var keyValues = queryString.split('&');
for(var i in keyValues) {
var key = keyValues[i].split('=');
if (key.length > 1) {
assoc[decode(key[0])] = decode(key[1]);
}
}
return assoc;
}
And use it like this...
var qs = getQueryStrings();
var myParam = qs["myParam"];
You should not be using buttons of the same name. It's bad semantics. Instead, you should modify your backend to look for different name values being set:
<input type="submit" name="COMMAND_PREV" value="‹ Prev">
<input type="submit" name="COMMAND_SAVE" value="Save">
<input type="reset" name="NOTHING" value="Reset">
<input type="submit" name="COMMAND_NEXT" value="Next ›">
<input type="button" name="NOTHING" value="Skip ›" onclick="window.location = 'yada-yada.asp';">
Since I don't know what language you are using on the backend, I'll give you some pseudocode:
if (input name COMMAND_PREV is set) {
} else if (input name COMMAND_SAVE is set) {
} else if (input name COMMENT_NEXT is set) {
}
For Kotlin Users don't forget to add ? in data: Intent?
like
public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {}
Useful reference to get file properties using a batch file, included is the last modified time:
FOR %%? IN ("C:\somefile\path\file.txt") DO (
ECHO File Name Only : %%~n?
ECHO File Extension : %%~x?
ECHO Name in 8.3 notation : %%~sn?
ECHO File Attributes : %%~a?
ECHO Located on Drive : %%~d?
ECHO File Size : %%~z?
ECHO Last-Modified Date : %%~t?
ECHO Drive and Path : %%~dp?
ECHO Drive : %%~d?
ECHO Fully Qualified Path : %%~f?
ECHO FQP in 8.3 notation : %%~sf?
ECHO Location in the PATH : %%~dp$PATH:?
)
If you want emulate enum of C/C++ (base num and nexts incrementals):
enum ids {
OPEN, CLOSE;
//
private static final int BASE_ORDINAL = 100;
public int getCode() {
return ordinal() + BASE_ORDINAL;
}
};
public class TestEnum {
public static void main (String... args){
for (ids i : new ids[] { ids.OPEN, ids.CLOSE }) {
System.out.println(i.toString() + " " +
i.ordinal() + " " +
i.getCode());
}
}
}
OPEN 0 100 CLOSE 1 101
what about this
<FORM METHOD="post" ACTION="mailto:[email protected]" ENCTYPE="multipart/form-data">
Attachment: <INPUT TYPE="file" NAME="attachedfile" MAXLENGTH=50 ALLOW="text/*" >
<input type="submit" name="submit" id="submit" value="Email"/>
</FORM>
I found when doing this that in order to set the gravity to center, and still have your password hint show when using inputType
, the android:gravity="Center"
must be at the end of your XML line.
<EditText android:textColor="#000000" android:id="@+id/editText2"
android:layout_width="fill_parent" android:hint="Password"
android:background="@drawable/rounded_corner"
android:layout_height="fill_parent"
android:nextFocusDown="@+id/imageButton1"
android:nextFocusRight="@+id/imageButton1"
android:nextFocusLeft="@+id/editText1"
android:nextFocusUp="@+id/editText1"
android:inputType="textVisiblePassword"
android:textColorHint="#999999"
android:textSize="16dp"
android:gravity="center">
</EditText>
Yes, MySQL allows multiple NULLs in a column with a unique constraint.
CREATE TABLE table1 (x INT NULL UNIQUE);
INSERT table1 VALUES (1);
INSERT table1 VALUES (1); -- Duplicate entry '1' for key 'x'
INSERT table1 VALUES (NULL);
INSERT table1 VALUES (NULL);
SELECT * FROM table1;
Result:
x
NULL
NULL
1
This is not true for all databases. SQL Server 2005 and older, for example, only allows a single NULL value in a column that has a unique constraint.
There are plenty of good solutions already, but here's a solution that I find more elegant for the way I want to work:
I put a script in my path called "git-put" that contains:
#!/bin/bash
git commit "$@" && git push -u
That allows me to run:
git put -am"my commit message"
..to add all files, commit them, and push them.
(I also added the "-u" because I like to do this anyway, even though it's not related to this issue. It ensures that the upstream branch is always set up for pulling.)
I like this approach because it also allows to to use "git put" without adding all the files (skip the "-a"), or with any other options I might want to pass to commit. Also, "put" is a short portmanteau of "push" and "commit"
right click somewhere on the file or in project explorer and choose 'run as'->'java application'
For simplicity you could create an extension:-
public static SolidColorBrush ToSolidColorBrush(this string hex_code)
{
return (SolidColorBrush)new BrushConverter().ConvertFromString(hex_code);
}
And then to use:-
SolidColorBrush accentBlue = "#3CACDC".ToSolidColorBrush();
To do it from a Base64 encoding you can use the following function:
function base64ToArrayBuffer(data) {
const bString = window.atob(data);
const bLength = bString.length;
const bytes = new Uint8Array(bLength);
for (let i = 0; i < bLength; i++) {
bytes[i] = bString.charCodeAt(i);
}
return bytes;
}
function base64toPDF(base64EncodedData, fileName = 'file') {
const bufferArray = base64ToArrayBuffer(base64EncodedData);
const blobStore = new Blob([bufferArray], { type: 'application/pdf' });
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blobStore);
return;
}
const data = window.URL.createObjectURL(blobStore);
const link = document.createElement('a');
document.body.appendChild(link);
link.href = data;
link.download = `${fileName}.pdf`;
link.click();
window.URL.revokeObjectURL(data);
link.remove();
}
Another option of course is to use Javascript (Jquery here):
$('.box1,.box2').each(function(){
$(this).height($(this).parent().height());
})
You could use this jQuery plugin: https://github.com/mathiasbynens/jquery-placeholder
But your link seems to be also a good solution.
Sometimes, it's easier to do this:
sudo ln -s /Applications/MAMP/bin/php/php5.6.10/bin/php /usr/bin/php;
Mamps version of PHP at the time of posting was php5.6.10
, so make sure you change that to the version you're using.
You'll be up in a jiffy.
Whats about just make a clone of it?
git clone --mirror other/repo.git
Every repository is a backup of its remote.
I agree it is generally preferable to use an Array
for this.
However, this can also be accomplished in JavaScript by simply adding properties to the current scope (the global scope, if top-level code; the function scope, if within a function) by simply using this
– which always refers to the current scope.
for (var i = 0; i < coords.length; ++i) {
this["marker"+i] = "some stuff";
}
You can later retrieve the stored values (if you are within the same scope as when they were set):
var foo = this.marker0;
console.log(foo); // "some stuff"
This slightly odd feature of JavaScript is rarely used (with good reason), but in certain situations it can be useful.
Bear in mind, this is a practice that Google explicitly advises not to do:
Warning: Because these resources can change between platform versions, you should not reference these icons using the Android platform resource IDs (i.e. menu icons under android.R.drawable).
Rather, you are adviced to make a local copy:
If you want to use any icons or other internal drawable resources, you should store a local copy of those icons or drawables in your application resources, then reference the local copy from your application code. In that way, you can maintain control over the appearance of your icons, even if the system's copy changes.
It (<>) is a function that is used to compare values in database table.
!= (Not equal to) functions the same as the <> (Not equal to) comparison operator.
This is just an improvement to the previous answers because it didn't work for me with some zipcodes even when in https://www.google.com/maps it does, I fixed just adding the word "zipcode " before to put the zipcode, like this:
function getLatLngByZipcode(zipcode) _x000D_
{_x000D_
var geocoder = new google.maps.Geocoder();_x000D_
var address = zipcode;_x000D_
geocoder.geocode({ 'address': 'zipcode '+address }, function (results, status) {_x000D_
if (status == google.maps.GeocoderStatus.OK) {_x000D_
var latitude = results[0].geometry.location.lat();_x000D_
var longitude = results[0].geometry.location.lng();_x000D_
alert("Latitude: " + latitude + "\nLongitude: " + longitude);_x000D_
} else {_x000D_
alert("Request failed.")_x000D_
}_x000D_
});_x000D_
return [latitude, longitude];_x000D_
}
_x000D_
You can try one even more simple:
<option value="1" ${item.quantity == 1 ? "selected" : ""}>1</option>
Just finish reading ALL the above, boring and sleepy (sorry but is true). Very technical, in-depth, detailed, and dry. Why am I writing? Because AngularJS is massive, lots of inter-connected concepts can turn anyone going nuts. I often asked myself, am I not smart enough to understand them? No! It's because so few can explain the tech in a for-dummie language w/o all the terminologies! Okay, let me try:
1) They are all event-driven things. (I hear the laugh, but read on)
If you don't know what event-driven is Then think you place a button on the page, hook it up w/ a function using "on-click", waiting for users to click on it to trigger the actions you plant inside the function. Or think of "trigger" of SQL Server / Oracle.
2) $watch is "on-click".
What's special about is it takes 2 functions as parameters, first one gives the value from the event, second one takes the value into consideration...
3) $digest is the boss who checks around tirelessly, bla-bla-bla but a good boss.
4) $apply gives you the way when you want to do it manually, like a fail-proof (in case on-click doesn't kick in, you force it to run.)
Now, let's make it visual. Picture this to make it even more easy to grab the idea:
In a restaurant,
- WAITERS
are supposed to take orders from customers, this is
$watch(
function(){return orders;},
function(){Kitchen make it;}
);
- MANAGER running around to make sure all waiters are awake, responsive to any sign of changes from customers. This is $digest()
- OWNER has the ultimate power to drive everyone upon request, this is $apply()
FIX 1:
Step1: Go to settings > then select the following configuration(Disable Floppy)
Alternatively, you can press F12 while booting the Guest OS and select CD from there, this is a one time setting, good enough for the installation.
Step 2: Place your Existing Guest OS bootable CD in the Disk Drive and start the Guest OS.
FIX 2:
Go to Settings > And Perform the following:
FIX 3:
Try Fix 1 & 2 together..
You start it like this:
int value = 123;
bgw1.RunWorkerAsync(argument: value); // the int will be boxed
and then
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
int value = (int) e.Argument; // the 'argument' parameter resurfaces here
...
// and to transport a result back to the main thread
double result = 0.1 * value;
e.Result = result;
}
// the Completed handler should follow this pattern
// for Error and (optionally) Cancellation handling
private void worker_Completed(object sender, RunWorkerCompletedEventArgs e)
{
// check error, check cancel, then use result
if (e.Error != null)
{
// handle the error
}
else if (e.Cancelled)
{
// handle cancellation
}
else
{
double result = (double) e.Result;
// use it on the UI thread
}
// general cleanup code, runs when there was an error or not.
}
Just paste this code into functions.php file:
add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);
function special_nav_class ($classes, $item) {
if (in_array('current-menu-item', $classes) ){
$classes[] = 'active ';
}
return $classes;
}
More on wordpress.org:
Most likely you're looking for something like
var targetElement = document.getElementById('idOfTargetElement');
targetElement.innerHTML = produceMessage();
provided that this is not something which happens on page load, in which case it should already be there from the start.
You should generally NOT ignore the exception. Take a look at the following paper:
Don't swallow interrupts
Sometimes throwing InterruptedException is not an option, such as when a task defined by Runnable calls an interruptible method. In this case, you can't rethrow InterruptedException, but you also do not want to do nothing. When a blocking method detects interruption and throws InterruptedException, it clears the interrupted status. If you catch InterruptedException but cannot rethrow it, you should preserve evidence that the interruption occurred so that code higher up on the call stack can learn of the interruption and respond to it if it wants to. This task is accomplished by calling interrupt() to "reinterrupt" the current thread, as shown in Listing 3. At the very least, whenever you catch InterruptedException and don't rethrow it, reinterrupt the current thread before returning.
public class TaskRunner implements Runnable { private BlockingQueue<Task> queue; public TaskRunner(BlockingQueue<Task> queue) { this.queue = queue; } public void run() { try { while (true) { Task task = queue.take(10, TimeUnit.SECONDS); task.execute(); } } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); } } }
See the entire paper here:
http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html?ca=drs-
here is a version that handles multiple requests, also checks for cancelled status in callback to suppress errors in error block. (in Typescript)
controller level:
requests = new Map<string, ng.IDeferred<{}>>();
in my http get:
getSomething(): void {
let url = '/api/someaction';
this.cancel(url); // cancel if this url is in progress
var req = this.$q.defer();
this.requests.set(url, req);
let config: ng.IRequestShortcutConfig = {
params: { id: someId}
, timeout: req.promise // <--- promise to trigger cancellation
};
this.$http.post(url, this.getPayload(), config).then(
promiseValue => this.updateEditor(promiseValue.data as IEditor),
reason => {
// if legitimate exception, show error in UI
if (!this.isCancelled(req)) {
this.showError(url, reason)
}
},
).finally(() => { });
}
helper methods
cancel(url: string) {
this.requests.forEach((req,key) => {
if (key == url)
req.resolve('cancelled');
});
this.requests.delete(url);
}
isCancelled(req: ng.IDeferred<{}>) {
var p = req.promise as any; // as any because typings are missing $$state
return p.$$state && p.$$state.value == 'cancelled';
}
now looking at the network tab, i see that it works beatuifully. i called the method 4 times and only the last one went through.
You need to specify a type on person:
void addStudent(struct student person) {
...
}
Also, you can typedef your struct to avoid having to type struct every time you use it:
typedef struct student{
...
} student_t;
void addStudent(student_t person) {
...
}
The following demonstrates an alternative approach for returning a key pair object using the form of (a, b)
. The first example uses the string 'key'
as the property name, and 'val'
as the value.
Example #1:
(function(o,a,b){return o[a]=b,o})({},'key','val');
Example: #2:
var obj = { foo: 'bar' };
(function(o,a,b){return o[a]=b,o})(obj,'key','val');
As shown in the second example, this can modify existing objects, too (if property is already defined in the object, value will be overwritten).
Result #1:
{ key: 'val' }
Result #2:
{ foo: 'bar', key: 'val' }
I suppose you have figured it out by now. The answer is hidden in your first mail itself.
The make
command by default looks for makefile
, Makefile
, and GNUMakefile
as the input file and you are having Makefile.txt
in your folder. Just remove the file extension (.txt
) and it should work.
You may want to know why this is happening. Together with the great explanation by that other guy, find a reference of Why does my shell script choke on whitespace or other special characters? written by Gilles in Unix & Linux:
Why do I need to write
"$foo"
? What happens without the quotes?
$foo
does not mean “take the value of the variablefoo
”. It means something much more complex:
- First, take the value of the variable.
- Field splitting: treat that value as a whitespace-separated list of fields, and build the resulting list. For example, if the variable contains
foo * bar ?
then the result of this step is the 3-element listfoo
,*
,bar
.- Filename generation: treat each field as a glob, i.e. as a wildcard pattern, and replace it by the list of file names that match this pattern. If the pattern doesn't match any files, it is left unmodified. In our example, this results in the list containing
foo
, following by the list of files in the current directory, and finallybar
. If the current directory is empty, the result isfoo
,*
,bar
.Note that the result is a list of strings. There are two contexts in shell syntax: list context and string context. Field splitting and filename generation only happen in list context, but that's most of the time. Double quotes delimit a string context: the whole double-quoted string is a single string, not to be split. (Exception:
"$@"
to expand to the list of positional parameters, e.g."$@"
is equivalent to"$1" "$2" "$3"
if there are three positional parameters. See What is the difference between $* and $@?)The same happens to command substitution with
$(foo)
or with`foo`
. On a side note, don't use`foo`
: its quoting rules are weird and non-portable, and all modern shells support$(foo)
which is absolutely equivalent except for having intuitive quoting rules.The output of arithmetic substitution also undergoes the same expansions, but that isn't normally a concern as it only contains non-expandable characters (assuming
IFS
doesn't contain digits or-
).See When is double-quoting necessary? for more details about the cases when you can leave out the quotes.
Unless you mean for all this rigmarole to happen, just remember to always use double quotes around variable and command substitutions. Do take care: leaving out the quotes can lead not just to errors but to security holes.
You could copy down a formula like the following in a new column...
=IF(ISNUMBER(FIND("-",A1)),1,0)
... then sort on that column, highlight all the rows where the value is 1 and delete them.
The system might be running "rootless". Try to set the firmware nvram variable boot-args to "rootless=0". Try to run set of commands:
sudo nvram boot-args="rootless=0";
sudo reboot
After reboot completes, run:
sudo gem install bundler
I have an utility method to switch to the required window as shown below
public class Utility
{
public static WebDriver getHandleToWindow(String title){
//parentWindowHandle = WebDriverInitialize.getDriver().getWindowHandle(); // save the current window handle.
WebDriver popup = null;
Set<String> windowIterator = WebDriverInitialize.getDriver().getWindowHandles();
System.err.println("No of windows : " + windowIterator.size());
for (String s : windowIterator) {
String windowHandle = s;
popup = WebDriverInitialize.getDriver().switchTo().window(windowHandle);
System.out.println("Window Title : " + popup.getTitle());
System.out.println("Window Url : " + popup.getCurrentUrl());
if (popup.getTitle().equals(title) ){
System.out.println("Selected Window Title : " + popup.getTitle());
return popup;
}
}
System.out.println("Window Title :" + popup.getTitle());
System.out.println();
return popup;
}
}
It will take you to desired window once title of the window is passed as parameter. In your case you can do.
Webdriver childDriver = Utility.getHandleToWindow("titleOfChildWindow");
and then again switch to parent window using the same method
Webdriver parentDriver = Utility.getHandleToWindow("titleOfParentWindow");
This method works effectively when dealing with multiple windows.
Print the least significant bit and shift it out on the right. Doing this until the integer becomes zero prints the binary representation without leading zeros but in reversed order. Using recursion, the order can be corrected quite easily.
#include <stdio.h>
void print_binary(unsigned int number)
{
if (number >> 1) {
print_binary(number >> 1);
}
putc((number & 1) ? '1' : '0', stdout);
}
To me, this is one of the cleanest solutions to the problem. If you like 0b
prefix and a trailing new line character, I suggest wrapping the function.
Once an instance has been started, there is no way to change the keypair associated with the instance at a meta data level, but you can change what ssh key you use to connect to the instance.
There is a startup process on most AMIs that downloads the public ssh key and installs it in a .ssh/authorized_keys file so that you can ssh in as that user using the corresponding private ssh key.
If you want to change what ssh key you use to access an instance, you will want to edit the authorized_keys file on the instance itself and convert to your new ssh public key.
The authorized_keys file is under the .ssh subdirectory under the home directory of the user you are logging in as. Depending on the AMI you are running, it might be in one of:
/home/ec2-user/.ssh/authorized_keys
/home/ubuntu/.ssh/authorized_keys
/root/.ssh/authorized_keys
After editing an authorized_keys file, always use a different terminal to confirm that you are able to ssh in to the instance before you disconnect from the session you are using to edit the file. You don't want to make a mistake and lock yourself out of the instance entirely.
While you're thinking about ssh keypairs on EC2, I recommend uploading your own personal ssh public key to EC2 instead of having Amazon generate the keypair for you.
Here's an article I wrote about this:
Uploading Personal ssh Keys to Amazon EC2
http://alestic.com/2010/10/ec2-ssh-keys
This would only apply to new instances you run.
This is an addition to Josh's answer.
You can also keep the values of other variables while filtering out duplicated rows in data.table
Example:
library(data.table)
#create data table
dt <- data.table(
V1=LETTERS[c(1,1,1,1,2,3,3,5,7,1)],
V2=LETTERS[c(2,3,4,2,1,4,4,6,7,2)],
V3=c(1),
V4=c(2) )
> dt
# V1 V2 V3 V4
# A B 1 2
# A C 1 2
# A D 1 2
# A B 1 2
# B A 1 2
# C D 1 2
# C D 1 2
# E F 1 2
# G G 1 2
# A B 1 2
# set the key to all columns
setkey(dt)
# Get Unique lines in the data table
unique( dt[list(V1, V2), nomatch = 0] )
# V1 V2 V3 V4
# A B 1 2
# A C 1 2
# A D 1 2
# B A 1 2
# C D 1 2
# E F 1 2
# G G 1 2
Alert: If there are different combinations of values in the other variables, then your result will be
unique combination of V1 and V2
Very simple:
import json
data = json.loads('{"one" : "1", "two" : "2", "three" : "3"}')
print data['two']
You can use:
type text1.txt >> combine.txt
echo >> combine.txt
type text2.txt >> combine.txt
or something like this:
echo blah >> combine.txt
echo blah2 >> combine.txt
echo >> combine.txt
echo other >> combine.txt
Here I am giving you a proper example of one callback method . so suppose we have a method like method login() :
public void login() {
loginService = new LoginService();
loginService.login(loginProvider, new LoginListener() {
@Override
public void onLoginSuccess() {
loginService.getresult(true);
}
@Override
public void onLoginFaliure() {
loginService.getresult(false);
}
});
System.out.print("@@##### get called");
}
I also put all the helper class here to make the example more clear: loginService class
public class LoginService implements Login.getresult{
public void login(LoginProvider loginProvider,LoginListener callback){
String username = loginProvider.getUsername();
String pwd = loginProvider.getPassword();
if(username != null && pwd != null){
callback.onLoginSuccess();
}else{
callback.onLoginFaliure();
}
}
@Override
public void getresult(boolean value) {
System.out.print("login success"+value);
}}
and we have listener LoginListener as :
interface LoginListener {
void onLoginSuccess();
void onLoginFaliure();
}
now I just wanted to test the method login() of class Login
@Test
public void loginTest() throws Exception {
LoginService service = mock(LoginService.class);
LoginProvider provider = mock(LoginProvider.class);
whenNew(LoginProvider.class).withNoArguments().thenReturn(provider);
whenNew(LoginService.class).withNoArguments().thenReturn(service);
when(provider.getPassword()).thenReturn("pwd");
when(provider.getUsername()).thenReturn("username");
login.getLoginDetail("username","password");
verify(provider).setPassword("password");
verify(provider).setUsername("username");
verify(service).login(eq(provider),captor.capture());
LoginListener listener = captor.getValue();
listener.onLoginSuccess();
verify(service).getresult(true);
also dont forget to add annotation above the test class as
@RunWith(PowerMockRunner.class)
@PrepareForTest(Login.class)
Your original problem was wrong pattern symbol "h" which stands for the clock hour (range 1-12). In this case, the am-pm-information is missing. Better, use the pattern symbol "H" instead (hour of day in range 0-23). So the pattern should rather have been like:
uuuu-MM-dd'T'HH:mm:ss.SSSX (best pattern also suitable for strict mode)
100% working solution:
Follow these steps:
Open the folder where you downloaded "python-3.8.2-amd64.exe" setup or any other version of python package
Double click on "python-3.8.2-amd64.exe'
Click "Modify"
You will see "Optional features"
Click "next"
Select "Add python to environment variables"
Click "install"
Then u can run jupyter in any desired folder u desire
E.g open "cmd" command prompt
Type :
E:
E:\>jupyter notebook
It will get started without showing
'Jupyter' is not recognized
Thanks
Are you referring to the server side or the client side?
For a client, you would want to adjust the sendTimeout attribute of a binding element. For a service, you would want to adjust the receiveTimeout attribute of a binding elemnent.
<system.serviceModel>
<bindings>
<netTcpBinding>
<binding name="longTimeoutBinding"
receiveTimeout="00:10:00" sendTimeout="00:10:00">
<security mode="None"/>
</binding>
</netTcpBinding>
</bindings>
<services>
<service name="longTimeoutService"
behaviorConfiguration="longTimeoutBehavior">
<endpoint address="net.tcp://localhost/longtimeout/"
binding="netTcpBinding" bindingConfiguration="longTimeoutBinding" />
</service>
....
Of course, you have to map your desired endpoint to that particular binding.
Install Homebrew first :
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Then run this : brew install gdb
You could read jQuery creator John Resig's post about it here: http://ejohn.org/blog/picking-time/.
I know of two ways to do it.
Method 1
The first method (which I prefer) is to use msbuild:
msbuild project.sln /Flags...
Method 2
You can also run:
vcexpress project.sln /build /Flags...
The vcexpress option returns immediately and does not print any output. I suppose that might be what you want for a script.
Note that DevEnv is not distributed with Visual Studio Express 2008 (I spent a lot of time trying to figure that out when I first had a similar issue).
So, the end result might be:
os.system("msbuild project.sln /p:Configuration=Debug")
You'll also want to make sure your environment variables are correct, as msbuild and vcexpress are not by default on the system path. Either start the Visual Studio build environment and run your script from there, or modify the paths in Python (with os.putenv).
Eclipse is the best IDE. It easy to setup android and debug applications in eclipse
Using CSS only:
Right/Left Flippiing: Working Fiddle
.Container
{
height: 200px;
overflow-x: auto;
}
.Content
{
height: 300px;
}
.Flipped
{
direction: rtl;
}
.Content
{
direction: ltr;
}
Top/Bottom Flipping: Working Fiddle
.Container
{
width: 200px;
overflow-y: auto;
}
.Content
{
width: 300px;
}
.Flipped, .Flipped .Content
{
transform:rotateX(180deg);
-ms-transform:rotateX(180deg); /* IE 9 */
-webkit-transform:rotateX(180deg); /* Safari and Chrome */
}
Although you can not set the default date format for a single database, you can change the default language for a login which is used to access this database:
ALTER LOGIN your_login WITH DEFAULT_LANGUAGE=British
In some cases it helps.
The idea behind C++ was that you would not pay any performance impact for features that you don't use. So adding garbage collection would have meant having some programs run straight on the hardware the way C does and some within some sort of runtime virtual machine.
Nothing prevents you from using some form of smart pointers that are bound to some third-party garbage collection mechanism. I seem to recall Microsoft doing something like that with COM and it didn't go to well.
First off, a disclaimer: I don't think marrying POST with URL parameters is a brilliant idea. Like others suggested, you're better off using a hidden form for passing user information.
However, a question made me curious how PHP is handling such a case. It turned out that it's possible in theory. Here's a proof:
post_url_params.html
<!DOCTYPE html>
<html>
<head></head>
<body>
<form method="post" action="post_url_params.php?key1=value1">
<input type="hidden" name="key2" value="value2">
<input type="hidden" name="key3" value="value3">
<input type="submit" value="click me">
</form>
</body>
</html>
post_url_params.php
<?php
print_r($_POST);
print_r($_GET);
echo $_SERVER['REQUEST_METHOD'];
?>
Output
Array ( [key2] => value2 [key3] => value3 )
Array ( [key1] => value1 )
POST
One can clearly see that PHP stores URL parameters in the $_GET variable and form data in the $_POST variable. I suspect it's very PHP- and server-specific, though, and is definitely not a thing to rely on.
$('textarea').val();
textarea.value
would be pure JavaScript, but here you're trying to use JavaScript as a not-valid jQuery method (.value
).
eliminate all the whitespace from a string, on both ends, and in between words.
>>> import re
>>> re.sub("\s+", # one or more repetition of whitespace
'', # replace with empty string (->remove)
''' hello
... apple
... ''')
'helloapple'
Python docs:
Had the same problem:
$params = array('redirect_uri' => 'facebook.com/pages/foobar-dev');
$facebook->getLoginUrl($params);
When I changed the redirect_uri from the devloper page to the live page, 191 Error came up.
So I deleted the $params:
$facebook->getLoginUrl();
After the app-request now FB redirects to the app url itself f.e.: my.domain.com
What I do now is checking in index.php of my app if I'm inside FB iframe or not. If not I redirect to the live FB page f.e.:
$app = 'facebook.com/pages/foobar-live';
$rd = (isset($_SERVER['HTTP_REFERER'])) ? parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST) : false;
if ($rd == 'apps.facebook.com' || (!isset($_REQUEST['signed_request']))) {
echo '<script>window.parent.location = "'.$app.'";</script>';
die();
}
"^.*$"
literally just means select everything
"^" // anchors to the beginning of the line
".*" // zero or more of any character
"$" // anchors to end of line
I tackled this problem a few years ago and uploaded my solution to github as https://github.com/rossturner/HTML5-ImageUploader
robertc's answer uses the solution proposed in the Mozilla Hacks blog post, however I found this gave really poor image quality when resizing to a scale that was not 2:1 (or a multiple thereof). I started experimenting with different image resizing algorithms, although most ended up being quite slow or else were not great in quality either.
Finally I came up with a solution which I believe executes quickly and has pretty good performance too - as the Mozilla solution of copying from 1 canvas to another works quickly and without loss of image quality at a 2:1 ratio, given a target of x pixels wide and y pixels tall, I use this canvas resizing method until the image is between x and 2 x, and y and 2 y. At this point I then turn to algorithmic image resizing for the final "step" of resizing down to the target size. After trying several different algorithms I settled on bilinear interpolation taken from a blog which is not online anymore but accessible via the Internet Archive, which gives good results, here's the applicable code:
ImageUploader.prototype.scaleImage = function(img, completionCallback) {
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, canvas.width, canvas.height);
while (canvas.width >= (2 * this.config.maxWidth)) {
canvas = this.getHalfScaleCanvas(canvas);
}
if (canvas.width > this.config.maxWidth) {
canvas = this.scaleCanvasWithAlgorithm(canvas);
}
var imageData = canvas.toDataURL('image/jpeg', this.config.quality);
this.performUpload(imageData, completionCallback);
};
ImageUploader.prototype.scaleCanvasWithAlgorithm = function(canvas) {
var scaledCanvas = document.createElement('canvas');
var scale = this.config.maxWidth / canvas.width;
scaledCanvas.width = canvas.width * scale;
scaledCanvas.height = canvas.height * scale;
var srcImgData = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
var destImgData = scaledCanvas.getContext('2d').createImageData(scaledCanvas.width, scaledCanvas.height);
this.applyBilinearInterpolation(srcImgData, destImgData, scale);
scaledCanvas.getContext('2d').putImageData(destImgData, 0, 0);
return scaledCanvas;
};
ImageUploader.prototype.getHalfScaleCanvas = function(canvas) {
var halfCanvas = document.createElement('canvas');
halfCanvas.width = canvas.width / 2;
halfCanvas.height = canvas.height / 2;
halfCanvas.getContext('2d').drawImage(canvas, 0, 0, halfCanvas.width, halfCanvas.height);
return halfCanvas;
};
ImageUploader.prototype.applyBilinearInterpolation = function(srcCanvasData, destCanvasData, scale) {
function inner(f00, f10, f01, f11, x, y) {
var un_x = 1.0 - x;
var un_y = 1.0 - y;
return (f00 * un_x * un_y + f10 * x * un_y + f01 * un_x * y + f11 * x * y);
}
var i, j;
var iyv, iy0, iy1, ixv, ix0, ix1;
var idxD, idxS00, idxS10, idxS01, idxS11;
var dx, dy;
var r, g, b, a;
for (i = 0; i < destCanvasData.height; ++i) {
iyv = i / scale;
iy0 = Math.floor(iyv);
// Math.ceil can go over bounds
iy1 = (Math.ceil(iyv) > (srcCanvasData.height - 1) ? (srcCanvasData.height - 1) : Math.ceil(iyv));
for (j = 0; j < destCanvasData.width; ++j) {
ixv = j / scale;
ix0 = Math.floor(ixv);
// Math.ceil can go over bounds
ix1 = (Math.ceil(ixv) > (srcCanvasData.width - 1) ? (srcCanvasData.width - 1) : Math.ceil(ixv));
idxD = (j + destCanvasData.width * i) * 4;
// matrix to vector indices
idxS00 = (ix0 + srcCanvasData.width * iy0) * 4;
idxS10 = (ix1 + srcCanvasData.width * iy0) * 4;
idxS01 = (ix0 + srcCanvasData.width * iy1) * 4;
idxS11 = (ix1 + srcCanvasData.width * iy1) * 4;
// overall coordinates to unit square
dx = ixv - ix0;
dy = iyv - iy0;
// I let the r, g, b, a on purpose for debugging
r = inner(srcCanvasData.data[idxS00], srcCanvasData.data[idxS10], srcCanvasData.data[idxS01], srcCanvasData.data[idxS11], dx, dy);
destCanvasData.data[idxD] = r;
g = inner(srcCanvasData.data[idxS00 + 1], srcCanvasData.data[idxS10 + 1], srcCanvasData.data[idxS01 + 1], srcCanvasData.data[idxS11 + 1], dx, dy);
destCanvasData.data[idxD + 1] = g;
b = inner(srcCanvasData.data[idxS00 + 2], srcCanvasData.data[idxS10 + 2], srcCanvasData.data[idxS01 + 2], srcCanvasData.data[idxS11 + 2], dx, dy);
destCanvasData.data[idxD + 2] = b;
a = inner(srcCanvasData.data[idxS00 + 3], srcCanvasData.data[idxS10 + 3], srcCanvasData.data[idxS01 + 3], srcCanvasData.data[idxS11 + 3], dx, dy);
destCanvasData.data[idxD + 3] = a;
}
}
};
This scales an image down to a width of config.maxWidth
, maintaining the original aspect ratio. At the time of development this worked on iPad/iPhone Safari in addition to major desktop browsers (IE9+, Firefox, Chrome) so I expect it will still be compatible given the broader uptake of HTML5 today. Note that the canvas.toDataURL() call takes a mime type and image quality which will allow you to control the quality and output file format (potentially different to input if you wish).
The only point this doesn't cover is maintaining the orientation information, without knowledge of this metadata the image is resized and saved as-is, losing any metadata within the image for orientation meaning that images taken on a tablet device "upside down" were rendered as such, although they would have been flipped in the device's camera viewfinder. If this is a concern, this blog post has a good guide and code examples on how to accomplish this, which I'm sure could be integrated to the above code.
I thought this looked pretty bad - because I was working on a Joomla template recently and I kept getting the template failing W3C because it was using the <i>
tag and that had deprecated, as it's original use was to italicize something, which is now done through CSS not HTML any more.
It does make really bad practice because when I saw it I went through the template and changed all the <i>
tags to <span style="font-style:italic">
instead and then wondered why the entire template looked strange.
This is the main reason it is a bad idea to use the <i>
tag in this way - you never know who is going to look at your work afterwards and "assume" that what you were really trying to do is italicize the text rather than display an icon. I've just put some icons in a website and I did it with the following code
<img class="icon" src="electricity.jpg" alt="Electricity" title="Electricity">
that way I've got all my icons in one class so any changes I make affects all the icons (say I wanted them larger or smaller, or rounded borders, etc), the alt text gives screen readers the chance to tell the person what the icon is rather than possibly getting just "text in italics, end of italics" (I don't exactly know how screen readers read screens but I guess it's something like that), and the title also gives the user a chance to mouse over the image and get a tooltip telling them what the icon is in case they can't figure it out. Much better than using <i>
- and also it passes W3C standard.
Here is another solution that works good.
(function() {
'use strict';
angular.module('cms').config(route);
route.$inject = ['$routeProvider'];
function route($routeProvider) {
$routeProvider
.when('/:section', {
templateUrl: buildPath
})
.when('/:section/:page', {
templateUrl: buildPath
})
.when('/:section/:page/:task', {
templateUrl: buildPath
});
}
function buildPath(path) {
var layout = 'layout';
angular.forEach(path, function(value) {
value = value.charAt(0).toUpperCase() + value.substring(1);
layout += value;
});
layout += '.tpl';
return 'client/app/layouts/' + layout;
}
})();
You could use the struct
Python built-in library:
Encode:
import struct
i = -6884376
print('{0:b}'.format(i))
packed = struct.pack('>l', i) # Packing a long number.
unpacked = struct.unpack('>L', packed)[0] # Unpacking a packed long number to unsigned long
print(unpacked)
print('{0:b}'.format(unpacked))
Out:
-11010010000110000011000
4288082920
11111111100101101111001111101000
Decode:
dec_pack = struct.pack('>L', unpacked) # Packing an unsigned long number.
dec_unpack = struct.unpack('>l', dec_pack)[0] # Unpacking a packed unsigned long number to long (revert action).
print(dec_unpack)
Out:
-6884376
[NOTE]:
>
is BigEndian operation.l
is long.L
is unsigned long.amd64
architecture int
and long
are 32bit, So you could use i
and I
instead of l
and L
respectively. <html>
<head>
<title>Ajax file upload</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function (e) {
$("#uploadimage").on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: "upload.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
alert(data);
}
});
}));
</script>
</head>
<body>
<div class="main">
<h1>Ajax Image Upload</h1><br/>
<hr>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<div id="image_preview"><img id="previewing" src="noimage.png" /></div>
<hr id="line">
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="file" id="file" required />
<input type="submit" value="Upload" class="submit" />
</div>
</form>
</div>
</body>
</html>
You can use the instanceof
operator for this. From MDN:
The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.
If you don't know what prototypes and prototype chains are I highly recommend looking it up. Also here is a JS (TS works similar in this respect) example which might clarify the concept:
class Animal {_x000D_
name;_x000D_
_x000D_
constructor(name) {_x000D_
this.name = name;_x000D_
}_x000D_
}_x000D_
_x000D_
const animal = new Animal('fluffy');_x000D_
_x000D_
// true because Animal in on the prototype chain of animal_x000D_
console.log(animal instanceof Animal); // true_x000D_
// Proof that Animal is on the prototype chain_x000D_
console.log(Object.getPrototypeOf(animal) === Animal.prototype); // true_x000D_
_x000D_
// true because Object in on the prototype chain of animal_x000D_
console.log(animal instanceof Object); _x000D_
// Proof that Object is on the prototype chain_x000D_
console.log(Object.getPrototypeOf(Animal.prototype) === Object.prototype); // true_x000D_
_x000D_
console.log(animal instanceof Function); // false, Function not on prototype chain_x000D_
_x000D_
_x000D_
The prototype chain in this example is:
animal > Animal.prototype > Object.prototype
Use DATESTR
>> datestr(40189)
ans =
12-Jan-0110
Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM
>> datenum(2010,1,11)
ans =
734149
>> datenum(2010,1,11)-40189
ans =
693960
>> datestr(40189+693960)
ans =
11-Jan-2010
In other words, to convert any serial Excel date, call
datestr(excelSerialDate + 693960)
EDIT
To get the date in mm/dd/yyyy format, call datestr
with the specified format
excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010
Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things
excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010
Don't use jsonObject.toString
on a JSON object.
Rely on a library: https://www.npmjs.com/package/valid-url
import { isWebUri } from 'valid-url';
// ...
if (!isWebUri(url)) {
return "Not a valid url.";
}
There are multiple ways you can remove/filter the null values from a column in DataFrame.
Lets create a simple DataFrame with below code:
date = ['2016-03-27','2016-03-28','2016-03-29', None, '2016-03-30','2016-03-31']
df = spark.createDataFrame(date, StringType())
Now you can try one of the below approach to filter out the null values.
# Approach - 1
df.filter("value is not null").show()
# Approach - 2
df.filter(col("value").isNotNull()).show()
# Approach - 3
df.filter(df["value"].isNotNull()).show()
# Approach - 4
df.filter(df.value.isNotNull()).show()
# Approach - 5
df.na.drop(subset=["value"]).show()
# Approach - 6
df.dropna(subset=["value"]).show()
# Note: You can also use where function instead of a filter.
You can also check the section "Working with NULL Values" on my blog for more information.
I hope it helps.
I'd highly recommend the Castle DictionaryAdapter, easily one of that project's best-kept secrets. You only need to define an interface with the properties you want, and in one line of code the adapter will generate an implementation, instantiate it, and synchronize its values with a dictionary you pass in. I use it to strongly-type my AppSettings in a web project:
var appSettings =
new DictionaryAdapterFactory().GetAdapter<IAppSettings>(ConfigurationManager.AppSettings);
Note that I did not need to create a class that implements IAppSettings - the adapter does that on the fly. Also, although in this case I'm only reading, in theory if I were setting property values on appSettings, the adapter would keep the underlying dictionary in sync with those changes.
MathGL have many plot types, C/Fortran interface and basic data analysis
It means the jar files are missing from the path that you have given while configuring Build Path/adding jars to the project.
Just once again configure the jars.
Whitespace is preserved by the browser. Text will wrap when necessary, and on line breaks
.pre-wrap {
white-space: pre-wrap;
word-break: break-word;
}
DEMO
td {_x000D_
word-break: break-word;_x000D_
white-space: pre-wrap;_x000D_
-moz-white-space: pre-wrap; _x000D_
}_x000D_
_x000D_
table {_x000D_
width: 100px;_x000D_
border: 1px solid black;_x000D_
display: block;_x000D_
}
_x000D_
<table>_x000D_
<tr><th>list</th>_x000D_
<td>_x000D_
1.longtextlongtextlongtextlongtextlongtextlongtextlongtextlongtextlongtextlongtextlongtextlongtext_x000D_
2.breaklinebreaklinebreaklinebreaklinebreaklinebreaklinebreaklinebreaklinebreaklinebreaklinebreakline_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Make sure that your Rails app is in the root of the repo, the Gemfile is present and properly named. It is basically not able to detect your code base as one of the supported project types and hence failing it. Also, even if you do have a proper project, make sure it is part of the repository and you have committed it fine (git status
will help you here and a ls
should help you verify the project structure).
Now the following wont help you with files that are already cached, but moving forward, you can use the following to easily force a request to get something new, without changing the actual filename.
# Rewrite all requests for JS and CSS files to files of the same name, without
# any numbers in them. This lets the JS and CSS be force out of cache easily
# by putting a number at the end of the filename
# e.g. a request for static/js/site-52.js will get the file static/js/site.js instead.
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^static/(js|css)/([a-z]+)-([0-9]+)\.(js|css)$ /site/$1/$2.$4 [R=302,NC,L]
</IfModule>
Of course, the higher up in your folder structure you do this type of approach, the more you kick things out of cache with a simple change.
So for example, if you store the entire css and javascript of your site in one main folder
/assets/js
/assets/css
/assets/...
Then you can could start referencing it as "assets-XXX" in your html, and use a rule like so to kick all assets content out of cache.
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^assets-([a-z0-9]+)/(.*) /$2 [R=302,NC,L]
</IfModule>
Note that if you do go with this, after you have it working, change the 302 to a 301, and then caching will kick in. When it's a 302 it wont cache at the browser level because it's a temporary redirect. If you do it this way, then you could bump up the expiry default time to 30 days for all assets, since you can easily kick things out of cache by simply changing the folder name in the login page.
<IfModule mod_expires.c>
ExpiresActive on
ExpiresDefault A2592000
</IfModule>
Someone should mark Johannes Weiß's comment as the answer to this question. That is exactly why xml documents can't just be loaded in a DOM Document class.
These are the two ways to do it:
SELECT `from` FROM TableName
SELECT TableName.from FROM TableName
In my case it had to work on modern mobile browsers, with a PNG image in different shapes and transparency. I created drop shadow using a duplicate of the image. That means I have two img
elements of the same image, one on top of the other (using position: absolute
), and the one behind has the following rules applied to it:
.image-shadow {
filter: blur(10px) brightness(-100);
-webkit-filter: blur(10px) brightness(-100);
opacity: .5;
}
This includes brightness filter in order to darken the bottom image, and a blur filter in order to cast the smudgy effect drop shadow usually has. Opacity at 50% is then applied in order to soften it.
This can be applied cross browser using moz
and ms
flags.
Example: https://jsfiddle.net/5mLssm7o/
The solution you are looking for is in Angular's official tutorial. In this tutorial Phones are loaded from a JSON file using Angulars $http service . In the code below we use $http.get to load a phones.json file saved in the phones directory:
var phonecatApp = angular.module('phonecatApp', []);
phonecatApp.controller('PhoneListCtrl', function ($scope, $http) {
$http.get('phones/phones.json').success(function(data) {
$scope.phones = data;
});
$scope.orderProp = 'age';
});
We then iterate over the phones:
<table>
<tbody ng-repeat="i in phones">
<tr><td>{{i.name}}</td><td>{{$index}}</td></tr>
<tr ng-repeat="e in i.details">
<td>{{$index}}</td>
<td>{{e.foo}}</td>
<td>{{e.bar}}</td></tr>
</tbody>
</table>
For parseInt to work, your string should have only numerical data. Something like this:
str1 = "123.00";
str2 = "50.00";
total = parseInt(str1)+parseInt(str2);
alert(total);
Can you split the string before you start processing them for a total?
You should use the print()
function which is available since Python 2.6+
from __future__ import print_function # Only needed for Python 2
print("hi there", file=f)
For Python 3 you don't need the import
, since the print()
function is the default.
The alternative would be to use:
f = open('myfile', 'w')
f.write('hi there\n') # python will convert \n to os.linesep
f.close() # you can omit in most cases as the destructor will call it
Quoting from Python documentation regarding newlines:
On output, if newline is None, any
'\n'
characters written are translated to the system default line separator,os.linesep
. If newline is''
, no translation takes place. If newline is any of the other legal values, any'\n'
characters written are translated to the given string.
Try something like:
Add to html:
<link id="shortcutIcon" rel="shortcut icon" type="image/x-icon">
<link id="icon" rel="icon" type="image/x-icon">
Add minified script after tag:
<script type="text/javascript">
(function(b,c,d,a){a=c+d+b,document.getElementById('shortcutIcon').href=a,document.getElementById('icon').href=a;}(Math.random()*100,(document.querySelector('base')||{}).href,'/assets/images/favicon.ico?v='));
</script>
where
Before test clear history: (ctr + shfit + del)
we had similar header issue with Amazon (AWS) S3 presigned Post failing on some browsers.
point was to tell bucket CORS to expose header <ExposeHeader>Access-Control-Allow-Origin</ExposeHeader>
more details in this answer: https://stackoverflow.com/a/37465080/473040
Delete the .git
directory in the root-directory of your repository if you only want to delete the git-related information (branches, versions).
If you want to delete everything (git-data, code, etc), just delete the whole directory.
.git directories are hidden by default, so you'll need to be able to view hidden files to delete it.
If there is a null
in an array and you want to avoid it:
db.test.find({"contain" : {$ne :[] }}).pretty()
In my notepad++ I press
Ctrl+A = To select all words
Ctrl+U = To convert lowercase
Ctrl+Shift+U = To convert uppercase
Hope to help you!
Let me start out by saying that I don't recommend using the method I'm about to suggest. It's much better to use event driven development and bind events only to the elements you're interested in knowing whether or not the mouse is over with mouseover
, mouseout
, mouseenter
, mouseleave
, etc.
If you absolutely must have the ability to know which element the mouse is over, you'd need to write a function that binds the mouseover
event to everything in the DOM, and then store whatever the current element is in some variable.
You could so something like this:
window.which_element_is_the_mouse_on = (function() {
var currentElement;
$("body *").on('mouseover', function(e) {
if(e.target === e.currentTarget) {
currentElement = this;
}
});
return function() {
console.log(currentElement);
}
}());
Basically, I've created an immediate function which sets the event on all elements and stores the current element within the closure to minimize your footprint.
Here's a working demo that calls window.which_element_is_the_mouse_on
every second and logs what element the mouse is currently over to the console.
I had a similar problem to the OP. Then I saw the answer from @Urs Marian which helped a lot. But additionally what I was looking for is, when there are multiple values in a column and they will be grouped, how I can get the last submitted value (e.g. ordered by a date/id column).
Example:
We have following table structure:
CREATE TABLE tablename(
[msgid] [int] NOT NULL,
[userid] [int] NOT NULL,
[username] [varchar](70) NOT NULL,
[message] [varchar](5000) NOT NULL
)
Now there are at least two datasets in the table:
+-------+--------+----------+---------+
| msgid | userid | username | message |
+-------+--------+----------+---------+
| 1 | 1 | userA | hello |
| 2 | 1 | userB | world |
+-------+--------+----------+---------+
Therefore following SQL script does work (checked on MSSQL) to group it, also if the same userid has different username values. In the example below, the username with the highest msgid will be shown:
SELECT m.userid,
(select top 1 username from table where userid = m.userid order by msgid desc) as username,
count(*) as messages
FROM tablename m
GROUP BY m.userid
ORDER BY count(*) DESC
Use this:
DateTime dateTime = DateTime.Now;
DateTime? newDateTime = null;
TimeSpan numberOfDays = new TimeSpan(2, 0, 0, 0, 0);
newDateTime = dateTime.Add(numberOfDays);
Since Spring 3.0.2 you can return ResponseEntity<T> as a result of the controller's method:
@RequestMapping.....
public ResponseEntity<Object> handleCall() {
if (isFound()) {
// do what you want
return new ResponseEntity<>(HttpStatus.OK);
}
else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
(ResponseEntity<T> is a more flexible than @ResponseBody annotation - see another question)
we are in 2017 now you can also use ES2016
var a = 'abc123.8<blah>';
console.log([...a].filter( e => isFinite(e)).join(''));
or
console.log([...'abc123.8<blah>'].filter( e => isFinite(e)).join(''));
The result is
1238
Use display instead of visibility. display: none for invisible and no setting for visible.
The URI is encoded as UTF-8, but Tomcat is decoding them as ISO-8859-1. You need to edit the connector settings in the server.xml and add the URIEncoding="UTF-8" attribute.
or edit this parameter on your application.properties
server.tomcat.uri-encoding=utf-8
import java.util.Scanner;
class Example{
//Checks to see if a string is consider an integer.
public static boolean isInteger(String s){
if(s.isEmpty())return false;
for (int i = 0; i <s.length();++i){
char c = s.charAt(i);
if(!Character.isDigit(c) && c !='-')
return false;
}
return true;
}
//Get integer. Prints out a prompt and checks if the input is an integer, if not it will keep asking.
public static int getInteger(String prompt){
Scanner input = new Scanner(System.in);
String in = "";
System.out.println(prompt);
in = input.nextLine();
while(!isInteger(in)){
System.out.println(prompt);
in = input.nextLine();
}
input.close();
return Integer.parseInt(in);
}
public static void main(String[] args){
int [] a = new int[6];
for (int i = 0; i < a.length;++i){
int tmp = getInteger("Enter integer for array_"+i+": ");//Force to read an int using the methods above.
a[i] = tmp;
}
}
}
The suggestion to use listdir
is a good one. The direct answer to your question in Python 2 is root, dirs, files = os.walk(dir_name).next()
.
The equivalent Python 3 syntax is root, dirs, files = next(os.walk(dir_name))
if someones is interested you can delete the form node from the DOM after the submission and it won't be there using the inspector.
https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/remove
I've got this down to just one line.
rows = [['a1', 'a2', 'a3'],['b1', 'b2', 'b3', 'b4'], ['c1', 'c2', 'c3'], ... ]
csv_str = rows.inject([]) { |csv, row| csv << CSV.generate_line(row) }.join("")
#=> "a1,a2,a3\nb1,b2,b3\nc1,c2,c3\n"
Do all of the above and save to a csv, in one line.
File.open("ss.csv", "w") {|f| f.write(rows.inject([]) { |csv, row| csv << CSV.generate_line(row) }.join(""))}
NOTE:
To convert an active record database to csv would be something like this I think
CSV.open(fn, 'w') do |csv|
csv << Model.column_names
Model.where(query).each do |m|
csv << m.attributes.values
end
end
Hmm @tamouse, that gist is somewhat confusing to me without reading the csv source, but generically, assuming each hash in your array has the same number of k/v pairs & that the keys are always the same, in the same order (i.e. if your data is structured), this should do the deed:
rowid = 0
CSV.open(fn, 'w') do |csv|
hsh_ary.each do |hsh|
rowid += 1
if rowid == 1
csv << hsh.keys# adding header row (column labels)
else
csv << hsh.values
end# of if/else inside hsh
end# of hsh's (rows)
end# of csv open
If your data isn't structured this obviously won't work
The following methods work on GitHub, on GitLab... and on Stackoverflow, which now uses CommonMark!
> One-Line Box made with Blockquote
One-Line Box made with Blockquote
`One-Line Box made with Backticks`
One-Line Box made with Backticks
```
Box made with Triple Backticks
```
Box made with Triple Backticks
~ ~ ~
Box made with Triple Tildes (remove the spaces between the tildes to make this work)
~ ~ ~
Box made with Triple Tildes
Box made with Four Spaces at the start of each line:
“Sometimes we must let go of our pride and do what is requested of us.”
Padmé Amidala
... or use horizontal lines?
Three dashes (---) make a horizontal line:
Note: “ Your focus determines your reality.” – Qui-Gon Jinn.
For more configurations, I strongly advise the excellent GitLab Markdown Guide.
You can also check the less detailed GitHub basic formatting syntax.
You can compare Markdown implementations using Babelmark.
Useful hints :
to force a newline, put two spaces at the end of the line;
to escape special characters, use \.
[Android] if someone looking to implement timer on android using java.
you need use UI thread like this to perform operations.
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
ActivityName.this.runOnUiThread(new Runnable(){
@Override
public void run() {
// do something
}
});
}
}, 2000));
Here's what I've been doing to cope with the situation.
I use global imports on a new test class.
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.mockito.Matchers.*;
When you are finished writing your test and need to commit, you just CTRL+SHIFT+O to organize the packages. For example, you may just be left with:
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.anyString;
This allows you to code away without getting 'stuck' trying to find the correct package to import.
Convert your x-axis data from text to datetime.datetime
, use datetime.strptime
:
>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
datetime.datetime(2012, 5, 31, 19, 0)
This is an example of how to plot data once you have an array of datetimes:
import matplotlib.pyplot as plt
import datetime
import numpy as np
x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)
plt.plot(x,y)
plt.show()
a <div> is a logical division in your content, semantically this would be my first choice if I wanted to group the heading with the list:
<div class="mydiv">
<h3>The heading</h3>
<ul>
<li>item</li>
<li>item</li>
<li>item</li>
</ul>
</div>
then you can use the following css to style everything together as one unit
.mydiv{}
.mydiv h3{}
.mydiv ul{}
.mydiv ul li{}
etc...
I have always used OLEDB
for this, something like...
Dim sSheetName As String
Dim sConnection As String
Dim dtTablesList As DataTable
Dim oleExcelCommand As OleDbCommand
Dim oleExcelReader As OleDbDataReader
Dim oleExcelConnection As OleDbConnection
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Test.xls;Extended Properties=""Excel 12.0;HDR=No;IMEX=1"""
oleExcelConnection = New OleDbConnection(sConnection)
oleExcelConnection.Open()
dtTablesList = oleExcelConnection.GetSchema("Tables")
If dtTablesList.Rows.Count > 0 Then
sSheetName = dtTablesList.Rows(0)("TABLE_NAME").ToString
End If
dtTablesList.Clear()
dtTablesList.Dispose()
If sSheetName <> "" Then
oleExcelCommand = oleExcelConnection.CreateCommand()
oleExcelCommand.CommandText = "Select * From [" & sSheetName & "]"
oleExcelCommand.CommandType = CommandType.Text
oleExcelReader = oleExcelCommand.ExecuteReader
nOutputRow = 0
While oleExcelReader.Read
End While
oleExcelReader.Close()
End If
oleExcelConnection.Close()
The ACE.OLEDB
provider will read both .xls
and .xlsx
files and I have always found the speed quite good.
Could you explain what exactly you try to accomplish? In general you NEVER have to get the onclick attribute from HTML elements. Also you should not specify the onclick on the element itself. Instead set the onclick dynamically using JQuery.
But as far as I understand you, you try to switch between two different onclick functions. What may be better is to implement your onclick function in such a way that it can handle both situations.
$("#google").click(function() {
if (situation) {
// ...
} else {
// ...
}
});
Here is a quick start to get the gears turning...
ParkingLot is a class.
ParkingSpace is a class.
ParkingSpace has an Entrance.
Entrance has a location or more specifically, distance from Entrance.
ParkingLotSign is a class.
ParkingLot has a ParkingLotSign.
ParkingLot has a finite number of ParkingSpaces.
HandicappedParkingSpace is a subclass of ParkingSpace.
RegularParkingSpace is a subclass of ParkingSpace.
CompactParkingSpace is a subclass of ParkingSpace.
ParkingLot keeps array of ParkingSpaces, and a separate array of vacant ParkingSpaces in order of distance from its Entrance.
ParkingLotSign can be told to display "full", or "empty", or "blank/normal/partially occupied" by calling .Full(), .Empty() or .Normal()
Parker is a class.
Parker can Park().
Parker can Unpark().
Valet is a subclass of Parker that can call ParkingLot.FindVacantSpaceNearestEntrance(), which returns a ParkingSpace.
Parker has a ParkingSpace.
Parker can call ParkingSpace.Take() and ParkingSpace.Vacate().
Parker calls Entrance.Entering() and Entrance.Exiting() and ParkingSpace notifies ParkingLot when it is taken or vacated so that ParkingLot can determine if it is full or not. If it is newly full or newly empty or newly not full or empty, it should change the ParkingLotSign.Full() or ParkingLotSign.Empty() or ParkingLotSign.Normal().
HandicappedParker could be a subclass of Parker and CompactParker a subclass of Parker and RegularParker a subclass of Parker. (might be overkill, actually.)
In this solution, it is possible that Parker should be renamed to be Car.
std::fill(v.begin(), v.end(), 0);
I solved this issue with commands bellow:
$ sudo apt-get install php7.3-intl
$ sudo /etc/init.d/php7.3-fpm restart
These commands works for me in homestead with php7.3
The .row
is meant to be used inside a container
. Since the container
has padding to adjust the negative margin in the .row
, grid columns used inside the .row
can then adjust to the full width of the container. See the Bootstrap docs: http://getbootstrap.com/css/#grid
Here's an example to illustrate: http://bootply.com/131054
So, a better solution may for you to place your .row
inside a .container
or .container-fluid
Hope it will help u:
//create a file to write bitmap data
File f = new File(context.getCacheDir(), filename);
f.createNewFile();
//Convert bitmap to byte array
Bitmap bitmap = your bitmap;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
In my case, on a Windows box, my TCP/IP stack seems to have needed to be reset. Resetting the TCP/IP stack of the client PC caused git to start behaving properly again. Run this command in Administrator mode at a command prompt and retry the git command:
netsh int ip reset
Manually disabling and re-enabling the network adapter via the Control Panel produces a similar result.
I suspect DNS resolution problems inside the TCP stack on my Windows box.
Just for the sake of diversity, you can also do this if your array is not an array of numbers, but rather an array of objects that have properties that are numbers (e.g. amount):
array.inject(0){|sum,x| sum + x.amount}
I followed this post and it worked great for me.
EDIT:
Following tips have been mentioned in the above post.
In gradle.properties
, put this:
org.gradle.daemon=true
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
org.gradle.parallel=true
org.gradle.configureondemand=true
And in build.gradle, put this (Note this will disable lint check):
tasks.whenTaskAdded { task ->
if (task.name.equals("lint")) {
task.enabled = false
}
}
I fixed the issue for me by opening the Android SDK Manager and installing the build tools for all 23.x.x versions.
See the screenshot.
Go to File->Invalidate Caches/ Restart. After restarting the preview window will come.
Still the preview window is not opened, Go to View -> Tool window -> click Preview
You should either make your Add
function static
like so:
static public int Add(int x, int y)
{
int result = x + y;
return result;
} //END Add
static
means that the function is not class instance dependent. So you can call it without needing to create a class instance of Program
class.
or you should create in instance of your Program
class, and then call Add
on this instance. Like so:
Program prog = new Program();
prog.Add(5,10);
I use []
.
The following is one of the simplest ways to do it, use the following code:
Dependencies
dependencies {
...
compile 'de.hdodenhof:circleimageview:2.1.0' // use this or use the latest compile version. In case u get bug.
}
XML Code
<de.hdodenhof.circleimageview.CircleImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/profile_image"
android:layout_width="96dp" // here u can adjust the width
android:layout_height="96dp" // here u can adjust the height
android:src="@drawable/profile" // here u can change the image
app:civ_border_width="2dp" // here u can adjust the border of the circle.
app:civ_border_color="#FF000000"/> // here u can adjust the border color
Screenshot:
PEP 3155 introduced __qualname__
, which was implemented in Python 3.3.
For top-level functions and classes, the
__qualname__
attribute is equal to the__name__
attribute. For nested classes, methods, and nested functions, the__qualname__
attribute contains a dotted path leading to the object from the module top-level.
It is accessible from within the very definition of a class or a function, so for instance:
class Foo:
print(__qualname__)
will effectively print Foo
.
You'll get the fully qualified name (excluding the module's name), so you might want to split it on the .
character.
However, there is no way to get an actual handle on the class being defined.
>>> class Foo:
... print('Foo' in globals())
...
False
<table style="width: auto;" ...
works fine. Tested in Chrome 38 , IE 11 and Firefox 34.
jsfiddle : http://jsfiddle.net/rpaul/taqodr8o/
I tried following options to fix this issue and it worked.
For example to install express I used following command.
npm install express --registry http://registry.npmjs.org/
or
npm install express -g --registry http://registry.npmjs.org/
If you want to install locally in any specific folder then use below command. Below command will install express on path C:\Sample\Example1
.
C:\Sample1\Example1> npm install /Sample/Example1 express --registry http://registry.npmjs.org/
Note: If you are installing locally in a specific location then first go to that directory using command and then run above command. If you are not inside that directory and giving only path in command that will not work.
If you get package.json
missing error then run below command before installing package locally
C:\Sample\Example1> npm init
above command will create package.json
file. No need to provide any data. just hit enter.
Note: If you are behind a firewall then you may need to set a proxy.
Do you want to get the number of rows?
SELECT columnName, COUNT(*) AS row_count
FROM eventsTable
WHERE columnName = 'Business'
GROUP BY columnName
You can download manually by parsing the XMLs that you see in Android SDK Manager log.
Currently the XMLs are addon_list and repository. These xmls can change over a course of time.
It has the location of the SDKs, you can browse to the link and download directly via browser. These files has to be placed under proper folder, example the files of google APIs has to be placed under add-ons
, if you don't know where the files has to go.
Here is something to help you.
The blogpost from my blog to Install Android SDKs offline --> Offline Installation of Android SDK's
Try add jQuery
to your project, like
npm i jquery --save
or if you use bower
bower i jquery --save
then
import $ from 'jquery';
int a = 0;
try {
int x = 4;
int y ;
try {
y = x / a;
} catch (Exception e) {
Console.WriteLine("inner ex");
//throw; // Line 1
//throw e; // Line 2
//throw new Exception("devide by 0"); // Line 3
}
} catch (Exception ex) {
Console.WriteLine(ex);
throw ex;
}
if all Line 1 ,2 and 3 are commented - Output - inner ex
if all Line 2 and 3 are commented - Output - inner ex System.DevideByZeroException: {"Attempted to divide by zero."}---------
if all Line 1 and 2 are commented - Output - inner ex System.Exception: devide by 0 ----
if all Line 1 and 3 are commented - Output - inner ex System.DevideByZeroException: {"Attempted to divide by zero."}---------
and StackTrace will be reset in case of throw ex;
Read this thread R - boolean operators && and ||.
Basically, the &
is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. &&
is not, returning a single logical.
I had the same issue while importing the CSV file in AWS MySQL 8.0 RDS.
mysql> LOAD DATA LOCAL INFILE '/tmp/your.csv' INTO TABLE test.demo2 FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES;
ERROR 1148 (42000): The used command is not allowed with this MySQL version
1) Check for local_infile
parameter
mysql> SHOW VARIABLES LIKE 'local_infile';
2) Log out from client and re-login using below parameter.
mysql -u root -p -h rdsendpoint --local-infile=1
3) Run the same command
mysql> LOAD DATA LOCAL INFILE '/tmp/your.csv' INTO TABLE test.demo2 FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES;
Query OK, 300 rows affected (0.01 sec)
Records: 300 Deleted: 0 Skipped: 0 Warnings: 0
FWIW, I experienced a similar issue w/mootools. Re-attaching my events was the correct move, but needed to be done at the end of the request..eg
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function() {...
Just something to keep in mind if beginRequest causes you to get null reference JS exceptions.
Cheers
Just simple use
=Format(today(), "dd/MM/yyyy")
will solve your problem.
You should use labels attribute inside plot function and the value of this attribute should be the vector containing the values that you want for each point to have.
var today = new Date();
var day = today.getDay();
var daylist = ["Sunday", "Monday", "Tuesday", "Wednesday ", "Thursday", "Friday", "Saturday"];
console.log("Today is : " + daylist[day] + ".");
var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();
var prepand = (hour >= 12) ? " PM " : " AM ";
hour = (hour >= 12) ? hour - 12 : hour;
if (hour === 0 && prepand === ' PM ') {
if (minute === 0 && second === 0) {
hour = 12;
prepand = ' Noon';
} else {
hour = 12;
prepand = ' PM';
}
}
if (hour === 0 && prepand === ' AM ') {
if (minute === 0 && second === 0) {
hour = 12;
prepand = ' Midnight';
} else {
hour = 12;
prepand = ' AM';
}
}
console.log("Current Time : " + hour + prepand + " : " + minute + " : " + second);
_x000D_
It's generally considered a bad idea to ignore exceptions. Usually, if it's appropriate, you want to either notify the user of the issue (if they would care) or at the very least, log the exception, or print the stack trace to the console.
However, if that's truly not necessary (you're the one making the decision) then no, there's no other way to ignore an exception that forces you to catch it. The only revision, in that case, that I would suggest is explicitly listing the the class of the Exceptions you're ignoring, and some comment as to why you're ignoring them, rather than simply ignoring any exception, as you've done in your example.
One more alternative options
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 1,
center: new google.maps.LatLng(35.137879, -82.836914),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(47.651968, 9.478485),
draggable: true
});
google.maps.event.addListener(myMarker, 'dragend', function (evt) {
document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
});
google.maps.event.addListener(myMarker, 'dragstart', function (evt) {
document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';
});
map.setCenter(myMarker.position);
myMarker.setMap(map);
and html file
<body>
<section>
<div id='map_canvas'></div>
<div id="current">Nothing yet...</div>
</section>
</body>
It is possible to extend the relation with query functions:
<?php
public function comments()
{
return $this->hasMany('Comment')->orderBy('column');
}
[edit after comment]
<?php
class User
{
public function comments()
{
return $this->hasMany('Comment');
}
}
class Controller
{
public function index()
{
$column = Input::get('orderBy', 'defaultColumn');
$comments = User::find(1)->comments()->orderBy($column)->get();
// use $comments in the template
}
}
default User model + simple Controller example; when getting the list of comments, just apply the orderBy() based on Input::get(). (be sure to do some input-checking ;) )
Zamples is another site where you write a java code and run it online. Here you have possibility to choose jdk version also. http://www.zamples.com/JspExplorer/index.jsp?format=jdk16cl
Which server are you using?
Like already said:
debug
For Glassfish:
Log in to admin-console > Configurations > server-config > JVM-Settings > check DEBUG checkbox > restart server
For Tomcat:
create file debug.bat/.sh
(depending on your OS) in %TOMCAT_HOME%/bin
directory and write
set JPDA_ADDRESS=8000
set JPDA_TRANSPORT=dt_socket
catalina.bat jpda start
in it.
After you've created this file start server by executing debug.bat/.sh.
Now you should be able to debug remotely in Eclipse after you set the necessary properties in your debug configuration.
Hope this helped! Have Fun!
EDIT
If you're running tomcat in a Win environment as a service you don't have a catalina.bat file in the bin-directory of your tomcat installation.
To set your server into debug-mode please try the following:
%catalina_home%/bin/tomcat6w.exe
options:-Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n
To append to an array, just use the +=
operator.
$Target += $TargetObject
Also, you need to declare $Target = @()
before your loop because otherwise, it will empty the array every loop.
Apparently YouTube constantly polls for Google Cast scripts even if the extension isn't installed.
From one commenter:
... it appears that Chrome attempts to get cast_sender.js on pages that have YouTube content. I'm guessing when Chrome sees media that it can stream it attempts to access the Chromecast extension. When the extension isn't present, the error is thrown.
The only solution I've come across is to install the Google Cast extension, whether you need it or not. You may then hide the toolbar button.
For more information and updates, see this SO question. Here's the official issue.
Off the top of my head I think it should be done like this:
var veggies = "carrot";
var fruitvegbasket = [];
fruitvegbasket.push(veggies);
Try this.
<asp:Button id="myButton" runat="server" style="display:none" Text="Click Me" />
<script type="text/javascript">
function ShowButton() {
var buttonID = '<%= myButton.ClientID %>';
var button = document.getElementById(buttonID);
if(button) { button.style.display = 'inherit'; }
}
</script>
Don't use server-side code to do this because that would require a postback. Instead of using Visibility="false", you can just set a CSS property that hides the button. Then, in javascript, switch that property back whenever you want to show the button again.
The ClientID is used because it can be different from the server ID if the button is inside a Naming Container control. These include Panels of various sorts.
I use the get_queried_object function to get the current category on a category.php template page.
$current_category = get_queried_object();
Jordan Eldredge is right, get_the_category is not suitable here.
I know this is an old question but according what @mikejones1477 said, modern front end libraries and frameworks escape the text giving you protection against XSS. The reason why cookies are not a secure method using credentials is that cookies doesn't prevent CSRF when localStorage does (also remember that cookies are accessible by javascript too, so XSS isn't the big problem here), this answer resume why.
The reason storing an authentication token in local storage and manually adding it to each request protects against CSRF is that key word: manual. Since the browser is not automatically sending that auth token, if I visit evil.com and it manages to send a POST http://example.com/delete-my-account, it will not be able to send my authn token, so the request is ignored.
Of course httpOnly is the holy grail but you can't access from reactjs or any js framework beside you still have CSRF vulnerability. My recommendation would be localstorage or if you want to use cookies make sure implemeting some solution to your CSRF problem like django does.
Regarding with the CDN's make sure you're not using some weird CDN, for example CDN like google or bootstrap provide, are maintained by the community and doesn't contain malicious code, if you are not sure, you're free to review.
Try this one:
console.log("Session: %j", session);
If the object could be converted into JSON, that will work.
I hear your pain. I'm going through this right now (years later). From what I've learned, you can think of RTSP as a "VCR controller", the protocol allows you to specify which streams (presentations) you want to play, it will then send you a description of the media, and then you can use RTSP to play, stop, pause, and record the remote stream. The media itself goes over RTP. RTSP is normally implemented over a different socket or communication layer. Although it is simply a protocol, most often it's implemented by a server over a socket. For live streams, the RTSP stream you request is simply a name of a stream. It doesn't need to refer to a file on the server, the server's RTSP implementation can parse that stream, put together a live graph, and then provide the SDP (description) for that stream name. But, this is of course specific to the way the RTSP server has been implemented. For "live" streams, it's probably simpler to just use RTP, but you'll need a way to transfer the SDP from the RTP server to the client that wants to play that stream.
random.randrange(0,2) this works!
It for example happens in this case here:
void initializeJSP(unknownType Experiment);
Try using std::string
instead of just string
(and include the <string>
header). C++ Standard library classes are within the namespace std::
.
If you do have a TemplateField
inside the columns of your GridView
and you have, say, a control named blah bound to it. Then place the outlook_id
as a HiddenField
there like this:
<asp:TemplateField HeaderText="OutlookID">
<ItemTemplate>
<asp:Label ID="blah" runat="server">Existing Control</asp:Label>
<asp:HiddenField ID="HiddenOutlookID" runat="server" Value='<%#Eval("Outlook_ID") %>'/>
</ItemTemplate>
</asp:TemplateField>
Now, grab the row in the event you want the outlook_id
and then access the control.
For RowDataBound
access it like:
string outlookid = ((HiddenField)e.Row.FindControl("HiddenOutlookID")).Value;
Do get back, if you have trouble accessing the clicked row. And don't forget to mention the event at which you would like to access that.
Python is an interesting language in that while there is usually one (or two) "obvious" ways to accomplish any given task, flexibility still exists.
s = "string"
i = 0
print (s + repr(i))
The above code snippet is written in Python3 syntax but the parentheses after print were always allowed (optional) until version 3 made them mandatory.
Hope this helps.
Caitlin
In Python 2, if you need to pass around a function, then you can assign os.sys.stdout.write
to a variable. You cannot do this (in the REPL) with print
.
>import os
>>> cmd=os.sys.stdout.write
>>> cmd('hello')
hello>>>
That works as expected.
>>> cmd=print
File "<stdin>", line 1
cmd=print
^
SyntaxError: invalid syntax
That does not work. print
is a magical function.
Here's my answer that sorts the list inside jq
(for those who use systems where sort -V
is not avalable) :
$ pythonPackage=certifi
$ curl -Ls https://pypi.org/pypi/$pythonPackage/json | jq -r '.releases | keys_unsorted | sort_by( split(".") | map(tonumber) )'
.............
"2019.3.9",
"2019.6.16",
"2019.9.11",
"2019.11.28",
"2020.4.5",
"2020.4.5.1",
"2020.4.5.2",
"2020.6.20",
"2020.11.8"
]
And to fetch the last version number of the package :
$ curl -Ls https://pypi.org/pypi/$pythonPackage/json | jq -r '.releases | keys_unsorted | sort_by( split(".") | map(tonumber) )[-1]'
2020.11.8
or a bit faster :
$ curl -Ls https://pypi.org/pypi/$pythonPackage/json | jq -r '.releases | keys_unsorted | max_by( split(".") | map(tonumber) )'
2020.11.8
Or even more simple :) :
$ curl -Ls https://pypi.org/pypi/$pythonPackage/json | jq -r .info.version
2020.11.8
I'm using ASP.Net CORE 2.1 and I got this error when I ran by selecting a .csproj from a list of about 40 in a big repo. When I opened the csproj file individually, the error was resolved. Something with how the program was launched was different when the csproj was opened.
I do think requests
is the best option. Also note the possibility of setting encoding manually.
import requests
response = requests.get("http://www.gutenberg.org/files/10/10-0.txt")
# response.encoding = "utf-8"
hehe = response.text
Simplified:
DateTime time = System.DateTime.Now;
ModelName m = context.TableName.Where(x=> DbFunctions.TruncateTime(x.Date) == time.Date)).FirstOrDefault();
Note that as of this commit in June 2015 (Jackson 2.6.2 and above) you can now simply write:
public enum Event {
@JsonProperty("forgot password")
FORGOT_PASSWORD;
}
The behavior is documented here: https://fasterxml.github.io/jackson-annotations/javadoc/2.11/com/fasterxml/jackson/annotation/JsonProperty.html
Starting with Jackson 2.6 this annotation may also be used to change serialization of Enum like so:
public enum MyEnum { @JsonProperty("theFirstValue") THE_FIRST_VALUE, @JsonProperty("another_value") ANOTHER_VALUE; }
as an alternative to using JsonValue annotation.
Since you've included the C++ tag, you could use the {fmt} library and avoid the PRIu64
macro and other printf
issues altogether:
#include <fmt/core.h>
int main() {
uint64_t ui64 = 90;
fmt::print("test uint64_t : {}\n", ui64);
}
The formatting facility based on this library is proposed for standardization in C++20: P0645.
Disclaimer: I'm the author of {fmt}.
This is the way I am using at this moment... it's very complicated but at least it handles all the possible situations. In case anyone is interested.
public final class MyFragment extends Fragment {
private TextView vstup;
private Bundle savedState = null;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.whatever, null);
vstup = (TextView)v.findViewById(R.id.whatever);
/* (...) */
/* If the Fragment was destroyed inbetween (screen rotation), we need to recover the savedState first */
/* However, if it was not, it stays in the instance from the last onDestroyView() and we don't want to overwrite it */
if(savedInstanceState != null && savedState == null) {
savedState = savedInstanceState.getBundle(App.STAV);
}
if(savedState != null) {
vstup.setText(savedState.getCharSequence(App.VSTUP));
}
savedState = null;
return v;
}
@Override
public void onDestroyView() {
super.onDestroyView();
savedState = saveState(); /* vstup defined here for sure */
vstup = null;
}
private Bundle saveState() { /* called either from onDestroyView() or onSaveInstanceState() */
Bundle state = new Bundle();
state.putCharSequence(App.VSTUP, vstup.getText());
return state;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
/* If onDestroyView() is called first, we can use the previously savedState but we can't call saveState() anymore */
/* If onSaveInstanceState() is called first, we don't have savedState, so we need to call saveState() */
/* => (?:) operator inevitable! */
outState.putBundle(App.STAV, (savedState != null) ? savedState : saveState());
}
/* (...) */
}
Alternatively, it is always a possibility to keep the data displayed in passive View
s in variables and using the View
s only for displaying them, keeping the two things in sync. I don't consider the last part very clean, though.
There are two method two remove index in mysql. First method is GUI. In this method you have to open GUI interface of MYSQL and then go to that database and then go to that particular table in which you want to remove index.
After that click on the structure option, Then you can see table structure and below you can see table indexes. You can remove indexes by clicking on drop option
Second method by
ALTER TABLE student_login_credentials DROP INDEX created_at;
here student_login_credentials is table name and created_at is column name
Well if you want to return your array from a function you must make sure that the values are not stored on the stack as they will be gone when you leave the function.
So either make your array static or allocate the memory (or pass it in but your initial attempt is with a void parameter). For your method I would define it like this:
int *gnabber(){
static int foo[] = {1,2,3}
return foo;
}
HTML
<div id="myDiv" style="display:none;" class="answer_list" >WELCOME</div>
<input type="button" name="answer" onclick="ShowDiv()" />
JavaScript
function ShowDiv() {
document.getElementById("myDiv").style.display = "";
}
Or if you wanted to use jQuery with a nice little animation:
<input id="myButton" type="button" name="answer" />
$('#myButton').click(function() {
$('#myDiv').toggle('slow', function() {
// Animation complete.
});
});
sp: scale independent pixel
You should use it with texts because it is automatically scaled according to the font size that is being used by the user in his device.
px: pixel or picture element is the single point on the screen
Doesn't sound like all the files needed to use that class are present. I would start over:
require_once('phpmailer/PHPMailerAutoload.php');
Try this
<a href="javascript:window.open('','_self').close();">close</a>