You can try below code:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim j As Integer = 0
Dim hfc As HttpFileCollection = Request.Files
Dim PathName As String
For i As Integer = 0 To hfc.Count - 1
Dim hpf As HttpPostedFile = hfc(i)
If hpf.ContentLength > 0 Then
hpf.SaveAs(Server.MapPath("~/E:\") & System.IO.Path.GetFileName(hpf.FileName))
PathName = Server.MapPath(hpf.FileName)
If j < hfc.Count Then
Dim strConnString As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
Dim sqlquery As String
sqlquery = "Insert_proc"
Dim con As New SqlConnection(strConnString)
Dim cmd As New SqlCommand(sqlquery, con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("@FilePath", SqlDbType.VarChar).Value = PathName
j = j + 1
Try
con.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Throw ex
Finally
con.Close()
con.Dispose()
End Try
If j = hfc.Count Then
Exit Sub
End If
End If
End If
Next
Catch generatedExceptionName As Exception
Throw
End Try
End Sub
$mylabel.text("-123456");
var string = $mylabel.text().replace('-', '');
if you have done it that way variable string
now holds "123456"
you can also (i guess the better way) do this...
$mylabel.text("-123456");
$mylabel.text(function(i,v){
return v.replace('-','');
});
Python
element.text
Java
element.getText()
C#
element.Text
Ruby
element.text
There is a really nice trick. My problem was that some really old C++ jni library leaked resources. At some point, it stopped functioning. The user tried to exit the app and launch it again -- with no result, because finishing an activity is not the same as finishing (or killing) the process. (By the way, the user could go to the list of the running applications and stop it from there -- this would work, but the users just do not know how to terminate applications.)
If you want to observe the effect of this feature, add a static
variable to your activity and increment it each, say, button press. If you exit the application activity and then invoke the application again, this static variable will keep its value. (If the application really was exited, the variable would be assigned the initial value.)
(And I have to comment on why I did not want to fix the bug instead. The library was written decades ago and leaked resources ever since. The management believes it always worked. The cost of providing a fix instead of a workaround... I think, you get the idea.)
Now, how could I reset a jni shared (a.k.a. dynamic, .so) library to the initial state? I chose to restart application as a new process.
The trick is that System.exit() closes the current activity and Android recreates the application with one activity less.
So the code is:
/** This activity shows nothing; instead, it restarts the android process */
public class MagicAppRestart extends Activity {
// Do not forget to add it to AndroidManifest.xml
// <activity android:name="your.package.name.MagicAppRestart"/>
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.exit(0);
}
public static void doRestart(Activity anyActivity) {
anyActivity.startActivity(new Intent(anyActivity.getApplicationContext(), MagicAppRestart.class));
}
}
The calling activity just executes the code MagicAppRestart.doRestart(this);
, the calling activity's onPause()
is executed, and then the process is re-created. And do not forget to mention this activity in AndroidManifest.xml
The advantage of this method is that there is no delays.
UPD: it worked in Android 2.x, but in Android 4 something has changed.
just another way to do it.
Label lbl = new Label();
new ToolTip().SetToolTip(lbl, "tooltip text here");
>>> class A(object): pass
>>> e = A()
>>> e
<__main__.A object at 0xb6d464ec>
>>> print type(e)
<class '__main__.A'>
>>> print type(e).__name__
A
>>>
what do you mean by convert into a string? you can define your own repr and str_ methods:
>>> class A(object):
def __repr__(self):
return 'hei, i am A or B or whatever'
>>> e = A()
>>> e
hei, i am A or B or whatever
>>> str(e)
hei, i am A or B or whatever
or i dont know..please add explainations ;)
Leaving alone any debates over when (if ever) it should be done, @functions is how you do it.
@functions {
// Add code here.
}
As of 2021 insted of null i had to add {} in order to make it work!
axios.post(
url,
{},
{
params: {
key,
checksum
}
}
)
.then(response => {
return success(response);
})
.catch(error => {
return fail(error);
});
-- TRY THIS --
select name= case when isnumeric(empname)= 1 then 'numeric' else 'notmumeric' end from [Employees]
But conversion is quit impossible
select empname=
case
when isnumeric(empname)= 1 then empname
else 'notmumeric'
end
from [Employees]
Download mingw-get and simply issue:
mingw-get install gcc.
See the Getting Started page.
Your javascript is executed before the HTML is generated, so it doesn't "see" the ungenerated INPUT elements. For jQuery, you would either stick the Javascript at the end of the HTML or wrap it like this:
<script type="text/javascript"> $(function() { //jQuery trick to say after all the HTML is parsed. $("input[type=radio]").click(function() { var total = 0; $("input[type=radio]:checked").each(function() { total += parseFloat($(this).val()); }); $("#totalSum").val(total); }); }); </script>
EDIT: This code works for me
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <strong>Choose a base package:</strong> <input id="item_0" type="radio" name="pkg" value="1942" />Base Package 1 - $1942 <input id="item_1" type="radio" name="pkg" value="2313" />Base Package 2 - $2313 <input id="item_2" type="radio" name="pkg" value="2829" />Base Package 3 - $2829 <strong>Choose an add on:</strong> <input id="item_10" type="radio" name="ext" value="0" />No add-on - +$0 <input id="item_12" type="radio" name="ext" value="2146" />Add-on 1 - (+$2146) <input id="item_13" type="radio" name="ext" value="2455" />Add-on 2 - (+$2455) <input id="item_14" type="radio" name="ext" value="2764" />Add-on 3 - (+$2764) <input id="item_15" type="radio" name="ext" value="3073" />Add-on 4 - (+$3073) <input id="item_16" type="radio" name="ext" value="3382" />Add-on 5 - (+$3382) <input id="item_17" type="radio" name="ext" value="3691" />Add-on 6 - (+$3691) <strong>Your total is:</strong> <input id="totalSum" type="text" name="totalSum" readonly="readonly" size="5" value="" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> $("input[type=radio]").click(function() { var total = 0; $("input[type=radio]:checked").each(function() { total += parseFloat($(this).val()); }); $("#totalSum").val(total); }); </script> </body> </html>
$password = Input::get('password_from_user');
$hashed = Hash::make($password); // save $hashed value
// $user is database object
// $inputs is Input from user
if( \Illuminate\Support\Facades\Hash::check( $inputs['password'], $user['password']) == false) {
// Password is not matching
} else {
// Password is matching
}
df = df.replace({np.nan: None})
Credit goes to this guy here on this Github issue.
Apache Commons Lang has
T[] t = ArrayUtils.add( initialArray, newitem );
it returns a new array, but if you're really working with arrays for some reason, this may be the ideal way to do this.
This is an other way to solve your problem. So please check out below solution. Hope it will help you.
let str = "{\"names\": [\"Bob\", \"Tim\", \"Tina\"]}"
let data = str.data(using: String.Encoding.utf8, allowLossyConversion: false)!
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject]
if let names = json["names"] as? [String] {
print(names)
}
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
Ok, finally found the solution.
Probably due to lack of experience with ReactJS and web development...
var Task = React.createClass({
render: function() {
var percentage = this.props.children + '%';
....
<div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
...
I created the percentage variable outside in the render function.
Use title attribute instead of alt
<img
height="90"
width="90"
src="http://www.google.com/intl/en_ALL/images/logos/images_logo_lg12.gif"
title="Image Not Found"
/>
Use the Reformat and Compile plugin (inspired by the Save Actions plugin of Alexandre DuBreuil):
https://plugins.jetbrains.com/plugin/8231?pr=idea_ce
At the moment I am only offering a jar file, but this is the most important part of the code:
private final static Set<Document> documentsToProcess = new HashSet<Document>();
private static VirtualFile[] fileToCompile = VirtualFile.EMPTY_ARRAY;
// The plugin extends FileDocumentManagerAdapter.
// beforeDocumentSaving calls reformatAndCompile
private static void reformatAndCompile(
@NotNull final Project project,
@NotNull final Document document,
@NotNull final PsiFile psiFile) {
documentsToProcess.add(document);
if (storage.isEnabled(Action.compileFile) && isDocumentActive(project, document)) {
fileToCompile = isFileCompilable(project, psiFile.getVirtualFile());
}
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
if (documentsToProcess.contains(document)) {
documentsToProcess.remove(document);
if (storage.isEnabled(Action.optimizeImports)
|| storage.isEnabled(Action.reformatCode)) {
CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() {
@Override
public void run() {
if (storage.isEnabled(Action.optimizeImports)) {
new OptimizeImportsProcessor(project, psiFile)
.run();
}
if (storage.isEnabled(Action.reformatCode)) {
new ReformatCodeProcessor(
project,
psiFile,
null,
ChangeListManager
.getInstance(project)
.getChange(psiFile.getVirtualFile()) != null)
.run();
}
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(psiFile);
}
});
}
});
}
}
if (fileToCompile.length > 0) {
if (documentsToProcess.isEmpty()) {
compileFile(project, fileToCompile);
fileToCompile = VirtualFile.EMPTY_ARRAY;
}
} else if (storage.isEnabled(Action.makeProject)) {
if (documentsToProcess.isEmpty()) {
makeProject(project);
}
} else {
saveFile(project, document, psiFile.getVirtualFile());
}
}
}, project.getDisposed());
}
private static void makeProject(@NotNull final Project project) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
CompilerManager.getInstance(project).make(null);
}
}, project.getDisposed());
}
private static void compileFile(
@NotNull final Project project,
@NotNull final VirtualFile[] files) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
CompilerManager.getInstance(project).compile(files, null);
}
}, project.getDisposed());
}
private static void saveFile(
@NotNull final Project project,
@NotNull final Document document,
@NotNull final VirtualFile file) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
final FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
if (fileDocumentManager.isFileModified(file)) {
fileDocumentManager.saveDocument(document);
}
}
}, project.getDisposed());
}
Just try encodeURI()
and encodeURIComponent()
yourself...
console.log(encodeURIComponent('@#$%^&*'));
_x000D_
Input: @#$%^&*
. Output: %40%23%24%25%5E%26*
. So, wait, what happened to *
? Why wasn't this converted? TLDR: You actually want fixedEncodeURIComponent()
and fixedEncodeURI()
. Long-story...
You should not be using encodeURIComponent()
or encodeURI()
. You should use fixedEncodeURIComponent()
and fixedEncodeURI()
, according to the MDN Documentation.
Regarding encodeURI()
...
If one wishes to follow the more recent RFC3986 for URLs, which makes square brackets reserved (for IPv6) and thus not encoded when forming something which could be part of a URL (such as a host), the following code snippet may help:
function fixedEncodeURI(str) { return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']'); }
Regarding encodeURIComponent()
...
To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:
function fixedEncodeURIComponent(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16); }); }
So, what is the difference? fixedEncodeURI()
and fixedEncodeURIComponent()
convert the same set of values, but fixedEncodeURIComponent()
also converts this set: +@?=:*#;,$&
. This set is used in GET
parameters (&
, +
, etc.), anchor tags (#
), wildcard tags (*
), email/username parts (@
), etc..
For example -- If you use encodeURI()
, [email protected]/?email=me@home
will not properly send the second @
to the server, except for your browser handling the compatibility (as Chrome naturally does often).
If you have initialized the form like this
form = CustomForm()
then the correct way as of Jan 2019, is to use .initial
to replace the data. This will replace the data in the intial
dict that goes along with the form. It also works if you have initialized using some instance such as form = CustomForm(instance=instance)
To replace data in the form, you need to
form.initial['Email'] = GetEmailString()
Generalizing this it would be,
form.initial['field_name'] = new_value
I had success after using ade.exe as explained above, plus using the latest version of Chrome Canary. Apparently your desktop version of Chrome has to be higher than the version running on your Android device.
You need this instead:
if(s.contains("+"))
contains()
method of String
class does not take regular expression as a parameter, it takes normal text.
EDIT:
String s = "ddjdjdj+kfkfkf";
if(s.contains("+"))
{
String parts[] = s.split("\\+");
System.out.print(parts[0]);
}
OUTPUT:
ddjdjdj
In my case, I experienced this error because my webapp was .NET v4, and the application pool was configured for .NET v2.
Double-clicking on the application pool brings up a popup window, where we can select the desired version of .NET Framework.
So the issue is in your array declaration you are declaring an empty array with the empty curly braces{} instead of an array that allows slots.
Roughly speaking, there can be three types of inputs :
1. int array[] = null; #Does not point to any memory locations so is a null arrau
2. int array[] = {) which is sort of equivalent to int array[] = new int[0];
3. int array[] = new int[n] where n is some number indicating the number of
memory locations in the array
I wrap the input[type=file]
in a label tag, then style the label
to your liking, and hide the input
.
<label class="btn btn-default fileLabel" data-toggle="tooltip" data-placement="top" title="Upload">
<input type="file">
<span><i class="fa fa-upload"></i></span>
</label>
<style>
.fileLabel input[type="file"] {
position: fixed;
top: -1000px;
}
</style>
Purely CSS Solution.
There seems a different consensus in the C# and Java camps on this. The majority of Java code I have seen uses:
// apply mutex to this instance
synchronized(this) {
// do work here
}
whereas the majority of C# code opts for the arguably safer:
// instance level lock object
private readonly object _syncObj = new object();
...
// apply mutex to private instance level field (a System.Object usually)
lock(_syncObj)
{
// do work here
}
The C# idiom is certainly safer. As mentioned previously, no malicious / accidental access to the lock can be made from outside the instance. Java code has this risk too, but it seems that the Java community has gravitated over time to the slightly less safe, but slightly more terse version.
That's not meant as a dig against Java, just a reflection of my experience working on both languages.
Do you have multiple Radio Buttons on the page..
Because what I see is that you are assigning the events to all the radio button's on the page when you click on a radio button
string[]
is an array (vector) of strings
string
is just a string (a list/array of characters)
Depending on how you want to convert this, the canonical answer could be:
return String.Join(" ", myStringArray);
return new []{ myString };
Action is a delegate (pointer) to a method, that takes zero, one or more input parameters, but does not return anything.
Func is a delegate (pointer) to a method, that takes zero, one or more input parameters, and returns a value (or reference).
Predicate is a special kind of Func often used for comparisons.
Though widely used with Linq, Action and Func are concepts logically independent of Linq. C++ already contained the basic concept in form of typed function pointers.
Here is a small example for Action and Func without using Linq:
class Program
{
static void Main(string[] args)
{
Action<int> myAction = new Action<int>(DoSomething);
myAction(123); // Prints out "123"
// can be also called as myAction.Invoke(123);
Func<int, double> myFunc = new Func<int, double>(CalculateSomething);
Console.WriteLine(myFunc(5)); // Prints out "2.5"
}
static void DoSomething(int i)
{
Console.WriteLine(i);
}
static double CalculateSomething(int i)
{
return (double)i/2;
}
}
I'd suggest to use .nth(0)
rather than .first()
if you need to get the first row.
The difference between them is how they handle NaNs, so .nth(0)
will return the first row of group no matter what are the values in this row, while .first()
will eventually return the first not NaN
value in each column.
E.g. if your dataset is :
df = pd.DataFrame({'id' : [1,1,1,2,2,3,3,3,3,4,4],
'value' : ["first","second","third", np.NaN,
"second","first","second","third",
"fourth","first","second"]})
>>> df.groupby('id').nth(0)
value
id
1 first
2 NaN
3 first
4 first
And
>>> df.groupby('id').first()
value
id
1 first
2 second
3 first
4 first
I suspect the error is caused by this:
foreach (KeyValuePair<int, int> kvp in rankings)
rankings is a dictionary, which is IEnumerable. By using it in a foreach loop, you're specifying that you want each KeyValuePair from the dictionary in a deferred manner. That is, the next KeyValuePair is not returned until your loop iterates again.
But you're modifying the dictionary inside your loop:
rankings[kvp.Key] = rankings[kvp.Key] + 4;
which isn't allowed...so you get the exception.
You could simply do this
foreach (KeyValuePair<int, int> kvp in rankings.ToArray())
Check that downloaded eclipse/JDK/JRE is compatible with your processor/OS architecture that is are they 32bit or 64bit?
Replacing localhost with 10.0.2.2 is correct, but you can alsor replace localhost with your physical machine's ip(it is better for debug purposes). Ofc, if ip is provided by dhcp you would have to change it each time...
Good luck!
var _login = function (loginData) {_x000D_
_x000D_
var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password;_x000D_
_x000D_
var deferred = $q.defer();_x000D_
_x000D_
$http.post(serviceBase + 'token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (response) {_x000D_
_x000D_
localStorageService.set('authorizationData', { token: response.access_token, userName: loginData.userName });_x000D_
_x000D_
_authentication.isAuth = true;_x000D_
_authentication.userName = loginData.userName;_x000D_
_x000D_
deferred.resolve(response);_x000D_
_x000D_
}).error(function (err, status) {_x000D_
_logOut();_x000D_
deferred.reject(err);_x000D_
});_x000D_
_x000D_
return deferred.promise;_x000D_
_x000D_
};_x000D_
_x000D_
In token-based authentication, the client exchanges hard credentials (such as username and password) for a piece of data called token. For each request, instead of sending the hard credentials, the client will send the token to the server to perform authentication and then authorization.
In a few words, an authentication scheme based on tokens follow these steps:
Note: The step 3 is not required if the server has issued a signed token (such as JWT, which allows you to perform stateless authentication).
This solution uses only the JAX-RS 2.0 API, avoiding any vendor specific solution. So, it should work with JAX-RS 2.0 implementations, such as Jersey, RESTEasy and Apache CXF.
It is worthwhile to mention that if you are using token-based authentication, you are not relying on the standard Java EE web application security mechanisms offered by the servlet container and configurable via application's web.xml
descriptor. It's a custom authentication.
Create a JAX-RS resource method which receives and validates the credentials (username and password) and issue a token for the user:
@Path("/authentication")
public class AuthenticationEndpoint {
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response authenticateUser(@FormParam("username") String username,
@FormParam("password") String password) {
try {
// Authenticate the user using the credentials provided
authenticate(username, password);
// Issue a token for the user
String token = issueToken(username);
// Return the token on the response
return Response.ok(token).build();
} catch (Exception e) {
return Response.status(Response.Status.FORBIDDEN).build();
}
}
private void authenticate(String username, String password) throws Exception {
// Authenticate against a database, LDAP, file or whatever
// Throw an Exception if the credentials are invalid
}
private String issueToken(String username) {
// Issue a token (can be a random String persisted to a database or a JWT token)
// The issued token must be associated to a user
// Return the issued token
}
}
If any exceptions are thrown when validating the credentials, a response with the status 403
(Forbidden) will be returned.
If the credentials are successfully validated, a response with the status 200
(OK) will be returned and the issued token will be sent to the client in the response payload. The client must send the token to the server in every request.
When consuming application/x-www-form-urlencoded
, the client must to send the credentials in the following format in the request payload:
username=admin&password=123456
Instead of form params, it's possible to wrap the username and the password into a class:
public class Credentials implements Serializable {
private String username;
private String password;
// Getters and setters omitted
}
And then consume it as JSON:
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response authenticateUser(Credentials credentials) {
String username = credentials.getUsername();
String password = credentials.getPassword();
// Authenticate the user, issue a token and return a response
}
Using this approach, the client must to send the credentials in the following format in the payload of the request:
{
"username": "admin",
"password": "123456"
}
The client should send the token in the standard HTTP Authorization
header of the request. For example:
Authorization: Bearer <token-goes-here>
The name of the standard HTTP header is unfortunate because it carries authentication information, not authorization. However, it's the standard HTTP header for sending credentials to the server.
JAX-RS provides @NameBinding
, a meta-annotation used to create other annotations to bind filters and interceptors to resource classes and methods. Define a @Secured
annotation as following:
@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Secured { }
The above defined name-binding annotation will be used to decorate a filter class, which implements ContainerRequestFilter
, allowing you to intercept the request before it be handled by a resource method. The ContainerRequestContext
can be used to access the HTTP request headers and then extract the token:
@Secured
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {
private static final String REALM = "example";
private static final String AUTHENTICATION_SCHEME = "Bearer";
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
// Get the Authorization header from the request
String authorizationHeader =
requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
// Validate the Authorization header
if (!isTokenBasedAuthentication(authorizationHeader)) {
abortWithUnauthorized(requestContext);
return;
}
// Extract the token from the Authorization header
String token = authorizationHeader
.substring(AUTHENTICATION_SCHEME.length()).trim();
try {
// Validate the token
validateToken(token);
} catch (Exception e) {
abortWithUnauthorized(requestContext);
}
}
private boolean isTokenBasedAuthentication(String authorizationHeader) {
// Check if the Authorization header is valid
// It must not be null and must be prefixed with "Bearer" plus a whitespace
// The authentication scheme comparison must be case-insensitive
return authorizationHeader != null && authorizationHeader.toLowerCase()
.startsWith(AUTHENTICATION_SCHEME.toLowerCase() + " ");
}
private void abortWithUnauthorized(ContainerRequestContext requestContext) {
// Abort the filter chain with a 401 status code response
// The WWW-Authenticate header is sent along with the response
requestContext.abortWith(
Response.status(Response.Status.UNAUTHORIZED)
.header(HttpHeaders.WWW_AUTHENTICATE,
AUTHENTICATION_SCHEME + " realm=\"" + REALM + "\"")
.build());
}
private void validateToken(String token) throws Exception {
// Check if the token was issued by the server and if it's not expired
// Throw an Exception if the token is invalid
}
}
If any problems happen during the token validation, a response with the status 401
(Unauthorized) will be returned. Otherwise the request will proceed to a resource method.
To bind the authentication filter to resource methods or resource classes, annotate them with the @Secured
annotation created above. For the methods and/or classes that are annotated, the filter will be executed. It means that such endpoints will only be reached if the request is performed with a valid token.
If some methods or classes do not need authentication, simply do not annotate them:
@Path("/example")
public class ExampleResource {
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response myUnsecuredMethod(@PathParam("id") Long id) {
// This method is not annotated with @Secured
// The authentication filter won't be executed before invoking this method
...
}
@DELETE
@Secured
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response mySecuredMethod(@PathParam("id") Long id) {
// This method is annotated with @Secured
// The authentication filter will be executed before invoking this method
// The HTTP request must be performed with a valid token
...
}
}
In the example shown above, the filter will be executed only for the mySecuredMethod(Long)
method because it's annotated with @Secured
.
It's very likely that you will need to know the user who is performing the request agains your REST API. The following approaches can be used to achieve it:
Within your ContainerRequestFilter.filter(ContainerRequestContext)
method, a new SecurityContext
instance can be set for the current request. Then override the SecurityContext.getUserPrincipal()
, returning a Principal
instance:
final SecurityContext currentSecurityContext = requestContext.getSecurityContext();
requestContext.setSecurityContext(new SecurityContext() {
@Override
public Principal getUserPrincipal() {
return () -> username;
}
@Override
public boolean isUserInRole(String role) {
return true;
}
@Override
public boolean isSecure() {
return currentSecurityContext.isSecure();
}
@Override
public String getAuthenticationScheme() {
return AUTHENTICATION_SCHEME;
}
});
Use the token to look up the user identifier (username), which will be the Principal
's name.
Inject the SecurityContext
in any JAX-RS resource class:
@Context
SecurityContext securityContext;
The same can be done in a JAX-RS resource method:
@GET
@Secured
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response myMethod(@PathParam("id") Long id,
@Context SecurityContext securityContext) {
...
}
And then get the Principal
:
Principal principal = securityContext.getUserPrincipal();
String username = principal.getName();
If, for some reason, you don't want to override the SecurityContext
, you can use CDI (Context and Dependency Injection), which provides useful features such as events and producers.
Create a CDI qualifier:
@Qualifier
@Retention(RUNTIME)
@Target({ METHOD, FIELD, PARAMETER })
public @interface AuthenticatedUser { }
In your AuthenticationFilter
created above, inject an Event
annotated with @AuthenticatedUser
:
@Inject
@AuthenticatedUser
Event<String> userAuthenticatedEvent;
If the authentication succeeds, fire the event passing the username as parameter (remember, the token is issued for a user and the token will be used to look up the user identifier):
userAuthenticatedEvent.fire(username);
It's very likely that there's a class that represents a user in your application. Let's call this class User
.
Create a CDI bean to handle the authentication event, find a User
instance with the correspondent username and assign it to the authenticatedUser
producer field:
@RequestScoped
public class AuthenticatedUserProducer {
@Produces
@RequestScoped
@AuthenticatedUser
private User authenticatedUser;
public void handleAuthenticationEvent(@Observes @AuthenticatedUser String username) {
this.authenticatedUser = findUser(username);
}
private User findUser(String username) {
// Hit the the database or a service to find a user by its username and return it
// Return the User instance
}
}
The authenticatedUser
field produces a User
instance that can be injected into container managed beans, such as JAX-RS services, CDI beans, servlets and EJBs. Use the following piece of code to inject a User
instance (in fact, it's a CDI proxy):
@Inject
@AuthenticatedUser
User authenticatedUser;
Note that the CDI @Produces
annotation is different from the JAX-RS @Produces
annotation:
javax.enterprise.inject.Produces
javax.ws.rs.Produces
Be sure you use the CDI @Produces
annotation in your AuthenticatedUserProducer
bean.
The key here is the bean annotated with @RequestScoped
, allowing you to share data between filters and your beans. If you don't wan't to use events, you can modify the filter to store the authenticated user in a request scoped bean and then read it from your JAX-RS resource classes.
Compared to the approach that overrides the SecurityContext
, the CDI approach allows you to get the authenticated user from beans other than JAX-RS resources and providers.
Please refer to my other answer for details on how to support role-based authorization.
A token can be:
See details below:
A token can be issued by generating a random string and persisting it to a database along with the user identifier and an expiration date. A good example of how to generate a random string in Java can be seen here. You also could use:
Random random = new SecureRandom();
String token = new BigInteger(130, random).toString(32);
JWT (JSON Web Token) is a standard method for representing claims securely between two parties and is defined by the RFC 7519.
It's a self-contained token and it enables you to store details in claims. These claims are stored in the token payload which is a JSON encoded as Base64. Here are some claims registered in the RFC 7519 and what they mean (read the full RFC for further details):
iss
: Principal that issued the token.sub
: Principal that is the subject of the JWT.exp
: Expiration date for the token.nbf
: Time on which the token will start to be accepted for processing.iat
: Time on which the token was issued. jti
: Unique identifier for the token.Be aware that you must not store sensitive data, such as passwords, in the token.
The payload can be read by the client and the integrity of the token can be easily checked by verifying its signature on the server. The signature is what prevents the token from being tampered with.
You won't need to persist JWT tokens if you don't need to track them. Althought, by persisting the tokens, you will have the possibility of invalidating and revoking the access of them. To keep the track of JWT tokens, instead of persisting the whole token on the server, you could persist the token identifier (jti
claim) along with some other details such as the user you issued the token for, the expiration date, etc.
When persisting tokens, always consider removing the old ones in order to prevent your database from growing indefinitely.
There are a few Java libraries to issue and validate JWT tokens such as:
To find some other great resources to work with JWT, have a look at http://jwt.io.
If you want to revoke tokens, you must keep the track of them. You don't need to store the whole token on server side, store only the token identifier (that must be unique) and some metadata if you need. For the token identifier you could use UUID.
The jti
claim should be used to store the token identifier on the token. When validating the token, ensure that it has not been revoked by checking the value of the jti
claim against the token identifiers you have on server side.
For security purposes, revoke all the tokens for a user when they change their password.
The simple and best solution is to use tables for layouts. You're doing it right. There are a number of reasons tables are better.
This tool appears to serve your purposes: http://www.nirsoft.net/utils/chrome_cache_view.html
I ran a test that just added 1 to the number instead of rand(). Results (on an x86-64) were:
jcenter() equals to https://bintray.com/bintray/jcenter
You need import jcenter's cerficate into your java keystore.
Steps:
If you are behind proxy, in gradle.properties, besides setting
systemProp.http.proxyHost and systemProp.http.proxyPort
also set
systemProp.https.proxyHost and systemProp.https.proxyPort
By now it should be fine.
Library makefiles, which are generated by autotools (the ./configure
you have to issue) often have a verbose option, so basically, using make VERBOSE=1
or make V=1
should give you the full commands.
But this depends on how the makefile was generated.
The -d
option might help, but it will give you an extremely long output.
Looks like the script executes before the DOM loads. Try loading the script asynchronously.
<script src="yourcode.js" async></script>
Use CopyOnWriteArrayList
and if you want to remove it, do the following:
for (Iterator<String> it = userList.iterator(); it.hasNext() ;)
{
if (wordsToRemove.contains(word))
{
it.remove();
}
}
Source article: Java: Calling super()
Yes. super(...)
will invoke the constructor of the super-class.
Illustration:
class Animal {
public Animal(String arg) {
System.out.println("Constructing an animal: " + arg);
}
}
class Dog extends Animal {
public Dog() {
super("From Dog constructor");
System.out.println("Constructing a dog.");
}
}
public class Test {
public static void main(String[] a) {
new Dog();
}
}
Prints:
Constructing an animal: From Dog constructor
Constructing a dog.
First, create a function (using CTE, common table expression does away with the need for a temp table)
create function dbo.SplitString
(
@str nvarchar(4000),
@separator char(1)
)
returns table
AS
return (
with tokens(p, a, b) AS (
select
1,
1,
charindex(@separator, @str)
union all
select
p + 1,
b + 1,
charindex(@separator, @str, b + 1)
from tokens
where b > 0
)
select
p-1 zeroBasedOccurance,
substring(
@str,
a,
case when b > 0 then b-a ELSE 4000 end)
AS s
from tokens
)
GO
Then, use it as any table (or modify it to fit within your existing stored proc) like this.
select s
from dbo.SplitString('Hello John Smith', ' ')
where zeroBasedOccurance=1
Update
Previous version would fail for input string longer than 4000 chars. This version takes care of the limitation:
create function dbo.SplitString
(
@str nvarchar(max),
@separator char(1)
)
returns table
AS
return (
with tokens(p, a, b) AS (
select
cast(1 as bigint),
cast(1 as bigint),
charindex(@separator, @str)
union all
select
p + 1,
b + 1,
charindex(@separator, @str, b + 1)
from tokens
where b > 0
)
select
p-1 ItemIndex,
substring(
@str,
a,
case when b > 0 then b-a ELSE LEN(@str) end)
AS s
from tokens
);
GO
Usage remains the same.
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
_x000D_
<meta charset="utf-8">_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<meta name="description" content="">_x000D_
<meta name="author" content="">_x000D_
_x000D_
<title>3 Col Portfolio - Start Bootstrap Template</title>_x000D_
_x000D_
<!-- Bootstrap Core CSS -->_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->_x000D_
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->_x000D_
<!--[if lt IE 9]>_x000D_
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>_x000D_
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>_x000D_
<![endif]-->_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<!-- Navigation -->_x000D_
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">_x000D_
<div class="container">_x000D_
<!-- Brand and toggle get grouped for better mobile display -->_x000D_
<div class="navbar-header">_x000D_
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">_x000D_
<span class="sr-only">Toggle navigation</span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href="#">Start Bootstrap</a>_x000D_
</div>_x000D_
<!-- Collect the nav links, forms, and other content for toggling -->_x000D_
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
<ul class="nav navbar-nav">_x000D_
<li>_x000D_
<a href="#">About</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">Services</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">Contact</a>_x000D_
</li>_x000D_
</ul>_x000D_
<form class="navbar-form navbar-right">_x000D_
<div class="input-group">_x000D_
<input type="text" name="keyword" placeholder="search..." class="form-control">_x000D_
<span class="input-group-btn">_x000D_
<button class="btn btn-default">Go</button>_x000D_
</span>_x000D_
</div>_x000D_
</form>_x000D_
</div>_x000D_
<!-- /.navbar-collapse -->_x000D_
</div>_x000D_
<!-- /.container -->_x000D_
</nav>_x000D_
_x000D_
<!-- Page Content -->_x000D_
<div class="container">_x000D_
_x000D_
<!-- Page Header -->_x000D_
<div class="row">_x000D_
<div class="col-lg-12">_x000D_
<h1 class="page-header">Page Heading_x000D_
<small>Secondary Text</small>_x000D_
</h1>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.row -->_x000D_
_x000D_
<!-- Projects Row -->_x000D_
<div class="row">_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.row -->_x000D_
_x000D_
<!-- Projects Row -->_x000D_
<div class="row">_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.row -->_x000D_
_x000D_
<!-- Projects Row -->_x000D_
<div class="row">_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.row -->_x000D_
_x000D_
<!-- Projects Row -->_x000D_
<div class="row">_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.row -->_x000D_
_x000D_
<hr>_x000D_
_x000D_
<!-- Pagination -->_x000D_
<div class="row text-center">_x000D_
<div class="col-lg-12">_x000D_
<ul class="pagination">_x000D_
<li>_x000D_
<a href="#">«</a>_x000D_
</li>_x000D_
<li class="active">_x000D_
<a href="#">1</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">2</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">3</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">4</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">5</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">»</a>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.row -->_x000D_
</div>_x000D_
<!-- Footer -->_x000D_
<footer>_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col-lg-4 col-md-4 col-sm-4">_x000D_
<h3>About</h3>_x000D_
<ul>_x000D_
<li>_x000D_
<i class="glyphicon glyphicon-home"></i> Your company address here_x000D_
</li>_x000D_
<li>_x000D_
<i class="glyphicon glyphicon-earphone"></i> 0982.808.065_x000D_
</li>_x000D_
<li>_x000D_
<i class="glyphicon glyphicon-envelope"></i> [email protected]_x000D_
</li>_x000D_
<li>_x000D_
<i class="glyphicon glyphicon-flag"></i> <a href="#">Fan page</a>_x000D_
</li>_x000D_
<li>_x000D_
<i class="glyphicon glyphicon-time"></i> 08:00-18:00 Monday to Friday_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
<div class="col-lg-4 col-md-4 col-sm-4">_x000D_
<h3>Support</h3>_x000D_
<ul>_x000D_
<li>_x000D_
<a href="#" class="link">Terms of Service</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#" class="link">Privacy policy</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#" class="link">Warranty commitment</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#" class="link">Site map</a>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
<div class="col-lg-4 col-md-4 col-sm-4">_x000D_
<h3>Other</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod_x000D_
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,_x000D_
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo_x000D_
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse_x000D_
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non_x000D_
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.row -->_x000D_
</footer>_x000D_
_x000D_
<!-- /.container -->_x000D_
_x000D_
<!-- jQuery -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<!-- Bootstrap Core JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
I'm using: Win Server 2012 R2 / IIS 8.5 / MVC4 / .Net 4.5
If none of the above worked then try this:
Uncheck "Precompile during Publishing"
This kicked my butt for a few days.
I think the docs aren't wonderful at exposing how to do this. It has been a supported feature for some time, however, and there are some details in this pull request.
So there are three different ways to do this:
Option A) Create a new session with the profile
dev = boto3.session.Session(profile_name='dev')
Option B) Change the profile of the default session in code
boto3.setup_default_session(profile_name='dev')
Option C) Change the profile of the default session with an environment variable
$ AWS_PROFILE=dev ipython
>>> import boto3
>>> s3dev = boto3.resource('s3')
you could also do show columns in $table
or see Hive, how do I retrieve all the database's tables columns for access to hive metadata
That's the RHEL release version.
You can see the kernel version by typing uname -r
. It'll be 2.6.something.
var myArray = new Array();
myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;
// Show the values stored
for (var i in myArray) {
alert('key is: ' + i + ', value is: ' + myArray[i]);
}
This is ok, but it iterates through every property of the array object.
If you want to only iterate through the properties myArray.one, myArray.two... you try like this:
myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;
myArray.push("one");
myArray.push("two");
myArray.push("three");
for(var i=0;i<maArray.length;i++){
console.log(myArray[myArray[i]])
}
Now you can access both by myArray["one"] and iterate only through these properties.
You can save the current scroll amount and then set it later:
var tempScrollTop = $(window).scrollTop();
..//Your code
$(window).scrollTop(tempScrollTop);
You can found more information on MSDN - facet of Entity Data Model. http://msdn.microsoft.com/en-us/library/ee382834.aspx Full recommended.
'Error Code: 1046'.
This error shows that the table does not exist may sometimes be caused by having selected a different database and running a query referring to another table. The results indicates 'No database selected Select the default DB to be used by double-clicking its name in the SCHEMAS list in the sidebar'. Will solve the issue and it worked for me very well.
For Debian/Ubuntu or Fedora, you can probably use the other answers. But if you don't have files under /etc/default/docker
or /etc/sysconfig/docker
, and your system is running systemd, you may want to follow this answer by h3nrik. I am using Arch, and this works for me.
Basically, you need to configure systemd to read the new docker image location as an environment variable, and pass that environment variable into the Docker daemon execution script.
For completeness, here is h3nrick's answer:
Do you have a /lib/systemd/system/docker.service
file?
If so, edit it so that the Docker service uses the usual /etc/default/docker
as an environment file: EnvironmentFile=-/etc/default/docker
.
In the /etc/default/docker
file then add DOCKER_OPTS="-g /home/rseixas/Programs/Docker/images"
.
At the end just do a systemctl daemon-reload && systemctl restart docker
.
For further information please also have a look at the documentation.
Even if you're willing to look up what behavior your implementation defines, multi-character constants will still vary with endianness.
Better to use a (POD) struct { char[4] }; ... and then use a UDL like "WAVE"_4cc to easily construct instances of that class
Check this out, you may like it (previously, please, clone table1 to table2):
table1.AsEnumerable().Take(recodCount).CopyToDataTable(table2,LoadOption.OverwriteChanges);
Or:
table1.AsEnumerable().Where ( yourcondition ) .CopyToDataTable(table2,LoadOption.OverwriteChanges);
sudo snap install androidsdk
You can use the sdkmanager to perform the following tasks.
androidsdk --list [options]
androidsdk packages [options]
The packages argument is an SDK-style path as shown with the --list command, wrapped in quotes (for example, "build-tools;29.0.0" or "platforms;android-28"). You can pass multiple package paths, separated with a space, but they must each be wrapped in their own set of quotes.
For example, here's how to install the latest platform tools (which includes adb and fastboot) and the SDK tools for API level 28:
androidsdk "platform-tools" "platforms;android-28"
Alternatively, you can pass a text file that specifies all packages:
androidsdk --package_file=package_file [options]
The package_file argument is the location of a text file in which each line is an SDK-style path of a package to install (without quotes).
To uninstall, simply add the --uninstall flag:
androidsdk --uninstall packages [options]
androidsdk --uninstall --package_file=package_file [options]
Update all installed packages
androidsdk --update [options]
androidsdk it is snap wraper of sdkmanager all options of sdkmanager work with androidsdk
Location of installed android sdk files : /home/user/AndroidSDK
See all sdkmanager options in google documentation
You can also get DateTime object from timestamp, including your current daylight saving time:
public DateTime getDateTimeFromTimestamp(Long value) {
TimeZone timeZone = TimeZone.getDefault();
long offset = timeZone.getOffset(value);
if (offset < 0) {
value -= offset;
} else {
value += offset;
}
return new DateTime(value);
}
I hit this exact same error and was Googling all over trying to find what I'm doing wrong as that is generated build values-26 code and not styles that I provided. I tried everything from Gradle 4.0 to Android Studio preview 3.0 to canary channel, you name it.
I never found the answer online. In the end, I was able to go back to standard Dev Android Studio and 2.3.3 Gradle as I ended up accidentally fixing it :).
Turned out I was so focused on updating my library project that I was not noticing that the error was caused from an unused sub module (demo app) that is nested in my library project. Once I updated the sub module to match the 26 build tools and 26+ design and support libraries my problem went away.
Not sure if that is what you are seeing as well, but personally I was only updating the lib to release again so wasn't caring about the sample app module, and the error sure appeared to be related to 26 sdk which I only touched in the lib module so wasn't thinking to check the other one. So that was the problem all along for me. Hopefully that fixes you as well. I had this error in 2 library projects and it fixed it in both.
Goodluck either way and if this doesn't resolve your issue, please share what did. BTW 26.0.01 build tools and 26.1.0 design and support is where I ended up going to in the end, although 26.0.1 worked fine as well.
To delete a cookie I set it again with an empty value and expiring in 1 second. In details, I always use one of the following flavours (I tend to prefer the second one):
1.
function setCookie(key, value, expireDays, expireHours, expireMinutes, expireSeconds) {
var expireDate = new Date();
if (expireDays) {
expireDate.setDate(expireDate.getDate() + expireDays);
}
if (expireHours) {
expireDate.setHours(expireDate.getHours() + expireHours);
}
if (expireMinutes) {
expireDate.setMinutes(expireDate.getMinutes() + expireMinutes);
}
if (expireSeconds) {
expireDate.setSeconds(expireDate.getSeconds() + expireSeconds);
}
document.cookie = key +"="+ escape(value) +
";domain="+ window.location.hostname +
";path=/"+
";expires="+expireDate.toUTCString();
}
function deleteCookie(name) {
setCookie(name, "", null , null , null, 1);
}
Usage:
setCookie("reminder", "buyCoffee", null, null, 20);
deleteCookie("reminder");
2
function setCookie(params) {
var name = params.name,
value = params.value,
expireDays = params.days,
expireHours = params.hours,
expireMinutes = params.minutes,
expireSeconds = params.seconds;
var expireDate = new Date();
if (expireDays) {
expireDate.setDate(expireDate.getDate() + expireDays);
}
if (expireHours) {
expireDate.setHours(expireDate.getHours() + expireHours);
}
if (expireMinutes) {
expireDate.setMinutes(expireDate.getMinutes() + expireMinutes);
}
if (expireSeconds) {
expireDate.setSeconds(expireDate.getSeconds() + expireSeconds);
}
document.cookie = name +"="+ escape(value) +
";domain="+ window.location.hostname +
";path=/"+
";expires="+expireDate.toUTCString();
}
function deleteCookie(name) {
setCookie({name: name, value: "", seconds: 1});
}
Usage:
setCookie({name: "reminder", value: "buyCoffee", minutes: 20});
deleteCookie("reminder");
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Configuration;
protected void Button1_Click(object sender, EventArgs e)
{
//Upload and save the file
string excelPath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(excelPath);
string conString = string.Empty;
string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
switch (extension)
{
case ".xls": //Excel 97-03
conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx": //Excel 07 or higher
conString = ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString;
break;
}
conString = string.Format(conString, excelPath);
using (OleDbConnection excel_con = new OleDbConnection(conString))
{
excel_con.Open();
string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
DataTable dtExcelData = new DataTable();
//[OPTIONAL]: It is recommended as otherwise the data will be considered as String by default.
dtExcelData.Columns.AddRange(new DataColumn[2] { new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)) });
using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con))
{
oda.Fill(dtExcelData);
}
excel_con.Close();
string consString = ConfigurationManager.ConnectionStrings["dbcn"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "dbo.Table1";
//[OPTIONAL]: Map the Excel columns with that of the database table
sqlBulkCopy.ColumnMappings.Add("Sl", "Id");
sqlBulkCopy.ColumnMappings.Add("Name", "Name");
con.Open();
sqlBulkCopy.WriteToServer(dtExcelData);
con.Close();
}
}
}
}
Copy this in web config
<add name="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>
<add name="Excel07+ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>
you can also refer this link : https://athiraji.blogspot.com/2019/03/how-to-upload-excel-fle-to-database.html
The function call still should be a valid SQL statement:
SELECT "saveUser"(3, 'asd','asd','asd','asd','asd');
You can't. Variables defined inside a method are local to that method.
If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).
Looks like you're using instance methods instead of static ones.
If you don't want to create an object, you should declare all your methods static, so something like
private static void methodName(Argument args...)
If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.
private static int[][] array = new int[3][5];
Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.
Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.
Here's a final (shortened) example of what your code should be like:
public class Test3 {
//Use this array in your methods
private static int[][] scores = new int[3][5];
/* Rather than just "Scores" name it so people know what
* to expect
*/
private static void createScores() {
//Code...
}
//Other methods...
/* Since you're now using static methods, you don't
* have to initialise an object and call its methods.
*/
public static void main(String[] args){
createScores();
MD(); //Don't know what these do
sumD(); //so I'll leave them.
}
}
Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.
You are creating those bytes
objects yourself:
item['title'] = [t.encode('utf-8') for t in title]
item['link'] = [l.encode('utf-8') for l in link]
item['desc'] = [d.encode('utf-8') for d in desc]
items.append(item)
Each of those t.encode()
, l.encode()
and d.encode()
calls creates a bytes
string. Do not do this, leave it to the JSON format to serialise these.
Next, you are making several other errors; you are encoding too much where there is no need to. Leave it to the json
module and the standard file object returned by the open()
call to handle encoding.
You also don't need to convert your items
list to a dictionary; it'll already be an object that can be JSON encoded directly:
class W3SchoolPipeline(object):
def __init__(self):
self.file = open('w3school_data_utf8.json', 'w', encoding='utf-8')
def process_item(self, item, spider):
line = json.dumps(item) + '\n'
self.file.write(line)
return item
I'm guessing you followed a tutorial that assumed Python 2, you are using Python 3 instead. I strongly suggest you find a different tutorial; not only is it written for an outdated version of Python, if it is advocating line.decode('unicode_escape')
it is teaching some extremely bad habits that'll lead to hard-to-track bugs. I can recommend you look at Think Python, 2nd edition for a good, free, book on learning Python 3.
I believe you can diff against files in your index and untracked files by simply supplying the path to both files.
git diff --no-index tracked_file untracked_file
Consider:
Object obj = new Book();
obj.equals("hi");
// Oh noes! What happens now? Can't call it with a String that isn't a Book...
i was trying trying to GRANT read-only privileges to a particular table to a user called walters-ro. So when i ran the sql command # GRANT SELECT ON table_name TO walters-ro; --- i got the following error..`syntax error at or near “-”
The solution to this was basically putting the user_name into double quotes since there is a dash(-) between the name.
# GRANT SELECT ON table_name TO "walters-ro";
That solved the problem.
I guess this would only work if the directory is fairly static and its contents don't change between the execution of the two dir commands. Maybe a way to combine this into one command to avoid that, but this worked for my purpose (I didn't want the full listing; just the summary).
GetDirSummary.bat Script:
@echo off
rem get total number of lines from dir output
FOR /F "delims=" %%i IN ('dir /S %1 ^| find "asdfasdfasdf" /C /V') DO set lineCount=%%i
rem dir summary is always last 3 lines; calculate starting line of summary info
set /a summaryStart="lineCount-3"
rem now output just the last 3 lines
dir /S %1 | more +%summaryStart%
Usage:
GetDirSummary.bat c:\temp
Output:
Total Files Listed:
22 File(s) 63,600 bytes
8 Dir(s) 104,350,330,880 bytes free
You mean this?
from string import punctuation, digits
takeout = punctuation + digits
turnthis = "(fjskl) 234 = -345 089 abcdef"
turnthis = turnthis.translate(None, takeout)[::-1]
print turnthis
$(function(){
var navMain = $("#your id");
navMain.on("click", "a", null, function () {
navMain.collapse('hide');
});
});
Convert.ToString(FileUpload1.PostedFile.FileName);
If someone is using column names like "key"
or "value"
, then you still see the same error that your mysql query syntax is bad. This should fix:
.where("`key` LIKE ?", "%#{key}%")
Make on class with this. And make 2 different images with the self width and height. Works in ie9.
See this link.
http://kyleschaeffer.com/development/pure-css-image-hover/
Also you can 2 differents images make and place in the self class name with in the hover the another images.
See example.
.myButtonLink {
margin-top: -5px;
display: block;
width: 45px;
height: 39px;
background: url('images/home1.png') bottom;
text-indent: -99999px;
margin-left:-17px;
margin-right:-17px;
margin-bottom: -5px;
border-radius: 3px;
-webkit-border-radius: 3px;
}
.myButtonLink:hover {
margin-top: -5px;
display: block;
width: 45px;
height: 39px;
background: url('images/home2.png') bottom;
text-indent: -99999px;
margin-left:-17px;
margin-right:-17px;
margin-bottom: -20x;
border-radius: 3px;
-webkit-border-radius: 3px;
}
>>> df
Station ID Pollutants
0 8809 {"a": "46", "b": "3", "c": "12"}
1 8810 {"a": "36", "b": "5", "c": "8"}
2 8811 {"b": "2", "c": "7"}
3 8812 {"c": "11"}
4 8813 {"a": "82", "c": "15"}
speed comparison for a large dataset of 10 million rows
>>> df = pd.concat([df]*100000).reset_index(drop=True)
>>> df = pd.concat([df]*20).reset_index(drop=True)
>>> print(df.shape)
(10000000, 2)
def apply_drop(df):
return df.join(df['Pollutants'].apply(pd.Series)).drop('Pollutants', axis=1)
def json_normalise_drop(df):
return df.join(pd.json_normalize(df.Pollutants)).drop('Pollutants', axis=1)
def tolist_drop(df):
return df.join(pd.DataFrame(df['Pollutants'].tolist())).drop('Pollutants', axis=1)
def vlues_tolist_drop(df):
return df.join(pd.DataFrame(df['Pollutants'].values.tolist())).drop('Pollutants', axis=1)
def pop_tolist(df):
return df.join(pd.DataFrame(df.pop('Pollutants').tolist()))
def pop_values_tolist(df):
return df.join(pd.DataFrame(df.pop('Pollutants').values.tolist()))
>>> %timeit apply_drop(df.copy())
1 loop, best of 3: 53min 20s per loop
>>> %timeit json_normalise_drop(df.copy())
1 loop, best of 3: 54.9 s per loop
>>> %timeit tolist_drop(df.copy())
1 loop, best of 3: 6.62 s per loop
>>> %timeit vlues_tolist_drop(df.copy())
1 loop, best of 3: 6.63 s per loop
>>> %timeit pop_tolist(df.copy())
1 loop, best of 3: 5.99 s per loop
>>> %timeit pop_values_tolist(df.copy())
1 loop, best of 3: 5.94 s per loop
+---------------------+-----------+
| apply_drop | 53min 20s |
| json_normalise_drop | 54.9 s |
| tolist_drop | 6.62 s |
| vlues_tolist_drop | 6.63 s |
| pop_tolist | 5.99 s |
| pop_values_tolist | 5.94 s |
+---------------------+-----------+
df.join(pd.DataFrame(df.pop('Pollutants').values.tolist()))
is the fastest
label {
width:200px;
display: inline-block;
}
OR
label {
width:200px;
display: inline-flex;
}
OR
label {
width:200px;
display: inline-table;
}
I guess that you are trying to play an .pls directly or something similar.
try this out:
1: the code
mediaPlayer = MediaPlayer.create(this, Uri.parse("http://vprbbc.streamguys.net:80/vprbbc24.mp3"));
mediaPlayer.start();
2: the .pls file
This URL is from BBC just as an example. It was an .pls file that on linux i downloaded with
wget http://foo.bar/file.pls
and then i opened with vim (use your favorite editor ;) and i've seen the real URLs inside this file. Unfortunately not all of the .pls are plain text like that.
I've read that 1.6 would not support streaming mp3 over http, but, i've just tested the obove code with android 1.6 and 2.2 and didn't have any issue.
good luck!
If you know the position of the date object in the string (for example in a log file), you can use .split()[index] to extract the date without fully knowing the format.
For example:
>>> string = 'monkey 2010-07-10 love banana'
>>> date = string.split()[1]
>>> date
'2010-07-10'
I agree with @Vishnu's answer. I would like to add that if you want to use the application user in your trigger you can use "context_info" to pass the info to the trigger.
I found following very helpful in doing that: http://jasondentler.com/blog/2010/01/exploiting-context_info-for-fun-and-audit
CERAS is a class name which cannot be assigned. As the class implements IDisposable a typical usage would be:
using (CERas.CERAS ceras = new CERas.CERAS())
{
// call some method on ceras
}
It is just a typo(I guess)-
p+=1;
instead of p +1=p;
is required .
As name suggest lvalue
expression should be left-hand operand of the assignment operator.
I have the same problem with spring 3.0.2 and spring-beans-3.0.xsd.
My solution:
Create a file META-INF/spring.schemas in the source folder and copy all necesary definitions. Create spring.handlers too.
I think that the class PluggableSchemaResolver is not working correctly.
from the javadoc:
"By default, this class will look for mapping files in the classpath using the pattern: META-INF/spring.schemas allowing for multiple files to exist on the classpath at any one time."
but in my case, this class only read the first spring.schemas finded.
Grettings. pacovr
You can do this simply by using pandas drop duplicates function
df.drop_duplicates(['A','B'],keep= 'last')
That would be the modulo operator, which produces the remainder of the division of two numbers.
I just added VCTargetsPath={c:\...}
as an environment variable to my Hudson job.
You can define your Enum as following code :
public enum Verbosity
{
BRIEF, NORMAL, FULL, ACTION_NOT_VALID;
private int value;
public int getValue()
{
return this.value;
}
public static final Verbosity getVerbosityByValue(int value)
{
for(Verbosity verbosity : Verbosity.values())
{
if(verbosity.getValue() == value)
return verbosity ;
}
return ACTION_NOT_VALID;
}
@Override
public String toString()
{
return ((Integer)this.getValue()).toString();
}
};
Perhaps this:
str = str.Split(",").First();
A few comments:
analog=True
in the call to butter
, and you should use scipy.signal.freqz
(not freqs
) to generate the frequency response.Here's my modified version of your script, followed by the plot that it generates.
import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt
def butter_lowpass(cutoff, fs, order=5):
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
b, a = butter(order, normal_cutoff, btype='low', analog=False)
return b, a
def butter_lowpass_filter(data, cutoff, fs, order=5):
b, a = butter_lowpass(cutoff, fs, order=order)
y = lfilter(b, a, data)
return y
# Filter requirements.
order = 6
fs = 30.0 # sample rate, Hz
cutoff = 3.667 # desired cutoff frequency of the filter, Hz
# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)
# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()
# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0 # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data. We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)
# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)
plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()
plt.subplots_adjust(hspace=0.35)
plt.show()
Make sure that both projects have same target framework version here: right click on project -> properties -> application (tab) -> target framework
Also, make sure that the project "logger" (which you want to include in the main project) has the output type "Class Library" in: right click on project -> properties -> application (tab) -> output type
Finally, Rebuild the solution.
Expanded answer, was my first answer so excuse if there wasn’t enough detail before.
For Bootstrap 3.x I personally prefer CSS animations and I've been using animate.css & along with the Bootstrap Dropdown Javascript Hooks. Although it might not have the exactly effect you're after it's a pretty flexible approach.
Step 1: Add animate.css to your page with the head tags:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.4.0/animate.min.css">
Step 2: Use the standard Bootstrap HTML on the trigger:
<div class="dropdown">
<button type="button" data-toggle="dropdown">Dropdown trigger</button>
<ul class="dropdown-menu">
...
</ul>
</div>
Step 3: Then add 2 custom data attributes to the dropdrop-menu element; data-dropdown-in for the in animation and data-dropdown-out for the out animation. These can be any animate.css effects like fadeIn or fadeOut
<ul class="dropdown-menu" data-dropdown-in="fadeIn" data-dropdown-out="fadeOut">
......
</ul>
Step 4: Next add the following Javascript to read the data-dropdown-in/out data attributes and react to the Bootstrap Javascript API hooks/events (http://getbootstrap.com/javascript/#dropdowns-events):
var dropdownSelectors = $('.dropdown, .dropup');
// Custom function to read dropdown data
// =========================
function dropdownEffectData(target) {
// @todo - page level global?
var effectInDefault = null,
effectOutDefault = null;
var dropdown = $(target),
dropdownMenu = $('.dropdown-menu', target);
var parentUl = dropdown.parents('ul.nav');
// If parent is ul.nav allow global effect settings
if (parentUl.size() > 0) {
effectInDefault = parentUl.data('dropdown-in') || null;
effectOutDefault = parentUl.data('dropdown-out') || null;
}
return {
target: target,
dropdown: dropdown,
dropdownMenu: dropdownMenu,
effectIn: dropdownMenu.data('dropdown-in') || effectInDefault,
effectOut: dropdownMenu.data('dropdown-out') || effectOutDefault,
};
}
// Custom function to start effect (in or out)
// =========================
function dropdownEffectStart(data, effectToStart) {
if (effectToStart) {
data.dropdown.addClass('dropdown-animating');
data.dropdownMenu.addClass('animated');
data.dropdownMenu.addClass(effectToStart);
}
}
// Custom function to read when animation is over
// =========================
function dropdownEffectEnd(data, callbackFunc) {
var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
data.dropdown.one(animationEnd, function() {
data.dropdown.removeClass('dropdown-animating');
data.dropdownMenu.removeClass('animated');
data.dropdownMenu.removeClass(data.effectIn);
data.dropdownMenu.removeClass(data.effectOut);
// Custom callback option, used to remove open class in out effect
if(typeof callbackFunc == 'function'){
callbackFunc();
}
});
}
// Bootstrap API hooks
// =========================
dropdownSelectors.on({
"show.bs.dropdown": function () {
// On show, start in effect
var dropdown = dropdownEffectData(this);
dropdownEffectStart(dropdown, dropdown.effectIn);
},
"shown.bs.dropdown": function () {
// On shown, remove in effect once complete
var dropdown = dropdownEffectData(this);
if (dropdown.effectIn && dropdown.effectOut) {
dropdownEffectEnd(dropdown, function() {});
}
},
"hide.bs.dropdown": function(e) {
// On hide, start out effect
var dropdown = dropdownEffectData(this);
if (dropdown.effectOut) {
e.preventDefault();
dropdownEffectStart(dropdown, dropdown.effectOut);
dropdownEffectEnd(dropdown, function() {
dropdown.dropdown.removeClass('open');
});
}
},
});
Step 5 (optional): If you want to speed up or alter the animation you can do so with CSS like the following:
.dropdown-menu.animated {
/* Speed up animations */
-webkit-animation-duration: 0.55s;
animation-duration: 0.55s;
-webkit-animation-timing-function: ease;
animation-timing-function: ease;
}
Wrote an article with more detail and a download if anyones interested: article: http://bootbites.com/tutorials/bootstrap-dropdown-effects-animatecss
Hope that’s helpful & this second write up has the level of detail that’s needed Tom
.NET Core 2.0 has Path.GetRelativePath which can be used like so:
var relativePath = Path.GetRelativePath(
@"C:\Program Files\Dummy Folder\MyProgram",
@"C:\Program Files\Dummy Folder\MyProgram\Data\datafile1.dat");
In the above example, the relativePath
variable is equal to Data\datafile1.dat
.
@Dave's solution does not work when the file paths do not end with a forward slash character (/
) which can happen if the path is a directory path. My solution fixes that problem and also makes use of the Uri.UriSchemeFile
constant instead of hard coding "FILE"
.
/// <summary>
/// Creates a relative path from one file or folder to another.
/// </summary>
/// <param name="fromPath">Contains the directory that defines the start of the relative path.</param>
/// <param name="toPath">Contains the path that defines the endpoint of the relative path.</param>
/// <returns>The relative path from the start directory to the end path.</returns>
/// <exception cref="ArgumentNullException"><paramref name="fromPath"/> or <paramref name="toPath"/> is <c>null</c>.</exception>
/// <exception cref="UriFormatException"></exception>
/// <exception cref="InvalidOperationException"></exception>
public static string GetRelativePath(string fromPath, string toPath)
{
if (string.IsNullOrEmpty(fromPath))
{
throw new ArgumentNullException("fromPath");
}
if (string.IsNullOrEmpty(toPath))
{
throw new ArgumentNullException("toPath");
}
Uri fromUri = new Uri(AppendDirectorySeparatorChar(fromPath));
Uri toUri = new Uri(AppendDirectorySeparatorChar(toPath));
if (fromUri.Scheme != toUri.Scheme)
{
return toPath;
}
Uri relativeUri = fromUri.MakeRelativeUri(toUri);
string relativePath = Uri.UnescapeDataString(relativeUri.ToString());
if (string.Equals(toUri.Scheme, Uri.UriSchemeFile, StringComparison.OrdinalIgnoreCase))
{
relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
}
return relativePath;
}
private static string AppendDirectorySeparatorChar(string path)
{
// Append a slash only if the path is a directory and does not have a slash.
if (!Path.HasExtension(path) &&
!path.EndsWith(Path.DirectorySeparatorChar.ToString()))
{
return path + Path.DirectorySeparatorChar;
}
return path;
}
There is a Windows API called PathRelativePathToA that can be used to find a relative path. Please note that the file or directory paths that you pass to the function must exist for it to work.
var relativePath = PathExtended.GetRelativePath(
@"C:\Program Files\Dummy Folder\MyProgram",
@"C:\Program Files\Dummy Folder\MyProgram\Data\datafile1.dat");
public static class PathExtended
{
private const int FILE_ATTRIBUTE_DIRECTORY = 0x10;
private const int FILE_ATTRIBUTE_NORMAL = 0x80;
private const int MaximumPath = 260;
public static string GetRelativePath(string fromPath, string toPath)
{
var fromAttribute = GetPathAttribute(fromPath);
var toAttribute = GetPathAttribute(toPath);
var stringBuilder = new StringBuilder(MaximumPath);
if (PathRelativePathTo(
stringBuilder,
fromPath,
fromAttribute,
toPath,
toAttribute) == 0)
{
throw new ArgumentException("Paths must have a common prefix.");
}
return stringBuilder.ToString();
}
private static int GetPathAttribute(string path)
{
var directory = new DirectoryInfo(path);
if (directory.Exists)
{
return FILE_ATTRIBUTE_DIRECTORY;
}
var file = new FileInfo(path);
if (file.Exists)
{
return FILE_ATTRIBUTE_NORMAL;
}
throw new FileNotFoundException(
"A file or directory with the specified path was not found.",
path);
}
[DllImport("shlwapi.dll", SetLastError = true)]
private static extern int PathRelativePathTo(
StringBuilder pszPath,
string pszFrom,
int dwAttrFrom,
string pszTo,
int dwAttrTo);
}
var regex = new RegExp("^[A-Za-z0-9? ,_-]+$");
var key = String.fromCharCode(event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
in the regExp [A-Za-z0-9?spaceHere,_-]
there is a literal space after the question mark '?'. This matches space. Others like /^[-\w\s]+$/
and /^[a-z\d\-_\s]+$/i
were not working for me.
If you wish to use es6 arrow functions you can add a .timeout(ms)
to the end of your it
definition:
it('should not timeout', (done) => {
doLongThing().then(() => {
done();
});
}).timeout(5000);
At least this works in Typescript.
You need to load a package (like magrittr
or dplyr
) that defines the function first, then it should work.
install.packages("magrittr") # package installations are only needed the first time you use it
install.packages("dplyr") # alternative installation of the %>%
library(magrittr) # needs to be run every time you start R and want to use %>%
library(dplyr) # alternatively, this also loads %>%
The pipe operator %>%
was introduced to "decrease development time and to improve readability and maintainability of code."
But everybody has to decide for himself if it really fits his workflow and makes things easier.
For more information on magrittr
, click here.
Not using the pipe %>%
, this code would return the same as your code:
words <- colnames(as.matrix(dtm))
words <- words[nchar(words) < 20]
words
EDIT: (I am extending my answer due to a very useful comment that was made by @Molx)
Despite being from
magrittr
, the pipe operator is more commonly used with the packagedplyr
(which requires and loadsmagrittr
), so whenever you see someone using%>%
make sure you shouldn't loaddplyr
instead.
Plus, you should make sure the MySQL server's config (/etc/mysql/my.cnf, /etc/default/mysql on Debian) doesn't have "skip-networking" activated and is not binded exclusively to the loopback interface (127.0.0.1) but also to the interface/IP address you want connect to.
It seems the original author has found their solution, but for anyone else who gets here looking to add actual custom headers, if you have access to mod the generated Protocol code you can override GetWebRequest
:
protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
System.Net.WebRequest request = base.GetWebRequest(uri);
request.Headers.Add("myheader", "myheader_value");
return request;
}
Make sure you remove the DebuggerStepThroughAttribute
attribute if you want to step into it.
Use Application.ActiveWorkbook.Path
for just the path itself (without the workbook name) or Application.ActiveWorkbook.FullName
for the path with the workbook name.
The question in the link you gave talks about naming of JavaScript variables, not about file naming, so forget about that for the context in which you ask your question.
As to file naming, it is purely a matter of preference and taste. I prefer naming files with hyphens because then I don't have to reach for the shift key, as I do when dealing with camelCase file names; and because I don't have to worry about differences between Windows and Linux file names (Windows file names are case-insensitive, at least through XP).
So the answer, like so many, is "it depends" or "it's up to you."
The one rule you should follow is to be consistent in the convention you choose.
It's been more than 8 years, but maybe someone will find it helpful anyway.
I was able to do the trick without rebase -i
.
The idea is to lead git to the same state it was before you did git commit
:
# first rewind back (mind the dot,
# though it can be any valid path,
# for instance if you want to apply only a subset of the commit)
git reset --hard <previous-commit> .
# apply the changes
git checkout <commit-you-want-to-split>
# we're almost there, but the changes are in the index at the moment,
# hence one more step (exactly as git gently suggests):
# (use "git reset HEAD <file>..." to unstage)
git reset
After this you'll see this shiny Unstaged changes after reset:
and your repo is in a state like you're about to commit all these files. From now on you can easily commit it again like you usually do. Hope it helps.
With Firefox, Safari (and other Gecko based browsers) you can easily use textarea.selectionStart, but for IE that doesn't work, so you will have to do something like this:
function getCaret(node) {
if (node.selectionStart) {
return node.selectionStart;
} else if (!document.selection) {
return 0;
}
var c = "\001",
sel = document.selection.createRange(),
dul = sel.duplicate(),
len = 0;
dul.moveToElementText(node);
sel.text = c;
len = dul.text.indexOf(c);
sel.moveStart('character',-1);
sel.text = "";
return len;
}
I also recommend you to check the jQuery FieldSelection Plugin, it allows you to do that and much more...
Edit: I actually re-implemented the above code:
function getCaret(el) {
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}
Check an example here.
This is the XML optional preamble.
version="1.0"
means that this is the XML standard this file conforms toencoding="utf-8"
means that the file is encoded using the UTF-8 Unicode encodingThe compileSdkVersion
is the version of the API the app is compiled against. This means you can use Android API features included in that version of the API (as well as all previous versions, obviously). If you try and use API 16 features but set compileSdkVersion
to 15, you will get a compilation error. If you set compileSdkVersion
to 16 you can still run the app on a API 15 device as long as your app's execution paths do not attempt to invoke any APIs specific to API 16.
The targetSdkVersion
has nothing to do with how your app is compiled or what APIs you can utilize. The targetSdkVersion
is supposed to indicate that you have tested your app on (presumably up to and including) the version you specify. This is more like a certification or sign off you are giving the Android OS as a hint to how it should handle your app in terms of OS features.
For example, as the documentation states:
For example, setting this value to "11" or higher allows the system to apply a new default theme (Holo) to your app when running on Android 3.0 or higher...
The Android OS, at runtime, may change how your app is stylized or otherwise executed in the context of the OS based on this value. There are a few other known examples that are influenced by this value and that list is likely to only increase over time.
For all practical purposes, most apps are going to want to set targetSdkVersion
to the latest released version of the API. This will ensure your app looks as good as possible on the most recent Android devices. If you do not specify the targetSdkVersion
, it defaults to the minSdkVersion
.
My solution in Header parameters with example is user="test" is:
@RequestMapping(value = "/restURL")
public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers){
System.out.println(headers.get("user"));
}
This worked for me for Windows 10, Java 8_144.
If the path contains spaces, use the shortened path name. For example, C:\Progra~1\Java\jdk1.8.0_65
The defaults for initiating a connection to a MySQL server were changed in the recent past, and (from a quick look through the most popular questions and answers on stack overflow) the new values are causing a lot of confusion. What is worse is that the standard advice seems to be to disable SSL altogether, which is a bit of a disaster in the making.
Now, if your connection is genuinely not exposed to the network (localhost only) or you are working in a non-production environment with no real data, then sure: there's no harm in disabling SSL by including the option useSSL=false
.
For everyone else, the following set of options are required to get SSL working with certificate and host verification:
As an added bonus, seeing as you're already playing with the options, it is simple to disable the weak SSL protocols too:
So as a working example you'll need to follow the following broad steps:
First, make sure you have a valid certificate generated for the MySQL server host, and that the CA certificate is installed onto the client host (if you are using self-signed, then you'll likely need to do this manually, but for the popular public CAs it'll already be there).
Next, make sure that the java keystore contains all the CA certificates. On Debian/Ubuntu this is achieved by running:
update-ca-certificates -f
chmod 644 /etc/ssl/certs/java/cacerts
Then finally, update the connection string to include all the required options, which on Debian/Ubuntu would be something a bit like (adapt as required):
jdbc:mysql://{mysql_server}/confluence?useSSL=true&sslMode=VERIFY_IDENTITY&trustCertificateKeyStoreUrl=file%3A%2Fetc%2Fssl%2Fcerts%2Fjava%2Fcacerts&trustCertificateKeyStorePassword=changeit&enabledTLSProtocols=TLSv1.2&useUnicode=true&characterEncoding=utf8
Reference: https://beansandanicechianti.blogspot.com/2019/11/mysql-ssl-configuration.html
Uninstall composer
To remove just composer package itself from Ubuntu 16.04 (Xenial Xerus) execute on terminal:
sudo apt-get remove composer
Uninstall composer and it's dependent packages
To remove the composer package and any other dependant package which are no longer needed from Ubuntu Xenial.
sudo apt-get remove --auto-remove composer
Purging composer
If you also want to delete configuration and/or data files of composer from Ubuntu Xenial then this will work:
sudo apt-get purge composer
To delete configuration and/or data files of composer and it's dependencies from Ubuntu Xenial then execute:
sudo apt-get purge --auto-remove composer
https://www.howtoinstall.co/en/ubuntu/xenial/composer?action=remove
As the previous answer implies, it is not easy to change the color of the ratingbar. The stars are not programmatically drawn, they are images with fixed size and specific color gradients. To change the color you have to create your own star images with different colors then proceed to create your own drawable XML resource and pass it to the ratingsBar class using setProgressDrawable(Drawable d) or XML attribute android:progressDrawable.
In Ansible >1.4 you can actually specify a remote user at the task level which should allow you to login as that user and execute that command without resorting to sudo. If you can't login as that user then the sudo_user solution will work too.
---
- hosts: webservers
remote_user: root
tasks:
- name: test connection
ping:
remote_user: yourname
See http://docs.ansible.com/playbooks_intro.html#hosts-and-users
See also: Which C I/O library should be used in C++ code?
struct Item
{
std::string artist;
std::string c;
integer price; // in cents (as floating point is not acurate)
std::string Genre;
integer disc;
integer sale;
integer tax;
};
std::cout << "Sales Report for September 15, 2010\n"
<< "Artist Title Price Genre Disc Sale Tax Cash\n";
FOREACH(Item loop,data)
{
fprintf(stdout,"%8s%8s%8.2f%7s%1s%8.2f%8.2f\n",
, loop.artist
, loop.title
, loop.price / 100.0
, loop.Genre
, loop.disc , "%"
, loop.sale / 100.0
, loop.tax / 100.0);
// or
std::cout << std::setw(8) << loop.artist
<< std::setw(8) << loop.title
<< std::setw(8) << fixed << setprecision(2) << loop.price / 100.0
<< std::setw(8) << loop.Genre
<< std::setw(7) << loop.disc << std::setw(1) << "%"
<< std::setw(8) << fixed << setprecision(2) << loop.sale / 100.0
<< std::setw(8) << fixed << setprecision(2) << loop.tax / 100.0
<< "\n";
// or
std::cout << boost::format("%8s%8s%8.2f%7s%1s%8.2f%8.2f\n")
% loop.artist
% loop.title
% loop.price / 100.0
% loop.Genre
% loop.disc % "%"
% loop.sale / 100.0
% loop.tax / 100.0;
}
Is it possible that you can avoid using wsdl2java? You can straight away use CXF FrontEnd APIs to invoke your SOAP Webservice. The only catch is that you need to create your SEI and VOs on your client end. Here is a sample code.
package com.aranin.weblog4j.client;
import com.aranin.weblog4j.services.BookShelfService;
import com.aranin.weblog4j.vo.BookVO;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
public class DemoClient {
public static void main(String[] args){
String serviceUrl = "http://localhost:8080/weblog4jdemo/bookshelfservice";
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.setServiceClass(BookShelfService.class);
factory.setAddress(serviceUrl);
BookShelfService bookService = (BookShelfService) factory.create();
//insert book
BookVO bookVO = new BookVO();
bookVO.setAuthor("Issac Asimov");
bookVO.setBookName("Foundation and Earth");
String result = bookService.insertBook(bookVO);
System.out.println("result : " + result);
bookVO = new BookVO();
bookVO.setAuthor("Issac Asimov");
bookVO.setBookName("Foundation and Empire");
result = bookService.insertBook(bookVO);
System.out.println("result : " + result);
bookVO = new BookVO();
bookVO.setAuthor("Arthur C Clarke");
bookVO.setBookName("Rama Revealed");
result = bookService.insertBook(bookVO);
System.out.println("result : " + result);
//retrieve book
bookVO = bookService.getBook("Foundation and Earth");
System.out.println("book name : " + bookVO.getBookName());
System.out.println("book author : " + bookVO.getAuthor());
}
}
You can see the full tutorial here http://weblog4j.com/2012/05/01/developing-soap-web-service-using-apache-cxf/
click here for full source code and learn more.
Before get permission you can check api version,
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
}
else
{
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 401);
}
}
else
{
// if version is below m then write code here,
}
Get the Result of the permission dialog,
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 401) {
if (grantResults.length == 0 || grantResults == null) {
} else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openGallery();
} else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
}
} else if (requestCode == 402) {
if (grantResults.length == 0 || grantResults == null) {
} else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
}
}
}
if you are using the less source, there should be a variable for the navbar height in the variables.less
file. If you are not using the source, then you can customize it using the customize utilty that bootstrap's site provides. And then you can downloaded it and include it in your project. The variable you are looking for is: @navbar-height
One way to avoid accidentally including the same script twice is to implement a script management module in your templating system. The typical way to include a script is to use the SCRIPT tag in your HTML page.
<script type="text/javascript" src="menu_1.0.17.js"></script>
An alternative in PHP would be to create a function called insertScript.
<?php insertScript("menu.js") ?>
jQuery does only make some regexp checking before calling the native browser method window.JSON.parse()
. If that is not available, it uses eval()
or more exactly new Function()
to create a Javascript object.
The opposite of JSON.parse()
is JSON.stringify()
which serializes a Javascript object into a string. jQuery does not have functionality of its own for that, you have to use the browser built-in version or json2.js
from http://www.json.org
JSON.stringify()
is available in all major browsers, but to be compatible with older browsers you still need that fallback.
I had the same issue. The problem is that the Spring Boot annotation processor generates the spring-configuration-metadata.json
file inside your /target/classes/META-INF
folder.
If you happen to have ignored this folder in IntelliJ like me (because what the heck, who cares about classes files?), the file won't be indexed by your IDE. Therefore, no completion, and the annoying message.
Just remove target
from the ignore files/folders list, located in Settings > Editor > File Types > Ignore files and folders
.
After the blog post How Can I Use Windows PowerShell to Delete All the .TMP Files on a Drive?, you can use something like this to delete all .tmp for example from a folder and all subfolders in PowerShell:
get-childitem [your path/ or leave empty for current path] -include
*.tmp -recurse | foreach ($_) {remove-item $_.fullname}
Problem statement – Getting java.awt.HeadlessException while trying to initialize java.awt.Component from the application as the tomcat environment does not have any head(terminal).
Issue – The linux virtual environment was setup without a virtual display terminal. Tried to install virtual display – Xvfb, but Xvfb has been taken off by the redhat community.
Solution – Installed ‘xorg-x11-drv-vmware.x86_64’ using yum install xorg-x11-drv-vmware.x86_64 and executed startx. Finally set the display to :0.0 using export DISPLAY=:0.0 and then executed xhost +
Building on @yunzen's great answer:
I'm guessing many people searching for this topic are trying use a large image as a "hero" background image, for example on a homepage. In this case, they would often want text to appear over the image and to have it scale down well on mobile devices.
Here is the perfect CSS for such a background image (use it on the <img>
tag):
/* Set left edge of inner element to 50% of the parent element */
margin-left: 50%;
/* Move to the left by 50% of own width */
transform: translateX(-50%);
/* Scale image...(101% - instead of 100% - avoids possible 1px white border on left of image due to rounding error */
width: 101%;
/* ...but don't scale it too small on mobile devices - adjust this as needed */
min-width: 1086px;
/* allow content below image to appear on top of image */
position: absolute;
z-index: -1;
/* OPTIONAL - try with/without based on your needs */
top: 0;
/* OPTIONAL - use if your outer element containing the img has "text-align: center" */
left: 0;
If there is polymorphism such as checking SQLRecoverableException vs SQLException, it can be done like that.
try {
// sth may throw exception
....
} catch (Exception e) {
if(SQLException.class.isAssignableFrom(e.getCause().getClass()))
{
// do sth
System.out.println("SQLException occurs!");
}
}
Simply say,
ChildClass child= new ChildClass();
if(ParentClass.class.isAssignableFrom(child.getClass()))
{
// do sth
...
}
Well, most other answers here refer to
sort -n
However, I'm not sure this works for negative numbers. Here are the results I get with sort version 6.10 on Fedora 9.
Input file:
-0.907928466796875
-0.61614990234375
1.135406494140625
0.48614501953125
-0.4140167236328125
Output:
-0.4140167236328125
0.48614501953125
-0.61614990234375
-0.907928466796875
1.135406494140625
Which is obviously not ordered by numeric value.
Then, I guess that a more precise answer would be to use sort -n
but only if all the values are positive.
P.S.: Using sort -g
returns just the same results for this example
Edit:
Looks like the locale settings affect how the minus sign affects the order (see here). In order to get proper results I just did:
LC_ALL=C sort -n filename.txt
Note: using // at the beginning of the xpath is a bit CPU intensitve -- it will search every node for a match. Using a more specific path, such as /root/DataSet will create a faster query.
footerText {
line-height: 20px;
}
you don't need to start playing with position or even layout of other elements... use this simple solution
UTC
is definitely a valid timezone. It is simply an abbreviation for Coordinated Universal Time. In addition, remember that date_default_timezone_set
accepts one of the following values:
$timezones=array(
"America/Adak",
"America/Argentina/Buenos_Aires",
"America/Argentina/La_Rioja",
"America/Argentina/San_Luis",
"America/Atikokan",
"America/Belem",
"America/Boise",
"America/Caracas",
"America/Chihuahua",
"America/Cuiaba",
"America/Denver",
"America/El_Salvador",
"America/Godthab",
"America/Guatemala",
"America/Hermosillo",
"America/Indiana/Tell_City",
"America/Inuvik",
"America/Kentucky/Louisville",
"America/Lima",
"America/Managua",
"America/Mazatlan",
"America/Mexico_City",
"America/Montreal",
"America/Nome",
"America/Ojinaga",
"America/Port-au-Prince",
"America/Rainy_River",
"America/Rio_Branco",
"America/Santo_Domingo",
"America/St_Barthelemy",
"America/St_Vincent",
"America/Tijuana",
"America/Whitehorse",
"America/Anchorage",
"America/Argentina/Catamarca",
"America/Argentina/Mendoza",
"America/Argentina/Tucuman",
"America/Atka",
"America/Belize",
"America/Buenos_Aires",
"America/Catamarca",
"America/Coral_Harbour",
"America/Curacao",
"America/Detroit",
"America/Ensenada",
"America/Goose_Bay",
"America/Guayaquil",
"America/Indiana/Indianapolis",
"America/Indiana/Vevay",
"America/Iqaluit",
"America/Kentucky/Monticello",
"America/Los_Angeles",
"America/Manaus",
"America/Mendoza",
"America/Miquelon",
"America/Montserrat",
"America/Noronha",
"America/Panama",
"America/Port_of_Spain",
"America/Rankin_Inlet",
"America/Rosario",
"America/Sao_Paulo",
"America/St_Johns",
"America/Swift_Current",
"America/Toronto",
"America/Winnipeg",
"America/Anguilla",
"America/Argentina/ComodRivadavia",
"America/Argentina/Rio_Gallegos",
"America/Argentina/Ushuaia",
"America/Bahia",
"America/Blanc-Sablon",
"America/Cambridge_Bay",
"America/Cayenne",
"America/Cordoba",
"America/Danmarkshavn",
"America/Dominica",
"America/Fort_Wayne",
"America/Grand_Turk",
"America/Guyana",
"America/Indiana/Knox",
"America/Indiana/Vincennes",
"America/Jamaica",
"America/Knox_IN",
"America/Louisville",
"America/Marigot",
"America/Menominee",
"America/Moncton",
"America/Nassau",
"America/North_Dakota/Beulah",
"America/Pangnirtung",
"America/Porto_Acre",
"America/Recife",
"America/Santa_Isabel",
"America/Scoresbysund",
"America/St_Kitts",
"America/Tegucigalpa",
"America/Tortola",
"America/Yakutat",
"America/Antigua",
"America/Argentina/Cordoba",
"America/Argentina/Salta",
"America/Aruba",
"America/Bahia_Banderas",
"America/Boa_Vista",
"America/Campo_Grande",
"America/Cayman",
"America/Costa_Rica",
"America/Dawson",
"America/Edmonton",
"America/Fortaleza",
"America/Grenada",
"America/Halifax",
"America/Indiana/Marengo",
"America/Indiana/Winamac",
"America/Jujuy",
"America/Kralendijk",
"America/Lower_Princes",
"America/Martinique",
"America/Merida",
"America/Monterrey",
"America/New_York",
"America/North_Dakota/Center",
"America/Paramaribo",
"America/Porto_Velho",
"America/Regina",
"America/Santarem",
"America/Shiprock",
"America/St_Lucia",
"America/Thule",
"America/Vancouver",
"America/Yellowknife",
"America/Araguaina",
"America/Argentina/Jujuy",
"America/Argentina/San_Juan",
"America/Asuncion",
"America/Barbados",
"America/Bogota",
"America/Cancun",
"America/Chicago",
"America/Creston",
"America/Dawson_Creek",
"America/Eirunepe",
"America/Glace_Bay",
"America/Guadeloupe",
"America/Havana",
"America/Indiana/Petersburg",
"America/Indianapolis",
"America/Juneau",
"America/La_Paz",
"America/Maceio",
"America/Matamoros",
"America/Metlakatla",
"America/Montevideo",
"America/Nipigon",
"America/North_Dakota/New_Salem",
"America/Phoenix",
"America/Puerto_Rico",
"America/Resolute",
"America/Santiago",
"America/Sitka",
"America/St_Thomas",
"America/Thunder_Bay",
"America/Virgin",
"Indian/Antananarivo",
"Indian/Kerguelen",
"Indian/Reunion",
"Australia/ACT",
"Australia/Currie",
"Australia/Lindeman",
"Australia/Perth",
"Australia/Victoria",
"Europe/Amsterdam",
"Europe/Berlin",
"Europe/Chisinau",
"Europe/Helsinki",
"Europe/Kiev",
"Europe/Madrid",
"Europe/Moscow",
"Europe/Prague",
"Europe/Sarajevo",
"Europe/Tallinn",
"Europe/Vatican",
"Europe/Zagreb",
"Pacific/Apia",
"Pacific/Efate",
"Pacific/Galapagos",
"Pacific/Johnston",
"Pacific/Marquesas",
"Pacific/Noumea",
"Pacific/Ponape",
"Pacific/Tahiti",
"Pacific/Wallis",
"Indian/Chagos",
"Indian/Mahe",
"Australia/Adelaide",
"Australia/Darwin",
"Australia/Lord_Howe",
"Australia/Queensland",
"Australia/West",
"Europe/Andorra",
"Europe/Bratislava",
"Europe/Copenhagen",
"Europe/Isle_of_Man",
"Europe/Lisbon",
"Europe/Malta",
"Europe/Nicosia",
"Europe/Riga",
"Europe/Simferopol",
"Europe/Tirane",
"Europe/Vienna",
"Europe/Zaporozhye",
"Pacific/Auckland",
"Pacific/Enderbury",
"Pacific/Gambier",
"Pacific/Kiritimati",
"Pacific/Midway",
"Pacific/Pago_Pago",
"Pacific/Port_Moresby",
"Pacific/Tarawa",
"Pacific/Yap",
"Africa/Abidjan",
"Africa/Asmera",
"Africa/Blantyre",
"Africa/Ceuta",
"Africa/Douala",
"Africa/Johannesburg",
"Africa/Kinshasa",
"Africa/Lubumbashi",
"Africa/Mbabane",
"Africa/Niamey",
"Africa/Timbuktu",
"Africa/Accra",
"Africa/Bamako",
"Africa/Brazzaville",
"Africa/Conakry",
"Africa/El_Aaiun",
"Africa/Juba",
"Africa/Lagos",
"Africa/Lusaka",
"Africa/Mogadishu",
"Africa/Nouakchott",
"Africa/Tripoli",
"Africa/Addis_Ababa",
"Africa/Bangui",
"Africa/Bujumbura",
"Africa/Dakar",
"Africa/Freetown",
"Africa/Kampala",
"Africa/Libreville",
"Africa/Malabo",
"Africa/Monrovia",
"Africa/Ouagadougou",
"Africa/Tunis",
"Africa/Algiers",
"Africa/Banjul",
"Africa/Cairo",
"Africa/Dar_es_Salaam",
"Africa/Gaborone",
"Africa/Khartoum",
"Africa/Lome",
"Africa/Maputo",
"Africa/Nairobi",
"Africa/Porto-Novo",
"Africa/Windhoek",
"Africa/Asmara",
"Africa/Bissau",
"Africa/Casablanca",
"Africa/Djibouti",
"Africa/Harare",
"Africa/Kigali",
"Africa/Luanda",
"Africa/Maseru",
"Africa/Ndjamena",
"Africa/Sao_Tome",
"Atlantic/Azores",
"Atlantic/Faroe",
"Atlantic/St_Helena",
"Atlantic/Bermuda",
"Atlantic/Jan_Mayen",
"Atlantic/Stanley",
"Atlantic/Canary",
"Atlantic/Madeira",
"Atlantic/Cape_Verde",
"Atlantic/Reykjavik",
"Atlantic/Faeroe",
"Atlantic/South_Georgia",
"Asia/Aden",
"Asia/Aqtobe",
"Asia/Baku",
"Asia/Calcutta",
"Asia/Dacca",
"Asia/Dushanbe",
"Asia/Hong_Kong",
"Asia/Jayapura",
"Asia/Kashgar",
"Asia/Kuala_Lumpur",
"Asia/Magadan",
"Asia/Novokuznetsk",
"Asia/Pontianak",
"Asia/Riyadh",
"Asia/Shanghai",
"Asia/Tehran",
"Asia/Ujung_Pandang",
"Asia/Vladivostok",
"Asia/Almaty",
"Asia/Ashgabat",
"Asia/Bangkok",
"Asia/Choibalsan",
"Asia/Damascus",
"Asia/Gaza",
"Asia/Hovd",
"Asia/Jerusalem",
"Asia/Kathmandu",
"Asia/Kuching",
"Asia/Makassar",
"Asia/Novosibirsk",
"Asia/Pyongyang",
"Asia/Saigon",
"Asia/Singapore",
"Asia/Tel_Aviv",
"Asia/Ulaanbaatar",
"Asia/Yakutsk",
"Asia/Amman",
"Asia/Ashkhabad",
"Asia/Beirut",
"Asia/Chongqing",
"Asia/Dhaka",
"Asia/Harbin",
"Asia/Irkutsk",
"Asia/Kabul",
"Asia/Katmandu",
"Asia/Kuwait",
"Asia/Manila",
"Asia/Omsk",
"Asia/Qatar",
"Asia/Sakhalin",
"Asia/Taipei",
"Asia/Thimbu",
"Asia/Ulan_Bator",
"Asia/Yekaterinburg",
"Asia/Anadyr",
"Asia/Baghdad",
"Asia/Bishkek",
"Asia/Chungking",
"Asia/Dili",
"Asia/Hebron",
"Asia/Istanbul",
"Asia/Kamchatka",
"Asia/Kolkata",
"Asia/Macao",
"Asia/Muscat",
"Asia/Oral",
"Asia/Qyzylorda",
"Asia/Samarkand",
"Asia/Tashkent",
"Asia/Thimphu",
"Asia/Urumqi",
"Asia/Yerevan",
"Asia/Aqtau",
"Asia/Bahrain",
"Asia/Brunei",
"Asia/Colombo",
"Asia/Dubai",
"Asia/Ho_Chi_Minh",
"Asia/Jakarta",
"Asia/Karachi",
"Asia/Krasnoyarsk",
"Asia/Macau",
"Asia/Nicosia",
"Asia/Phnom_Penh",
"Asia/Rangoon",
"Asia/Seoul",
"Asia/Tbilisi",
"Asia/Tokyo",
"Asia/Vientiane",
"Australia/Canberra",
"Australia/LHI",
"Australia/NSW",
"Australia/Tasmania",
"Australia/Broken_Hill",
"Australia/Hobart",
"Australia/North",
"Australia/Sydney",
"Pacific/Chuuk",
"Pacific/Fiji",
"Pacific/Guam",
"Pacific/Kwajalein",
"Pacific/Niue",
"Pacific/Pitcairn",
"Pacific/Saipan",
"Pacific/Truk",
"Pacific/Chatham",
"Pacific/Fakaofo",
"Pacific/Guadalcanal",
"Pacific/Kosrae",
"Pacific/Nauru",
"Pacific/Palau",
"Pacific/Rarotonga",
"Pacific/Tongatapu",
"Pacific/Easter",
"Pacific/Funafuti",
"Pacific/Honolulu",
"Pacific/Majuro",
"Pacific/Norfolk",
"Pacific/Pohnpei",
"Pacific/Samoa",
"Pacific/Wake",
"Antarctica/Casey",
"Antarctica/McMurdo",
"Antarctica/Vostok",
"Antarctica/Davis",
"Antarctica/Palmer",
"Antarctica/DumontDUrville",
"Antarctica/Rothera",
"Antarctica/Macquarie",
"Antarctica/South_Pole",
"Antarctica/Mawson",
"Antarctica/Syowa",
"Arctic/Longyearbyen",
"Europe/Athens",
"Europe/Brussels",
"Europe/Dublin",
"Europe/Istanbul",
"Europe/Ljubljana",
"Europe/Mariehamn",
"Europe/Oslo",
"Europe/Rome",
"Europe/Skopje",
"Europe/Tiraspol",
"Europe/Vilnius",
"Europe/Zurich",
"Europe/Belfast",
"Europe/Bucharest",
"Europe/Gibraltar",
"Europe/Jersey",
"Europe/London",
"Europe/Minsk",
"Europe/Paris",
"Europe/Samara",
"Europe/Sofia",
"Europe/Uzhgorod",
"Europe/Volgograd",
"Europe/Belgrade",
"Europe/Budapest",
"Europe/Guernsey",
"Europe/Kaliningrad",
"Europe/Luxembourg",
"Europe/Monaco",
"Europe/Podgorica",
"Europe/San_Marino",
"Europe/Stockholm",
"Europe/Vaduz",
"Europe/Warsaw",
"Indian/Cocos",
"Indian/Mauritius",
"Indian/Christmas",
"Indian/Maldives",
"Indian/Comoro",
"Indian/Mayotte",
"Australia/Brisbane",
"Australia/Eucla",
"Australia/Melbourne",
"Australia/South",
"Australia/Yancowinna",
);
Timezones in PHP at http://www.php.net/manual/en/timezones.php
[Personal Option] Avoiding using $scope, based on John Papa Angular Style Guide
so my idea is take advantage of the current model:
(function(){_x000D_
'use strict';_x000D_
_x000D_
var app = angular.module('way', [])_x000D_
app.controller('Decision', Decision);_x000D_
_x000D_
Decision.$inject = []; _x000D_
_x000D_
function Decision(){_x000D_
var vm = this;_x000D_
vm.checkItOut = _register;_x000D_
_x000D_
function _register(newOption){_x000D_
console.log('should I stay or should I go');_x000D_
console.log(newOption); _x000D_
}_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
})();
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<div ng-app="way">_x000D_
<div ng-controller="Decision as vm">_x000D_
<form name="myCheckboxTest" ng-submit="vm.checkItOut(decision)">_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="option" ng-model="decision.myWay"_x000D_
ng-value="false" ng-checked="!decision.myWay"> Should I stay?_x000D_
</label>_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="option" ng-value="true"_x000D_
ng-model="decision.myWay" > Should I go?_x000D_
</label>_x000D_
_x000D_
</form>_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
I hope I could help ;)
For student level programs, Clang has the benefit that it is, by default, stricter wrt. the C standard. For example, the following K&R version of Hello World is accepted without warning by GCC, but rejected by Clang with some pretty descriptive error messages:
main()
{
puts("Hello, world!");
}
With GCC, you have to give it -Werror
to get it to really make a point about this not being a valid C89 program. Also, you still need to use c99
or gcc -std=c99
to get the C99 language.
To check if a lateinit var
were initialised or not use a .isInitialized
on the reference to that property:
if (foo::bar.isInitialized) {
println(foo.bar)
}
This checking is only available for the properties that are accessible lexically, i.e. declared in the same type or in one of the outer types, or at top level in the same file.
Pretty easy to do this across multiple cells, without having to add '%' to each individually.
Select all the cells you want to change to percent, right Click, then format Cells, choose Custom. Type in 0.0\%
.
The jQuery docs for text()
says
Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space.
I'd use $td.html()
instead.
I hope what you are trying to achieve is like this. For this please use Box layout.
package com.kcing.kailas.sample.client;
import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
public class Testing extends JFrame {
private JPanel jContentPane = null;
public Testing() {
super();
initialize();
}
private void initialize() {
this.setSize(300, 200);
this.setContentPane(getJContentPane());
this.setTitle("JFrame");
}
private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel();
jContentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(61, 11, 81, 140);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
jContentPane.add(panel);
JCheckBox c1 = new JCheckBox("Check1");
panel.add(c1);
c1 = new JCheckBox("Check2");
panel.add(c1);
c1 = new JCheckBox("Check3");
panel.add(c1);
c1 = new JCheckBox("Check4");
panel.add(c1);
}
return jContentPane;
}
public static void main(String[] args) throws Exception {
Testing frame = new Testing();
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
}
now append is a method in JavaScript
MDN documentation on append method
Quoting MDN
The
ParentNode.append
method inserts a set of Node objects orDOMString
objects after the last child of theParentNode
.DOMString
objects are inserted as equivalent Text nodes.
This is not supported by IE and Edge but supported by Chrome(54+), Firefox(49+) and Opera(39+).
The JavaScript's append is similar to jQuery's append.
You can pass multiple arguments.
var elm = document.getElementById('div1');
elm.append(document.createElement('p'),document.createElement('span'),document.createElement('div'));
console.log(elm.innerHTML);
_x000D_
<div id="div1"></div>
_x000D_
Use a vector:
#include <vector>
void foo() {
std::vector <int> v;
v.push_back( 1 ); // equivalent to v[0] = 1
}
Before you implement any of the other suggestions, ask yourself these questions...
The answers to these questions are easier in certain types of applications (Web apps, for example) than they are in others, but are worth asking anyway.
Accessing the ApplicationContext does kind of violate the whole dependency injection principle, but sometimes you've not got much choice.
As @dblood points out, the main pain is in the DataContractSerializer, that doens't correctly re-use the types. There are already some answers here so I'll start by adding some pro's and cons about these:
Fortunately, if you are in control of your service, there is a simple solution that solves all these issues. This means you can still re-use service interfaces across DLL's - which is IMO a must-have for a proper solution. This is how the solution works:
Use the same DLL to construct the client using your favorite method. For example (IMyInterface is the service contract interface):
var httpBinding = new BasicHttpBinding();
var identity = new DnsEndpointIdentity("");
var address = new EndpointAddress(url, identity, new AddressHeaderCollection());
var channel = new ChannelFactory<IMyInterface>(httpBinding, address);
return channel.CreateChannel();
In other words: Don't use the 'add service reference' functionality, but force WCF to use the (correct) service types by bypassing the proxy generation. After all, you already have these classes.
Pro's:
Cons:
This solved my problem : Sample alter table statement to change the ownership.
ALTER TABLE databasechangelog OWNER TO arwin_ash;
ALTER TABLE databasechangeloglock OWNER TO arwin_ash;
For Angular9+, according to this, you can use:
.mat-select-panel {
background: red;
....
}
mat-select-content
as class name for the select list content. For its styling I would suggest four options.
1. Use ::ng-deep:
Use the /deep/ shadow-piercing descendant combinator to force a style down through the child component tree into all the child component views. The /deep/ combinator works to any depth of nested components, and it applies to both the view children and content children of the component. Use /deep/, >>> and ::ng-deep only with emulated view encapsulation. Emulated is the default and most commonly used view encapsulation. For more information, see the Controlling view encapsulation section. The shadow-piercing descendant combinator is deprecated and support is being removed from major browsers and tools. As such we plan to drop support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until then ::ng-deep should be preferred for a broader compatibility with the tools.
CSS:
::ng-deep .mat-select-content{
width:2000px;
background-color: red;
font-size: 10px;
}
2. Use ViewEncapsulation
... component CSS styles are encapsulated into the component's view and don't affect the rest of the application. To control how this encapsulation happens on a per component basis, you can set the view encapsulation mode in the component metadata. Choose from the following modes: .... None means that Angular does no view encapsulation. Angular adds the CSS to the global styles. The scoping rules, isolations, and protections discussed earlier don't apply. This is essentially the same as pasting the component's styles into the HTML.
None value is what you will need to break the encapsulation and set material style from your component. So can set on the component's selector:
Typscript:
import {ViewEncapsulation } from '@angular/core';
....
@Component({
....
encapsulation: ViewEncapsulation.None
})
CSS
.mat-select-content{
width:2000px;
background-color: red;
font-size: 10px;
}
3. Set class style in style.css
This time you have to 'force' styles with !important
too.
style.css
.mat-select-content{
width:2000px !important;
background-color: red !important;
font-size: 10px !important;
}
4. Use inline style
<mat-option style="width:2000px; background-color: red; font-size: 10px;" ...>
Add your image path like fullPathname='assets/images/therealdealportfoliohero.jpg'
in your constructor. It will work definitely.
To change Title, Description and Image, we need to add some meta tags under head tag.
STEP 1 :
Add meta tags under head tag
<html>
<head>
<meta property="og:url" content="http://www.test.com/" />
<meta property="og:image" content="http://www.test.com/img/fb-logo.png" />
<meta property="og:title" content="Prepaid Phone Cards, low rates for International calls with Lucky Prepay" />
<meta property="og:description" content="Cheap prepaid Phone Cards. Low rates for international calls anywhere in the world." />
NEXT STEP :
Click on below link
https://developers.facebook.com/tools/debug
Add your URL in text box (e.g http://www.test.com/) where you mentioned the tags. Click on DEBUG button.
Its done.
You can verify here https://www.facebook.com/sharer/sharer.php?u=http://www.test.com/
In above url, u = your website link
ENJOY !!!!
This is because the CHARINDEX-1 is returning a -ive value if the look-up for " " (space) is 0. The simplest solution would be to avoid '-ve' by adding
ABS(CHARINDEX(' ', PostCode ) -1))
which will return only +ive values for your length even if CHARINDEX(' ', PostCode ) -1)
is a -ve value. Correct me if I'm wrong!
If I have understood your question correctly you want to display one particular cell of your populated datatable? This what I used to display the given cell in my DataGrid.
var s = dataGridView2.Rows[i].Cells[j].Value;
txt_Country.Text = s.ToString();
Hope this helps
public class Network {
Context context;
public Network(Context context){
this.context = context;
}
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
}
}
Try below code to get currently loaded product id:
$product_id = $this->getProduct()->getId();
When you don’t have access to $this, you can use Magento registry:
$product_id = Mage::registry('current_product')->getId();
Also for product type i think
$product = Mage::getModel('catalog/product')->load($product_id);
$productType = $product->getTypeId();
Here's how you can do it by using loops.
public static int[][] makeCopy(int[][] array){
b=new int[array.length][];
for(int row=0; row<array.length; ++row){
b[row]=new int[array[row].length];
for(int col=0; col<b[row].length; ++col){
b[row][col]=array[row][col];
}
}
return b;
}
Swift 2 and below
let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
var dateString = dateFormatter.stringFromDate(date)
println(dateString)
And in Swift 3 and higher this would now be written as:
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
var dateString = dateFormatter.string(from: date)
Note that using const user = {} as UserType
just provides intellisense but at runtime user
is empty object {}
and has no property inside. that means user.Email
will give undefined
instead of ""
type UserType = {
Username: string;
Email: string;
}
So, use class
with constructor
for actually creating objects with default properties.
type UserType = {
Username: string;
Email: string;
};
class User implements UserType {
constructor() {
this.Username = "";
this.Email = "";
}
Username: string;
Email: string;
}
const myUser = new User();
console.log(myUser); // output: {Username: "", Email: ""}
console.log("val: "+myUser.Email); // output: ""
You can also use interface
instead of type
interface UserType {
Username: string;
Email: string;
};
...and rest of code remains same.
Actually, you can even skip the constructor
part and use it like this:
class User implements UserType {
Username = ""; // will be added to new obj
Email: string; // will not be added
}
const myUser = new User();
console.log(myUser); // output: {Username: ""}
This is an older post, however as the info is still relevant today an additional option may help others.
Define a constant for the file path per Stefan's answer. The definition can be placed at the top of the PHP page itself, or within an included/required external file such as config.php. (http://php.net/manual/en/function.include.php)
Echo the constant in PHP tags, then add the filename directly after.
That's it!
Works for other linked files such as JavaScript as well.
<?php define('CSS_PATH', 'template/css/'); //define CSS path define('JS_PATH', 'template/js/'); //define JavaScript path ?> <!-- Doctype should be declared, even in PHP file --> <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="<?php echo CSS_PATH; ?>main.css"> <script type="text/javascript" src="<?php echo JS_PATH; ?>main.js"></script> </head> <body> </body> </html>
why, how and which parameters are passed to Asynctask<>, see detail here. I think it is the best explanation.
Google's Android Documentation Says that :
An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
AsyncTask's generic types :
The three types used by an asynchronous task are the following:
Params, the type of the parameters sent to the task upon execution. Progress, the type of the progress units published during the background computation. Result, the type of the result of the background computation. Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:
private class MyTask extends AsyncTask<Void, Void, Void> { ... }
You Can further refer : http://developer.android.com/reference/android/os/AsyncTask.html
Or You Can clear whats the role of AsyncTask by refering Sankar-Ganesh's Blog
Well The structure of a typical AsyncTask class goes like :
private class MyTask extends AsyncTask<X, Y, Z>
protected void onPreExecute(){
}
This method is executed before starting the new Thread. There is no input/output values, so just initialize variables or whatever you think you need to do.
protected Z doInBackground(X...x){
}
The most important method in the AsyncTask class. You have to place here all the stuff you want to do in the background, in a different thread from the main one. Here we have as an input value an array of objects from the type “X” (Do you see in the header? We have “...extends AsyncTask” These are the TYPES of the input parameters) and returns an object from the type “Z”.
protected void onProgressUpdate(Y y){
} This method is called using the method publishProgress(y) and it is usually used when you want to show any progress or information in the main screen, like a progress bar showing the progress of the operation you are doing in the background.
protected void onPostExecute(Z z){
} This method is called after the operation in the background is done. As an input parameter you will receive the output parameter of the doInBackground method.
What about the X, Y and Z types?
As you can deduce from the above structure:
X – The type of the input variables value you want to set to the background process. This can be an array of objects.
Y – The type of the objects you are going to enter in the onProgressUpdate method.
Z – The type of the result from the operations you have done in the background process.
How do we call this task from an outside class? Just with the following two lines:
MyTask myTask = new MyTask();
myTask.execute(x);
Where x is the input parameter of the type X.
Once we have our task running, we can find out its status from “outside”. Using the “getStatus()” method.
myTask.getStatus(); and we can receive the following status:
RUNNING - Indicates that the task is running.
PENDING - Indicates that the task has not been executed yet.
FINISHED - Indicates that onPostExecute(Z) has finished.
Hints about using AsyncTask
Do not call the methods onPreExecute, doInBackground and onPostExecute manually. This is automatically done by the system.
You cannot call an AsyncTask inside another AsyncTask or Thread. The call of the method execute must be done in the UI Thread.
The method onPostExecute is executed in the UI Thread (here you can call another AsyncTask!).
The input parameters of the task can be an Object array, this way you can put whatever objects and types you want.
From the announcement Git 1.7.10 (April 2012):
git clone
learned--single-branch
option to limit cloning to a single branch (surprise!); tags that do not point into the history of the branch are not fetched.
Git actually allows you to clone only one branch, for example:
git clone -b mybranch --single-branch git://sub.domain.com/repo.git
Note: Also you can add another single branch or "undo" this action.
Disable the antivirus on the folders where is the code of the web application. In my case I have observed a big improvement with Avast antivirus.
No one has mentioned the obvious:
var myCallback = function() { console.log("name or age changed"); };
$scope.$watch("name", myCallback);
$scope.$watch("age", myCallback);
This might mean a little less polling. If you watch both name + age
(for this) and name
(elsewhere) then I assume Angular will effectively look at name
twice to see if it's dirty.
It's arguably more readable to use the callback by name instead of inlining it. Especially if you can give it a better name than in my example.
And you can watch the values in different ways if you need to:
$scope.$watch("buyers", myCallback, true);
$scope.$watchCollection("sellers", myCallback);
$watchGroup
is nice if you can use it, but as far as I can tell, it doesn't let you watch the group members as a collection or with object equality.
If you need the old and new values of both expressions inside one and the same callback function call, then perhaps some of the other proposed solutions are more convenient.
I wasn't able to ever accomplish this but rather used view html source apps available on the Play Store to simply look for the element.
The keyword for Oracle PL/SQL is "ELSIF" ( no extra "E"), not ELSEIF (yes, confusing and stupid)
declare
var_number number;
begin
var_number := 10;
if var_number > 100 then
dbms_output.put_line(var_number||' is greater than 100');
elsif var_number < 100 then
dbms_output.put_line(var_number||' is less than 100');
else
dbms_output.put_line(var_number||' is equal to 100');
end if;
end;
basically if you already specify the year range there is no need to use mindate
and maxdate
if only year is required
you should use rownum in oracle to do what you seek
where rownum <= 100
see also those answers to help you
The Jenkinsfile is written in groovy which uses the Java (and C) form of comments:
/* this
is a
multi-line comment */
// this is a single line comment
Below code checks for same number, sequence number and reverse number sequence.
function checkNumSequnce(arrayNM2) {
inseqCounter=1;
continousSeq = 1;
decsequenceConter = 1;
var isequence = true;
for (i=0;i<arrayNM2.length-1;i++) {
j=i+1;
if (arrayNM2[i] == arrayNM2[i+1]) {
if(inseqCounter > 1 || decsequenceConter > 1){
isequence = false; break;
}
continousSeq++;
}
else if (arrayNM2[j]- arrayNM2[i] == 1) {
if(decsequenceConter > 1 || continousSeq > 1){
isequence = false; break;
}
inseqCounter++;
} else if(arrayNM2[i]- arrayNM2[j] == 1){
if(inseqCounter > 1 || continousSeq > 1){
isequence = false; break;
}
decsequenceConter++;
}else{
isequence= false;
break;
}
};
console.log("isequence: "+ isequence);
};
To be able to build with C# 6 syntax use this in path:
C:\Program Files (x86)\MSBuild\14.0\Bin
It gives you the remainder of a division.
int c=11, d=5;
cout << (c/d) * d + c % d; // gives you the value of c
This is documented on the doxygen website, but to summarize here:
You can use doxygen to document your Python code. You can either use the Python documentation string syntax:
"""@package docstring
Documentation for this module.
More details.
"""
def func():
"""Documentation for a function.
More details.
"""
pass
In which case the comments will be extracted by doxygen, but you won't be able to use any of the special doxygen commands.
Or you can (similar to C-style languages under doxygen) double up the comment marker (#
) on the first line before the member:
## @package pyexample
# Documentation for this module.
#
# More details.
## Documentation for a function.
#
# More details.
def func():
pass
In that case, you can use the special doxygen commands. There's no particular Python output mode, but you can apparently improve the results by setting OPTMIZE_OUTPUT_JAVA
to YES
.
Honestly, I'm a little surprised at the difference - it seems like once doxygen can detect the comments in ## blocks or """ blocks, most of the work would be done and you'd be able to use the special commands in either case. Maybe they expect people using """ to adhere to more Pythonic documentation practices and that would interfere with the special doxygen commands?
DateTime dt1 = DateTime.Now.Date;
DateTime dt2 = Convert.ToDateTime(TextBox4.Text.Trim()).Date;
if (dt1 >= dt2)
{
MessageBox.Show("Valid Date");
}
else
{
MessageBox.Show("Invalid Date... Please Give Correct Date....");
}
Two ways of doing it.
<asp:Calendar ID="planning" runat="server" SelectedDate="<%# DateTime.Now %>"></asp:Calendar>
protected void Page_Load(object sender, EventArgs e)
{
BindCalendar();
}
private void BindCalendar()
{
planning.SelectedDate = DateTime.Today;
}
Altough, I strongly recommend to do it from a BindMyStuff way. Single entry point easier to debug. But since you seems to know your game, you're all set.
They definitely may give different results. The better one is
select count(*) from pg_stat_activity;
It's because it includes connections to WAL sender processes which are treated as regular connections and count towards max_connections
.
See max_wal_senders
I had exactly the same problem try to put the two classes in the same package and add line in the pom.xml
<dependency>
<groupId> org.springframework.boot </groupId>
<artifactId> spring-boot-starter-web </artifactId>
<version> 1.2.0.RELEASE </version>
</dependency>
txt_name.value
txt_name.onkeyup = e=> alert(txt_name.value);
_x000D_
<input type="text" id="txt_name" />
_x000D_
HTTP transaction, basic access authentication, is not suitable for RBAC, because basic access authentication uses the encrypted username:password every time to identify, while what is needed in RBAC is the Role the user wants to use for a specific call. RBAC does not validate permissions on username, but on roles.
You could tric around to concatenate like this: usernameRole:password, but this is bad practice, and it is also inefficient because when a user has more roles, the authentication engine would need to test all roles in concatenation, and that every call again. This would destroy one of the biggest technical advantages of RBAC, namely a very quick authorization-test.
So that problem cannot be solved using basic access authentication.
To solve this problem, session-maintaining is necessary, and that seems, according to some answers, in contradiction with REST.
That is what I like about the answer that REST should not be treated as a religion. In complex business cases, in healthcare, for example, RBAC is absolutely common and necessary. And it would be a pity if they would not be allowed to use REST because all REST-tools designers would treat REST as a religion.
For me there are not many ways to maintain a session over HTTP. One can use cookies, with a sessionId, or a header with a sessionId.
If someone has another idea I will be glad to hear it.
This is the code you need:
string strInput = "0001234";
strInput = strInput.TrimStart('0');
In controller:
function innerItem($scope, $element){
var jQueryInnerItem = $($element);
}
I had to do a similar thing but I needed to add values with same keys. When I use merge or update I can't push values with same keys. So I had to use array of hashes.
my_hash_static = {:header =>{:company => 'xx', :usercode => 'xx', :password => 'xx',
:type=> 'n:n', :msgheader => from}, :body=>[]}
my_hash_dynamic = {:mp=>{:msg=>message, :no=>phones} }
my_hash_full = my_hash_static[:body].push my_hash_dynamic
Are you referring to the full resolution one?:
https://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg
I don't believe you can get 'multiple' images of HQ because the one you have is the one.
Check the following answer out for more information on the URLs: How do I get a YouTube video thumbnail from the YouTube API?
For live videos use
https://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault_live.jpg
- cornips
1) Normally, you would want to return a Task
. The main exception should be when you need to have a void
return type (for events). If there's no reason to disallow having the caller await
your task, why disallow it?
2) async
methods that return void
are special in another aspect: they represent top-level async operations, and have additional rules that come into play when your task returns an exception. The easiest way is to show the difference is with an example:
static async void f()
{
await h();
}
static async Task g()
{
await h();
}
static async Task h()
{
throw new NotImplementedException();
}
private void button1_Click(object sender, EventArgs e)
{
f();
}
private void button2_Click(object sender, EventArgs e)
{
g();
}
private void button3_Click(object sender, EventArgs e)
{
GC.Collect();
}
f
's exception is always "observed". An exception that leaves a top-level asynchronous method is simply treated like any other unhandled exception. g
's exception is never observed. When the garbage collector comes to clean up the task, it sees that the task resulted in an exception, and nobody handled the exception. When that happens, the TaskScheduler.UnobservedTaskException
handler runs. You should never let this happen. To use your example,
public static async void AsyncMethod2(int num)
{
await Task.Factory.StartNew(() => Thread.Sleep(num));
}
Yes, use async
and await
here, they make sure your method still works correctly if an exception is thrown.
for more information see: http://msdn.microsoft.com/en-us/magazine/jj991977.aspx
I have used this simple function for this:
private static Pattern pattern = Pattern.compile("[^ -~]");
private static String cleanTheText(String text) {
Matcher matcher = pattern.matcher(text);
if ( matcher.find() ) {
text = text.replace(matcher.group(0), "");
}
return text;
}
Hope this is useful.
For a small enum like this, I find the most readable solution to be:
public enum Direction {
NORTH {
@Override
public Direction getOppositeDirection() {
return SOUTH;
}
},
SOUTH {
@Override
public Direction getOppositeDirection() {
return NORTH;
}
},
EAST {
@Override
public Direction getOppositeDirection() {
return WEST;
}
},
WEST {
@Override
public Direction getOppositeDirection() {
return EAST;
}
};
public abstract Direction getOppositeDirection();
}
I solved this issue by using sudo ie
sudo yarn start
or
sudo npm start
Another way using jQuery:
var exists = false;
$('#yourSelect option').each(function(){
if (this.value == yourValue) {
exists = true;
}
});
the thing that kept on killing me was that i didn't know that this app was installed for my guest account (although I had uninstalled it for the other accounts..)
so i searched for the app in the app manager, and simply clicked on uninstall for all users
Try just parent.myfunction()
Looks like I'm a bit late but for others with this issue try this code
p { font-size: 3vmax; }
use whatever tag you prefer and size you prefer (replace the 3)
p { font-size: 3vmin; }
is used for a max size.
In my opinion you should not load and use plugins you don't have to. This particular jQuery plugin doesn't give you anything since directly using the JavaScript sessionStorage
object is exactly the same level of complexity. Nor, does the plugin provide some easier way to interact with other jQuery functionality. In addition the practice of using a plugin discourages a deep understanding of how something works. sessionStorage should be used only if its understood. If its understood, then using the jQuery plugin is actually MORE effort.
Consider using sessionStorage
directly:
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#sessionStorage
There was an issue posted here about this: https://github.com/twbs/bootstrap/issues/14107
The issue was solved by this commit: https://github.com/twbs/bootstrap/commit/bd292ca3b89da982abf34473318c77ace3417fb5
The solution therefore is to override it back to #999
and not white
as suggested (and also overriding all bootstraps styles, not just for webkit-styles):
.form-control::-moz-placeholder {
color: #999;
}
.form-control:-ms-input-placeholder {
color: #999;
}
.form-control::-webkit-input-placeholder {
color: #999;
}
Why it's happening?
due to lock icon
on some folder(not having read/write access) in
"/yourpath/android-studio-SDK"
Sort and sweet solution
-Open Terminal (Ctrl +alt +t)
-copy pest sudo chown -R $USER: $HOME
-wait for a while.....
-now Try again to update your SDK
Happy Coding :)
ReDim aFirstArray(0)
This will resize the array to zero and erase all data.
This worked for me like a charm:
proxy = "localhost:8080"
desired_capabilities = webdriver.DesiredCapabilities.CHROME.copy()
desired_capabilities['proxy'] = {
"httpProxy": proxy,
"ftpProxy": proxy,
"sslProxy": proxy,
"noProxy": None,
"proxyType": "MANUAL",
"class": "org.openqa.selenium.Proxy",
"autodetect": False
}
The Web Tools Platform provides the Java EE development tools, and is included in the IDE for Java EE Developers. Among other things, it provides the Servers view and makes it easy to launch a Tomcat server from there. You can either download the IDE for Java EE Developers, or go to the Help menu and Install New Software, looking for the Java EE features.
Assert can help you give separate messaging behavior between testing and release. For example,
Debug.Assert(x > 2)
will only trigger a break if you are running a "debug" build, not a release build. There's a full example of this behavior here
Here is another alternate without reduce that performs well with large numbers. It uses sum
to flatten the list.
def factors(n):
return set(sum([[i, n//i] for i in xrange(1, int(n**0.5)+1) if not n%i], []))
You'll probably want to handle spaces in your file names, abhorrent though they are :-)
So I would opt initially for something like:
pax> cat qq.in
normalfile.txt
file with spaces.doc
pax> sed 's/ /\\ /g' qq.in | xargs -n 1 cat
<<contents of 'normalfile.txt'>>
<<contents of 'file with spaces.doc'>>
pax> _
Try this:
Integer startIn = null;
try {
startIn = Integer.valueOf(startField.getText());
} catch (NumberFormatException e) {
.
.
.
}
if (startIn == null) {
// Prompt for value...
}
The MIT licensed HtmlAgilityPack has in one of its samples a method that converts from HTML to plain text.
var plainText = HtmlUtilities.ConvertToPlainText(string html);
Feed it an HTML string like
<b>hello, <i>world!</i></b>
And you'll get a plain text result like:
hello world!
select *
from user
left join edge
on user.userid = edge.tailuser
and edge.headuser = 5043
I found that the following worked for me. These steps come from BTD's YouTube video, Managing Zipfile's in R:
zip.url <- "url_address.zip"
dir <- getwd()
zip.file <- "file_name.zip"
zip.combine <- as.character(paste(dir, zip.file, sep = "/"))
download.file(zip.url, destfile = zip.combine)
unzip(zip.file)
IB and Swift
Given the flowing layout where yellow is the superview and red, green, and blue are sibling subviews of yellow,
the goal is to move a subview (let's say green) to the top.
In the Interface Builder all you need to do is drag the view you want showing on the top to the bottom of the list in the Documents Outline.
Alternatively, you can select the view and then in the menu go to Editor > Arrange > Send to Front.
There are a couple of different ways to do this programmatically.
Method 1
yellowView.bringSubviewToFront(greenView)
This method is the programmatic equivalent of the IB answer above.
It only works if the subviews are siblings of each other.
An array of the subviews is contained in yellowView.subviews
. Here, bringSubviewToFront
moves the greenView
from index 0
to 2
. This can be observed with
print(yellowView.subviews.indexOf(greenView))
Method 2
greenView.layer.zPosition = 1
0
for all the other views, the result is that the greenView
looks like it is on top. However, it still remains at index 0
of the yellowView.subviews
array. This can cause some unexpected results, though, because things like tap events will still go first to the view with the highest index number. For that reason, it might be better to go with Method 1 above.zPosition
could be set to CGFloat.greatestFiniteMagnitude
(CGFloat(FLT_MAX)
in older versions of Swift) to ensure that it is on top.This will get you a list of all files that were deleted in all branches, sorted by their path:
git log --diff-filter=D --summary | grep "delete mode 100" | cut -c 21- | sort > deleted.txt
Works in msysgit (2.6.1.windows.1). Note we need "delete mode 100" as git files may have been commited as mode 100644 or 100755.
Rethink your approach. Why would you copy only part of the sheet? You are referring to a named range "WholePrintArea" which doesn't exist. Also you should never use activate, select, copy or paste in your script. These make the "script" vulnerable to user actions and other simultaneous executions. In worst case scenario data ends up in wrong hands.
Not entirely sure what you want here, but if you want to discount blank cells in the range and pass over zeros then this would do it; if a little contrived:
=MIN(IF(A1:E1=0,MAX(A1:E1),A1:E1))
With Ctrl+Shift+Enter as an array.
What I'm doing here is replacing zeros with the maximum value in the list.
Tensorflow on windows needs python 3.5. You can follow following steps to activate python 3.5 in anaconda:
conda search python
conda create -n py35 python=3.5 anaconda
to create python 3.5activate py35
conda install tensorflow
If step4 is not working i.e, something like "tensorflow: no package found " then follow this tutorial to forge conda-forge
channel and then try installing tensorflow using step4. It worked for me.
HTML Form Element Validation
Run Function
<script>
$("#validationForm").validation({
button: "#btnGonder",
onSubmit: function () {
alert("Submit Process");
},
onCompleted: function () {
alert("onCompleted");
},
onError: function () {
alert("Error Process");
}
});
</script>
Go to example and download https://github.com/naimserin/Validation.