Connections have a close
method as specified in PEP-249 (Python Database API Specification v2.0):
import pyodbc
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest')
csr = conn.cursor()
csr.close()
conn.close() #<--- Close the connection
Since the pyodbc
connection and cursor are both context managers, nowadays it would be more convenient (and preferable) to write this as:
import pyodbc
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest')
with conn:
crs = conn.cursor()
do_stuff
# conn.commit() will automatically be called when Python leaves the outer `with` statement
# Neither crs.close() nor conn.close() will be called upon leaving the `with` statement!!
See https://github.com/mkleehammer/pyodbc/issues/43 for an explanation for why conn.close() is not called.
Note that unlike the original code, this causes conn.commit()
to be called. Use the outer with
statement to control when you want commit
to be called.
Also note that regardless of whether or not you use the with
statements, per the docs,
Connections are automatically closed when they are deleted (typically when they go out of scope) so you should not normally need to call [
conn.close()
], but you can explicitly close the connection if you wish.
and similarly for cursors (my emphasis):
Cursors are closed automatically when they are deleted (typically when they go out of scope), so calling [
csr.close()
] is not usually necessary.
long
and long int
are identical. So are long long
and long long int
. In both cases, the int
is optional.
As to the difference between the two sets, the C++ standard mandates minimum ranges for each, and that long long
is at least as wide as long
.
The controlling parts of the standard (C++11, but this has been around for a long time) are, for one, 3.9.1 Fundamental types
, section 2 (a later section gives similar rules for the unsigned integral types):
There are five standard signed integer types : signed char, short int, int, long int, and long long int. In this list, each type provides at least as much storage as those preceding it in the list.
There's also a table 9 in 7.1.6.2 Simple type specifiers
, which shows the "mappings" of the specifiers to actual types (showing that the int
is optional), a section of which is shown below:
Specifier(s) Type
------------- -------------
long long int long long int
long long long long int
long int long int
long long int
Note the distinction there between the specifier and the type. The specifier is how you tell the compiler what the type is but you can use different specifiers to end up at the same type.
Hence long
on its own is neither a type nor a modifier as your question posits, it's simply a specifier for the long int
type. Ditto for long long
being a specifier for the long long int
type.
Although the C++ standard itself doesn't specify the minimum ranges of integral types, it does cite C99, in 1.2 Normative references
, as applying. Hence the minimal ranges as set out in C99 5.2.4.2.1 Sizes of integer types <limits.h>
are applicable.
In terms of long double
, that's actually a floating point value rather than an integer. Similarly to the integral types, it's required to have at least as much precision as a double
and to provide a superset of values over that type (meaning at least those values, not necessarily more values).
Renaming the file by moving it to a new name. (FileUtils is from Apache Commons IO lib)
String newFilePath = oldFile.getAbsolutePath().replace(oldFile.getName(), "") + newName;
File newFile = new File(newFilePath);
try {
FileUtils.moveFile(oldFile, newFile);
} catch (IOException e) {
e.printStackTrace();
}
Full version:
<? echo date('F Y'); ?>
Short version:
<? echo date('M Y'); ?>
Here is a good reference for the different date options.
update
To show the previous month we would have to introduce the mktime() function and make use of the optional timestamp
parameter for the date() function. Like this:
echo date('F Y', mktime(0, 0, 0, date('m')-1, 1, date('Y')));
This will also work (it's typically used to get the last day of the previous month):
echo date('F Y', mktime(0, 0, 0, date('m'), 0, date('Y')));
Hope that helps.
var_dump(json_decode('{"0":0}')); // output: object(0=>0)
var_dump(json_decode('[0]')); //output: [0]
var_dump(json_decode('{"0":0}', true));//output: [0]
var_dump(json_decode('[0]', true)); //output: [0]
If you decode the json into array, information will be lost in this situation.
The problem is almost certainly that you're not using the MPI compiler wrappers. Whenever you're compiling an MPI program, you should use the MPI wrappers:
mpicc
mpiCC
, mpicxx
, mpic++
mpifort
, mpif77
, mpif90
These wrappers do all of the dirty work for you of making sure that all of the appropriate compiler flags, libraries, include directories, library directories, etc. are included when you compile your program.
FWIW, in case anyone revisits this question later, you might also check what you are handing to your onKeyPress handler function.
I ran into this error when I mistakenly passed onKeyPress(this) instead of onKeyPress(event).
Just something else to check.
Know the master key yourself. Don't hard code it.
Use py-bcrypt
(bcrypt), powerful hashing technique to generate a password yourself.
Basically you can do this (an idea...)
import bcrypt
from getpass import getpass
master_secret_key = getpass('tell me the master secret key you are going to use')
salt = bcrypt.gensalt()
combo_password = raw_password + salt + master_secret_key
hashed_password = bcrypt.hashpw(combo_password, salt)
save salt and hashed password somewhere so whenever you need to use the password, you are reading the encrypted password, and test against the raw password you are entering again.
This is basically how login should work these days.
Sorry for being late, I have tried all above answers but none of them is giving me correct value, After doing the lot of R&D I have found a simple way that gives me exact value.
Declare this method in your class
private String hmacSha(String KEY, String VALUE, String SHA_TYPE) {
try {
SecretKeySpec signingKey = new SecretKeySpec(KEY.getBytes("UTF-8"), SHA_TYPE);
Mac mac = Mac.getInstance(SHA_TYPE);
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(VALUE.getBytes("UTF-8"));
byte[] hexArray = {(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f'};
byte[] hexChars = new byte[rawHmac.length * 2];
for ( int j = 0; j < rawHmac.length; j++ ) {
int v = rawHmac[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
}
Use this like
Log.e("TAG", "onCreate: "+hmacSha("key","text","HmacSHA256"));
Verification
1.Android studio output 2. Online HMAC generator Output(Visit here for Online Genrator)
for me with bootstrap 4 datetime picker (http://www.eyecon.ro/bootstrap-datepicker/) format worked only with upper case:
$('.datepicker').datetimepicker({
format: 'DD/MM/YYYY'
});
Just call plt.show()
at the end:
import numpy as np
import matplotlib.pyplot as plt
plt.axis([0,50,60,80])
for i in np.arange(1,5):
z = 68 + 4 * np.random.randn(50)
zm = np.cumsum(z) / range(1,len(z)+1)
plt.plot(zm)
n = np.arange(1,51)
su = 68 + 4 / np.sqrt(n)
sl = 68 - 4 / np.sqrt(n)
plt.plot(n,su,n,sl)
plt.show()
The number of itemId
s in your list will be the same as the number of elements in your list:
int itemCount = list.size();
However, if you're looking to count the number of unique itemIds (per @pst) then you should use a set to keep track of them.
Set<String> itemIds = new HashSet<String>();
//...
itemId = p.getItemId();
itemIds.add(itemId);
//... later ...
int uniqueItemIdCount = itemIds.size();
Vavr (formerly called Javaslang) (http://www.vavr.io) provides tuples (til size of 8) as well. Here is the javadoc: https://static.javadoc.io/io.vavr/vavr/0.9.0/io/vavr/Tuple.html.
This is a simple example:
Tuple2<Integer, String> entry = Tuple.of(1, "A");
Integer key = entry._1;
String value = entry._2;
Why JDK itself did not come with a simple kind of tuples til now is a mystery to me. Writing wrapper classes seems to be an every day business.
This works relatively well. It flattens the json to write it to a csv file. Nested elements are managed :)
That's for python 3
import json
o = json.loads('your json string') # Be careful, o must be a list, each of its objects will make a line of the csv.
def flatten(o, k='/'):
global l, c_line
if isinstance(o, dict):
for key, value in o.items():
flatten(value, k + '/' + key)
elif isinstance(o, list):
for ov in o:
flatten(ov, '')
elif isinstance(o, str):
o = o.replace('\r',' ').replace('\n',' ').replace(';', ',')
if not k in l:
l[k]={}
l[k][c_line]=o
def render_csv(l):
ftime = True
for i in range(100): #len(l[list(l.keys())[0]])
for k in l:
if ftime :
print('%s;' % k, end='')
continue
v = l[k]
try:
print('%s;' % v[i], end='')
except:
print(';', end='')
print()
ftime = False
i = 0
def json_to_csv(object_list):
global l, c_line
l = {}
c_line = 0
for ov in object_list : # Assumes json is a list of objects
flatten(ov)
c_line += 1
render_csv(l)
json_to_csv(o)
enjoy.
Open your build.gradle file and make sure you have versionCode
and versionName
inside defaultConfig
element. If not, add them. Refer to this link for more details.
https://en.wikipedia.org/wiki/Shunting-yard_algorithm
The shunting yard algorithm can also be applied to produce prefix notation (also known as polish notation). To do this one would simply start from the end of a string of tokens to be parsed and work backwards, reverse the output queue (therefore making the output queue an output stack), and flip the left and right parenthesis behavior (remembering that the now-left parenthesis behavior should pop until it finds a now-right parenthesis).
from collections import deque
def convertToPN(expression):
precedence = {}
precedence["*"] = precedence["/"] = 3
precedence["+"] = precedence["-"] = 2
precedence[")"] = 1
stack = []
result = deque([])
for token in expression[::-1]:
if token == ')':
stack.append(token)
elif token == '(':
while stack:
t = stack.pop()
if t == ")": break
result.appendleft(t)
elif token not in precedence:
result.appendleft(token)
else:
# XXX: associativity should be considered here
# https://en.wikipedia.org/wiki/Operator_associativity
while stack and precedence[stack[-1]] > precedence[token]:
result.appendleft(stack.pop())
stack.append(token)
while stack:
result.appendleft(stack.pop())
return list(result)
expression = "(a - b) / c * (d + e - f / g)".replace(" ", "")
convertToPN(expression)
step through:
step 1 : token ) ; stack:[ ) ]
result:[ ]
step 2 : token g ; stack:[ ) ]
result:[ g ]
step 3 : token / ; stack:[ ) / ]
result:[ g ]
step 4 : token f ; stack:[ ) / ]
result:[ f g ]
step 5 : token - ; stack:[ ) - ]
result:[ / f g ]
step 6 : token e ; stack:[ ) - ]
result:[ e / f g ]
step 7 : token + ; stack:[ ) - + ]
result:[ e / f g ]
step 8 : token d ; stack:[ ) - + ]
result:[ d e / f g ]
step 9 : token ( ; stack:[ ]
result:[ - + d e / f g ]
step 10 : token * ; stack:[ * ]
result:[ - + d e / f g ]
step 11 : token c ; stack:[ * ]
result:[ c - + d e / f g ]
step 12 : token / ; stack:[ * / ]
result:[ c - + d e / f g ]
step 13 : token ) ; stack:[ * / ) ]
result:[ c - + d e / f g ]
step 14 : token b ; stack:[ * / ) ]
result:[ b c - + d e / f g ]
step 15 : token - ; stack:[ * / ) - ]
result:[ b c - + d e / f g ]
step 16 : token a ; stack:[ * / ) - ]
result:[ a b c - + d e / f g ]
step 17 : token ( ; stack:[ * / ]
result:[ - a b c - + d e / f g ]
# the final while
step 18 : token ( ; stack:[ ]
result:[ * / - a b c - + d e / f g ]
return n
from main
is equivalent to exit(n)
.
The valid returned is the rest of your program. It's meaning is OS dependent. On unix, 0 means normal termination and non-zero indicates that so form of error forced your program to terminate without fulfilling its intended purpose.
It's unusual that your example returns 0 (normal termination) when it seems to have run out of memory.
You can add a DLL (or EXE) to a project only if it is a .NET assembly. If it's not you will see this error message.
regsvr32 also makes certain assumptions about the structure and exported function in the DLL. It has been a while since I used it but it has to do with registering COM servers so certain entry points need to be available. If regsvr32 fails the DLL doesn't provide those entry points and the DLL does not contain a COM component.
You only chance for using the DLL is to import it like any other non-.NET binary, e.g. when you use certain Win32 APIs. There is an old MSDN Magazine Article that might be helpful. See the following update for info where to get the article.
Update 12 March 2018: The link to the MSDN Magazine no longer works as it used to in August 2010. The article by Jason Clark is titled ".NET Column: Calling Win32 DLLs in C# with P/Invoke". It was published in the July 2010 issue of MSDN Magazine. The "Wayback Machine" has the article here at the moment (formatting is limited). The entire MSDN Magazine issue July 2010 is available here (HCM format only, instructions for how to use HCM files here).
Just try with
$("._statusDDL").val("2");
and not with
$("._statusDDL").val(2);
I was faced with this same problem today but since our daylight saving starts and stops at differing times from the USA (at least from my understanding), I used a slightly different route..
var arr = [];
for (var i = 0; i < 365; i++) {
var d = new Date();
d.setDate(i);
newoffset = d.getTimezoneOffset();
arr.push(newoffset);
}
DST = Math.min.apply(null, arr);
nonDST = Math.max.apply(null, arr);
Then you simply compare the current timezone offset with DST and nonDST to see which one matches.
The answer offered by @Daniel Kamil Kozar is the correct answer - gettimeofday actually should not be used to measure the elapsed time. Use clock_gettime(CLOCK_MONOTONIC) instead.
Man Pages say - The time returned by gettimeofday() is affected by discontinuous jumps in the system time (e.g., if the system administrator manually changes the system time). If you need a monotonically increasing clock, see clock_gettime(2).
The Opengroup says - Applications should use the clock_gettime() function instead of the obsolescent gettimeofday() function.
Everyone seems to love gettimeofday until they run into a case where it does not work or is not there (VxWorks) ... clock_gettime is fantastically awesome and portable.
<<
Easy:
print my_queryset.query
For example:
from django.contrib.auth.models import User
print User.objects.filter(last_name__icontains = 'ax').query
It should also be mentioned that if you have DEBUG = True, then all of your queries are logged, and you can get them by accessing connection.queries:
from django.db import connections
connections['default'].queries
The django debug toolbar project uses this to present the queries on a page in a neat manner.
Putting this information here for future readers' benefit.
401 (Unauthorized) response header -> Request authentication header
Here are several WWW-Authenticate
response headers. (The full list is at IANA: HTTP Authentication Schemes.)
WWW-Authenticate: Basic
-> Authorization: Basic + token - Use for basic authentication WWW-Authenticate: NTLM
-> Authorization: NTLM + token (2 challenges)WWW-Authenticate: Negotiate
-> Authorization: Negotiate + token - used for Kerberos authentication
Negotiate
: This authentication scheme violates both HTTP semantics (being connection-oriented) and syntax (use of syntax incompatible with the WWW-Authenticate and Authorization header field syntax).You can set the Authorization: Basic
header only when you also have the WWW-Authenticate: Basic
header on your 401 challenge.
But since you have WWW-Authenticate: Negotiate
this should be the case for Kerberos based authentication.
One has exactly space for 11 bytes, the other for exactly 11 characters. Some charsets such as Unicode variants may use more than one byte per char, therefore the 11 byte field might have space for less than 11 chars depending on the encoding.
See also http://www.joelonsoftware.com/articles/Unicode.html
If you want to delete all subdirectories under /path/to/base
, for example
/path/to/base/dir1
/path/to/base/dir2
/path/to/base/dir3
but you don't want to delete the root /path/to/base
, you have to add -mindepth 1
and -maxdepth 1
options, which will access only the subdirectories under /path/to/base
-mindepth 1
excludes the root /path/to/base
from the matches.
-maxdepth 1
will ONLY match subdirectories immediately under /path/to/base
such as /path/to/base/dir1
, /path/to/base/dir2
and /path/to/base/dir3
but it will not list subdirectories of these in a recursive manner. So these example subdirectories will not be listed:
/path/to/base/dir1/dir1
/path/to/base/dir2/dir1
/path/to/base/dir3/dir1
and so forth.
So , to delete all the sub-directories under /path/to/base
which are older than 10 days;
find /path/to/base -mindepth 1 -maxdepth 1 -type d -ctime +10 | xargs rm -rf
<img title="<a href="javascript:alert('hello world')">The Link</a>" />
Perhaps you don't have a recent enough version of Greasemonkey. It was version 0.8 that added @require
.
// @require https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js
If you don't have 0.8, then use the technique Joan Piedra describes for manually adding a script
element to the page.
Between version 0.8 and 0.9, @require
is only processed when the script is first installed. If you change the list of required scripts, you need to uninstall your script and reinstall it; Greasemonkey downloads the required script once at installation and uses a cached copy thereafter.
As of 0.9, Greasemonkey behavior has changed (to address a tangentially related issue) so that it now loads the required scripts after every edit; reinstalling the script is no longer necessary.
I have my sample code working but want to make it somewhat more better refrencing the tab from list:
Public Class Form1
Dim State1 As Integer = 1
Dim AllTabs As List(Of TabPage) = New List(Of TabPage)
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Check1(State1)
State1 = CInt(IIf(State1 = 1, 0, 1))
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
AllTabs.Add(TabControl1.TabPages("TabPage1"))
AllTabs.Add(TabControl1.TabPages("TabPage2"))
End Sub
Sub Check1(ByVal No As Integer)
If TabControl1.TabPages.ContainsKey("TabPage1") Then
TabControl1.TabPages.Remove(TabControl1.TabPages("TabPage1"))
End If
If TabControl1.TabPages.ContainsKey("TabPage2") Then
TabControl1.TabPages.Remove(TabControl1.TabPages("TabPage2"))
End If
TabControl1.TabPages.Add(AllTabs(No))
End Sub
End Class
Note the plural in this method:
document.getElementsByName()
That returns an array of elements, so use [0] to get the first occurence, e.g.
document.getElementsByName()[0]
SEL is a type that represents a selector in Objective-C. The @selector() keyword returns a SEL that you describe. It's not a function pointer and you can't pass it any objects or references of any kind. For each variable in the selector (method), you have to represent that in the call to @selector. For example:
-(void)methodWithNoParameters;
SEL noParameterSelector = @selector(methodWithNoParameters);
-(void)methodWithOneParameter:(id)parameter;
SEL oneParameterSelector = @selector(methodWithOneParameter:); // notice the colon here
-(void)methodWIthTwoParameters:(id)parameterOne and:(id)parameterTwo;
SEL twoParameterSelector = @selector(methodWithTwoParameters:and:); // notice the parameter names are omitted
Selectors are generally passed to delegate methods and to callbacks to specify which method should be called on a specific object during a callback. For instance, when you create a timer, the callback method is specifically defined as:
-(void)someMethod:(NSTimer*)timer;
So when you schedule the timer you would use @selector to specify which method on your object will actually be responsible for the callback:
@implementation MyObject
-(void)myTimerCallback:(NSTimer*)timer
{
// do some computations
if( timerShouldEnd ) {
[timer invalidate];
}
}
@end
// ...
int main(int argc, const char **argv)
{
// do setup stuff
MyObject* obj = [[MyObject alloc] init];
SEL mySelector = @selector(myTimerCallback:);
[NSTimer scheduledTimerWithTimeInterval:30.0 target:obj selector:mySelector userInfo:nil repeats:YES];
// do some tear-down
return 0;
}
In this case you are specifying that the object obj be messaged with myTimerCallback every 30 seconds.
It can be usefull. Bindings dose not always work.
<select id="product" class="form-control" name="product" required
ng-model="issue.productId"
ng-change="getProductVersions()"
ng-options="p.id as p.shortName for p in products">
</select>
For example. You fill options list source model from rest-service. Selected value was known befor filling list and was set. After executing rest-request with $http list option be done. But selected option is not set. By unknown reasons AngularJS in shadow $digest executing not bind selected as it shuold be. I gotta use JQuery to set selected. It`s important! Angular in shadow add prefix to value of attr "value" for generated by ng-repeat optinos. For int it is "number:".
$scope.issue.productId = productId;
function activate() {
$http.get('/product/list')
.then(function (response) {
$scope.products = response.data;
if (productId) {
console.log("" + $("#product option").length);//for clarity
$timeout(function () {
console.log("" + $("#product option").length);//for clarity
$('#product').val('number:'+productId);
//$scope.issue.productId = productId;//not work at all
}, 200);
}
});
}
Instead of using divider in dialog, use the view in the custom layout and set the layout as custom layout in dialog.
custom_popup.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.divago.view.TextViewMedium
android:id="@+id/txtTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:text="AlertDialog"
android:textColor="@android:color/black"
android:textSize="20sp" />
<View
android:id="@+id/border"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="@id/txtTitle"
android:background="@color/txt_dark_grey" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/border"
android:scrollbars="vertical">
<com.divago.view.TextViewRegular
android:id="@+id/txtPopup"
android:layout_margin="15dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
</RelativeLayout>
activity.java:
public void showPopUp(String title, String text) {
LayoutInflater inflater = getLayoutInflater();
View alertLayout = inflater.inflate(R.layout.custom_popup, null);
TextView txtContent = alertLayout.findViewById(R.id.txtPopup);
txtContent.setText(text);
TextView txtTitle = alertLayout.findViewById(R.id.txtTitle);
txtTitle.setText(title);
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setView(alertLayout);
alert.setCancelable(true);
alert.setPositiveButton("Done", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = alert.create();
dialog.show();
}
If your host not at pvn or dedicated, it's dificult to restart server.
Better solution from me, just edit your CSS file (at another domain or your subdomain) that call font eot, woff etc to your origin (your-domain or www yourdomain). it will solve your problem.
I mean, edit relative url on css to absolute url origin domain
What is a plain English explanation of Big O? With as little formal definition as possible and simple mathematics.
A Plain English Explanation of the Need for Big-O Notation:
When we program, we are trying to solve a problem. What we code is called an algorithm. Big O notation allows us to compare the worse case performance of our algorithms in a standardized way. Hardware specs vary over time and improvements in hardware can reduce the time it takes an algorithms to run. But replacing the hardware does not mean our algorithm is any better or improved over time, as our algorithm is still the same. So in order to allow us to compare different algorithms, to determine if one is better or not, we use Big O notation.
A Plain English Explanation of What Big O Notation is:
Not all algorithms run in the same amount of time, and can vary based on the number of items in the input, which we'll call n. Based on this, we consider the worse case analysis, or an upper-bound of the run-time as n get larger and larger. We must be aware of what n is, because many of the Big O notations reference it.
C++ has no built-in concepts of interfaces. You can implement it using abstract classes which contains only pure virtual functions. Since it allows multiple inheritance, you can inherit this class to create another class which will then contain this interface (I mean, object interface :) ) in it.
An example would be something like this -
class Interface
{
public:
Interface(){}
virtual ~Interface(){}
virtual void method1() = 0; // "= 0" part makes this method pure virtual, and
// also makes this class abstract.
virtual void method2() = 0;
};
class Concrete : public Interface
{
private:
int myMember;
public:
Concrete(){}
~Concrete(){}
void method1();
void method2();
};
// Provide implementation for the first method
void Concrete::method1()
{
// Your implementation
}
// Provide implementation for the second method
void Concrete::method2()
{
// Your implementation
}
int main(void)
{
Interface *f = new Concrete();
f->method1();
f->method2();
delete f;
return 0;
}
If all else fails, and if you are seeing this error while trying to import in a PyCharm "Python console" (or "Django console"):
Try restarting the console.
This is pretty embarassing, but it took me a while before I realized I had forgotten to do that.
Here's what happened:
Added a fresh app, then added a minimal model, then tried to import the model in the Python/Django console (PyCharm pro 2019.2). This raised the doesn't declare an explicit app_label
error, because I had not added the new app to INSTALLED_APPS
.
So, I added the app to INSTALLED_APPS
, tried the import again, but still got the same error.
Came here, read all the other answers, but nothing seemed to fit.
Finally it hit me that I had not yet restarted the Python console after adding the new app to INSTALLED_APPS
.
Note: failing to restart the PyCharm Python console, after adding a new object to a module, is also a great way to get a very confusing ImportError: Cannot import name ...
According to vnportnoy the syntax
GenSet<Integer> intSet[] = new GenSet[3];
creates an array of null references, to be filled as
for (int i = 0; i < 3; i++)
{
intSet[i] = new GenSet<Integer>();
}
which is type safe.
check it: Android Studio->file->project structure->app->flavors->min sdk version and if you want to run your application on your mobile you have to set min sdk version less than your device sdk(API) you can install any API levels.
Some versions of Excel don't have date-time formats available in the standard pick lists, but you can just enter a custom format string such as yyyy-mm-dd hh:mm:ss by:
This works on my Excel 2010
In PostgresQL it is:
ALTER TABLE tableName ALTER COLUMN columnName DROP NOT NULL;
You can always take the CTE, (Common Tabular Expression), approach.
;WITH updateCTE AS
(
SELECT ID, TITLE
FROM HOLD_TABLE
WHERE ID = 101
)
UPDATE updateCTE
SET TITLE = 'TEST';
You can create a Text Field that doesn't accept any events on top of a Text View like this:
CGRect frameRect = descriptionTextField.frame;
frameRect.size.height = 50;
descriptionTextField.frame = frameRect;
descriptionTextView.frame = frameRect;
descriptionTextField.backgroundColor = [UIColor clearColor];
descriptionTextField.enabled = NO;
descriptionTextView.layer.cornerRadius = 5;
descriptionTextView.clipsToBounds = YES;
Using Google Collections, assuming K is your key type:
Maps.filterKeys(treeMap, new Predicate<K>() {
@Override
public boolean apply(K key) {
return false; //return true here if you need the entry to be in your new map
}});
You can use filterEntries
instead if you need the value as well.
Help
/ Install New Software...
Add
buttonAdd Repository
dialog that appears, click the Archive
button next to the Location
fieldOK
You could also just copy plugins to the eclipse/plugins
directory, but it's not recommended.
Another way to do it that hasn't been mentioned yet is the tolist method:
myseries.tolist().index(7)
should return the correct index, assuming the value exists in the Series.
Only because no one else has mentioned it:
>>> 'bob'.title()
'Bob'
>>> 'sandy'.title()
'Sandy'
>>> '1bob'.title()
'1Bob'
>>> '1sandy'.title()
'1Sandy'
However, this would also give
>>> '1bob sandy'.title()
'1Bob Sandy'
>>> '1JoeBob'.title()
'1Joebob'
i.e. it doesn't just capitalize the first alphabetic character. But then .capitalize()
has the same issue, at least in that 'joe Bob'.capitalize() == 'Joe bob'
, so meh.
Using console.log(object)
will throw your object to the Javascript console, but that's not always what you want. Using JSON.stringify(object)
will return most stuff to be stored in a variable, for example to send it to a textarea input and submit the content back to the server.
dict((k, v) for (k, v) in points.iteritems() if v[0] < 5 and v[1] < 5)
There is another way if all you want is the text up to the first line feed:
x='some
thing'
y=${x%$'\n'*}
After that y
will contain some
and nothing else (no line feed).
What is happening here?
We perform a parameter expansion substring removal (${PARAMETER%PATTERN}
) for the shortest match up to the first ANSI C line feed ($'\n'
) and drop everything that follows (*
).
My solution may also be of help to someone.
Tested and Works on IntelliJ 2017.3.2 with Gradle 4.4
Scenario:
I have 2 flavours in my application, and so I wanted each release to be named appropriately according to each flavor.
The code below will be placed into your module gradle build file found in:
{app-root}/app/build.gradle
Gradle code to be added to android{ }
block:
android {
// ...
defaultConfig {
versionCode 10
versionName "1.2.3_build5"
}
buildTypes {
// ...
release {
// ...
applicationVariants.all {
variant.outputs.each { output ->
output.outputFile = new File(output.outputFile.parent, output.outputFile.name.replace(output.outputFile.name, variant.flavorName + "-" + defaultConfig.versionName + "_v" + defaultConfig.versionCode + ".apk"))
}
}
}
}
productFlavors {
myspicyflavor {
applicationIdSuffix ".MySpicyFlavor"
signingConfig signingConfigs.debug
}
mystandardflavor {
applicationIdSuffix ".MyStandardFlavor"
signingConfig signingConfigs.config
}
}
}
The above provides the following APKs found in {app-root}/app/
:
myspicyflavor-release-1.2.3_build5_v10.apk
mystandardflavor-release-1.2.3_build5_v10.apk
Hope it can be of use to someone.
For more info, see other answers mentioned in the question
Check that there isn't a firewall that is ending the connection after certain period of time (this was the cause of a similar problem we had)
This should work but must be used within an unsafe context:
byte[] buffer = new byte[255];
fixed (byte* p = buffer)
{
IntPtr ptr = (IntPtr)p;
// do you stuff here
}
beware, you have to use the pointer in the fixed block! The gc can move the object once you are not anymore in the fixed block.
I'm partial to C#. I ran the following using linqpad. But it could just as easily be compiled with csc and ran through the called from the command line.
Don't forget to add excel packages to namespace.
void Main()
{
var oExcelApp = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
try{
var WB = oExcelApp.ActiveWorkbook;
var WS = (Worksheet)WB.ActiveSheet;
((string)((Range)WS.Cells[1,1]).Value).Dump("Cell Value"); //cel A1 val
oExcelApp.Run("test_macro_name").Dump("macro");
}
finally{
if(oExcelApp != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcelApp);
oExcelApp = null;
}
}
For DD-MM-YY use this code:
var array = ["03-03-2017', '03-10-2017', '03-25-2017"]
$('#datepicker').datepicker({
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('dd-mm-yy', date);
return [ array.indexOf(string) == -1 ]
}
});
function highlightDays(date) {
for (var i = 0; i < dates.length; i++) {
if (new Date(dates[i]).toString() == date.toString()) {
return [true, 'highlight'];
}
}
return [true, ''];
}
Just wrap all that inside a ScrollView
:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- Here you put the rest of your current view-->
</ScrollView>
As David Hedlund said, ScrollView
can contain just one item... so if you had something like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- bla bla bla-->
</LinearLayout>
You must change it to:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- bla bla bla-->
</LinearLayout>
</ScrollView>
You can use
System.getProperty("line.separator");
to get the line separator
use this: data.peek() != '\0'
I've been searching for an hour until finaly this helped!
Method that will work. The way it is used above will not work.
declare @str varchar(50)='79136'
select
case
when @str LIKE replicate('[0-9]',LEN(@str)) then 1
else 0
end
declare @str2 varchar(50)='79D136'
select
case
when @str2 LIKE replicate('[0-9]',LEN(@str)) then 1
else 0
end
Can't add a comment to the excellent explanation in the other post but wanted to mention that a great documentation source can be found here.
It is enough to register an event function for accelerometer like so:
if(window.DeviceMotionEvent){
window.addEventListener("devicemotion", motion, false);
}else{
console.log("DeviceMotionEvent is not supported");
}
with the handler:
function motion(event){
console.log("Accelerometer: "
+ event.accelerationIncludingGravity.x + ", "
+ event.accelerationIncludingGravity.y + ", "
+ event.accelerationIncludingGravity.z
);
}
And for magnetometer a following event handler has to be registered:
if(window.DeviceOrientationEvent){
window.addEventListener("deviceorientation", orientation, false);
}else{
console.log("DeviceOrientationEvent is not supported");
}
with a handler:
function orientation(event){
console.log("Magnetometer: "
+ event.alpha + ", "
+ event.beta + ", "
+ event.gamma
);
}
There are also fields specified in the motion event for a gyroscope but that does not seem to be universally supported (e.g. it didn't work on a Samsung Galaxy Note).
There is a simple working code on GitHub
There is no verifyTextPresent in Selenium 2 webdriver, so you've to check for the text within the page source. See some practical examples below.
In Python driver you can write the following function:
def is_text_present(self, text):
return str(text) in self.driver.page_source
then use it as:
try: self.is_text_present("Some text.")
except AssertionError as e: self.verificationErrors.append(str(e))
To use regular expression, try:
def is_regex_text_present(self, text = "(?i)Example|Lorem|ipsum"):
self.assertRegex(self.driver.page_source, text)
return True
See: FooTest.py
file for full example.
Or check below few other alternatives:
self.assertRegexpMatches(self.driver.find_element_by_xpath("html/body/div[1]/div[2]/div/div[1]/label").text, r"^[\s\S]*Weather[\s\S]*$")
assert "Weather" in self.driver.find_element_by_css_selector("div.classname1.classname2>div.clearfix>label").text
Source: Another way to check (assert) if text exists using Selenium Python
In Java the following function:
public void verifyTextPresent(String value)
{
driver.PageSource.Contains(value);
}
and the usage would be:
try
{
Assert.IsTrue(verifyTextPresent("Selenium Wiki"));
Console.WriteLine("Selenium Wiki test is present on the home page");
}
catch (Exception)
{
Console.WriteLine("Selenium Wiki test is not present on the home page");
}
Source: Using verifyTextPresent in Selenium 2 Webdriver
For Behat, you can use Mink extension. It has the following methods defined in MinkContext.php
:
/**
* Checks, that page doesn't contain text matching specified pattern
* Example: Then I should see text matching "Bruce Wayne, the vigilante"
* Example: And I should not see "Bruce Wayne, the vigilante"
*
* @Then /^(?:|I )should not see text matching (?P<pattern>"(?:[^"]|\\")*")$/
*/
public function assertPageNotMatchesText($pattern)
{
$this->assertSession()->pageTextNotMatches($this->fixStepArgument($pattern));
}
/**
* Checks, that HTML response contains specified string
* Example: Then the response should contain "Batman is the hero Gotham deserves."
* Example: And the response should contain "Batman is the hero Gotham deserves."
*
* @Then /^the response should contain "(?P<text>(?:[^"]|\\")*)"$/
*/
public function assertResponseContains($text)
{
$this->assertSession()->responseContains($this->fixStepArgument($text));
}
About the progressbar
control in a userform, it won't show any progress if you don't use the repaint
event. You have to code this event inside the looping (and obviously increment the progressbar
value).
Example of use:
userFormName.repaint
$day_number = date('N', $date);
This will return a 1 for Monday to 7 for Sunday, for the date that is stored in $date. Omitting the second argument will cause date() to return the number for the current day.
In my case, I've loaded both the js
and css
visjs
files using the above technique - which works great. I call the new function from ngOnInit()
Note: I could not get it to load by simply adding a <script>
and <link>
tag to the html template file.
loadVisJsScript() {_x000D_
console.log('Loading visjs js/css files...');_x000D_
let script = document.createElement('script');_x000D_
script.src = "../../assets/vis/vis.min.js";_x000D_
script.type = 'text/javascript';_x000D_
script.async = true;_x000D_
script.charset = 'utf-8';_x000D_
document.getElementsByTagName('head')[0].appendChild(script); _x000D_
_x000D_
let link = document.createElement("link");_x000D_
link.type = "stylesheet";_x000D_
link.href = "../../assets/vis/vis.min.css";_x000D_
document.getElementsByTagName('head')[0].appendChild(link); _x000D_
}
_x000D_
I feel like none of the answers have crystallized why mapDispatchToProps
is useful.
This can really only be answered in the context of the container-component
pattern, which I found best understood by first reading:Container Components then Usage with React.
In a nutshell, your components
are supposed to be concerned only with displaying stuff. The only place they are supposed to get information from is their props.
Separated from "displaying stuff" (components) is:
That is what containers
are for.
Therefore, a "well designed" component
in the pattern look like this:
class FancyAlerter extends Component {
sendAlert = () => {
this.props.sendTheAlert()
}
render() {
<div>
<h1>Today's Fancy Alert is {this.props.fancyInfo}</h1>
<Button onClick={sendAlert}/>
</div>
}
}
See how this component gets the info it displays from props (which came from the redux store via mapStateToProps
) and it also gets its action function from its props: sendTheAlert()
.
That's where mapDispatchToProps
comes in: in the corresponding container
// FancyButtonContainer.js
function mapDispatchToProps(dispatch) {
return({
sendTheAlert: () => {dispatch(ALERT_ACTION)}
})
}
function mapStateToProps(state) {
return({fancyInfo: "Fancy this:" + state.currentFunnyString})
}
export const FancyButtonContainer = connect(
mapStateToProps, mapDispatchToProps)(
FancyAlerter
)
I wonder if you can see, now that it's the container
1 that knows about redux and dispatch and store and state and ... stuff.
The component
in the pattern, FancyAlerter
, which does the rendering doesn't need to know about any of that stuff: it gets its method to call at onClick
of the button, via its props.
And ... mapDispatchToProps
was the useful means that redux provides to let the container easily pass that function into the wrapped component on its props.
All this looks very like the todo example in docs, and another answer here, but I have tried to cast it in the light of the pattern to emphasize why.
(Note: you can't use mapStateToProps
for the same purpose as mapDispatchToProps
for the basic reason that you don't have access to dispatch
inside mapStateToProp
. So you couldn't use mapStateToProps
to give the wrapped component a method that uses dispatch
.
I don't know why they chose to break it into two mapping functions - it might have been tidier to have mapToProps(state, dispatch, props)
IE one function to do both!
1 Note that I deliberately explicitly named the container FancyButtonContainer
, to highlight that it is a "thing" - the identity (and hence existence!) of the container as "a thing" is sometimes lost in the shorthand
export default connect(...)
????????????
syntax that is shown in most examples
//Fields
String myID;
int myversion = 0;
myversion = Integer.valueOf(android.os.Build.VERSION.SDK);
if (myversion < 23) {
TelephonyManager mngr = (TelephonyManager)
getSystemService(Context.TELEPHONY_SERVICE);
myID= mngr.getDeviceId();
}
else
{
myID =
Settings.Secure.getString(getApplicationContext().getContentResolver(),
Settings.Secure.ANDROID_ID);
}
Yes, Secure.ANDROID_ID is unique for each device.
Make sure you declare the package at the top. In my groovy code this stops at breakpoints:
package Pkg1
import java.awt.event.ItemEvent;
isMule = false
class LineItem {
// Structure defining individual DB rows
public String ACCOUNT_CODE
public String ACCOUNT_DESC
...
This does not stop at breakpoints:
import java.awt.event.ItemEvent;
isMule = false
class LineItem {
// Structure defining individual DB rows
public String ACCOUNT_CODE
public String ACCOUNT_DESC
...
Using recursion, you can do the following (using ternary operators, one line max):
public static final String repeat(String string, long number) {
return number == 1 ? string : (number % 2 == 0 ? repeat(string + string, number / 2) : string + repeat(string + string, (number - 1) / 2));
}
I know, it's ugly and probably not efficient, but it's one line!
var empty = true;
$('input[type="text"]').each(function() {
if ($(this).val() != "") {
empty = false;
return false;
}
});
This should look all the input and set the empty var to false, if at least one is not empty.
EDIT:
To match the OP edit request, this can be used to filter input based on name substring.
$('input[name*="denominationcomune_"]').each(...
I created empty data frame using following code
df = data.frame(id = numeric(0), jobs = numeric(0));
and tried to bind some rows to populate the same as follows.
newrow = c(3, 4)
df <- rbind(df, newrow)
but it started giving incorrect column names as follows
X3 X4
1 3 4
Solution to this is to convert newrow to type df as follows
newrow = data.frame(id=3, jobs=4)
df <- rbind(df, newrow)
now gives correct data frame when displayed with column names as follows
id nobs
1 3 4
"singleton" in spring is using bean factory get instance, then cache it; which singleton design pattern is strictly, the instance can only be retrieved from static get method, and the object can never be publicly instantiated.
Different ways:
Using SQL Server Agent (If local instance)
schedule a job in sql server agent with a new step having type as "T-SQL" then run the job.
Using SQLCMD
To use SQLCMD refer http://technet.microsoft.com/en-us/library/ms162773.aspx
Using SQLPS
To use SQLPS refer http://technet.microsoft.com/en-us/library/cc280450.aspx
Very useful, especially for those dealing with Node.js where we want to avoid searching inside "node_modules":
find ./ -not -path "*/node_modules/*" -name "*.js" | xargs grep keyword
No, Python does not support labels and goto, if that is what you're after. It's a (highly) structured programming language.
If we need to share multiple variables use the below format
//module.js
let name='foobar';
let city='xyz';
let company='companyName';
module.exports={
name,
city,
company
}
Usage
// main.js
require('./modules');
console.log(name); // print 'foobar'
Use integers instead of strings.
make sure to cast your string to ints
price = int('1') * 9
The actual example code you posted will return 9
not 111111111
You try this one update method in SQLite
int id;
ContentValues con = new ContentValues();
con.put(TITLE, title);
con.put(AREA, area);
con.put(DESCR, desc);
con.put(TAG, tag);
myDataBase.update(TABLE, con, KEY_ID + "=" + id,null);
See https://stackoverflow.com/a/15662720/687315. As a workaround, you can listen for the afterPrint
event on the window (Firefox and IE) and listen for mouse movement on the document (indicating that the user has closed the print dialog and returned to the page) after the window.mediaMatch
API indicates that the media no longer matches "print" (Firefox and Chrome).
Keep in mind that the user may or may not have actually printed the document. Also, if you call window.print()
too often in Chrome, the user may not have even been prompted to print.
Download and install LINQPad, it works for SQL Server, MySQL, SQLite and also SDF (SQL CE 4.0).
Steps for open SDF Files:
Click Add Connection
Select Build data context automatically and Default (LINQ to SQL), then Next.
Under Provider choose SQL CE 4.0.
Under Database with Attach database file selected, choose Browse to select your .sdf file.
Click OK.
The same problem arrised for me when I installed Kaliko CMS Nuget Package. When I removed it, it started working fine again. So, your problem could be because of a recently installed Nuget Package. Uninstall it and your solution will work just fine.
Yes.
ThisWorkbook.RefreshAll
Or, if your Excel version is old enough,
Dim Sheet as WorkSheet, Pivot as PivotTable
For Each Sheet in ThisWorkbook.WorkSheets
For Each Pivot in Sheet.PivotTables
Pivot.RefreshTable
Pivot.Update
Next
Next
Automatically entering the password for the rsync command is difficult. My simple solution to avoid the problem is to mount the folder to be backed up. Then use a local rsync command to backup the mounted folder.
mount -t cifs //server/source/ /mnt/source-tmp -o username=Username,password=password
rsync -a /mnt/source-tmp /media/destination/
umount /mnt/source-tmp
In case anybody else comes across this problem, as I just have, the answer is to wrap the content which you want to collapse inside a div
and collapse the wrapper div rather than the content itself.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
<div class="form-group">_x000D_
<a for="collapseOne" data-toggle="collapse" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne" class="btn btn-primary">+ addInfo</a>_x000D_
<div id="collapseOne" class="collapse">_x000D_
<textarea class="form-control" rows="4"></textarea>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="form-group">_x000D_
<a for="collapseTwo" data-toggle="collapse" href="#collapseTwo" aria-expanded="true" aria-controls="collapseOne" class="btn btn-info">+ subtitle</a>_x000D_
<input type="text" class="form-control collapse" id="collapseTwo">_x000D_
</div>
_x000D_
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) ) ;
Boolean isBetween =
( ! today.isBefore( localDate1 ) ) // “not-before” is short for “is-equal-to or later-than”.
&&
today.isBefore( localDate3 ) ;
Or, better, if you add the ThreeTen-Extra library to your project.
LocalDateRange.of(
LocalDate.of( … ) ,
LocalDate.of( … )
).contains(
LocalDate.now()
)
Half-open approach, where beginning is inclusive while ending is exclusive.
By the way, that is a bad choice of format for a text representation of a date or date-time value. Whenever possible, stick with the standard ISO 8601 formats. ISO 8601 formats are unambiguous, understandable across human cultures, and are easy to parse by machine.
For a date-only value, the standard format is YYYY-MM-DD. Note how this format has the benefit of being chronological when sorted alphabetically.
LocalDate
The LocalDate
class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
DateTimeFormatter
As your input strings are non-standard format, we must define a formatting pattern to match.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" );
Use that to parse the input strings.
LocalDate start = LocalDate.parse( "22-02-2010" , f );
LocalDate stop = LocalDate.parse( "25-12-2010" , f );
In date-time work, usually best to define a span of time by the Half-Open approach where the beginning is inclusive while the ending is exclusive. So we want to know if today is the same or later than the start and also before the stop. A briefer way of saying “is the same or later than the start” is “not before the start”.
Boolean intervalContainsToday = ( ! today.isBefore( start ) ) && today.isBefore( stop ) ;
See the Answer by gstackoverflow showing the list of comparison methods you can call.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
UPDATE: This “Joda-Time” section below is left intact as history. The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
Other answers are correct with regard to the bundled java.util.Date and java.util.Calendar classes. But those classes are notoriously troublesome. So here's some example code using the Joda-Time 2.3 library.
If you truly want a date without any time portion and no time zone, then use the LocalDate
class in Joda-Time. That class provides methods of comparison including compareTo
(used with Java Comparators), isBefore
, isAfter
, and isEqual
.
Inputs…
String string1 = "22-02-2010";
String string2 = "07-04-2010";
String string3 = "25-12-2010";
Define a formatter describing the input strings…
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd-MM-yyyy" );
Use formatter to parse the strings into LocalDate objects…
LocalDate localDate1 = formatter.parseLocalDate( string1 );
LocalDate localDate2 = formatter.parseLocalDate( string2 );
LocalDate localDate3 = formatter.parseLocalDate( string3 );
boolean is1After2 = localDate1.isAfter( localDate2 );
boolean is2Before3 = localDate2.isBefore( localDate3 );
Dump to console…
System.out.println( "Dates: " + localDate1 + " " + localDate2 + " " + localDate3 );
System.out.println( "is1After2 " + is1After2 );
System.out.println( "is2Before3 " + is2Before3 );
When run…
Dates: 2010-02-22 2010-04-07 2010-12-25
is1After2 false
is2Before3 true
So see if the second is between the other two (exclusively, meaning not equal to either endpoint)…
boolean is2Between1And3 = ( ( localDate2.isAfter( localDate1 ) ) && ( localDate2.isBefore( localDate3 ) ) );
If you are working with spans of time, I suggest exploring in Joda-Time the classes: Duration, Interval, and Period. Methods such as overlap
and contains
make comparisons easy.
For text representations, look at the ISO 8601 standard’s:
Joda-Time classes can work with strings in both those formats, both as input (parsing) and output (generating strings).
Joda-Time performs comparisons using the Half-Open approach where the beginning of the span is inclusive while the ending is exclusive. This approach is a wise one for handling spans of time. Search StackOverflow for more info.
If you have have a images folder and the icon is saved in that use this
stage.getIcons().add(new Image(<yourclassname>.class.getResourceAsStream("/images/comparison.png")));
and if you are directly using it from your package which is not a good practice use this
stage.getIcons().add(new Image(<yourclassname>.class.getResourceAsStream("comparison.png")));
and if you have a folder structure and you have your icon inside that use
stage.getIcons().add(new Image(<yourclassname>.class.getResourceAsStream("../images/comparison.png")));
In MCEdit toggle Shift+F3 (ie F13) or F9->Edit ->Mark columns.
P.S. In this case, MCEdit is an editor written for the Midnight Commander.
This answer builds upon the earlier answer by Keith.
egrep -v "^[[:blank:]]*#"
should filter out comment lines.
egrep -v "^[[:blank:]]*(#|$)"
should filter out both comments and empty lines, as is frequently useful.
For information about [:blank:]
and other character classes, refer to https://en.wikipedia.org/wiki/Regular_expression#Character_classes.
If you're really lucky, like I was, you can go back into your text editor and hit 'undo'.
I know that's not really a proper answer, but it saved me half a day's work so hopefully it'll do the same for someone else!
var iDiv = document.createElement('div'),
jDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';
jDiv.className = 'block-2';
iDiv.appendChild(jDiv);
document.getElementsByTagName('body')[0].appendChild(iDiv);
If you have to use an image as the transparent background, you might be able to work around it using a pseudo element:
html
<div class="wrap">
<p>I have 100% opacity</p>
</div>
css
.wrap, .wrap > * {
position: relative;
}
.wrap:before {
content: " ";
opacity: 0.2;
background: url("http://placehold.it/100x100/FF0000") repeat;
position: absolute;
width: 100%;
height: 100%;
}
colection view exam
#import "CollectionViewController.h"
#import "BuyViewController.h"
#import "CollectionViewCell.h"
@interface CollectionViewController ()
{
NSArray *mobiles;
NSArray *costumes;
NSArray *shoes;
NSInteger selectpath;
NSArray *mobilerate;
NSArray *costumerate;
NSArray *shoerate;
}
@end
@implementation CollectionViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = self.receivename;
mobiles = [[NSArray alloc]initWithObjects:@"7.jpg",@"6.jpg",@"5.jpg", nil];
costumes = [[NSArray alloc]initWithObjects:@"shirt.jpg",@"costume2.jpg",@"costume1.jpg", nil];
shoes = [[NSArray alloc]initWithObjects:@"shoe.jpg",@"shoe1.jpg",@"shoe2.jpg", nil];
mobilerate = [[NSArray alloc]initWithObjects:@"10000",@"11000",@"13000",nil];
costumerate = [[NSArray alloc]initWithObjects:@"699",@"999",@"899", nil];
shoerate = [[NSArray alloc]initWithObjects:@"599",@"499",@"300", nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 3;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellId = @"cell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
UIImageView *collectionImg = (UIImageView *)[cell viewWithTag:100];
if ([self.receivename isEqualToString:@"Mobiles"])
{
collectionImg.image = [UIImage imageNamed:[mobiles objectAtIndex:indexPath.row]];
}
else if ([self.receivename isEqualToString:@"Costumes"])
{
collectionImg.image = [UIImage imageNamed:[costumes objectAtIndex:indexPath.row]];
}
else
{
collectionImg.image = [UIImage imageNamed:[shoes objectAtIndex:indexPath.row]];
}
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
selectpath = indexPath.row;
[self performSegueWithIdentifier:@"buynow" sender:self];
}
// In a storyboard-based application, you will often want to do a little
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"buynow"])
{
BuyViewController *obj = segue.destinationViewController;
if ([self.receivename isEqualToString:@"Mobiles"])
{
obj.reciveimg = [mobiles objectAtIndex:selectpath];
obj.labelrecive = [mobilerate objectAtIndex:selectpath];
}
else if ([self.receivename isEqualToString:@"Costumes"])
{
obj.reciveimg = [costumes objectAtIndex:selectpath];
obj.labelrecive = [costumerate objectAtIndex:selectpath];
}
else
{
obj.reciveimg = [shoes objectAtIndex:selectpath];
obj.labelrecive = [shoerate objectAtIndex:selectpath];
}
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
}
@end
.h file
@interface CollectionViewController :
UIViewController<UICollectionViewDelegate,UICollectionViewDataSource>
@property (strong, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong,nonatomic) NSString *receiveimg;
@property (strong,nonatomic) NSString *receivecostume;
@property (strong,nonatomic)NSString *receivename;
@end
On MAC OS X(/BSD): you can try to use the lsof (list open files) command
$ sudo lsof -nPi -sTCP:LISTEN
and so
$ kill -9 3320
You can simply call setTimeout at the end of the function. This will add it again to the event queue. You can use any kind of logic to vary the delay values. For example,
function multiStep() {
// do some work here
blah_blah_whatever();
var newtime = 60000;
if (!requestStop) {
setTimeout(multiStep, newtime);
}
}
Here is a simple function which does exactly this :
#include <windows.h>
#include <string>
bool dirExists(const std::string& dirName_in)
{
DWORD ftyp = GetFileAttributesA(dirName_in.c_str());
if (ftyp == INVALID_FILE_ATTRIBUTES)
return false; //something is wrong with your path!
if (ftyp & FILE_ATTRIBUTE_DIRECTORY)
return true; // this is a directory!
return false; // this is not a directory!
}
Couple of things to try...
Comment out the second "Set NewBook" line of code...
You already have an object reference to the workbook.
Do your SaveAs after copying the sheets.
For those who are using TypeScript
, it's caused by incremental
option in the compilerOptions
of your settings.
This causes to build tsconfig.tsbuildinfo
file which stores all the data for cache. If you remove that file and recompile the project it should work straight away.
you have to use self as the first parameters of a method
in the second case you should use
class MathOperations:
def testAddition (self,x, y):
return x + y
def testMultiplication (self,a, b):
return a * b
and in your code you could do the following
tmp = MathOperations
print tmp.testAddition(2,3)
if you use the class without instantiating a variable first
print MathOperation.testAddtion(2,3)
it gives you an error "TypeError: unbound method"
if you want to do that you will need the @staticmethod
decorator
For example:
class MathsOperations:
@staticmethod
def testAddition (x, y):
return x + y
@staticmethod
def testMultiplication (a, b):
return a * b
then in your code you could use
print MathsOperations.testAddition(2,3)
This usually happens to me when I forget to change the company to match mine.
When you create a new app, it usually says, "com.yourcompany". Change it to whatever you registered with, in my case com.DavidKanarek
@interface UIDevice (Screen)
typedef enum
{
iPhone = 1 << 1,
iPhoneRetina = 1 << 2,
iPhone5 = 1 << 3,
iPad = 1 << 4,
iPadRetina = 1 << 5
} DeviceType;
+ (DeviceType)deviceType;
@end
.m
#import "UIDevice+Screen.h"
@implementation UIDevice (Screen)
+ (DeviceType)deviceType
{
DeviceType thisDevice = 0;
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
{
thisDevice |= iPhone;
if ([[UIScreen mainScreen] respondsToSelector: @selector(scale)])
{
thisDevice |= iPhoneRetina;
if ([[UIScreen mainScreen] bounds].size.height == 568)
thisDevice |= iPhone5;
}
}
else
{
thisDevice |= iPad;
if ([[UIScreen mainScreen] respondsToSelector: @selector(scale)])
thisDevice |= iPadRetina;
}
return thisDevice;
}
@end
This way, if you want to detect whether it is just an iPhone or iPad (regardless of screen-size), you just use:
if ([UIDevice deviceType] & iPhone)
or
if ([UIDevice deviceType] & iPad)
If you want to detect just the iPhone 5, you can use
if ([UIDevice deviceType] & iPhone5)
As opposed to Malcoms answer where you would need to check just to figure out if it's an iPhone,
if ([UIDevice currentResolution] == UIDevice_iPhoneHiRes ||
[UIDevice currentResolution] == UIDevice_iPhoneStandardRes ||
[UIDevice currentResolution] == UIDevice_iPhoneTallerHiRes)`
Neither way has a major advantage over one another, it is just a personal preference.
Try This...
Go to your notification area in the taskbar.
Right click on Bluestacks Agent>Rotate Portrait Apps>Enabled.
There are several options available..
a. Automatic - Selected By Default - It will rotate the app player in portrait mode for portrait apps.
b. Disabled - It will force the portrait apps to work in landscape mode.
c. Enabled - It will force the portrait apps to work in portrait mode only.
This May help you..
How if you want to watch a property for a while and then to un-watch it?
Or to watch a library child component property?
You can use the "dynamic watcher":
this.$watch(
'object.property', //what you want to watch
(newVal, oldVal) => {
//execute your code here
}
)
The $watch
returns an unwatch function which will stop watching if it is called.
var unwatch = vm.$watch('a', cb)
// later, teardown the watcher
unwatch()
Also you can use the deep
option:
this.$watch(
'someObject', () => {
//execute your code here
},
{ deep: true }
)
Please make sure to take a look to docs
Tried many method above and adding forward slash /
to the end of key name, to create directory didn't work for me:
client.put_object(Bucket="foo-bucket", Key="test-folder/")
You have to supply Body
parameter in order to create directory:
client.put_object(Bucket='foo-bucket',Body='', Key='test-folder/')
Source: ryantuck in boto3 issue
CGContextSetFillColorWithColor(context,[[UIColor colorWithRed:(255/255.f) green:(0/255.f) blue: (0/255.f) alpha:1] CGColor]);
A Python 2+3 compatible solution is:
import sys
if sys.version_info[0] >= 3:
from urllib.request import urlretrieve
else:
# Not Python 3 - today, it is most likely to be Python 2
# But note that this might need an update when Python 4
# might be around one day
from urllib import urlretrieve
# Get file from URL like this:
urlretrieve("http://www-scf.usc.edu/~chiso/oldspice/m-b1-hello.mp3")
EDIT: A more structured approach, including all escape sequences for string
s and char
s.
Doesn't replace unicode characters with their literal equivalent.
Doesn't cook eggs, either.
public class ReplaceString
{
static readonly IDictionary<string, string> m_replaceDict
= new Dictionary<string, string>();
const string ms_regexEscapes = @"[\a\b\f\n\r\t\v\\""]";
public static string StringLiteral(string i_string)
{
return Regex.Replace(i_string, ms_regexEscapes, match);
}
public static string CharLiteral(char c)
{
return c == '\'' ? @"'\''" : string.Format("'{0}'", c);
}
private static string match(Match m)
{
string match = m.ToString();
if (m_replaceDict.ContainsKey(match))
{
return m_replaceDict[match];
}
throw new NotSupportedException();
}
static ReplaceString()
{
m_replaceDict.Add("\a", @"\a");
m_replaceDict.Add("\b", @"\b");
m_replaceDict.Add("\f", @"\f");
m_replaceDict.Add("\n", @"\n");
m_replaceDict.Add("\r", @"\r");
m_replaceDict.Add("\t", @"\t");
m_replaceDict.Add("\v", @"\v");
m_replaceDict.Add("\\", @"\\");
m_replaceDict.Add("\0", @"\0");
//The SO parser gets fooled by the verbatim version
//of the string to replace - @"\"""
//so use the 'regular' version
m_replaceDict.Add("\"", "\\\"");
}
static void Main(string[] args){
string s = "here's a \"\n\tstring\" to test";
Console.WriteLine(ReplaceString.StringLiteral(s));
Console.WriteLine(ReplaceString.CharLiteral('c'));
Console.WriteLine(ReplaceString.CharLiteral('\''));
}
}
This works for MVC 5:
<a href="@Url.Action("ActionName", "ControllerName", new { paramName1 = item.paramValue1, paramName2 = item.paramValue2 })" >
Link text
</a>
The nature of arrays is that their length is immutable. You can't add or delete any of the array items.
You will have to create a new array that is one element shorter and copy the old items to the new array, excluding the element you want to delete.
So it is probably better to use a List instead of an array.
Didn't find any answer using closest()
and I think it's the most simple answer when you don't know how many levels up the required element is, so posting an answer:
You can use the closest()
function combined with selectors to get the first element that matches when traversing upwards from the element:
('#element').closest('div') // returns the innermost 'div' in its parents
('#element').closest('.container') // returns innermost element with 'container' class among parents
('#element').closest('#foo') // returns the closest parent with id 'foo'
What is interrupt ?
An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.
How is it implemented ?
The interrupt mechanism is implemented using an internal flag known as the interrupt status. Invoking Thread.interrupt sets this flag. When a thread checks for an interrupt by invoking the static method Thread.interrupted, interrupt status is cleared. The non-static Thread.isInterrupted, which is used by one thread to query the interrupt status of another, does not change the interrupt status flag.
Quote from Thread.interrupt()
API:
Interrupts this thread. First the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.
If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.
If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.
If this thread is blocked in a Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.
If none of the previous conditions hold then this thread's interrupt status will be set.
Check this out for complete understanding about same :
http://download.oracle.com/javase/tutorial/essential/concurrency/interrupt.html
To avoid syntax errors, be sure to always put BEGIN
and END
after an IF
clause, eg:
IF (@A!= @SA)
BEGIN
--do stuff
END
IF (@C!= @SC)
BEGIN
--do stuff
END
... and so on. This should work as expected. Imagine BEGIN
and END
keyword as the opening and closing bracket, respectively.
It's the comma which is providing that extra white space.
One way is to use the string %
method:
print 'Value is "%d"' % (value)
which is like printf
in C, allowing you to incorporate and format the items after %
by using format specifiers in the string itself. Another example, showing the use of multiple values:
print '%s is %3d.%d' % ('pi', 3, 14159)
For what it's worth, Python 3 greatly improves the situation by allowing you to specify the separator and terminator for a single print
call:
>>> print(1,2,3,4,5)
1 2 3 4 5
>>> print(1,2,3,4,5,end='<<\n')
1 2 3 4 5<<
>>> print(1,2,3,4,5,sep=':',end='<<\n')
1:2:3:4:5<<
In your Page_Load you will want to clear out the normal output and write your own, for example:
string json = "{\"name\":\"Joe\"}";
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(json);
Response.End();
To convert a C# object to JSON you can use a library such as Json.NET.
Instead of getting your .aspx page to output JSON though, consider using a Web Service (asmx) or WCF, both of which can output JSON.
You need to make sure that the exe is in a folder that's on the PATH
environment variable.
You can do this by either installing it into a folder that's already on the PATH
or by adding your folder to the PATH
.
You can have your installer do this - but you will need to restart the machine to make sure it gets picked up.
There you go, this is what I used to fix your problem:
CSS CODE
nav ul { list-style-type: none; }
HTML CODE
<nav>
<ul>
<li><a href="#">Milk</a>
<ul>
<li><a href="#">Goat</a></li>
<li><a href="#">Cow</a></li>
</ul>
</li>
<li><a href="#">Eggs</a>
<ul>
<li><a href="#">Free-range</a></li>
<li><a href="#">Other</a></li>
</ul>
</li>
<li><a href="#">Cheese</a>
<ul>
<li><a href="#">Smelly</a></li>
<li><a href="#">Extra smelly</a></li>
</ul>
</li>
</ul>
</nav>
If you can't edit this part of code where your dict was defined you can still order it at any point in any way you want, like this:
from collections import OrderedDict
order_of_keys = ["key1", "key2", "key3", "key4", "key5"]
list_of_tuples = [(key, your_dict[key]) for key in order_of_keys]
your_dict = OrderedDict(list_of_tuples)
C based languages copy C to some degree. The tm
structure (defined in time.h
) has an integer field tm_mon
with the (commented) range of 0-11.
C based languages start arrays at index 0. So this was convenient for outputting a string in an array of month names, with tm_mon
as the index.
Another way to do this solely with css:
input[type='checkbox'] {
float: left;
width: 20px;
}
input[type='checkbox'] + label {
display: block;
width: 30px;
}
Note that this forces each checkbox and its label onto a separate line, rather than only doing so only when there's overflow.
purrr::flatten_*()
is also a good option. the flatten_*
functions add thin sanity checks and ensure type safety.
myList <- list('A'=1, 'B'=2, 'C'=3)
purrr::flatten_dbl(myList)
## [1] 1 2 3
Use AdapterDataObserver in custom RecyclerView
Kotlin:
RecyclerViewEnum.kt
enum class RecyclerViewEnum {
LOADING,
NORMAL,
EMPTY_STATE
}
RecyclerViewEmptyLoadingSupport.kt
class RecyclerViewEmptyLoadingSupport : RecyclerView {
var stateView: RecyclerViewEnum? = RecyclerViewEnum.LOADING
set(value) {
field = value
setState()
}
var emptyStateView: View? = null
var loadingStateView: View? = null
constructor(context: Context) : super(context) {}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {}
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {}
private val dataObserver = object : AdapterDataObserver() {
override fun onChanged() {
onChangeState()
}
override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
super.onItemRangeRemoved(positionStart, itemCount)
onChangeState()
}
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
super.onItemRangeInserted(positionStart, itemCount)
onChangeState()
}
}
override fun setAdapter(adapter: RecyclerView.Adapter<*>?) {
super.setAdapter(adapter)
adapter?.registerAdapterDataObserver(dataObserver)
dataObserver.onChanged()
}
fun onChangeState() {
if (adapter?.itemCount == 0) {
emptyStateView?.visibility = View.VISIBLE
loadingStateView?.visibility = View.GONE
[email protected] = View.GONE
} else {
emptyStateView?.visibility = View.GONE
loadingStateView?.visibility = View.GONE
[email protected] = View.VISIBLE
}
}
private fun setState() {
when (this.stateView) {
RecyclerViewEnum.LOADING -> {
loadingStateView?.visibility = View.VISIBLE
[email protected] = View.GONE
emptyStateView?.visibility = View.GONE
}
RecyclerViewEnum.NORMAL -> {
loadingStateView?.visibility = View.GONE
[email protected] = View.VISIBLE
emptyStateView?.visibility = View.GONE
}
RecyclerViewEnum.EMPTY_STATE -> {
loadingStateView?.visibility = View.GONE
[email protected] = View.GONE
emptyStateView?.visibility = View.VISIBLE
}
}
}
}
layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="@+id/emptyView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/emptyLabelTv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="empty" />
</LinearLayout>
<LinearLayout
android:id="@+id/loadingView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:gravity="center"
android:orientation="vertical">
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_gravity="center"
android:indeterminate="true"
android:theme="@style/progressBarBlue" />
</LinearLayout>
<com.peeyade.components.recyclerView.RecyclerViewEmptyLoadingSupport
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
in activity use this way:
recyclerView?.apply {
layoutManager = GridLayoutManager(context, 2)
emptyStateView = emptyView
loadingStateView = loadingView
adapter = adapterGrid
}
// you can set LoadingView or emptyView manual
recyclerView.stateView = RecyclerViewEnum.EMPTY_STATE
recyclerView.stateView = RecyclerViewEnum.LOADING
If you are in taxonomy page.
That's how you get all details about the taxonomy.
get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
This is how you get the taxonomy id
$termId = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) )->term_id;
But if you are in post page (taxomony -> child)
$terms = wp_get_object_terms( get_queried_object_id(), 'taxonomy-name');
$term_id = $terms[0]->term_id;
If it were me, I'd put the EXE file in the root directory (C:) and see if it works like that. If so, it's probably the (already mentioned) spaces in the directory name. If not, it may be some environment variables.
Also, try to check you stderr (using an earlier answer by int3):
import subprocess
process = subprocess.Popen(["C:/Documents and Settings/flow_model/flow.exe"], \
stderr = subprocess.PIPE)
if process.stderr:
print process.stderr.readlines()
The code might not be entirely correct as I usually don't use Popen or Windows, but should give the idea. It might well be that the error message is on the error stream.
I know this is too old, but, just i case someone gets to this question from Google now, you can install it by typing apt-get install phantomjs
have you tried:
$("#yourAnchor").click(function () {
$("#yourTextarea").val("your text");
});
not sure about autohighlighting, though.
EDIT:
To append:
$("#yourAnchor").click(function () {
$("#yourTextarea").append("your text to append");
});
you can do it so simple:
First: For Example in Models you have User.cs with this implementation
public class User
{
public string username { get; set; }
public string age { get; set; }
}
We are passing the empty model to user – This model would be filled with user’s data when he submits the form like this
public ActionResult Add()
{
var model = new User();
return View(model);
}
When you return the View by empty User as model, it maps with the structure of the form that you implemented. We have this on HTML side:
@model MyApp.Models.Student
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Student</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.username, htmlAttributes: new {
@class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.username, new {
htmlAttributes = new { @class = "form-
control" } })
@Html.ValidationMessageFor(model => model.userame, "",
new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.age, htmlAttributes: new { @class
= "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.age, new { htmlAttributes =
new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.age, "", new {
@class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default"
/>
</div>
</div>
</div>
}
So on button submit you will use it like this
[HttpPost]
public ActionResult Add(User user)
{
// now user.username has the value that user entered on form
}
select object_name(c.object_id) as table_name
, schema_name(t.schema_id) as schema_name
from sys.columns c
join sys.tables t on c.object_id = t.object_id
where c.name=N'CreatedDate';
It gets a little more complicated if you want alsoother table properties, but you'll refer to the object catalog views like sys.tables, sys.columns etc.
Since my tableView
is full of all kinds of insets, this was the only thing that worked well:
Swift 3
if tableView.numberOfSections > 0 && tableView.numberOfRows(inSection: 0) > 0 {
tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
}
Swift 2
if tableView.numberOfSections > 0 && tableView.numberOfRowsInSection(0) > 0 {
tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: .Top, animated: true)
}
I know this is old post but I struggled today with this problem also and I used template from this page: http://maven.apache.org/plugins/maven-dependency-plugin/usage.html
<project>
[...]
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.7</version>
<executions>
<execution>
<id>copy</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>[ groupId ]</groupId>
<artifactId>[ artifactId ]</artifactId>
<version>[ version ]</version>
<type>[ packaging ]</type>
<classifier> [classifier - optional] </classifier>
<overWrite>[ true or false ]</overWrite>
<outputDirectory>[ output directory ]</outputDirectory>
<destFileName>[ filename ]</destFileName>
</artifactItem>
</artifactItems>
<!-- other configurations here -->
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
[...]
</project>
and everything works fine under m2e
1.3.1.
When I tried to use
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.4</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/dependencies</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
I also got m2e
error.
you can use ES6 back quits
var inputs = [_x000D_
`<input type='checkbox' id='chbox0' onclick='checkboxChecked(this);'> <input type='text' class='noteinputs0'id='note` + 0 + `' placeholder='task0'><button id='notebtn0' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 1 + `' placeholder='task1'><button class='notebuttons' id='notebtn1' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 2 + `' placeholder='task2'><button class='notebuttons' id='notebtn2' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 3 + `' placeholder='task3'><button class='notebuttons' id='notebtn3' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 4 + `' placeholder='task4'><button class='notebuttons' id='notebtn4' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 5 + `' placeholder='task5'><button class='notebuttons' id='notebtn5' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 6 + `' placeholder='task6'><button class='notebuttons' id='notebtn6' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 7 + `' placeholder='task7'><button class='notebuttons' id='notebtn7' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 8 + `' placeholder='task8'><button class='notebuttons' id='notebtn8' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 9 + `' placeholder='task9'><button class='notebuttons' id='notebtn9' >creat</button>`_x000D_
].sort().join(" ");_x000D_
document.querySelector('#hi').innerHTML += `<br>` +inputs;
_x000D_
<div id="hi"></div>
_x000D_
Yes. With gjson all you have to do now is:
bar := gjson.Get(json, "foo.bar")
bar
could be a struct property if you like. Also, no maps.
You just need to use Dispatcher to perform graphical operation from a thread other then UI thread. I don't think that this will affect behavior of the main form. This may help you : Accessing UI Control from BackgroundWorker Thread
You have an array, convert it to an object, something like:
data: [{"id": 3636, "is_default": true, "name": "Unit", "quantity": 1, "stock": "100000.00", "unit_cost": "0"}, {"id": 4592, "is_default": false, "name": "Bundle", "quantity": 5, "stock": "100000.00", "unit_cost": "0"}]
Quote from the documentation:
The "standard" and "singleTop" modes differ from each other in just one respect: Every time there's new intent for a "standard" activity, a new instance of the class is created to respond to that intent. Each instance handles a single intent. Similarly, a new instance of a "singleTop" activity may also be created to handle a new intent. However, if the target task already has an existing instance of the activity at the top of its stack, that instance will receive the new intent (in an onNewIntent() call); a new instance is not created.
I'm not 100% sure what "already has an existing instance of the activity at the top of its stack" means, but perhaps your activity isn't meeting this condition.
Would singleTask
or singleInstance
work for you? Or perhaps you could try setting FLAG_ACTIVITY_SINGLE_TOP
on the intent you are creating to see if that makes a difference, although I don't think it will.
And as an addendum to all answers, FYI: override
is not a keyword, but a special kind of identifier! It has meaning only in the context of declaring/defining virtual functions, in other contexts it's just an ordinary identifier. For details read 2.11.2 of The Standard.
#include <iostream>
struct base
{
virtual void foo() = 0;
};
struct derived : base
{
virtual void foo() override
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
};
int main()
{
base* override = new derived();
override->foo();
return 0;
}
Output:
zaufi@gentop /work/tests $ g++ -std=c++11 -o override-test override-test.cc
zaufi@gentop /work/tests $ ./override-test
virtual void derived::foo()
If you want to turn off app verification programmatically, you can do so with the following code:
boolean success = true;
boolean enabled = Settings.Secure.getInt(context.getContentResolver(), "package_verifier_enable", 1) == 1;
if (enabled) {
success = Settings.Secure.putString(context.getContentResolver(), "package_verifier_enable", "0");
}
You will also need the following system permissions:
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
Also worth noting is that the "package_verifier_enable" string comes from the Settings.Glabal.PACKAGE_VERIFIER_ENABLE
member which seems to be inaccessible.
Either bind the global Math object onto the scope (remember to use $window not window)
$scope.abs = $window.Math.abs;
Use the binding in your HTML:
<p>Distance from zero: {{abs(distance)}}</p>
Or create a filter for the specific Math function you're after:
module.filter('abs', ['$window', function($window) {
return function(n) {
return $window.Math.abs($window.parseInt(n));
};
});
Use the filter in your HTML:
<p>Distance from zero: {{distance | abs}}</p>
I have the same problem and I followed this Post, it solved my problem.
Follow the following 2 steps:
-O0
-ggdb
flag when compiling your programGood luck!
I encountered this problem today and eventually I realize it was the comment on the line before the mysql dll's that was causing the problem.
This is what you should have in php.ini by default for PHP 5.5.16:
;extension=php_exif.dll Must be after mbstring as it depends on it
;extension=php_mysql.dll
;extension=php_mysqli.dll
Besides removing the semi-colons, you also need to delete the line of comment that came after php_exif.dll. This leaves you with
extension=php_exif.dll
extension=php_mysql.dll
extension=php_mysqli.dll
This solves the problem in my case.
If you are using Spring 3.2.x and <mvc:annotation-driven />
, create this little BeanPostProcessor
:
package spring;
public final class DoNotTruncateMyUrls implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof RequestMappingHandlerMapping) {
((RequestMappingHandlerMapping)bean).setUseSuffixPatternMatch(false);
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
Then put this in your MVC config xml:
<bean class="spring.DoNotTruncateMyUrls" />
Using file extension and getimagesize
function to detect if uploaded file has right format is just the entry level check and it can simply bypass by uploading a file with true extension and some byte of an image header but wrong content.
for being secure and safe you may make thumbnail/resize (even with original image sizes) the uploaded picture and save this version instead the uploaded one.
Also its possible to get uploaded file content and search it for special character like <?php
to find the file is image or not.
Adding skipLibCheck: true
in compilerOptions
inside tsconfig.json
file fixed my issue.
"compilerOptions": {
"skipLibCheck": true,
},
The solution I end up using most is based off of Tomas Petricek's answer. I usually want to do something with both the attribute and property.
var props = from p in this.GetType().GetProperties()
let attr = p.GetCustomAttributes(typeof(MyAttribute), true)
where attr.Length == 1
select new { Property = p, Attribute = attr.First() as MyAttribute};
"How does
this
and$scope
work in AngularJS controllers?"
Short answer:
this
this
is the controller.$scope
object is called, this
is the "scope in effect when the function was called". This may (or may not!) be the $scope
that the function is defined on. So, inside the function, this
and $scope
may not be the same.$scope
$scope
object.$scope
.$scope
object (and parent scope objects, if prototypical inheritance is in play) are accessible from the HTML/view. E.g., from ng-click
, filters, etc.Long answer:
A controller function is a JavaScript constructor function. When the constructor function executes (e.g., when a view loads), this
(i.e., the "function context") is set to the controller object. So in the "tabs" controller constructor function, when the addPane function is created
this.addPane = function(pane) { ... }
it is created on the controller object, not on $scope. Views cannot see the addPane function -- they only have access to functions defined on $scope. In other words, in the HTML, this won't work:
<a ng-click="addPane(newPane)">won't work</a>
After the "tabs" controller constructor function executes, we have the following:
The dashed black line indicates prototypal inheritance -- an isolate scope prototypically inherits from Scope. (It does not prototypically inherit from the scope in effect where the directive was encountered in the HTML.)
Now, the pane directive's link function wants to communicate with the tabs directive (which really means it needs to affect the tabs isolate $scope in some way). Events could be used, but another mechanism is to have the pane directive require
the tabs controller. (There appears to be no mechanism for the pane directive to require
the tabs $scope.)
So, this begs the question: if we only have access to the tabs controller, how do we get access to the tabs isolate $scope (which is what we really want)?
Well, the red dotted line is the answer. The addPane() function's "scope" (I'm referring to JavaScript's function scope/closures here) gives the function access to the tabs isolate $scope. I.e., addPane() has access to the "tabs IsolateScope" in the diagram above because of a closure that was created when addPane() was defined. (If we instead defined addPane() on the tabs $scope object, the pane directive would not have access to this function, and hence it would have no way to communicate with the tabs $scope.)
To answer the other part of your question: how does $scope work in controllers?
:
Within functions defined on $scope, this
is set to "the $scope in effect where/when the function was called". Suppose we have the following HTML:
<div ng-controller="ParentCtrl">
<a ng-click="logThisAndScope()">log "this" and $scope</a> - parent scope
<div ng-controller="ChildCtrl">
<a ng-click="logThisAndScope()">log "this" and $scope</a> - child scope
</div>
</div>
And the ParentCtrl
(Solely) has
$scope.logThisAndScope = function() {
console.log(this, $scope)
}
Clicking the first link will show that this
and $scope
are the same, since "the scope in effect when the function was called" is the scope associated with the ParentCtrl
.
Clicking the second link will reveal this
and $scope
are not the same, since "the scope in effect when the function was called" is the scope associated with the ChildCtrl
. So here, this
is set to ChildCtrl
's $scope
. Inside the method, $scope
is still the ParentCtrl
's $scope.
I try to not use this
inside of a function defined on $scope, as it becomes confusing which $scope is being affected, especially considering that ng-repeat, ng-include, ng-switch, and directives can all create their own child scopes.
Simple solution:
/\s{2,}/
This matches all occurrences of one or more whitespace characters. If you need to match the entire line, but only if it contains two or more consecutive whitespace characters:
/^.*\s{2,}.*$/
If the whitespaces don't need to be consecutive:
/^(.*\s.*){2,}$/
Look at this one: Convert List/IEnumerable to DataTable/DataView
In my code I changed it into a extension method:
public static DataTable ToDataTable<T>(this List<T> items)
{
var tb = new DataTable(typeof(T).Name);
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach(var prop in props)
{
tb.Columns.Add(prop.Name, prop.PropertyType);
}
foreach (var item in items)
{
var values = new object[props.Length];
for (var i=0; i<props.Length; i++)
{
values[i] = props[i].GetValue(item, null);
}
tb.Rows.Add(values);
}
return tb;
}
A simple way to see the Git commit short version and the Git commit message is:
git log --oneline
Note that this is shorthand for
git log --pretty=oneline --abbrev-commit
For me, I had to have OpenCV (3.4.2), Py-OpenCV (3.4.2), LibOpenCV (3.4.2).
My Python was version 3.5.6 with Anaconda in Windows OS 10.
Darrel is of course right on with his response. One thing to add is that the reason why attempting to bind to a body containing a single token like "hello".
is that it isn’t quite URL form encoded data. By adding “=” in front like this:
=hello
it becomes a URL form encoding of a single key value pair with an empty name and value of “hello”.
However, a better solution is to use application/json when uploading a string:
POST /api/sample HTTP/1.1
Content-Type: application/json; charset=utf-8
Host: host:8080
Content-Length: 7
"Hello"
Using HttpClient you can do it as follows:
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsJsonAsync(_baseAddress + "api/json", "Hello");
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
Henrik
I had the same problem as Marko and come across a solution like this:
/*Create a Table*/
CREATE TABLE tableGrandTotal
(
columnGrandtotal int
)
/*Create a Stored Procedure*/
CREATE PROCEDURE GetGrandTotal
AS
/*Delete the 'tableGrandTotal' table for another usage of the stored procedure*/
DROP TABLE tableGrandTotal
/*Create a new Table which will include just one column*/
CREATE TABLE tableGrandTotal
(
columnGrandtotal int
)
/*Insert the query which returns subtotal for each orderitem row into tableGrandTotal*/
INSERT INTO tableGrandTotal
SELECT oi.Quantity * p.Price AS columnGrandTotal
FROM OrderItem oi
JOIN Product p ON oi.Id = p.Id
/*And return the sum of columnGrandTotal from the newly created table*/
SELECT SUM(columnGrandTotal) as [Grand Total]
FROM tableGrandTotal
And just simply use the GetGrandTotal Stored Procedure to retrieve the Grand Total :)
EXEC GetGrandTotal
typeOf is a C# keyword that is used when you have the name of the class. It is calculated at compile time and thus cannot be used on an instance, which is created at runtime. GetType is a method of the object class that can be used on an instance.
This one is ugly, but just want to throw there some other options to the mix. This one has no loops. I use it for debugging purposes
var myObject = {a:1,b:2,c:3,d:{a:1,b:2,c:3,e:{a:1}}}
var myStrObj = JSON.stringify(myObject)
var myHtmlTableObj = myStrObj.replace(/{/g,"<table><tr><td>").replace(/:/g,"</td><td>","g").replace(/,/g,"</td></tr><tr><td>","g").replace(/}/g,"</table>")
$('#myDiv').html(myHtmlTableObj)
Example:
var myObject = {a:1,b:2,c:3,d:{a:1,b:2,c:3,e:{a:1}}}_x000D_
var myStrObj = JSON.stringify(myObject)_x000D_
var myHtmlTableObj = myStrObj.replace(/\"/g,"").replace(/{/g,"<table><tr><td>").replace(/:/g,"</td><td>","g").replace(/,/g,"</td></tr><tr><td>","g").replace(/}/g,"</table>")_x000D_
_x000D_
$('#myDiv').html(myHtmlTableObj)
_x000D_
#myDiv table td{background:whitesmoke;border:1px solid lightgray}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<div id='myDiv'>table goes here</div>
_x000D_
You can actually add a key pair through the elastic beanstalk config page. it then restarts your instance for you and everything works.
Not Bootstrap specific really... You can use inline styles or define a custom class to specify the desired "background-color".
On the other hand, Bootstrap does have a few built in background colors that have semantic meaning like "bg-success" (green) and "bg-danger" (red).
I hope my late answer can be of some help.
This will go to rails database console.
rails db
pretty print your query output
.headers on
.mode columns
(turn headers on and show database data in column mode )
Show the tables
.table
'.help' to see help.
Or use SQL statements like 'Select * from cars'
comment on the "private constructor" arguments: come on, developers are not that stupid; but they ARE lazy. creating an object then call static methods? not gonna happen.
don't spend too much time to make sure your class cannot be misused. have some faith for your colleagues. and there is always a way to misuse your class no matter how you protect it. the only thing that cannot be misused is a thing that is completely useless.
Thanks to kind and patient help from golang-nuts, recipe is the following:
1) One needs to compile Go compiler for different target platforms and architectures. This is done from src folder in go installation. In my case Go installation is located in /usr/local/go
thus to compile a compiler you need to issue make
utility. Before doing this you need to know some caveats.
There is an issue about CGO library when cross compiling so it is needed to disable CGO library.
Compiling is done by changing location to source dir, since compiling has to be done in that folder
cd /usr/local/go/src
then compile the Go compiler:
sudo GOOS=windows GOARCH=386 CGO_ENABLED=0 ./make.bash --no-clean
You need to repeat this step for each OS and Architecture you wish to cross compile by changing the GOOS and GOARCH parameters.
If you are working in user mode as I do, sudo is needed because Go compiler is in the system dir. Otherwise you need to be logged in as super user. On Mac you may need to enable/configure SU access (it is not available by default), but if you have managed to install Go you possibly already have root access.
2) Once you have all cross compilers built, you can happily cross compile your application by using the following settings for example:
GOOS=windows GOARCH=386 go build -o appname.exe appname.go
GOOS=linux GOARCH=386 CGO_ENABLED=0 go build -o appname.linux appname.go
Change the GOOS and GOARCH to targets you wish to build.
If you encounter problems with CGO include CGO_ENABLED=0 in the command line. Also note that binaries for linux and mac have no extension so you may add extension for the sake of having different files. -o switch instructs Go to make output file similar to old compilers for c/c++ thus above used appname.linux can be any other extension.
As with all css properties that contain hyphens, their corresponding names in JS is to remove the hyphen and make the following letter capital: backgroundColor
alert(myDiv.style.backgroundColor);
it takes this command about 2 mins to return the data as there is a lot of data
Probably, Bad Design. Consider using paging here.
default connection time is 30 secs, how do I increase this
As you are facing a timeout on your command, therefore you need to increase the timeout of your sql command. You can specify it in your command like this
// Setting command timeout to 2 minutes
scGetruntotals.CommandTimeout = 120;
All solutions including the accepted one have some issues as stated in their respective comments. The accepted answer by @jonathan-leffler is already quite good but does not take into effect that prerequisites are not necessarily to be built in order (during make -j
for example). However simply moving the directories
prerequisite from all
to program
provokes rebuilds on every run AFAICT.
The following solution does not have that problem and AFAICS works as intended.
MKDIR_P := mkdir -p
OUT_DIR := build
.PHONY: directories all clean
all: $(OUT_DIR)/program
directories: $(OUT_DIR)
$(OUT_DIR):
${MKDIR_P} $(OUT_DIR)
$(OUT_DIR)/program: | directories
touch $(OUT_DIR)/program
clean:
rm -rf $(OUT_DIR)
Note that the bb.array() doesn't honor the byte-buffers position, and might be even worse if the bytebuffer you are working on is a slice of some other buffer.
I.e.
byte[] test = "Hello World".getBytes("Latin1");
ByteBuffer b1 = ByteBuffer.wrap(test);
byte[] hello = new byte[6];
b1.get(hello); // "Hello "
ByteBuffer b2 = b1.slice(); // position = 0, string = "World"
byte[] tooLong = b2.array(); // Will NOT be "World", but will be "Hello World".
byte[] world = new byte[5];
b2.get(world); // world = "World"
Which might not be what you intend to do.
If you really do not want to copy the byte-array, a work-around could be to use the byte-buffer's arrayOffset() + remaining(), but this only works if the application supports index+length of the byte-buffers it needs.
You could set the @Input
on the setter directly, as described below:
_allowDay: boolean;
get allowDay(): boolean {
return this._allowDay;
}
@Input() set allowDay(value: boolean) {
this._allowDay = value;
this.updatePeriodTypes();
}
See this Plunkr: https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p?p=preview.
This is working perfect:
PD: Remember to import the destination VC:
#import "DestinationVCName.h"
- (IBAction)NameOfTheAction:(id)sender
{
DestinationVCName *destinationvcname = [self.storyboard instantiateViewControllerWithIdentifier:@"DestinationVCName"];
[self presentViewController:destinationvcname animated:YES completion:nil];
}
Here is an example code. Put this into your activity class:
/* put this into your activity class */
private SensorManager mSensorManager;
private float mAccel; // acceleration apart from gravity
private float mAccelCurrent; // current acceleration including gravity
private float mAccelLast; // last acceleration including gravity
private final SensorEventListener mSensorListener = new SensorEventListener() {
public void onSensorChanged(SensorEvent se) {
float x = se.values[0];
float y = se.values[1];
float z = se.values[2];
mAccelLast = mAccelCurrent;
mAccelCurrent = (float) Math.sqrt((double) (x*x + y*y + z*z));
float delta = mAccelCurrent - mAccelLast;
mAccel = mAccel * 0.9f + delta; // perform low-cut filter
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
mSensorManager.unregisterListener(mSensorListener);
super.onPause();
}
And add this to your onCreate method:
/* do this in onCreate */
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
mAccel = 0.00f;
mAccelCurrent = SensorManager.GRAVITY_EARTH;
mAccelLast = SensorManager.GRAVITY_EARTH;
You can then ask "mAccel" wherever you want in your application for the current acceleration, independent from the axis and cleaned from static acceleration such as gravity. It will be approx. 0 if there is no movement, and, lets say >2 if the device is shaked.
Based on the comments - to test this:
if (mAccel > 12) {
Toast toast = Toast.makeText(getApplicationContext(), "Device has shaken.", Toast.LENGTH_LONG);
toast.show();
}
Notes:
The accelometer should be deactivated onPause and activated onResume to save resources (CPU, Battery). The code assumes we are on planet Earth ;-) and initializes the acceleration to earth gravity. Otherwise you would get a strong "shake" when the application starts and "hits" the ground from free-fall. However, the code gets used to the gravitation due to the low-cut filter and would work also on other planets or in free space, once it is initialized. (you never know how long your application will be in use...;-)
Starting from version 19.1 they have renamed filenames:
? SmartGit grep -rl 'listx' ./19.1
./19.1/preferences.yml
./19.1/.backup/preferences.yml
It is possible to delete them to reset the license setting.
I managed to download the file generated by the rest API URL much easier with this kind of code which worked just fine on my local:
import React, {Component} from "react";
import {saveAs} from "file-saver";
class MyForm extends Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
const form = event.target;
let queryParam = buildQueryParams(form.elements);
let url = 'http://localhost:8080/...whatever?' + queryParam;
fetch(url, {
method: 'GET',
headers: {
// whatever
},
})
.then(function (response) {
return response.blob();
}
)
.then(function(blob) {
saveAs(blob, "yourFilename.xlsx");
})
.catch(error => {
//whatever
})
}
render() {
return (
<form onSubmit={this.handleSubmit} id="whateverFormId">
<table>
<tbody>
<tr>
<td>
<input type="text" key="myText" name="myText" id="myText"/>
</td>
<td><input key="startDate" name="from" id="startDate" type="date"/></td>
<td><input key="endDate" name="to" id="endDate" type="date"/></td>
</tr>
<tr>
<td colSpan="3" align="right">
<button>Export</button>
</td>
</tr>
</tbody>
</table>
</form>
);
}
}
function buildQueryParams(formElements) {
let queryParam = "";
//do code here
return queryParam;
}
export default MyForm;
There is an .Offset property on a Range class which allows you to do just what you need
ActiveCell.Offset(numRows, numCols)
follow up on a comment:
Dim newRange as Range
Set newRange = Range(ActiveCell, ActiveCell.Offset(numRows, numCols))
and you can verify by MsgBox newRange.Address
The MySQL extension:
Since it is deprecated, using it makes your code less future proof.
Lack of support for prepared statements is particularly important as they provide a clearer, less error-prone method of escaping and quoting external data than manually escaping it with a separate function call.
I'd just like to add to the very helpful answer from Kurt Pfeifle - there is now a Python wrapper for Tabula, and this seems to work very well so far: https://github.com/chezou/tabula-py
This will convert your PDF table to a Pandas data frame. You can also set the area in x,y co-ordinates which is obviously very handy for irregular data.
I think the easiest way to accomplish it is to use querystring instead of HTTP headers.
Date to LocalDate
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate to Date
LocalDate localDate = LocalDate.now();
Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
(I do realise the question is old, but it's among the top hits on Google.)
A common situation where you want to know the response code is in exception handling. As of C# 7, you can use pattern matching to actually only enter the catch clause if the exception matches your predicate:
catch (WebException ex) when (ex.Response is HttpWebResponse response)
{
doSomething(response.StatusCode)
}
This can easily be extended to further levels, such as in this case where the WebException
was actually the inner exception of another (and we're only interested in 404
):
catch (StorageException ex) when (ex.InnerException is WebException wex && wex.Response is HttpWebResponse r && r.StatusCode == HttpStatusCode.NotFound)
Finally: note how there's no need to re-throw the exception in the catch clause when it doesn't match your criteria, since we don't enter the clause in the first place with the above solution.
function Do-SendKeys {
param (
$SENDKEYS,
$WINDOWTITLE
)
$wshell = New-Object -ComObject wscript.shell;
IF ($WINDOWTITLE) {$wshell.AppActivate($WINDOWTITLE)}
Sleep 1
IF ($SENDKEYS) {$wshell.SendKeys($SENDKEYS)}
}
Do-SendKeys -WINDOWTITLE Print -SENDKEYS '{TAB}{TAB}'
Do-SendKeys -WINDOWTITLE Print
Do-SendKeys -SENDKEYS '%{f4}'
This is what worked for me.
In the Project panel, right click on the project name, and
select Open Module Settings
from the popup menu.
then change the Compile SDK Version
to the minimum version available (the minimum sdk version you set in the project).
wait for android studio to load everything.
It will give you some errors, ignore those.
Now go to your java file and android studio will suggest you import
import android.support.v4.app.FragmentActivity;
Import it, then go back to Open Module Settings
and change the compile sdk version back to what it was before.
Wait for things to load and voila.
Eek, don't do anything that complicated : )
Just filter()
your tags. bool()
returns False
for empty strings, so instead of
new_tag_list = f1.striplist(tag_string.split(",") + selected_tags)
you should write
new_tag_list = filter(bool, f1.striplist(tag_string.split(",") + selected_tags))
or better yet, put this logic inside striplist()
so that it doesn't return empty strings in the first place.
is working but MacOs recently has autoplay policy for user: https://webkit.org/blog/7734/auto-play-policy-changes-for-macos/, I resolved the same issue using a button to enable sound:
ejm:
<video autoplay loop muted id="myVideo">_x000D_
<source src="amazon.mp4" type="video/mp4">_x000D_
Sorry, your browser doesn't support embedded videos..._x000D_
</video>_x000D_
_x000D_
<button class="pausee" onclick="disableMute()" type="button">Enable sound</button>_x000D_
_x000D_
<script>_x000D_
var vid = document.getElementById("myVideo");_x000D_
function disableMute() { _x000D_
vid.muted = false;_x000D_
}_x000D_
</script>
_x000D_
I ended up using a variation of Shawn's solution:
Create a custom UITableView class with a delegate:
protocol CustomTableViewDelegate {
func CustomTableViewDidLayoutSubviews()
}
class CustomTableView: UITableView {
var customDelegate: CustomTableViewDelegate?
override func layoutSubviews() {
super.layoutSubviews()
self.customDelegate?.CustomTableViewDidLayoutSubviews()
}
}
Then in my code, I use
class SomeClass: UIViewController, CustomTableViewDelegate {
@IBOutlet weak var myTableView: CustomTableView!
override func viewDidLoad() {
super.viewDidLoad()
self.myTableView.customDelegate = self
}
func CustomTableViewDidLayoutSubviews() {
print("didlayoutsubviews")
// DO other cool things here!!
}
}
Also make sure you set your table view to CustomTableView in the interface builder:
The last-child
selector is used to select the last child element of a parent. It cannot be used to select the last child element with a specific class under a given parent element.
The other part of the compound selector (which is attached before the :last-child
) specifies extra conditions which the last child element must satisfy in-order for it to be selected. In the below snippet, you would see how the selected elements differ depending on the rest of the compound selector.
.parent :last-child{ /* this will select all elements which are last child of .parent */_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
.parent div:last-child{ /* this will select the last child of .parent only if it is a div*/_x000D_
background: crimson;_x000D_
}_x000D_
_x000D_
.parent div.child-2:last-child{ /* this will select the last child of .parent only if it is a div and has the class child-2*/_x000D_
color: beige;_x000D_
}
_x000D_
<div class='parent'>_x000D_
<div class='child'>Child</div>_x000D_
<div class='child'>Child</div>_x000D_
<div class='child'>Child</div>_x000D_
<div>Child w/o class</div>_x000D_
</div>_x000D_
<div class='parent'>_x000D_
<div class='child'>Child</div>_x000D_
<div class='child'>Child</div>_x000D_
<div class='child'>Child</div>_x000D_
<div class='child-2'>Child w/o class</div>_x000D_
</div>_x000D_
<div class='parent'>_x000D_
<div class='child'>Child</div>_x000D_
<div class='child'>Child</div>_x000D_
<div class='child'>Child</div>_x000D_
<p>Child w/o class</p>_x000D_
</div>
_x000D_
To answer your question, the below would style the last child li
element with background color as red.
li:last-child{
background-color: red;
}
But the following selector would not work for your markup because the last-child
does not have the class='complete'
even though it is an li
.
li.complete:last-child{
background-color: green;
}
It would have worked if (and only if) the last li
in your markup also had class='complete'
.
To address your query in the comments:
@Harry I find it rather odd that: .complete:last-of-type does not work, yet .complete:first-of-type does work, regardless of it's position it's parents element. Thanks for your help.
The selector .complete:first-of-type
works in the fiddle because it (that is, the element with class='complete'
) is still the first element of type li
within the parent. Try to add <li>0</li>
as the first element under the ul
and you will find that first-of-type
also flops. This is because the first-of-type
and last-of-type
selectors select the first/last element of each type under the parent.
Refer to the answer posted by BoltClock, in this thread for more details about how the selector works. That is as comprehensive as it gets :)
Here is how you can test if a variable is not NULL:
if (myVar !== null) {...}
the block will be executed if myVar is not null.. it will be executed if myVar is undefined or false or 0
or NaN
or anything else..
I found dotnetperls examples on DataRow
very helpful. Code snippet for new DataTable
from there:
static DataTable GetTable()
{
// Here we create a DataTable with four columns.
DataTable table = new DataTable();
table.Columns.Add("Weight", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Breed", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
// Here we add five DataRows.
table.Rows.Add(57, "Koko", "Shar Pei", DateTime.Now);
table.Rows.Add(130, "Fido", "Bullmastiff", DateTime.Now);
table.Rows.Add(92, "Alex", "Anatolian Shepherd Dog", DateTime.Now);
table.Rows.Add(25, "Charles", "Cavalier King Charles Spaniel", DateTime.Now);
table.Rows.Add(7, "Candy", "Yorkshire Terrier", DateTime.Now);
return table;
}
Microsoft introduced schema in version 2008. For those who didn’t know about schema, and those who didn’t care, objects were put into a default schema dbo
.
dbo
stands for DataBase Owner, but that’s not really important.
Think of a schema as you would a folder for files:
You can always access any object from any schema.
Because dbo
is the default, you normally don’t need to specify it within a single database:
SELECT * FROM customers;
SELECT * FROM dbo.customers;
mean the same thing.
I am inclined to disagree with the notion of always using the dbo.
prefix, since the more you clutter your code with unnecessary detail, the harder it is to read and manage.
For the most part, you can ignore the schema. However, the schema will make itself apparent in the following situations:
If you view the tables in either the object navigator or in an external application, such as Microsoft Excel or Access, you will see the dbo.
prefix. You can still ignore it.
If you reference a table in another database, you will need its full name in the form database.schema.table
:
SELECT * FROM bookshop.dbo.customers;
For historical reasons, if you write a user defined scalar function, you will need to call it with the schema prefix:
CREATE FUNCTION tax(@amount DECIMAL(6,2) RETURNS DECIMAL(6,2) AS
BEGIN
RETURN @amount * 0.1;
END;
GO
SELECT total, dbo.tax(total) FROM pricelist;
This does not apply to other objects, such as table functions, procedures and views.
You can use schema to overcome naming conflicts. For example, if every user has a personal schema, they can create additional objects without having to fight with other users over the name.
void srand (unsigned int seed)
This function establishes seed as the seed for a new series of pseudo-random numbers. If you call rand before a seed has been established with srand, it uses the value 1 as a default seed.
To produce a different pseudo-random series each time your program is run, do srand (time (0))
Function to return stream that contain zip file
public static Stream ZipGenerator(List<string> files)
{
ZipArchiveEntry fileInArchive;
Stream entryStream;
int i = 0;
List<byte[]> byteArray = new List<byte[]>();
foreach (var file in files)
{
byteArray.Add(File.ReadAllBytes(file));
}
var outStream = new MemoryStream();
using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
{
foreach (var file in files)
{
fileInArchive=(archive.CreateEntry(Path.GetFileName(file), CompressionLevel.Optimal));
using (entryStream = fileInArchive.Open())
{
using (var fileToCompressStream = new MemoryStream(byteArray[i]))
{
fileToCompressStream.CopyTo(entryStream);
}
i++;
}
}
}
outStream.Position = 0;
return outStream;
}
If you want , write zip to file stream.
using (var fileStream = new FileStream(@"D:\Tools\DBExtractor\DBExtractor\bin\Debug\test.zip", FileMode.Create))
{
outStream.Position = 0;
outStream.WriteTo(fileStream);
}
`
Best way to design table is add one temporary row as auto increment and keep as primary key. So we can avoid such above issues.
DateTime.Now will not work, use DateTime.Today instead.
You can add/remove Appender programmatically to Log4j:
ConsoleAppender console = new ConsoleAppender(); //create appender
//configure the appender
String PATTERN = "%d [%p|%c|%C{1}] %m%n";
console.setLayout(new PatternLayout(PATTERN));
console.setThreshold(Level.FATAL);
console.activateOptions();
//add appender to any Logger (here is root)
Logger.getRootLogger().addAppender(console);
FileAppender fa = new FileAppender();
fa.setName("FileLogger");
fa.setFile("mylog.log");
fa.setLayout(new PatternLayout("%d %-5p [%c{1}] %m%n"));
fa.setThreshold(Level.DEBUG);
fa.setAppend(true);
fa.activateOptions();
//add appender to any Logger (here is root)
Logger.getRootLogger().addAppender(fa);
//repeat with all other desired appenders
I'd suggest you put it into an init() somewhere, where you are sure, that this will be executed before anything else. You can then remove all existing appenders on the root logger with
Logger.getRootLogger().getLoggerRepository().resetConfiguration();
and start with adding your own. You need log4j in the classpath of course for this to work.
Remark:
You can take any Logger.getLogger(...)
you like to add appenders. I just took the root logger because it is at the bottom of all things and will handle everything that is passed through other appenders in other categories (unless configured otherwise by setting the additivity flag).
If you need to know how logging works and how is decided where logs are written read this manual for more infos about that.
In Short:
Logger fizz = LoggerFactory.getLogger("com.fizz")
will give you a logger for the category "com.fizz".
For the above example this means that everything logged with it will be referred to the console and file appender on the root logger.
If you add an appender to
Logger.getLogger("com.fizz").addAppender(newAppender)
then logging from fizz
will be handled by alle the appenders from the root logger and the newAppender
.
You don't create Loggers with the configuration, you just provide handlers for all possible categories in your system.
You want to follow the same pattern as before:
for (Type curInstance: CollectionOf<Type>) {
// use currInstance
}
In this case it would be:
for (Bullet bullet : gunList.get(2).getBullet()) {
System.out.println(bullet);
}
CSS is the styling language that any browser understands to style webpages.
SCSS is a special type of file for SASS
, a program written in Ruby that assembles CSS
style sheets for a browser, and for information, SASS
adds lots of additional functionality to CSS
like variables, nesting and more which can make writing CSS
easier and faster.
SCSS files are processed by the server running a web app to output a traditional CSS
that your browser can understand.
I recommend you just use the requests module.
It is much easier than the built in http clients: http://docs.python-requests.org/en/latest/index.html
Sample usage:
r = requests.get('http://www.thepage.com', proxies={"http":"http://myproxy:3129"})
thedata = r.content
As a side note processes that uses virtual accounts (NT Service\MyService and IIS AppPool\MyAppPool) are still running under the "NETWORK SERVICE" account as this post suggests http://www.adopenstatic.com/cs/blogs/ken/archive/2008/01/29/15759.aspx. The only difference is that these processes are members of the "NT Service\MyService" or "IIS AppPool\MyAppPool" groups (as these are actually groups and not users). This is also the reason why the processes authenticate at the network as the machine the same way NETWORK SERVICE account does.
The way to secure access is not to depend upon this accounts not having NETWORK SERVICE privileges but to grant more permissions specifically to "NT Service\MyService" or "IIS AppPool\MyAppPool" and to remove permissions for "Users" if necessary.
If anyone has more accurate or contradictional information please post.
that depends on what kind of information are you passing to the conditional..
sometimes your result will be null
or undefined
or ''
or 0
, for my simple validation i use this if.
( $('#id').val() == '0' || $('#id').val() == '' || $('#id').val() == 'undefined' || $('#id').val() == null )
NOTE: null
!= 'null'
I know this is old, but I ran into the same issue. I'm on a Mac/Ubuntu and switch back and forth. What I have found is that just sending a simple interrupt signal to the main R process does exactly what you're looking for. I've ran scripts that went on for as long as 24 hours and the signal interrupt works very well. You should be able to run kill in terminal:
$ kill -2 pid
You can find the pid by running
$ps aux | grep exec/R
Not sure about Windows since I'm not ever on there, but I can't imagine there's not an option to do this as well in Command Prompt/Task Manager
Hope this helps!
Are there other ways?
Negative margins were also used for horizontal (and vertical!) centering but there are quite a few drawbacks when you resize the window browser: no window slider; the content can't be seen anymore if the size of the window browser is too small.
No surprise as it uses absolute positioning, a beast never completely tamed!
Example: http://bluerobot.com/web/css/center2.html
So that was only FYI as you asked for it, margin: 0 auto;
is a better solution.
THIS WORKS GREAT - I tested it so, please SET NAME for every object
give the name to the object upon creation
mesh.name = 'nameMeshObject';
and use this if you have to delete an object
delete3DOBJ('nameMeshObject');
function delete3DOBJ(objName){
var selectedObject = scene.getObjectByName(objName);
scene.remove( selectedObject );
animate();
}
This example from Java Doc helped me understand the concepts clearly:
class Driver { // ...
void main() throws InterruptedException {
CountDownLatch startSignal = new CountDownLatch(1);
CountDownLatch doneSignal = new CountDownLatch(N);
for (int i = 0; i < N; ++i) // create and start threads
new Thread(new Worker(startSignal, doneSignal)).start();
doSomethingElse(); // don't let run yet
startSignal.countDown(); // let all threads proceed
doSomethingElse();
doneSignal.await(); // wait for all to finish
}
}
class Worker implements Runnable {
private final CountDownLatch startSignal;
private final CountDownLatch doneSignal;
Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
this.startSignal = startSignal;
this.doneSignal = doneSignal;
}
public void run() {
try {
startSignal.await();
doWork();
doneSignal.countDown();
} catch (InterruptedException ex) {} // return;
}
void doWork() { ... }
}
Visual interpretation:
Evidently, CountDownLatch
allows one thread (here Driver
) to wait until a bunch of running threads (here Worker
) are done with their execution.
Forget everything. Just use the appcompat library downloaded using the Android Studio. It has all the missing definitions. No matter whether you are using in Eclipse or not.