In EF6
Add-Migration Initial
.Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -
sign before value
:
ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) +
geom_bar(stat = "identity")
which gives:
Used data:
corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
value = c(7L, 75L, 70L, 5L, 10L, 47L)),
class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))
Example:
ALTER TABLE [Employees] ADD Seniority int not null default 0 GO
Alternative #6233....
Add the UTC offset to the local time then convert it to the desired format with the toLocaleDateString()
method of the Date
object:
// Using the current date/time
let now_local = new Date();
let now_utc = new Date();
// Adding the UTC offset to create the UTC date/time
now_utc.setMinutes(now_utc.getMinutes() + now_utc.getTimezoneOffset())
// Specify the format you want
let date_format = {};
date_format.year = 'numeric';
date_format.month = 'numeric';
date_format.day = '2-digit';
date_format.hour = 'numeric';
date_format.minute = 'numeric';
date_format.second = 'numeric';
// Printing the date/time in UTC then local format
console.log('Date in UTC: ', now_utc.toLocaleDateString('us-EN', date_format));
console.log('Date in LOC: ', now_local.toLocaleDateString('us-EN', date_format));
I'm creating a date object defaulting to the local time. I'm adding the UTC off-set to it. I'm creating a date-formatting object. I'm displaying the UTC date/time in the desired format:
You aren't going to be able to do this from the HashMap class alone.
I would take the Map<String, String> codes
, construct a reverse map of TreeMap<String, String> reversedMap
where you map the values of the codes
Map to the keys (this would require your original Map to have a one-to-one mapping from key-to-value). Since the TreeMap provides Iterators which returns entries in ascending key order, this will give you the value/key combination of the first map in the order (sorted by values) you desire.
Map<String, String> reversedMap = new TreeMap<String, String>(codes);
//then you just access the reversedMap however you like...
for (Map.Entry entry : reversedMap.entrySet()) {
System.out.println(entry.getKey() + ", " + entry.getValue());
}
There are several collections libraries (commons-collections, Google Collections, etc) which have similar bidirectional Map implementations.
You can use std::reverse
like this
std::reverse(str.begin(), str.end());
You have to pass $ in function()
<script>
jQuery(document).ready(function($){
// jQuery code is in here
});
</script>
If, like me, you don't like to rely on JavaScript for links on buttons. You can also use a anchor and style it like your buttons using CSS.
<a href="/Controller/View" class="Button">Text</a>
how remote is that url ? is it from the same domain ? the code looks okay
try this
$.ajaxSetup({async:false});
$.get(remote_url, function(data) { remote = data; });
// or
remote = $.get(remote_url).responseText;
Clearing screen in Java is not supported, but you can try some hacks to achieve this.
a) Use OS-depends command, like this for Windows:
Runtime.getRuntime().exec("cls");
b) Put bunch of new lines (this makes ilusion that screen is clear)
c) If you ever want to turn off System.out, you can try this:
System.setOut(new PrintStream(new OutputStream() {
@Override public void write(int b) throws IOException {}
}));
I had to kill off all instances of mysql by first finding all the process IDs:
ps aux | grep mysql
And then killing them off:
kill -9 {pid}
Then:
mysql.server start
Worked for me.
What about providing a custom N-Factor authentication mechanism?
Before combining available methods, let's assume we can perform the following:
1) Hard-code inside the Java program
2) Store in a .properties file
3) Ask user to type password from command line
4) Ask user to type password from a form
5) Ask user to load a password-file from command line or a form
6) Provide the password through network
7) many alternatives (eg Draw A Secret, Fingerprint, IP-specific, bla bla bla)
1st option: We could make things more complicated for an attacker by using obfuscation, but this is not considered a good countermeasure. A good coder can easily understand how it works if he/she can access the file. We could even export a per-user binary (or just the obfuscation part or key-part), so an attacker must have access to this user-specific file, not another distro. Again, we should find a way to change passwords, eg by recompiling or using reflection to on-the-fly change class behavior.
2nd option: We can store the password in the .properties file in an encrypted format, so it's not directly visible from an attacker (just like jasypt does). If we need a password manager we'll need a master password too which again should be stored somewhere - inside a .class file, the keystore, kernel, another file or even in memory - all have their pros and cons.
But, now users will just edit the .properties file for password change.
3rd option: type the password when running from command line e.g. java -jar /myprogram.jar -p sdflhjkiweHIUHIU8976hyd
.
This doesn't require the password to be stored and will stay in memory. However, history
commands and OS logs, may be your worst enemy here.
To change passwords on-the-fly, you will need to implement some methods (eg listen for console inputs, RMI, sockets, REST bla bla bla), but the password will always stay in memory.
One can even temporarily decrypt it only when required -> then delete the decrypted, but always keep the encrypted password in memory. Unfortunately, the aforementioned method does not increase security against unauthorized in-memory access, because the person who achieves that, will probably have access to the algorithm, salt and any other secrets being used.
4th option: provide the password from a custom form, rather than the command line. This will circumvent the problem of logging exposure.
5th option: provide a file as a password stored previously on a another medium -> then hard delete file. This will again circumvent the problem of logging exposure, plus no typing is required that could be shoulder-surfing stolen. When a change is required, provide another file, then delete again.
6th option: again to avoid shoulder-surfing, one can implement an RMI method call, to provide the password (through an encrypted channel) from another device, eg via a mobile phone. However, you now need to protect your network channel and access to the other device.
I would choose a combination of the above methods to achieve maximum security so one would have to access the .class files, the property file, logs, network channel, shoulder surfing, man in the middle, other files bla bla bla. This can be easily implemented using a XOR operation between all sub_passwords to produce the actual password.
We can't be protected from unauthorized in-memory access though, this can only be achieved by using some access-restricted hardware (eg smartcards, HSMs, SGX), where everything is computed into them, without anyone, even the legitimate owner being able to access decryption keys or algorithms. Again, one can steal this hardware too, there are reported side-channel attacks that may help attackers in key extraction and in some cases you need to trust another party (eg with SGX you trust Intel). Of course, situation may worsen when secure-enclave cloning (de-assembling) will be possible, but I guess this will take some years to be practical.
Also, one may consider a key sharing solution where the full key is split between different servers. However, upon reconstruction, the full key can be stolen. The only way to mitigate the aforementioned issue is by secure multiparty computation.
We should always keep in mind that whatever the input method, we need to ensure we are not vulnerable from network sniffing (MITM attacks) and/or key-loggers.
In addition to other answers which helped me, you can also add to surrounding div. In my case this was for sign on with user Name/Password fields.
<div (keyup.enter)="login()" class="container-fluid">
XSD defines a schema which is a definition of how an XML document can be structured. You can use it to check that a given XML document is valid and follows the rules you've laid out in the schema.
WSDL is a XML document that describes a web service. It shows which operations are available and how data should be structured to send to those operations.
WSDL documents have an associated XSD that show what is valid to put in a WSDL document.
Kindly check whether you have installed right version of ChromeDriver or not . In my case , installing correct version helped.
If you want data validation too
<!-- form -->
<form name="loginForm">
...
<input type="email" ng-keyup="$loginForm.$valid && $event.keyCode == 13 && signIn()" ng-model="email"... />
<input type="password" ng-keyup="$loginForm.$valid && $event.keyCode == 13 && signIn()" ng-model="password"... />
</form>
The important addition here is $loginForm.$valid
which will validate the form before executing function. You will have to add other attributes for validation which is beyond the scope of this question.
Good Luck.
Try using the float
package and then the [H]
option for your figure.
\usepackage{float}
...
\begin{figure}[H]
\centering
\includegraphics{fig1}
\caption{Write some caption here}\label{fig1}
\end{figure}
as already suggested by this insightful answer!
https://tex.stackexchange.com/questions/8625/force-figure-placement-in-text
You can fill an array with arrays using a function:
var arr = [];
var rows = 11;
var columns = 12;
fill2DimensionsArray(arr, rows, columns);
function fill2DimensionsArray(arr, rows, columns){
for (var i = 0; i < rows; i++) {
arr.push([0])
for (var j = 0; j < columns; j++) {
arr[i][j] = 0;
}
}
}
The result is:
Array(11)
0:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
1:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
2:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
3:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
4:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
5:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
6:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
7:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
8:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
9:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
10:(12)[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
By XPath: inspect the element on target page, copy Xpath and use the below script:worked for me.
WebElement nameInputField = driver.findElement(By.xpath("html/body/div[6]/div[1]/div[3]/div/div/div[1]/div[3]/ul/li[4]/a"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", nameInputField);
If you want to check for false and alert if not, then no there isn't.
If you use if(val)
, then anything that evaluates to 'truthy', like a non-empty string, will also pass. So it depends on how stringent your criterion is. Using ===
and !==
is generally considered good practice, to avoid accidentally matching truthy or falsy conditions via JavaScript's implicit boolean tests.
[root@piwik-dev tmp]# mail -v root@localhost
Subject: Test
Hello world
Cc: <Ctrl+D>
root@localhost... Connecting to [127.0.0.1] via relay...
220 piwik-dev.example.com ESMTP Sendmail 8.13.8/8.13.8; Thu, 23 Aug 2012 10:49:40 -0400
>>> EHLO piwik-dev.example.com
250-piwik-dev.example.com Hello localhost.localdomain [127.0.0.1], pleased to meet you
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-8BITMIME
250-SIZE
250-DSN
250-ETRN
250-DELIVERBY
250 HELP
>>> MAIL From:<[email protected]> SIZE=46
250 2.1.0 <[email protected]>... Sender ok
>>> RCPT To:<[email protected]>
>>> DATA
250 2.1.5 <[email protected]>... Recipient ok
354 Enter mail, end with "." on a line by itself
>>> .
250 2.0.0 q7NEneju002633 Message accepted for delivery
root@localhost... Sent (q7NEneju002633 Message accepted for delivery)
Closing connection to [127.0.0.1]
>>> QUIT
221 2.0.0 piwik-dev.example.com closing connection
As what Jakob said: windows sdk 7.1 cannot be installed if MS VC++ x64 and x86 runtimes and redisrtibutables of version 10.0.40219 are present. after removing them win sdk install is okay, VS C++ SP1 can be installed fine again.
Kind regards
You can scale the image with pygame.transform.scale
:
import pygame
picture = pygame.image.load(filename)
picture = pygame.transform.scale(picture, (1280, 720))
You can then get the bounding rectangle of picture
with
rect = picture.get_rect()
and move the picture with
rect = rect.move((x, y))
screen.blit(picture, rect)
where screen
was set with something like
screen = pygame.display.set_mode((1600, 900))
To allow your widgets to adjust to various screen sizes, you could make the display resizable:
import os
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((500, 500), HWSURFACE | DOUBLEBUF | RESIZABLE)
pic = pygame.image.load("image.png")
screen.blit(pygame.transform.scale(pic, (500, 500)), (0, 0))
pygame.display.flip()
while True:
pygame.event.pump()
event = pygame.event.wait()
if event.type == QUIT:
pygame.display.quit()
elif event.type == VIDEORESIZE:
screen = pygame.display.set_mode(
event.dict['size'], HWSURFACE | DOUBLEBUF | RESIZABLE)
screen.blit(pygame.transform.scale(pic, event.dict['size']), (0, 0))
pygame.display.flip()
You can also use the following construct:
String[][] myStringArray = new String [][] { { "X0", "Y0"},
{ "X1", "Y1"},
{ "X2", "Y2"},
{ "X3", "Y3"},
{ "X4", "Y4"} };
You will need a custom class loader for this, have a look at One Jar.
One-JAR lets you package a Java application together with its dependency Jars into a single executable Jar file.
It has an ant task which can simplify the building of it as well.
REFERENCE (from background)
Most developers reasonably assume that putting a dependency Jar file into their own Jar file, and adding a Class-Path attribute to the META-INF/MANIFEST will do the trick:
jarname.jar
| /META-INF
| | MANIFEST.MF
| | Main-Class: com.mydomain.mypackage.Main
| | Class-Path: commons-logging.jar
| /com/mydomain/mypackage
| | Main.class
| commons-logging.jar
Unfortunately this is does not work. The Java
Launcher$AppClassLoader
does not know how to load classes from a Jar inside a Jar with this kind ofClass-Path
. Trying to usejar:file:jarname.jar!/commons-logging.jar
also leads down a dead-end. This approach will only work if you install (i.e. scatter) the supporting Jar files into the directory where the jarname.jar file is installed.
There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:
With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.
Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/
Update 2019:
Probably the biggest problem of heap allocation versus stack allocation, is that heap allocation in the general case is an unbounded operation, and thus you can't use it where timing is an issue.
For other applications where timing isn't an issue, it may not matter as much, but if you heap allocate a lot, this will affect the execution speed. Always try to use the stack for short lived and often allocated memory (for instance in loops), and as long as possible - do heap allocation during application startup.
The text uses combining characters, also known as combining marks. See section 2.11 of Combining Characters in the Unicode Standard (PDF).
In Unicode, character rendering does not use a simple character cell model where each glyph fits into a box with given height. Combining marks may be rendered above, below, or inside a base character
So you can easily construct a character sequence, consisting of a base character and “combining above” marks, of any length, to reach any desired visual height, assuming that the rendering software conforms to the Unicode rendering model. Such a sequence has no meaning of course, and even a monkey could produce it (e.g., given a keyboard with suitable driver).
And you can mix “combining above” and “combining below” marks.
The sample text in the question starts with:
H
ͭ
̓
̓
̇
For me Fake Sendmail works.
What to do:
1) Edit C:\wamp\sendmail\sendmail.ini:
smtp_server=smtp.gmail.com
smtp_port=465
[email protected]
auth_password=your_password
2) Edit php.ini
and set sendmail_path
sendmail_path = "C:\wamp\sendmail\sendmail.exe -t"
That's it. Now you can test a mail.
You can try overflow
css property.
You can use the sequence of a no-break space (U+00a0
) followed by two spaces (U+0020
×2) followed by a newline (U+000a
) repeatedly to achieve this. Two or more times is required depending on your use case.
Using (not markdown interpreted here, but) actual white space characters (theoretically copy-and-paste-able):
Preceding Following.
@Adam Rosenfield's solution, although correct, could be implemented with a more lightweight circular_buffer
structure that does not invlove count
and capacity
.
The structure could only hold the following 4 pointers:
buffer
: Points to the start of the buffer in memory.buffer_end
: Points to the end of the buffer in memory.head
: Points to the end of stored data.tail
: Points to the start of stored data.We could keep the sz
attribute to allow the parametrisation of the unit of storage.
Both the count
and the capacity
values should be derive-able using the above pointers.
capacity
is straight forward, as it can be derived by dividing the distance between the buffer_end
pointer and the buffer
pointer by the unit of storage sz
(snippet below is pseudocode):
capacity = (buffer_end - buffer) / sz
For count though, things get a bit more complicated. For example, there is no way to determine whether the buffer is empty or full, in the scenario of head
and tail
pointing to the same location.
To tackle that, the buffer should allocate memory for an additional element. For example, if the desired capacity of our circular buffer is 10 * sz
, then we need to allocate 11 * sz
.
Capacity formula will then become (snippet below is pseudocode):
capacity_bytes = buffer_end - buffer - sz
capacity = capacity_bytes / sz
This extra element semantic allows us to construct conditions that evaluate whether the buffer is empty or full.
In order for the buffer to be empty, the head
pointer points to the same location as the tail
pointer:
head == tail
If the above evaluates to true, the buffer is empty.
In order for the buffer to be full, the head
pointer should be 1 element behind the tail
pointer. Thus, the space needed to cover in order to jump from the head
location to the tail
location should be equal to 1 * sz
.
tail
is larger that head
:tail - head == sz
If the above evaluates to true, the buffer is full.
head
is larger that tail
:buffer_end - head
returns the space to jump from the head
to the end of the buffer.tail - buffer
returns the space needed to jump from the start of the buffer to the `tail.head
to the tail
1 * sz
(buffer_end - head) + (tail - buffer) == sz
=> buffer_end - buffer - head + tail == sz
=> buffer_end - buffer - sz == head - tail
=> head - tail == buffer_end - buffer - sz
=> head - tail == capacity_bytes
If the above evaluates to true, the buffer is full.
Modifying @Adam Rosenfield's to use the above circular_buffer
structure:
#include <string.h>
#define CB_SUCCESS 0 /* CB operation was successful */
#define CB_MEMORY_ERROR 1 /* Failed to allocate memory */
#define CB_OVERFLOW_ERROR 2 /* CB is full. Cannot push more items. */
#define CB_EMPTY_ERROR 3 /* CB is empty. Cannot pop more items. */
typedef struct circular_buffer {
void *buffer;
void *buffer_end;
size_t sz;
void *head;
void *tail;
} circular_buffer;
int cb_init(circular_buffer *cb, size_t capacity, size_t sz) {
const int incremented_capacity = capacity + 1; // Add extra element to evaluate count
cb->buffer = malloc(incremented_capacity * sz);
if (cb->buffer == NULL)
return CB_MEMORY_ERROR;
cb->buffer_end = (char *)cb->buffer + incremented_capacity * sz;
cb->sz = sz;
cb->head = cb->buffer;
cb->tail = cb->buffer;
return CB_SUCCESS;
}
int cb_free(circular_buffer *cb) {
free(cb->buffer);
return CB_SUCCESS;
}
const int _cb_length(circular_buffer *cb) {
return (char *)cb->buffer_end - (char *)cb->buffer;
}
int cb_push_back(circular_buffer *cb, const void *item) {
const int buffer_length = _cb_length(cb);
const int capacity_length = buffer_length - cb->sz;
if ((char *)cb->tail - (char *)cb->head == cb->sz ||
(char *)cb->head - (char *)cb->tail == capacity_length)
return CB_OVERFLOW_ERROR;
memcpy(cb->head, item, cb->sz);
cb->head = (char*)cb->head + cb->sz;
if(cb->head == cb->buffer_end)
cb->head = cb->buffer;
return CB_SUCCESS;
}
int cb_pop_front(circular_buffer *cb, void *item) {
if (cb->head == cb->tail)
return CB_EMPTY_ERROR;
memcpy(item, cb->tail, cb->sz);
cb->tail = (char*)cb->tail + cb->sz;
if(cb->tail == cb->buffer_end)
cb->tail = cb->buffer;
return CB_SUCCESS;
}
I could not make @Clockwork-Muse work actually. But I could make this variation work:
WITH Tmp AS (SELECT * FROM (VALUES (id1, newsPosX1, newPosY1),
(id2, newsPosX2, newPosY2),
......................... ,
(idN, newsPosXN, newPosYN)) d(id, px, py))
UPDATE t
SET posX = (SELECT px FROM Tmp WHERE t.id = Tmp.id),
posY = (SELECT py FROM Tmp WHERE t.id = Tmp.id)
FROM TableToUpdate t
I hope this works for you too!
-Module name gulp-task
-Project name project-x
You want to link gulp-task:
1: Go to the gulp-task directory then do npm link
this will symlink the project to your global modules
2: Go to your project project-x then do npm install
make sure to remove the current node_modules directory
Now you want to remove this madness and use the real gulp-task, we have two options:
1: Go to your project and do npm unlink gulp-task
this will remove the linked installed module
2: Go to the gulp-task directory and do npm unlink
to remove symlink. Notice we didn't use the name of the module
3: celebrate
What if this didn't work, verify by locating your global installed module. My are location ls -la /usr/local/lib/node_modules/
if you are using nvm it will be a different path
1: locate your global dependencies cd /usr/local/lib/node_modules/
2: removing symlink is simply using the rm
command
rm gulp-task
make sure you don't have /
at the end
rm gulp-task/
is wrong
rm gulp-task
??
Yes and no. All the common web browsers has a security measure to prevent that. The goal is to prevent people from creating replicas of websites, change the URL to make it look correct, and then be able to trick people and get their info.
However, some HTML5 compatible web browsers has implemented an History API that can be used for something similar to what you want:
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?myNewUrlQuery=1';
window.history.pushState({path:newurl},'',newurl);
}
I tested, and it worked fine. It does not reload the page, but it only allows you to change the URL query. You would not be able to change the protocol or the host values.
For more information:
http://diveintohtml5.info/history.html
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
As suggested you can use JAD to decompile it and view the files. To make it easier to read you can use the JADclipse plugin for eclipse to integrate JAD directly to eclipse or use DJ Java Decompiler which is much easier to use than command line JAD
Whats the value for the SqlException.ErrorCode property? Can you work with that?
When having timeouts, it may be worth checking the code for -2146232060.
I would set this up as a static const in your data code.
This answer is all about authorization and it is a complement of my previous answer about authentication
Why another answer? I attempted to expand my previous answer by adding details on how to support JSR-250 annotations. However the original answer became the way too long and exceeded the maximum length of 30,000 characters. So I moved the whole authorization details to this answer, keeping the other answer focused on performing authentication and issuing tokens.
@Secured
annotationBesides authentication flow shown in the other answer, role-based authorization can be supported in the REST endpoints.
Create an enumeration and define the roles according to your needs:
public enum Role {
ROLE_1,
ROLE_2,
ROLE_3
}
Change the @Secured
name binding annotation created before to support roles:
@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Secured {
Role[] value() default {};
}
And then annotate the resource classes and methods with @Secured
to perform the authorization. The method annotations will override the class annotations:
@Path("/example")
@Secured({Role.ROLE_1})
public class ExampleResource {
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response myMethod(@PathParam("id") Long id) {
// This method is not annotated with @Secured
// But it's declared within a class annotated with @Secured({Role.ROLE_1})
// So it only can be executed by the users who have the ROLE_1 role
...
}
@DELETE
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
@Secured({Role.ROLE_1, Role.ROLE_2})
public Response myOtherMethod(@PathParam("id") Long id) {
// This method is annotated with @Secured({Role.ROLE_1, Role.ROLE_2})
// The method annotation overrides the class annotation
// So it only can be executed by the users who have the ROLE_1 or ROLE_2 roles
...
}
}
Create a filter with the AUTHORIZATION
priority, which is executed after the AUTHENTICATION
priority filter defined previously.
The ResourceInfo
can be used to get the resource Method
and resource Class
that will handle the request and then extract the @Secured
annotations from them:
@Secured
@Provider
@Priority(Priorities.AUTHORIZATION)
public class AuthorizationFilter implements ContainerRequestFilter {
@Context
private ResourceInfo resourceInfo;
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
// Get the resource class which matches with the requested URL
// Extract the roles declared by it
Class<?> resourceClass = resourceInfo.getResourceClass();
List<Role> classRoles = extractRoles(resourceClass);
// Get the resource method which matches with the requested URL
// Extract the roles declared by it
Method resourceMethod = resourceInfo.getResourceMethod();
List<Role> methodRoles = extractRoles(resourceMethod);
try {
// Check if the user is allowed to execute the method
// The method annotations override the class annotations
if (methodRoles.isEmpty()) {
checkPermissions(classRoles);
} else {
checkPermissions(methodRoles);
}
} catch (Exception e) {
requestContext.abortWith(
Response.status(Response.Status.FORBIDDEN).build());
}
}
// Extract the roles from the annotated element
private List<Role> extractRoles(AnnotatedElement annotatedElement) {
if (annotatedElement == null) {
return new ArrayList<Role>();
} else {
Secured secured = annotatedElement.getAnnotation(Secured.class);
if (secured == null) {
return new ArrayList<Role>();
} else {
Role[] allowedRoles = secured.value();
return Arrays.asList(allowedRoles);
}
}
}
private void checkPermissions(List<Role> allowedRoles) throws Exception {
// Check if the user contains one of the allowed roles
// Throw an Exception if the user has not permission to execute the method
}
}
If the user has no permission to execute the operation, the request is aborted with a 403
(Forbidden).
To know the user who is performing the request, see my previous answer. You can get it from the SecurityContext
(which should be already set in the ContainerRequestContext
) or inject it using CDI, depending on the approach you go for.
If a @Secured
annotation has no roles declared, you can assume all authenticated users can access that endpoint, disregarding the roles the users have.
Alternatively to defining the roles in the @Secured
annotation as shown above, you could consider JSR-250 annotations such as @RolesAllowed
, @PermitAll
and @DenyAll
.
JAX-RS doesn't support such annotations out-of-the-box, but it could be achieved with a filter. Here are a few considerations to keep in mind if you want to support all of them:
@DenyAll
on the method takes precedence over @RolesAllowed
and @PermitAll
on the class.@RolesAllowed
on the method takes precedence over @PermitAll
on the class.@PermitAll
on the method takes precedence over @RolesAllowed
on the class.@DenyAll
can't be attached to classes.@RolesAllowed
on the class takes precedence over @PermitAll
on the class.So an authorization filter that checks JSR-250 annotations could be like:
@Provider
@Priority(Priorities.AUTHORIZATION)
public class AuthorizationFilter implements ContainerRequestFilter {
@Context
private ResourceInfo resourceInfo;
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
Method method = resourceInfo.getResourceMethod();
// @DenyAll on the method takes precedence over @RolesAllowed and @PermitAll
if (method.isAnnotationPresent(DenyAll.class)) {
refuseRequest();
}
// @RolesAllowed on the method takes precedence over @PermitAll
RolesAllowed rolesAllowed = method.getAnnotation(RolesAllowed.class);
if (rolesAllowed != null) {
performAuthorization(rolesAllowed.value(), requestContext);
return;
}
// @PermitAll on the method takes precedence over @RolesAllowed on the class
if (method.isAnnotationPresent(PermitAll.class)) {
// Do nothing
return;
}
// @DenyAll can't be attached to classes
// @RolesAllowed on the class takes precedence over @PermitAll on the class
rolesAllowed =
resourceInfo.getResourceClass().getAnnotation(RolesAllowed.class);
if (rolesAllowed != null) {
performAuthorization(rolesAllowed.value(), requestContext);
}
// @PermitAll on the class
if (resourceInfo.getResourceClass().isAnnotationPresent(PermitAll.class)) {
// Do nothing
return;
}
// Authentication is required for non-annotated methods
if (!isAuthenticated(requestContext)) {
refuseRequest();
}
}
/**
* Perform authorization based on roles.
*
* @param rolesAllowed
* @param requestContext
*/
private void performAuthorization(String[] rolesAllowed,
ContainerRequestContext requestContext) {
if (rolesAllowed.length > 0 && !isAuthenticated(requestContext)) {
refuseRequest();
}
for (final String role : rolesAllowed) {
if (requestContext.getSecurityContext().isUserInRole(role)) {
return;
}
}
refuseRequest();
}
/**
* Check if the user is authenticated.
*
* @param requestContext
* @return
*/
private boolean isAuthenticated(final ContainerRequestContext requestContext) {
// Return true if the user is authenticated or false otherwise
// An implementation could be like:
// return requestContext.getSecurityContext().getUserPrincipal() != null;
}
/**
* Refuse the request.
*/
private void refuseRequest() {
throw new AccessDeniedException(
"You don't have permissions to perform this action.");
}
}
Note: The above implementation is based on the Jersey RolesAllowedDynamicFeature
. If you use Jersey, you don't need to write your own filter, just use the existing implementation.
Its not exactly elegant, but if you use List.listIterator(int index) you can get a bi-directional ListIterator to the end of the list:
//Assume List<String> foo;
ListIterator li = foo.listIterator(foo.size());
while (li.hasPrevious()) {
String curr = li.previous()
}
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 56.69 56.69">_x000D_
_x000D_
<style>_x000D_
@import url(main.css);_x000D_
</style>_x000D_
_x000D_
<g>_x000D_
<path d="M28.44......./>_x000D_
</g>_x000D_
</svg>
_x000D_
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 56.69 56.69">_x000D_
_x000D_
<style>_x000D_
.socIcon g {fill:red;}_x000D_
</style>_x000D_
_x000D_
<g>_x000D_
<path d="M28.44......./>_x000D_
</g>_x000D_
</svg>
_x000D_
Note: External Styles will not work if you include SVG inside <img>
tag. It will work perfectly inside <div>
tag
This is actually compiler dependent, and not supported by any standard.
Here however you have a macro implementation that does the count:
#define PP_NARG(...) \
PP_NARG_(__VA_ARGS__,PP_RSEQ_N())
#define PP_NARG_(...) \
PP_ARG_N(__VA_ARGS__)
#define PP_ARG_N( \
_1, _2, _3, _4, _5, _6, _7, _8, _9,_10, \
_11,_12,_13,_14,_15,_16,_17,_18,_19,_20, \
_21,_22,_23,_24,_25,_26,_27,_28,_29,_30, \
_31,_32,_33,_34,_35,_36,_37,_38,_39,_40, \
_41,_42,_43,_44,_45,_46,_47,_48,_49,_50, \
_51,_52,_53,_54,_55,_56,_57,_58,_59,_60, \
_61,_62,_63,N,...) N
#define PP_RSEQ_N() \
63,62,61,60, \
59,58,57,56,55,54,53,52,51,50, \
49,48,47,46,45,44,43,42,41,40, \
39,38,37,36,35,34,33,32,31,30, \
29,28,27,26,25,24,23,22,21,20, \
19,18,17,16,15,14,13,12,11,10, \
9,8,7,6,5,4,3,2,1,0
/* Some test cases */
PP_NARG(A) -> 1
PP_NARG(A,B) -> 2
PP_NARG(A,B,C) -> 3
PP_NARG(A,B,C,D) -> 4
PP_NARG(A,B,C,D,E) -> 5
PP_NARG(1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3) -> 63
I saw someone use this example as part of a job application test. My feedback to him was that it lacks an escape from the outer loop when the array is mostly sorted.
consider what would happen in this case:
int[] arr = {1,2,3,4,5,6,7,8};
here's something that makes more sense:
int[] arr = {1,2,3,4,5,6,7,8};
int temp = 0;
int loopCount=0;
bool doBreak=true;
for (int write = 0; write < arr.Length; write++)
{
doBreak=true;
for (int sort = 0; sort < arr.Length - 1; sort++)
{
if (arr[sort] > arr[sort + 1])
{
temp = arr[sort + 1];
arr[sort + 1] = arr[sort];
arr[sort] = temp;
doBreak=false;
}
loopCount++;
}
if(doBreak){ break; /*early escape*/ }
}
Console.WriteLine(loopCount);
for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + " ");
I am working with a AWS DeepAMI P2 instance and suddenly I found that Nvidia-driver command doesn't working and GPU is not found torch or tensorflow library. Then I have resolved the problem in the following way,
Run nvcc --version
if it doesn't work
Then run the following
apt install nvidia-cuda-toolkit
Hopefully that will solve the problem.
[u'String']
is a text representation of a list that contains a Unicode string on Python 2.
If you run print(some_list)
then it is equivalent to
print'[%s]' % ', '.join(map(repr, some_list))
i.e., to create a text representation of a Python object with the type list
, repr()
function is called for each item.
Don't confuse a Python object and its text representation—repr('a') != 'a'
and even the text representation of the text representation differs: repr(repr('a')) != repr('a')
.
repr(obj)
returns a string that contains a printable representation of an object. Its purpose is to be an unambiguous representation of an object that can be useful for debugging, in a REPL. Often eval(repr(obj)) == obj
.
To avoid calling repr()
, you could print list items directly (if they are all Unicode strings) e.g.: print ",".join(some_list)
—it prints a comma separated list of the strings: String
Do not encode a Unicode string to bytes using a hardcoded character encoding, print Unicode directly instead. Otherwise, the code may fail because the encoding can't represent all the characters e.g., if you try to use 'ascii'
encoding with non-ascii characters. Or the code silently produces mojibake (corrupted data is passed further in a pipeline) if the environment uses an encoding that is incompatible with the hardcoded encoding.
Two points to consider -
Modern hardware can overlap instructions, execute them in parallel and reorder them to make best use of the hardware. And also, any significant floating point program is likely to have significant integer work too even if it's only calculating indices into arrays, loop counter etc. so even if you have a slow floating point instruction it may well be running on a separate bit of hardware overlapped with some of the integer work. My point being that even if the floating point instructions are slow that integer ones, your overall program may run faster because it can make use of more of the hardware.
As always, the only way to be sure is to profile your actual program.
Second point is that most CPUs these days have SIMD instructions for floating point that can operate on multiple floating point values all at the same time. For example you can load 4 floats into a single SSE register and the perform 4 multiplications on them all in parallel. If you can rewrite parts of your code to use SSE instructions then it seems likely it will be faster than an integer version. Visual c++ provides compiler intrinsic functions to do this, see http://msdn.microsoft.com/en-us/library/x5c07e2a(v=VS.80).aspx for some information.
I often use row_number() as a quick way to discard duplicate records from my select statements. Just add a where clause. Something like...
select a,b,rn
from (select a, b, row_number() over (partition by a,b order by a,b) as rn
from table)
where rn=1;
I found a solution for how to set a global variable in a mailinglist posting via assign:
a <- "old"
test <- function () {
assign("a", "new", envir = .GlobalEnv)
}
test()
a # display the new value
For latest socket.io version use
socket.request.connection.remoteAddress
For example:
var socket = io.listen(server);
socket.on('connection', function (client) {
var client_ip_address = socket.request.connection.remoteAddress;
}
beware that the code below returns the Server's IP, not the Client's IP
var address = socket.handshake.address;
console.log('New connection from ' + address.address + ':' + address.port);
From Sql Server 2008 you have "date" format.
So you can use
SELECT * FROM LOGS WHERE CONVERT(date,[CHECK_IN]) BETWEEN '2013-10-18' AND '2013-10-18'
https://docs.microsoft.com/en-us/sql/t-sql/data-types/date-transact-sql
Some tips:
About your questions:
An inputMethod is basically an Android Service
, so yes, you can do HTTP and all the stuff you can do in a Service
.
You can open Activities
and dialogs from the InputMethod
. Once again, it's just a Service
.
I've been developing an IME, so ask again if you run into an issue.
Actually you have 2 problems here: First is that you don't have ssh installed, second is that you don't know how to deploy
It seems that ssh is not installed on your computer.
You can install openssh from here : http://openssh.en.softonic.com/download
Than you will have to geneate your ssh-key. There's a good tutorial about this here:
https://help.github.com/articles/generating-ssh-keys#platform-windows
To deploy, you just have to push your code over git. Something like this:
git push fort master
If you get permission denied, be sure that you have put your public_key in the dashboard in the git tab.
The ssh command gives you access to your remote node. You should have received a password by email and now that you have ssh installed, you should be asked for a password when trying to connect. just input that password. If you want to use your private ssh key to connect to your server rather then typing that password, you can follow this : http://fortrabbit.com/docs/how-to/ssh-sftp/enable-public-key-authentication
The simplest solution I have found is to wrap your Font Awesome Icon in an <a></a>
tag:
<Tooltip title="Node.js" >
<a>
<FontAwesomeIcon icon={faNode} size="2x" />
</a>
</Tooltip>
Problem solved, I've not added the index.html. Which is point out in the web.xml
Note: a project may have more than one web.xml file.
if there are another web.xml in
src/main/webapp/WEB-INF
Then you might need to add another index (this time index.jsp) to
src/main/webapp/WEB-INF/pages/
For your property example do:
mvn install "-Dmyproperty=my property from command line"
Note quotes around whole property definition. You'll need them if your property contains spaces.
A bit late, and not a complete solution either, but for everyone who gets hit by this error without any obvious reason (having all the references defined, etc.) This thread put me on the correct track though. The issue seems to originate from some caching related bug in MS Office VBA Editor.
After making some changes to a project including about 40 forms with code modules plus 40 classes and some global modules in MS Access 2016 the compilation failed.
Commenting out code was obviously not an option, nor did exporting and re-importing all the 80+ files seem reasonable. Concentrating on what had recently been changed, my suspicions focused on removal of one class module.
Having no better ideas I re-cereated an empty class module with the same name that had previously been removed. And voliá the error was gone! It was even possible to remove the unused class module again without the error reappearing, until any changes were saved to a form module which previously had contained a WithEvents declaration involving the now removed class.
Not completely sure if WithEvents declaration really is what triggers the error even after the declaration has been removed. And no clues how to actually find out (without having information about the development history) which Form might be the culprit...
But what finally solved the issue was:
The diffrence is very simple:
Long version
If you want to have better readability, use Math.floor
. But if you want to minimize it, use tilde ~~
.
There are a lot of sources on the internet saying Math.floor
is faster, but sometimes ~~
. I would not recommend you think about speed because it is not going to be noticed when running the code. Maybe in tests etc, but no human can see a diffrence here. What would be faster is to use ~~
for a faster load time.
Short version
~~
is shorter/takes less space. Math.floor
improves the readability. Sometimes tilde is faster, sometimes Math.floor
is faster, but it is not noticeable.
Casting the integer to a char will do what you want.
char theChar=' ';
int theInt = 97;
theChar=(char) theInt;
cout<<theChar<<endl;
There is no difference between 'a' and 97 besides the way you interperet them.
I thinks it is vary helpful way.
models.py
from django.db import models
class User(models.Model):
user_name = models.CharField(max_length=100)
password = models.CharField(max_length=32)
forms.py
from django import forms
from Admin.models import *
class User_forms(forms.ModelForm):
class Meta:
model= User
fields=[
'user_name',
'password'
]
widgets = {
'password': forms.PasswordInput()
}
run this command with sudo
sudo npm install -g yo
run cmd as administrator
and then run this command again
run this command and then try
npm config set registry http://registry.npmjs.org/
The accepted answer gethostname() may infact give you inaccurate value as in my case
gethostname() = my-macbook-pro (incorrect)
$_SERVER['host_name'] = mysite.git (correct)
The value from gethostname() is obvsiously wrong. Be careful with it.
Host name gives you computer name, not website name, my bad. My result on local machine is
gethostname() = my-macbook-pro (which is my machine name)
$_SERVER['host_name'] = mysite.git (which is my website name)
For example:
XAML:
<Button Content="ok" Click="Button_Click"/>
<TextBlock Name="textBoxName"/>
In code:
private void Button_Click(object sender, RoutedEventArgs e)
{
textBoxName.Text = "";
}
if (Enum.IsDefined(typeof(foo), value))
{
return (Foo)Enum.Parse(typeof(foo), value);
}
Hope this helps
Edit This answer got down voted as value in my example is a string, where as the question asked for an int. My applogies; the following should be a bit clearer :-)
Type fooType = typeof(foo);
if (Enum.IsDefined(fooType , value.ToString()))
{
return (Foo)Enum.Parse(fooType , value.ToString());
}
So, first of all, your Javascript isn't even using jQuery. There are a couple ways to do this. For example:
First way, using the jQuery toggle
method:
<div class="expandContent">
<a href="#">Click Here to Display More Content</a>
</div>
<div class="showMe" style="display:none">
This content was hidden, but now shows up
</div>
<script>
$('.expandContent').click(function(){
$('.showMe').toggle();
});
</script>
jsFiddle: http://jsfiddle.net/pM3DF/
Another way is simply to use the jQuery show
method:
<div class="expandContent">
<a href="#">Click Here to Display More Content</a>
</div>
<div class="showMe" style="display:none">
This content was hidden, but now shows up
</div>
<script>
$('.expandContent').click(function(){
$('.showMe').show();
});
</script>
jsFiddle: http://jsfiddle.net/Q2wfM/
Yet a third way is to use the slideToggle
method of jQuery which allows for some effects. Such as $('#showMe').slideToggle('slow');
which will slowly display the hidden div.
When it asks for username and password. Just add gitlab user name and password for clonning. For the box to pop up asking credentials, do the following:
go to "control panel"-> user accounts-> manage credentials->windows credentials->git:https://[email protected]>click on down arrow-> then click remove.
Hope this helps!
In case you have to download a file with a size larger than the allowed memory limit (memory_limit
ini setting), which would cause the PHP Fatal error: Allowed memory size of 5242880 bytes exhausted
error, you can do this:
// File to download.
$file = '/path/to/file';
// Maximum size of chunks (in bytes).
$maxRead = 1 * 1024 * 1024; // 1MB
// Give a nice name to your download.
$fileName = 'download_file.txt';
// Open a file in read mode.
$fh = fopen($file, 'r');
// These headers will force download on browser,
// and set the custom file name for the download, respectively.
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $fileName . '"');
// Run this until we have read the whole file.
// feof (eof means "end of file") returns `true` when the handler
// has reached the end of file.
while (!feof($fh)) {
// Read and output the next chunk.
echo fread($fh, $maxRead);
// Flush the output buffer to free memory.
ob_flush();
}
// Exit to make sure not to output anything else.
exit;
To use a simple example, I had a counter that needed to summarise unique IP addresses per visited page on a site. Which is basically grouping by pagename and then by IP. I solved it with a combination of DISTINCT and GROUP BY.
SELECT pagename, COUNT(DISTINCT ipaddress) AS visit_count FROM log_visitors GROUP BY pagename ORDER BY visit_count DESC;
IDEA may ignore some of your maven dependency files. The "External Libraries" node in your project structure might be empty or incomplete.
Go to:
The key "Transactional Resources" looks like you are talking to the database without a proper transaction. Make sure transaction management is configured properly and no invocation path to the DAO exists that doesn't run under a @Transactional annotation. This can easily happen when you configured transaction management on the Controller level but are invoking DAOs in a timer or are using @PostConstruct annotations. I wrote it up here http://georgovassilis.blogspot.nl/2014/01/tomcat-spring-and-memory-leaks-when.html
Edit: It looks like this is (also?) a bug with spring-data-jpa which has been fixed with v1.4.3. I looked it up in the spring-data-jpa sources of LockModeRepositoryPostProcessor which sets the "Transactional Resources" key. In 1.4.3 it also clears the key again.
You can use typeof operator.
if( (typeof A === "object" || typeof A === 'function') && (A !== null) )
{
alert("A is object");
}
Note that because typeof new Number(1) === 'object'
while typeof Number(1) === 'number';
the first syntax should be avoided.
Because the numbers after point is only zero, the best solution is to use the Math.Round(MyNumber)
I had this problem when upgrading my solution from Microsoft Visual Studio 2012 Express for Web to Microsoft Visual Studio 2013.
I had created a Unit Tests project in 2012, and after opening in 2013 the Unit Test project wouldn't show any tests in the tests explorer. Everytime I tried to run or debug tests it failed, saying the following in the output window:
Failed to initialize client proxy:
could not connect to vstest.discoveryengine.x86.exe
I also noticed that on debugging the tests, it was launching an instance of Visual Studio 2012. This clued me into the fact that the Unit Tests project was still referencing 2012. Looking at the test project reference I realised it was targeting the wrong Microsoft Visual Studio Unit Test Framework DLL for this version of Visual Studio:
C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\PublicAssemblies\Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll
I changed the version number from 11.0 to 12.0:
C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\PublicAssemblies\Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll
I rebuilt all and this fixed the issue - all tests were found in the Test Explorer and now all tests are found and running perfectly.
nl2br() worked for me, but I needed to wrap the variable with double quotes:
This works:
$description = nl2br("$description");
This doesn't work:
$description = nl2br($description);
There is a Win32 (C++) function in shlwapi.dll that does exactly what you want: PathRelativePathTo()
I'm not aware of any way to access this from .NET other than to P/Invoke it, though.
In our enterprise I don't have access to MSSQL Server, so I can'r access the system tables.
What works for me is:
Wireshark
(run as Administrator, select Network Interface),while opening connection to server.ping
ip.dst == x.x.x.x
The port is shown in the column info
in the format src.port -> dst.port
You need to change permissions on the folder bootstrap/css. Your super user may be able to access it but it doesn't mean apache or nginx have access to it, that's why you still need to change the permissions.
Tip: I usually make the apache/nginx's user group owner of that kind of folders and give 775 permission to it.
Changing compile 'com.android.support:appcompat-v7:21.0.0'
into compile 'com.android.support:appcompat-v7:20.0.0'
in gradle.build works for me.
Go to your build settings and switch the target's settings to ENABLE_BITCODE = YES
for now.
Here is an efficient solution when there is a large set of inputs (i.e. 25 to 30)
I made efficiency gains in two ways:
This solution works with negative numbers, decimal amounts, and repeated input values. Due to the wonky way that floating point decimal math works in most languages, you will want to keep your input set to only a few decimal places or you may have some unpredictable behavior.
On my old 2012-era desktop computer the given code processes 25 input values in about 0.8 seconds in javascript/node.js, and 3.4 seconds in C#.
let numbers = [-0.47, -0.35, -0.19, 0.23, 0.36, 0.47, 0.51, 0.59, 0.63, 0.79, 0.85,
0.91, 0.99, 1.02, 1.17, 1.25, 1.39, 1.44, 1.59, 1.60, 1.79, 1.88, 1.99, 2.14, 2.31];
let target = 24.16;
displaySubsetsThatSumTo(target, numbers);
function displaySubsetsThatSumTo(target, numbers)
{
let wheel = [0];
let resultsCount = 0;
let sum = 0;
const start = new Date();
do {
sum = incrementWheel(0, sum, numbers, wheel);
//Use subtraction comparison due to javascript float imprecision
if (sum != null && Math.abs(target - sum) < 0.000001) {
//Found a subset. Display the result.
console.log(numbers.filter(function(num, index) {
return wheel[index] === 1;
}).join(' + ') + ' = ' + target);
resultsCount++;
}
} while (sum != null);
const end = new Date();
console.log('--------------------------');
console.log(`Processed ${numbers.length} numbers in ${(end - start) / 1000} seconds (${resultsCount} results)`);
}
function incrementWheel(position, sum, numbers, wheel) {
if (position === numbers.length || sum === null) {
return null;
}
wheel[position]++;
if (wheel[position] === 2) {
wheel[position] = 0;
sum -= numbers[position];
if (wheel.length < position + 2) {
wheel.push(0);
}
sum = incrementWheel(position + 1, sum, numbers, wheel);
}
else {
sum += numbers[position];
}
return sum;
}
-----------------------------------------------------------------
Alternate, more efficient version using Gray Code binary counting
technique as suggested in comment
-----------------------------------------------------------------
const numbers = [-0.47, -0.35, -0.19, 0.23, 0.36, 0.47, 0.51,
0.59, 0.63, 0.79, 0.85, 0.91, 0.99, 1.02, 1.17, 1.25,
1.39, 1.44, 1.59, 1.60, 1.79, 1.88, 1.99, 2.14, 2.31];
const target = 24.16;
displaySubsetsThatSumTo(target, numbers);
function displaySubsetsThatSumTo(target, numbers)
{
let resultsCount = 0;
let sum = 0;
let wheel = []; //binary counter
let changeEvery = []; //how often each binary digit flips
let nextChange = []; //when each binary digit will next flip
for(let i = 0; i < numbers.length; i++) {
//Initialize wheel and wheel-update data. Using Gray Code binary counting technique,
// whereby only one binary digit in the wheel changes on each iteration. Then only
// a single sum operation is required each iteration.
wheel.push(0);
changeEvery.push(2 ** (numbers.length - i));
nextChange.push(2 ** (numbers.length - i - 1));
}
const start = new Date();
const numIterations = 2 ** numbers.length;
for (counter = 1; counter < numIterations; counter++) {
for (let i = nextChange.length - 1; i >= 0; i--) {
if(nextChange[i] === counter) {
nextChange[i] += changeEvery[i];
if (wheel[i] === 1) {
wheel[i] = 0;
sum -= numbers[i];
}
else {
wheel[i] = 1;
sum += numbers[i];
}
break;
}
}
//Use subtraction comparison due to javascript float imprecision
if (Math.abs(target - sum) < 0.000001) {
//Found a subset. Display the result.
console.log(numbers.filter((num, index) => wheel[index] === 1)
.join(' + ') + ' = ' + target);
resultsCount++;
}
}
const end = new Date();
console.log('--------------------------');
console.log(`Processed ${numbers.length} numbers in ${(end - start) / 1000} seconds (${resultsCount} results)`);
}
public class Program
{
static void Main(string[] args)
{
double[] numbers = { -0.47, -0.35, -0.19, 0.23, 0.36, 0.47, 0.51, 0.59, 0.63, 0.79, 0.85,
0.91, 0.99, 1.02, 1.17, 1.25, 1.39, 1.44, 1.59, 1.60, 1.79, 1.88, 1.99, 2.14, 2.31 };
double target = 24.16;
DisplaySubsetsThatSumTo(target, numbers);
}
private static void DisplaySubsetsThatSumTo(double Target, double[] numbers)
{
var stopwatch = new System.Diagnostics.Stopwatch();
bool[] wheel = new bool[numbers.Length];
int resultsCount = 0;
double? sum = 0;
stopwatch.Start();
do
{
sum = IncrementWheel(0, sum, numbers, wheel);
//Use subtraction comparison due to double type imprecision
if (sum.HasValue && Math.Abs(sum.Value - Target) < 0.000001F)
{
//Found a subset. Display the result.
Console.WriteLine(string.Join(" + ", numbers.Where((n, idx) => wheel[idx])) + " = " + Target);
resultsCount++;
}
} while (sum != null);
stopwatch.Stop();
Console.WriteLine("--------------------------");
Console.WriteLine($"Processed {numbers.Length} numbers in {stopwatch.ElapsedMilliseconds / 1000.0} seconds ({resultsCount} results). Press any key to exit.");
Console.ReadKey();
}
private static double? IncrementWheel(int Position, double? Sum, double[] numbers, bool[] wheel)
{
if (Position == numbers.Length || !Sum.HasValue)
{
return null;
}
wheel[Position] = !wheel[Position];
if (!wheel[Position])
{
Sum -= numbers[Position];
Sum = IncrementWheel(Position + 1, Sum, numbers, wheel);
}
else
{
Sum += numbers[Position];
}
return Sum;
}
}
-0.35 + 0.23 + 0.36 + 0.47 + 0.51 + 0.59 + 0.63 + 0.79 + 0.85 + 0.91 + 0.99 + 1.02 + 1.17 + 1.25 + 1.44 + 1.59 + 1.6 + 1.79 + 1.88 + 1.99 + 2.14 + 2.31 = 24.16
0.23 + 0.51 + 0.59 + 0.63 + 0.79 + 0.85 + 0.99 + 1.02 + 1.17 + 1.25 + 1.39 + 1.44 + 1.59 + 1.6 + 1.79 + 1.88 + 1.99 + 2.14 + 2.31 = 24.16
-0.47 + 0.23 + 0.47 + 0.51 + 0.59 + 0.63 + 0.79 + 0.85 + 0.99 + 1.02 + 1.17 + 1.25 + 1.39 + 1.44 + 1.59 + 1.6 + 1.79 + 1.88 + 1.99 + 2.14 + 2.31 = 24.16
-0.19 + 0.36 + 0.51 + 0.59 + 0.63 + 0.79 + 0.91 + 0.99 + 1.02 + 1.17 + 1.25 + 1.39 + 1.44 + 1.59 + 1.6 + 1.79 + 1.88 + 1.99 + 2.14 + 2.31 = 24.16
-0.47 + -0.19 + 0.36 + 0.47 + 0.51 + 0.59 + 0.63 + 0.79 + 0.91 + 0.99 + 1.02 + 1.17 + 1.25 + 1.39 + 1.44 + 1.59 + 1.6 + 1.79 + 1.88 + 1.99 + 2.14 + 2.31 = 24.16
0.23 + 0.47 + 0.51 + 0.63 + 0.85 + 0.91 + 0.99 + 1.02 + 1.17 + 1.25 + 1.39 + 1.44 + 1.59 + 1.6 + 1.79 + 1.88 + 1.99 + 2.14 + 2.31 = 24.16
--------------------------
Processed 25 numbers in 0.823 seconds (6 results)
Your code returns 0
if the execution of the commands passed is successful and non zero if it fails. The following program works on python2.7, haven checked 3 and versions above. Try this code.
>>> import commands
>>> ret = commands.getoutput("ps -p 2993 -o time --no-headers")
>>> print ret
go to the directory of the laravel project on your terminal and write:
sudo chown -R your-user:www-data /path/to/your/laravel/project/
sudo find /same/path/ -type f -exec chmod 664 {} \;
sudo find /same/path/ -type d -exec chmod 775 {} \;
sudo chgrp -R www-data storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache
This way you're making your user the owner and giving privileges:
1 Execute, 2 Write, 4 Read
1+2+4 = 7 means (rwx)
2+4 = 6 means (rw)
finally, for the storage access, ug+rwx means you're giving the user and group a 7
Login in with System Admin User Account and execute below SQL Procedure.
begin
dbms_xdb.sethttpport('Your Port Number');
end;
Then open the Browser and access the below URL
User johannes told you how to do add existing files to a Git repository in a general situation. Because you talk about Bitbucket, I suggest you do the following:
Create a new repository on Bitbucket (you can see a Create button on the top of your profile page) and you will go to this page:
Fill in the form, click next and then you automatically go to this page:
Choose to add existing files and you go to this page:
You use those commands and you upload the existing files to Bitbucket. After that, the files are online.
You are missing zlib.h
header file, on Linux install it via:
sudo apt-get install libz-dev
As a matter of fact, the module presents as zlib1g-dev
in the apt repo, so this is the up-to-date call (Feb 2019):
sudo apt install zlib1g-dev
On Fedora: sudo dnf install zlib-devel
(in older versions: sudo dnf install libz-devel
).
This will provide the development support files for a library implementing the deflate compression method found in gzip and PKZIP.
If you've already zlib
library, make sure you're compiling your code sources with -lz
. See: How to fix undefined references to inflate/deflate functions?.
To hide the element visually, but keep it in the html, you can use:
<div style='visibility:hidden; overflow:hidden; height:0; width:0;'>
[content]
</div>
or
<div style='visibility:hidden; overflow:hidden; position:absolute;'>
[content]
</div>
What may go wrong with display:none
? It removes the element completely from the html, so some functionalities may be broken if they need to access something in the hidden element.
I solved it easily via running these codes:
npm uninstall mongodb --save
npm install [email protected] --save
Happy Coding!
I'm using out of the box MVC4 with this code (note the two parameters inside ToDictionary
)
var result = new JsonResult()
{
Data = new
{
partials = GetPartials(data.Partials).ToDictionary(x => x.Key, y=> y.Value)
}
};
I get what's expected:
{"partials":{"cartSummary":"\u003cb\u003eCART SUMMARY\u003c/b\u003e"}}
Important: WebAPI in MVC4 uses JSON.NET serialization out of the box, but the standard web JsonResult
action result doesn't. Therefore I recommend using a custom ActionResult to force JSON.NET serialization. You can also get nice formatting
Here's a simple actionresult JsonNetResult
http://james.newtonking.com/archive/2008/10/16/asp-net-mvc-and-json-net.aspx
You'll see the difference (and can make sure you're using the right one) when serializing a date:
Microsoft way:
{"wireTime":"\/Date(1355627201572)\/"}
JSON.NET way:
{"wireTime":"2012-12-15T19:07:03.5247384-08:00"}
You can use the ansible.cfg file, it should look like this (There are other parameters which you might want to include):
[defaults]
inventory = <PATH TO INVENTORY FILE>
remote_user = <YOUR USER>
private_key_file = <PATH TO KEY_FILE>
Hope this saves you some typing
I know this is already answered, but I looked at the suggested sample site, and I see they do it like this:
<script type="text/javascript">
if(document.getElementsByTagName("iframe").item(0) == null) {
document.write("<div style="width: 160px; height: 600px; padding-top: 280px; margin-left: 5px; border: 1px solid #666666; color: #FFF; background-color: #666; text-align:center; font-family: Maven Pro, century gothic, arial, helvetica, sans-serif; padding-left: 5px; padding-right: 5px; border-radius: 7px; font-size: 18px;">Advertising seems to be blocked by your browser.<br><br><span style="font-size: 12px;">Please notice that advertising helps us to host the project.<br><br>If you find these ads intrusive or inappropriate, please contact me.</span><br><img src="http://www.playonlinux.com/images/abp.png" alt="Adblock Plus"></div>");
};
</script>
Simple Steps
Most of the answers describe some sort of recvall()
method. If your bottleneck when receiving data is creating the byte array in a for
loop, I benchmarked three approaches of allocating the received data in the recvall()
method:
Byte string method:
arr = b''
while len(arr) < msg_len:
arr += sock.recv(max_msg_size)
List method:
fragments = []
while True:
chunk = sock.recv(max_msg_size)
if not chunk:
break
fragments.append(chunk)
arr = b''.join(fragments)
Pre-allocated bytearray
method:
arr = bytearray(msg_len)
pos = 0
while pos < msg_len:
arr[pos:pos+max_msg_size] = sock.recv(max_msg_size)
pos += max_msg_size
Results:
There are a lot of solutions to this question already, but I wanted to post one that:
Here is such a solution:
// variables for shake detection
private static final float SHAKE_THRESHOLD = 3.25f; // m/S**2
private static final int MIN_TIME_BETWEEN_SHAKES_MILLISECS = 1000;
private long mLastShakeTime;
private SensorManager mSensorMgr;
To initialize the timer:
// Get a sensor manager to listen for shakes
mSensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
// Listen for shakes
Sensor accelerometer = mSensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if (accelerometer != null) {
mSensorMgr.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
SensorEventListener
methods to override:
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
long curTime = System.currentTimeMillis();
if ((curTime - mLastShakeTime) > MIN_TIME_BETWEEN_SHAKES_MILLISECS) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
double acceleration = Math.sqrt(Math.pow(x, 2) +
Math.pow(y, 2) +
Math.pow(z, 2)) - SensorManager.GRAVITY_EARTH;
Log.d(APP_NAME, "Acceleration is " + acceleration + "m/s^2");
if (acceleration > SHAKE_THRESHOLD) {
mLastShakeTime = curTime;
Log.d(APP_NAME, "Shake, Rattle, and Roll");
}
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// Ignore
}
When you are all done
// Stop listening for shakes
mSensorMgr.unregisterListener(this);
htmlFor
to replace for
!you can find more info by following the below links.
https://facebook.github.io/react/docs/dom-elements.html#htmlfor
You could also use the stringr
package:
library(stringr)
str_length("foo")
[1] 3
Using CLR, here's a much simpler alternative that works in all cases, yet 40% faster than the accepted answer:
using System;
using System.Collections;
using System.Data.SqlTypes;
using System.Text.RegularExpressions;
using Microsoft.SqlServer.Server;
public class UDF
{
[SqlFunction(FillRowMethodName="FillRow")]
public static IEnumerable RegexSplit(SqlString s, SqlString delimiter)
{
return Regex.Split(s.Value, delimiter.Value);
}
public static void FillRow(object row, out SqlString str)
{
str = new SqlString((string) row);
}
}
Of course, it is still 8 times slower than PostgreSQL's regexp_split_to_table
.
I to use this type of declaration:
const identity: { <T>(arg: T): T } = (arg) => arg;
It allows defining additional props to your function if you ever need to and in some cases, it helps keeping the function body cleaner from the generic definition.
If you don't need the additional props (namespace sort of thing), it can be simplified to:
const identity: <T>(arg: T) => T = (arg) => arg;
Just use Array.length
:
var arr = [];
if (arr.length)
console.log('not empty');
else
console.log('empty');
See MDN
For recent hadoop versions (I'm using 2.7.1)
The start\stop scripts are located in the sbin
folder. The scripts are:
I didn't have to do anything with yarn though to get the NameNodeServer instance running.
Now my mistake was that I didn't format the NameNodeServer HDFS.
bin/hdfs namenode -format
I'm not quite sure what that does at the moment but it obviously prepares the space on which the NameNodeServer will use to operate.
The proper way to do this is to use dispatch_async in the main_queue, as I did in the following code
dispatch_async(dispatch_get_main_queue(), {
(self.delegate as TBGQRCodeViewController).displayQRCode(receiveAddr, withAmountInBTC:amountBTC)
})
A lot of good answers have been posted, but I'd like to append one more.
Not all numbers can be represented via floats/doubles For example, the number "0.2" will be represented as "0.200000003" in single precision in IEEE754 float point standard.
Model for store real numbers under the hood represent float numbers as
Even though you can type 0.2
easily, FLT_RADIX
and DBL_RADIX
is 2; not 10 for a computer with FPU which uses "IEEE Standard for Binary Floating-Point Arithmetic (ISO/IEEE Std 754-1985)".
So it is a bit hard to represent such numbers exactly. Even if you specify this variable explicitly without any intermediate calculation.
I've just put together what you may be looking for: http://www.graphdracula.net
It's JavaScript with directed graph layouting, SVG and you can even drag the nodes around. Still needs some tweaking, but is totally usable. You create nodes and edges easily with JavaScript code like this:
var g = new Graph();
g.addEdge("strawberry", "cherry");
g.addEdge("cherry", "apple");
g.addEdge("id34", "cherry");
I used the previously mentioned Raphael JS library (the graffle example) plus some code for a force based graph layout algorithm I found on the net (everything open source, MIT license). If you have any remarks or need a certain feature, I may implement it, just ask!
You may want to have a look at other projects, too! Below are two meta-comparisons:
SocialCompare has an extensive list of libraries, and the "Node / edge graph" line will filter for graph visualization ones.
DataVisualization.ch has evaluated many libraries, including node/graph ones. Unfortunately there's no direct link so you'll have to filter for "graph":
Here's a list of similar projects (some have been already mentioned here):
vis.js supports many types of network/edge graphs, plus timelines and 2D/3D charts. Auto-layout, auto-clustering, springy physics engine, mobile-friendly, keyboard navigation, hierarchical layout, animation etc. MIT licensed and developed by a Dutch firm specializing in research on self-organizing networks.
Cytoscape.js - interactive graph analysis and visualization with mobile support, following jQuery conventions. Funded via NIH grants and developed by by @maxkfranz (see his answer below) with help from several universities and other organizations.
The JavaScript InfoVis Toolkit - Jit, an interactive, multi-purpose graph drawing and layout framework. See for example the Hyperbolic Tree. Built by Twitter dataviz architect Nicolas Garcia Belmonte and bought by Sencha in 2010.
D3.js Powerful multi-purpose JS visualization library, the successor of Protovis. See the force-directed graph example, and other graph examples in the gallery.
Plotly's JS visualization library uses D3.js with JS, Python, R, and MATLAB bindings. See a nexworkx example in IPython here, human interaction example here, and JS Embed API.
sigma.js Lightweight but powerful library for drawing graphs
jsPlumb jQuery plug-in for creating interactive connected graphs
Springy - a force-directed graph layout algorithm
Processing.js Javascript port of the Processing library by John Resig
JS Graph It - drag'n'drop boxes connected by straight lines. Minimal auto-layout of the lines.
RaphaelJS's Graffle - interactive graph example of a generic multi-purpose vector drawing library. RaphaelJS can't layout nodes automatically; you'll need another library for that.
JointJS Core - David Durman's MPL-licensed open source diagramming library. It can be used to create either static diagrams or fully interactive diagramming tools and application builders. Works in browsers supporting SVG. Layout algorithms not-included in the core package
mxGraph Previously commercial HTML 5 diagramming library, now available under Apache v2.0. mxGraph is the base library used in draw.io.
GoJS Interactive graph drawing and layout library
yFiles for HTML Commercial graph drawing and layout library
KeyLines Commercial JS network visualization toolkit
ZoomCharts Commercial multi-purpose visualization library
Syncfusion JavaScript Diagram Commercial diagram library for drawing and visualization.
Cytoscape Web Embeddable JS Network viewer (no new features planned; succeeded by Cytoscape.js)
Canviz JS renderer for Graphviz graphs. Abandoned in Sep 2013.
arbor.js Sophisticated graphing with nice physics and eye-candy. Abandoned in May 2012. Several semi-maintained forks exist.
jssvggraph "The simplest possible force directed graph layout algorithm implemented as a Javascript library that uses SVG objects". Abandoned in 2012.
jsdot Client side graph drawing application. Abandoned in 2011.
Protovis Graphical Toolkit for Visualization (JavaScript). Replaced by d3.
Moo Wheel Interactive JS representation for connections and relations (2008)
JSViz 2007-era graph visualization script
dagre Graph layout for JavaScript
Graphviz Sophisticated graph visualization language
Flare Beautiful and powerful Flash based graph drawing
NodeBox Python Graph Visualization
You can also use plt.setp
as follows:
import matplotlib.pyplot as plt
import seaborn as sns
plot=sns.barplot(data=df, x=" ", y=" ")
plt.setp(plot.get_xticklabels(), rotation=90)
to rotate the labels 90 degrees.
I tried everything here (and some otherplaces), and what worked for me (after doing all of these, the registry changes are mandatory I think) was to change the setting for Icon Overlays\Status Cache from Default to Shell, and I also checked "Show overlays and context menu only in explorer". Not sure which of those two did it but it works now.
(But use this in rare occasions, because HTML method is PREFERRED WAY).
.container{_x000D_
position:relative;_x000D_
}_x000D_
.container::before{ _x000D_
content:"";_x000D_
width: 100%; height: 100%; position: absolute; background: black; opacity: 0.3; z-index: 1; top: 0; left: 0;_x000D_
background: black;_x000D_
}_x000D_
.container::after{ _x000D_
content: "Your Text"; position: absolute; top: 0; left: 0; bottom: 0; right: 0; z-index: 3; overflow: hidden; font-size: 2em; color: red; text-align: center; text-shadow: 0px 0px 5px black; background: #0a0a0a8c; padding: 5px;_x000D_
animation-name: blinking;_x000D_
animation-duration: 1s;_x000D_
animation-iteration-count: infinite;_x000D_
animation-direction: alternate;_x000D_
}_x000D_
@keyframes blinking {_x000D_
0% {opacity: 0;}_x000D_
100% {opacity: 1;}_x000D_
}
_x000D_
<div class="container">here is main content, text , <br/> images and other page details</div>
_x000D_
$prompt: /path/to/script
and hit enter. Note you need to make sure the script has execute permissions.
The documentation for writelines()
states:
writelines()
does not add line separators
So you'll need to add them yourself. For example:
line_list.append(new_line + "\n")
whenever you append a new item to line_list
.
I added export PATH=${PATH}:/Users/mishrapranjal/android-sdks/platform-tools/
into both places .bash_profile
and .profile
to make sure it works. Still it wasn't working and then I looked at sarnold's tip about restarting terminal and it worked like a charm.
It saved my time of adding every time this into the PATH
whenever I had to run adb
.
Thank you guys.
One possible reason is JAVA_HOME is not set because java is not installed.
I encountered the same issue. It says
Exception in thread "main" java.lang.UnsupportedClassVersionError: org/apache/spark/launcher/Main : Unsupported major.minor version 51.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:643)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:277)
at java.net.URLClassLoader.access$000(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:212)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:323)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:296)
at java.lang.ClassLoader.loadClass(ClassLoader.java:268)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:406)
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/opt/spark/python/pyspark/conf.py", line 104, in __init__
SparkContext._ensure_initialized()
File "/opt/spark/python/pyspark/context.py", line 243, in _ensure_initialized
SparkContext._gateway = gateway or launch_gateway()
File "/opt/spark/python/pyspark/java_gateway.py", line 94, in launch_gateway
raise Exception("Java gateway process exited before sending the driver its port number")
Exception: Java gateway process exited before sending the driver its port number
at sc = pyspark.SparkConf()
. I solved it by running
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer
which is from https://www.digitalocean.com/community/tutorials/how-to-install-java-with-apt-get-on-ubuntu-16-04
I think the available libraries, tools, examples, and communities completely trumps the paradigm these days. For example, ML (or whatever) might be the ultimate all-purpose programming language but if you can't get any good libraries for what you are doing you're screwed.
For example, if you're making a video game, there are more good code examples and SDKs in C++, so you're probably better off with that. For a small web application, there are some great Python, PHP, and Ruby frameworks that'll get you off and running very quickly. Java is a great choice for larger projects because of the compile-time checking and enterprise libraries and platforms.
It used to be the case that the standard libraries for different languages were pretty small and easily replicated - C, C++, Assembler, ML, LISP, etc.. came with the basics, but tended to chicken out when it came to standardizing on things like network communications, encryption, graphics, data file formats (including XML), even basic data structures like balanced trees and hashtables were left out!
Modern languages like Python, PHP, Ruby, and Java now come with a far more decent standard library and have many good third party libraries you can easily use, thanks in great part to their adoption of namespaces to keep libraries from colliding with one another, and garbage collection to standardize the memory management schemes of the libraries.
Scenario :
Solution
git stash // to save all existing changes in local branch
git checkout master // Switch to master branch from branch-1
git pull // take changes from the master
git checkout branch-1 // switchback to your own branch
git rebase master // merge all the changes and move you git head forward
git stash apply // reapply all you saved changes
You can find conflicts on your file after executing "git stash apply". You need to fix it manually and now you are ready to push.
Swift 4.2
In Swift 4.2 the name of table is a little changed.
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 18))
let label = UILabel(frame: CGRect(x: 10, y: 5, width: tableView.frame.size.width, height: 18))
label.font = UIFont.systemFont(ofSize: 14)
label.text = list.objectAtIndex(section) as! String
view.addSubview(label)
view.backgroundColor = UIColor.gray // Set your background color
return view
}
Mind you that in my experience and also of other (PHP - Why is new SQLSRV driver slower than the old mssql driver?) that using PDO_SQLSRV is way slower than through PDO_ODBC.
If you want to use the faster PDO_ODBC you can use:
//use any of these or check exact MSSQL ODBC drivername in "ODBC Data Source Administrator"
$mssqldriver = '{SQL Server}';
$mssqldriver = '{SQL Server Native Client 11.0}';
$mssqldriver = '{ODBC Driver 11 for SQL Server}';
$hostname='127.0.0.1';
$dbname='test';
$username='user';
$password='pw';
$dbDB = new PDO("odbc:Driver=$mssqldriver;Server=$hostname;Database=$dbname", $username, $password);
My mistake was that I was keeping the Javascript file ( tag) above the html declaration.
It worked by placing the js script tag at the bottom of the body inside the body. (I did not the script on load of the page.)
I know the question is quite old, but I got here searching for answers. There is actually a better (and faster) way now of doing this using json_normalize
:
import pandas as pd
df2 = pd.json_normalize(df['Pollutant Levels'])
This avoids costly apply functions...
A tab is a tab. How many spaces it consumes is a display issue, and depends on the settings of your shell.
If you want to control the width of your data, then you could use the width
sub-specifiers in the printf
format string. Eg. :
printf("%5d", 2);
It's not a complete solution (if the value is longer than 5 characters, it will not be truncated), but might be ok for your needs.
If you want complete control, you'll probably have to implement it yourself.
Ant and Maven are widely used. I prefer Ant, I feel it's more lightweight and you the developer are more in control. Some would suggest that's its downside :-)
sortedWith
+ compareBy
(taking a vararg of lambdas) do the trick:
val sortedList = list.sortedWith(compareBy({ it.age }, { it.name }))
You can also use the somewhat more succinct callable reference syntax:
val sortedList = list.sortedWith(compareBy(Person::age, Person::name))
See which folder django try to load template look at Template-loader postmortem
in error page, for example, error will sothing like this:
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.filesystem.Loader: d:\projects\vcsrc\vcsrc\templates\base.html (Source does not exist)
In my error vcsrc\vcsrc\templates\base.html
not in path.
Then change TEMPLATES
in setting.py
file to your templates path
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# 'DIRS': [],
'DIRS': [os.path.join(BASE_DIR, 'vcsrc/templates')],
...
it is different for different icons.(eg, diff sizes for action bar icons, laucnher icons, etc.) please follow this link icons handbook to learn more.
Here's a super-simple example with basic authentication, headers, and exception handling...
private HttpHeaders createHttpHeaders(String user, String password)
{
String notEncoded = user + ":" + password;
String encodedAuth = "Basic " + Base64.getEncoder().encodeToString(notEncoded.getBytes());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", encodedAuth);
return headers;
}
private void doYourThing()
{
String theUrl = "http://blah.blah.com:8080/rest/api/blah";
RestTemplate restTemplate = new RestTemplate();
try {
HttpHeaders headers = createHttpHeaders("fred","1234");
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> response = restTemplate.exchange(theUrl, HttpMethod.GET, entity, String.class);
System.out.println("Result - status ("+ response.getStatusCode() + ") has body: " + response.hasBody());
}
catch (Exception eek) {
System.out.println("** Exception: "+ eek.getMessage());
}
}
I think it is important to mention, now that this question is over 1 year old, that Socket.IO has since come out and seems to be the primary way to work with sockets in the browser now; it is also compatible with Node.js as far as I know.
complete.cases
gives TRUE
when all values in a row are not NA
DF[!complete.cases(DF), ]
getElementById
returns a reference to the element using its id
. The element is the input
in the first case and the paragraph in the second case.
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById
std::string var = "sometext" + somevar + "sometext" + somevar;
This doesn't work because the additions are performed left-to-right and "sometext"
(the first one) is just a const char *
. It has no operator+
to call. The simplest fix is this:
std::string var = std::string("sometext") + somevar + "sometext" + somevar;
Now, the first parameter in the left-to-right list of +
operations is a std::string
, which has an operator+(const char *)
. That operator produces a string, which makes the rest of the chain work.
You can also make all the operations be on var
, which is a std::string
and so has all the necessary operators:
var = "sometext";
var += somevar;
var += "sometext";
var += somevar;
I would like to improve answer from chris-b a little bit more.
See below for my code:
from threading import Thread, Lock
import threading
mutex = Lock()
def processData(data, thread_safe):
if thread_safe:
mutex.acquire()
try:
thread_id = threading.get_ident()
print('\nProcessing data:', data, "ThreadId:", thread_id)
finally:
if thread_safe:
mutex.release()
counter = 0
max_run = 100
thread_safe = False
while True:
some_data = counter
t = Thread(target=processData, args=(some_data, thread_safe))
t.start()
counter = counter + 1
if counter >= max_run:
break
In your first run if you set thread_safe = False
in while loop, mutex will not be used, and threads will step over each others in print method as below;
but, if you set thread_safe = True
and run it, you will see all the output comes perfectly fine;
hope this helps.
A combination of what NailItDown and Victor said. The preferred/easiest way is to use your Global.Asax to store the error and then redirect to your custom error page.
Global.asax:
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Exception ex = Server.GetLastError();
Application["TheException"] = ex; //store the error for later
Server.ClearError(); //clear the error so we can continue onwards
Response.Redirect("~/myErrorPage.aspx"); //direct user to error page
}
In addition, you need to set up your web.config:
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="~/myErrorPage.aspx">
</customErrors>
</system.web>
And finally, do whatever you need to with the exception you've stored in your error page:
protected void Page_Load(object sender, EventArgs e)
{
// ... do stuff ...
//we caught an exception in our Global.asax, do stuff with it.
Exception caughtException = (Exception)Application["TheException"];
//... do stuff ...
}
Try the -HideTableHeaders
parameter to Format-Table
:
gci | ft -HideTableHeaders
(I'm using PowerShell v2. I don't know if this was in v1.)
TINYTEXT 256 bytes TEXT 65,535 bytes ~64kb MEDIUMTEXT 16,777,215 bytes ~16MB LONGTEXT 4,294,967,295 bytes ~4GB
TINYTEXT
is a string data type that can store up to to 255
characters.
TEXT
is a string data type that can store up to 65,535
characters. TEXT
is commonly used for brief articles.
LONGTEXT
is a string data type with a maximum length of 4,294,967,295
characters. Use LONGTEXT
if you need to store large text, such as a chapter of a novel.
I know this question was answered a while ago, but when dealing with large data sets, nested queries can be costly. Here is a different solution where the nested query will only be ran once, instead of for each row returned.
SELECT
Orders.OrderNumber,
LineItems.Quantity,
LineItems.Description
FROM
Orders
INNER JOIN (
SELECT
Orders.OrderNumber,
Max(LineItem.LineItemID) AS LineItemID
FROM
Orders INNER JOIN LineItems
ON Orders.OrderNumber = LineItems.OrderNumber
GROUP BY Orders.OrderNumber
) AS Items ON Orders.OrderNumber = Items.OrderNumber
INNER JOIN LineItems
ON Items.LineItemID = LineItems.LineItemID
you could make them all #
's.
You would then need to add return false;
to the end of any function that is called onclick of the anchor to not have the page jump up to the top.
Below solution may help you.
var unmanagedDownloadcountwithfilter = from count in unmanagedDownloadCount.Where(d =>d.downloaddate >= startDate && d.downloaddate <= endDate)
group count by count.unmanagedassetregistryid into grouped
where grouped.Count() > request.Download
select new
{
UnmanagedAssetRegistryID = grouped.Key,
Count = grouped.Count()
};
I did the test (but it is not your example) and the data does not return them orderly or complete
>>> ind = ['p5','p1','p8','p4','p2','p8']
>>> newind = {x.replace('p','') for x in ind}
>>> newind
{'1', '2', '8', '5', '4'}
I proved that this works:
>>> ind = ['p5','p1','p8','p4','p2','p8']
>>> newind = [x.replace('p','') for x in ind]
>>> newind
['5', '1', '8', '4', '2', '8']
or
>>> newind = []
>>> ind = ['p5','p1','p8','p4','p2','p8']
>>> for x in ind:
... newind.append(x.replace('p',''))
>>> newind
['5', '1', '8', '4', '2', '8']
You'll want something like this:
var RandomBgApp = React.createClass({
render: function() {
var getRandomColor = function() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
};
var rows = [
{ name: 'row 1'},
{ name: 'row 2'},
{ name: 'row 3'}
];
var rowNodes = rows.map(function(row) {
return <Text style={{backgroundColor:getRandomColor()}}>{row.name}</Text>
});
return (
<View>
{rowNodes}
</View>
);
}
});
In this example I take the rows array, containing the data for the rows in the component, and map it into an array of Text components. I use inline styles to call the getRandomColor
function every time I create a new Text component.
The issue with your code is that you define the style once and therefore getRandomColor only gets called once - when you define the style.
To get an actual working example going that returns what one would expect:
var startdate = "20.03.2014";
var new_date = moment(startdate, "DD.MM.YYYY");
var thing = new_date.add(5, 'days').format('DD/MM/YYYY');
window.console.log(thing)
Just need to update the width of the th
tag.
th {
width: 100px;
}
jQuery 'fixes up' events to account for browser differences. When it does so, you can always access the 'native' event with event.originalEvent
(see the Special Properties subheading on this page).
AgilData launched recently the Gibbs MySQL Scalability Advisor (a free self-service tool) which allows users to capture a live stream of queries to be uploaded to Gibbs. Spyglass (which is Open Source) will watch interactions between your MySQL Servers and client applications. No reconfiguration or restart of the MySQL database server is needed (either client or app).
GitHub: AgilData/gibbs-mysql-spyglass
Learn more: Packet Capturing MySQL with Rust
Install command:
curl -s https://raw.githubusercontent.com/AgilData/gibbs-mysql-spyglass/master/install.sh | bash
The aim of having the kernel support different ones is that you can try them out without a reboot; you can then run test workloads through the sytsem, measure performance, and then make that the standard one for your app.
On modern server-grade hardware, only the noop one appears to be at all useful. The others seem slower in my tests.
Make sure that each Application Pool in IIS, under Advanced Settings
has Enable 32 bit Applications
set to True
It is not necessary to use another library like newChart or use other people's pull requests to pull this off. All you have to do is define an options object and add the label wherever and however you want it in the tooltip.
var optionsPie = {
tooltipTemplate: "<%= label %> - <%= value %>"
}
If you want the tooltip to be always shown you can make some other edits to the options:
var optionsPie = {
tooltipEvents: [],
showTooltips: true,
onAnimationComplete: function() {
this.showTooltip(this.segments, true);
},
tooltipTemplate: "<%= label %> - <%= value %>"
}
In your data items, you have to add the desired label property and value and that's all.
data = [
{
value: 480000,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Tobacco"
}
];
Now, all you have to do is pass the options object after the data to the new Pie like this: new Chart(ctx).Pie(data,optionsPie)
and you are done.
This probably works best for pies which are not very small in size.
Jacob Helwig mentions in his answer that:
It looks like rev-parse is being used without sufficient error checking before-hand
Commit 62f162f from Jeff King (peff
) should improve the robustness of git rev-parse
in Git 1.9/2.0 (Q1 2014) (in addition of commit 1418567):
For cases where we do not match (e.g., "
doesnotexist..HEAD
"), we would then want to try to treat the argument as a filename.
try_difference()
gets this right, and always unmunges in this case.
However,try_parent_shorthand()
never unmunges, leading to incorrect error messages, or even incorrect results:
$ git rev-parse foobar^@
foobar
fatal: ambiguous argument 'foobar': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
I use numpy.fromiter to invert a 8-greyscale bitmap, yet no signs of side-effects
import Image
import numpy as np
im = Image.load('foo.jpg')
im = im.convert('L')
arr = np.fromiter(iter(im.getdata()), np.uint8)
arr.resize(im.height, im.width)
arr ^= 0xFF # invert
inverted_im = Image.fromarray(arr, mode='L')
inverted_im.show()
The accepted answer works but leaves an empty style
attribute on the DOM in my tests. No big deal, but this removes it all:
removeAttr( 'style' );
This assumes you want to remove all dynamic styling and return back to the stylesheet styling.
In the step 5 of Phil, "Resources" is no longer available in the new version of the Chrome. You need to click the page icon just beside the Ajax page listed in the bottom pane with the columns of Name, Method, Status, ...
Then it will show you more panels where you will find the error messages.
You don't want to stretch the span in height?
You have the possiblity to affect one or more flex-items to don't stretch the full height of the container.
To affect all flex-items of the container, choose this:
You have to set align-items: flex-start;
to div
and all flex-items of this container get the height of their content.
div {_x000D_
align-items: flex-start;_x000D_
background: tan;_x000D_
display: flex;_x000D_
height: 200px;_x000D_
}_x000D_
span {_x000D_
background: red;_x000D_
}
_x000D_
<div>_x000D_
<span>This is some text.</span>_x000D_
</div>
_x000D_
To affect only a single flex-item, choose this:
If you want to unstretch a single flex-item on the container, you have to set align-self: flex-start;
to this flex-item. All other flex-items of the container aren't affected.
div {_x000D_
display: flex;_x000D_
height: 200px;_x000D_
background: tan;_x000D_
}_x000D_
span.only {_x000D_
background: red;_x000D_
align-self:flex-start;_x000D_
}_x000D_
span {_x000D_
background:green;_x000D_
}
_x000D_
<div>_x000D_
<span class="only">This is some text.</span>_x000D_
<span>This is more text.</span>_x000D_
</div>
_x000D_
Why is this happening to the span
?
The default value of the property align-items
is stretch
. This is the reason why the span
fill the height of the div
.
Difference between baseline
and flex-start
?
If you have some text on the flex-items, with different font-sizes, you can use the baseline of the first line to place the flex-item vertically. A flex-item with a smaller font-size have some space between the container and itself at top. With flex-start
the flex-item will be set to the top of the container (without space).
div {_x000D_
align-items: baseline;_x000D_
background: tan;_x000D_
display: flex;_x000D_
height: 200px;_x000D_
}_x000D_
span {_x000D_
background: red;_x000D_
}_x000D_
span.fontsize {_x000D_
font-size:2em;_x000D_
}
_x000D_
<div>_x000D_
<span class="fontsize">This is some text.</span>_x000D_
<span>This is more text.</span>_x000D_
</div>
_x000D_
You can find more information about the difference between
baseline
andflex-start
here:
What's the difference between flex-start and baseline?
This is based on Jim's answer,
SELECT
@field_text + SPACE(@pad_length - LEN(@field_text)) AS RightPad
,SPACE(@pad_length - LEN(@field_text)) + @field_text AS LeftPad
Advantages
Disadvantages
// Bind combobox to dictionary
Dictionary<string, string>test = new Dictionary<string, string>();
test.Add("1", "dfdfdf");
test.Add("2", "dfdfdf");
test.Add("3", "dfdfdf");
comboBox1.DataSource = new BindingSource(test, null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";
// Get combobox selection (in handler)
string value = ((KeyValuePair<string, string>)comboBox1.SelectedItem).Value;
I used title and it worked!
The title attribute gives the title of the link. With one exception, it is purely advisory. The value is text. The exception is for style sheet links, where the title attribute defines alternative style sheet sets.
<a class="navbar-brand" href="http://www.alberghierocastelnuovocilento.gov.it/sito/index.php" title="sito dell'Istituto Ancel Keys">A.K.</a>
One way to do it will be to move all the php code above the HTML, copy the result to a variable and then add the result in the <input>
tag.
Try this -
<?php
//Adding the php to the top.
if(isset($_POST['submit']))
{
$value1=$_POST['value1'];
$value2=$_POST['value2'];
$sign=$_POST['sign'];
...
//Adding to $result variable
if($sign=='-') {
$result = $value1-$value2;
}
//Rest of your code...
}
?>
<html>
<!--Rest of your tags...-->
Result:<br><input type"text" name="result" value = "<?php echo (isset($result))?$result:'';?>">
From sed1line:
# print line number 52
sed -n '52p' # method 1
sed '52!d' # method 2
sed '52q;d' # method 3, efficient on large files
From awk1line:
# print line number 52
awk 'NR==52'
awk 'NR==52 {print;exit}' # more efficient on large files
Here's a simple function using a regexp that imitates the a
tag behavior.
Pros
Cons
-
function getLocation(href) {
var match = href.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);
return match && {
href: href,
protocol: match[1],
host: match[2],
hostname: match[3],
port: match[4],
pathname: match[5],
search: match[6],
hash: match[7]
}
}
-
getLocation("http://example.com/");
/*
{
"protocol": "http:",
"host": "example.com",
"hostname": "example.com",
"port": undefined,
"pathname": "/"
"search": "",
"hash": "",
}
*/
getLocation("http://example.com:3000/pathname/?search=test#hash");
/*
{
"protocol": "http:",
"host": "example.com:3000",
"hostname": "example.com",
"port": "3000",
"pathname": "/pathname/",
"search": "?search=test",
"hash": "#hash"
}
*/
EDIT:
Here's a breakdown of the regular expression
var reURLInformation = new RegExp([
'^(https?:)//', // protocol
'(([^:/?#]*)(?::([0-9]+))?)', // host (hostname and port)
'(/{0,1}[^?#]*)', // pathname
'(\\?[^#]*|)', // search
'(#.*|)$' // hash
].join(''));
var match = href.match(reURLInformation);
UPDATE
Bootstrap 4 has spacing utilities to handle this https://getbootstrap.com/docs/4.0/utilities/spacing/
.mt-0 {
margin-top: 0 !important;
}
--
ORIGINAL ANSWER
If you are using SASS, this is what I normally do.
$margins: (xs: 0.5rem, sm: 1rem, md: 1.5rem, lg: 2rem, xl: 2.5rem);
@each $name, $value in $margins {
.margin-top-#{$name} {
margin-top: $value;
}
.margin-bottom-#{$name} {
margin-bottom: $value;
}
}
so you can later use margin-top-xs
for example
The humanize solution is fine if your website is in English. For other languages, you need another solution: I recommend using Babel. One solution is to create a custom template tag to display numbers properly. Here's how: just create the following file in your_project/your_app/templatetags/sexify.py
:
# -*- coding: utf-8 -*-
from django import template
from django.utils.translation import to_locale, get_language
from babel.numbers import format_number
register = template.Library()
def sexy_number(context, number, locale = None):
if locale is None:
locale = to_locale(get_language())
return format_number(number, locale = locale)
register.simple_tag(takes_context=True)(sexy_number)
Then you can use this template tag in your templates like this:
{% load sexy_number from sexify %}
{% sexy_number 1234.56 %}
Of course you can use variables instead:
{% sexy_number some_variable %}
Note: the context
parameter is currently not used in my example, but I put it there to show that you can easily tweak this template tag to make it use anything that's in the template context.
I tried re-creating this, and .someclass.notip
was being generated for me but .someclass:not(.notip)
was not, for as long as I did not have the @mixin tip()
defined. Once I had that, it all worked.
http://sassmeister.com/gist/9775949
$dropdown-width: 100px;
$comp-tip: true;
@mixin tip($pos:right) {
}
@mixin dropdown-pos($pos:right) {
&:not(.notip) {
@if $comp-tip == true{
@if $pos == right {
top:$dropdown-width * -0.6;
background-color: #f00;
@include tip($pos:$pos);
}
}
}
&.notip {
@if $pos == right {
top: 0;
left:$dropdown-width * 0.8;
background-color: #00f;
}
}
}
.someclass { @include dropdown-pos(); }
EDIT: http://sassmeister.com/ is a good place to debug your SASS because it gives you error messages. Undefined mixin 'tip'.
it what I get when I remove @mixin tip($pos:right) { }
It turns out the answer was ridiculously simple, but mystifying as to why it was necessary.
In the IIS Manager on the server, I set the application pool for my web application to not allow 32-bit assemblies.
It seems it assumes, on a 64-bit system, that you must want the 32 bit assembly. Bizarre.
when your add permission in manifest then in eclipse go to project and clic
k on clean project
If you do not want to include that your code script (as advised by others above), then simply you may do the following after generating the figure window:
Go to "Edit" in the figure window
Go to "Figure Properties"
At the bottom, you can type the name you want in "Figure Name" field. You can uncheck "Show Figure Number".
That's all.
Good luck.
References are "hidden pointers" (non-null) to things which can change (lvalues). You cannot define them to a constant. It should be a "variable" thing.
EDIT::
I am thinking of
int &x = y;
as almost equivalent of
int* __px = &y;
#define x (*__px)
where __px
is a fresh name, and the #define x
works only inside the block containing the declaration of x
reference.
To see the difference between:
Your working copy and staging area:
% git diff
Staging area and the latest commit:
% git diff --staged
Your working copy and commit 4ac0a6733:
% git diff 4ac0a6733
Commit 4ac0a6733 and the latest commit:
% git diff 4ac0a6733 HEAD
Commit 4ac0a6733 and commit 826793951
% git diff 4ac0a6733 826793951
For more explanation see the official documentation.
Recently, when I was dealing with an AJAX application/RIA, I was having the same issue! And I used implicit wait, with a time of around 90 seconds. It waits, till the element is available...So, what we can do to make sure, that page gets loaded completely is,
add a boolean statement, checking for whether the condition(a particular part of the element), is present and assign it to a variable, check for the condition and only when it is true, " do the necessary actions!"...In this way, I figured out, both waits could be used...
Ex:
@Before
{ implicit wait statement}
@Test
{
boolean tr1=Driver.findElement(By.xpath("xx")).isEnabled/isDisplayed;
if (tr1==true && ____)//as many conditions, to make sure, the page is loaded
{
//do the necessary set of actions...
driver.findElement(By.xpath("yy")).click();
}
}
Hope this helps!! It is in implementation stage, for me too...
Reload the datasource of your grid after the update
myGrid.ItemsSource = null;
myGrid.ItemsSource = myDataSource;
#include <iostream>
#include <string>
#include <sstream>
int main(){
std::string myText("some-text-to-tokenize");
std::istringstream iss(myText);
std::string token;
while (std::getline(iss, token, '-'))
{
std::cout << token << std::endl;
}
return 0;
}
Or, as mentioned, use boost for more flexibility.
You can customise the credits, changing the URL, text, Position etc. All the info is documented here: http://api.highcharts.com/highcharts/credits. To simply disable them altogether, use:
credits: {
enabled: false
},
Either add an event listener, or have the image announce itself with onload. Then figure out the dimensions from there.
<img id="photo"
onload='loaded(this.id)'
src="a_really_big_file.jpg"
alt="this is some alt text"
title="this is some title text" />
I spent a lot of time trying different answers all around the internet, and I suspect the reasons why one thing works for some people and not for others is due to very small weird differences in application. For context, I needed to read in file names from a csv file that had strange and/or unmappable unicode characters and write them to a new csv file. For what it's worth, here's what worked for me:
s = '\u00e7\u00a3\u0085\u00e5\u008d\u0095' # csv freaks if you try to write this
s = repr(s.encode('utf-8', 'ignore'))[2:-1]
You can use AtomicReference when applying optimistic locks. You have a shared object and you want to change it from more than 1 thread.
As other thread might have modified it and/can modify between these 2 steps. You need to do it in an atomic operation. this is where AtomicReference can help
I have tried this
C:\Users\radhason\AppData\Local\NetBeans\Cache
Press Ok button , then cache folder will be shown and delete this cache folder of netbeans.
Old post but worth a look for someone who stumbles upon like me
ISNULL(NULLIF(ColumnName, ' '), NULL) IS NOT NULL
ISNULL(NULLIF(ColumnName, ' '), NULL) IS NULL
Java has Reflection (java.reflection.*), but I would suggest looking into a library like Apache Beanutils, it will make the process much less hairy than using reflection directly.
I also had this issue and ended up using Andy's code to create a function to clean things up when multiple commands need to be run.
It'll return stderr, stdout, and exit codes as objects. One thing to note: the function won't accept .\
in the path; full paths must be used.
Function Execute-Command ($commandTitle, $commandPath, $commandArguments)
{
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = $commandPath
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = $commandArguments
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
[pscustomobject]@{
commandTitle = $commandTitle
stdout = $p.StandardOutput.ReadToEnd()
stderr = $p.StandardError.ReadToEnd()
ExitCode = $p.ExitCode
}
}
Here's how to use it:
$DisableACMonitorTimeOut = Execute-Command -commandTitle "Disable Monitor Timeout" -commandPath "C:\Windows\System32\powercfg.exe" -commandArguments " -x monitor-timeout-ac 0"
Google has this to say on transferring data between accounts.
http://support.google.com/accounts/bin/answer.py?hl=en&answer=63304
It lists certain types of data that CAN be transferred and certain types of data that CAN NOT be transferred. Unfortunately Google Play Apps falls into the NOT category.
It's conveniently titled: "Moving Product Data"
http://support.google.com/accounts/bin/answer.py?hl=en&answer=58582
For any future googlers ending up here like me, I used @tatu Ulmanen's concept and just turned it into an array of objects. This simple function takes a string of pasted excel (or Google sheet) data (preferably from a textarea
) and turns it into an array of objects. It uses the first row for column/property names.
function excelToObjects(stringData){
var objects = [];
//split into rows
var rows = stringData.split('\n');
//Make columns
columns = rows[0].split('\t');
//Note how we start at rowNr = 1, because 0 is the column row
for (var rowNr = 1; rowNr < rows.length; rowNr++) {
var o = {};
var data = rows[rowNr].split('\t');
//Loop through all the data
for (var cellNr = 0; cellNr < data.length; cellNr++) {
o[columns[cellNr]] = data[cellNr];
}
objects.push(o);
}
return objects;
}
Hopefully it helps someone in the future.
For Ubuntu 18.04 installnasm
. Open the terminal and type:
sudo apt install as31 nasm
nasm docs
For compiling and running:
nasm -f elf64 example.asm # assemble the program
ld -s -o example example.o # link the object file nasm produced into an executable file
./example # example is an executable file
Why not the old fashioned easy way?
public int[] ToASCII(string s)
{
char c;
int[] cByte = new int[s.Length]; / the ASCII string
for (int i = 0; i < s.Length; i++)
{
c = s[i]; // get a character from the string s
cByte[i] = Convert.ToInt16(c); // and convert it to ASCII
}
return cByte;
}
Primary keys always need to be unique, foreign keys need to allow non-unique values if the table is a one-to-many relationship. It is perfectly fine to use a foreign key as the primary key if the table is connected by a one-to-one relationship, not a one-to-many relationship.
A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.
I would be inclined to do a one liner with a ternary if.
var bool_value = value == "true" ? true : false
Edit: Even quicker would be to simply avoid using the a logical statement and instead just use the expression itself:
var bool_value = value == 'true';
This works because value == 'true'
is evaluated based on whether the value
variable is a string of 'true'
. If it is, that whole expression becomes true
and if not, it becomes false
, then that result gets assigned to bool_value
after evaluation.
Usually Vu (or VU for uppercase) is enough to turn the whole line into lowercase as V already selects the whole line to apply the action against.
Tilda (~) changes the case of the individual letter, resulting in camel case or the similar.
It is really great how Vim has many many different modes to deal with various occasions and how those modes are neatly organized.
For instance, v - the true visual mode, and the related V - visual line, and Ctrl+Q - visual block modes (what allows you to select blocks, a great feature some other advanced editors also offer usually by holding the Alt key and selecting the text).
OFFSET is what you are looking for.
SELECT * FROM table LIMIT 10 OFFSET 10
Following DrJokepu's and David Murdoch idea I implemented a more complete version. It requires jQuery on both the parent and iframe and the iframe to be in your control.
iframe code:
var iframe = window.frameElement;
if (iframe){
iframe.contentDocument = document;//normalization: some browsers don't set the contentDocument, only the contentWindow
var parent = window.parent;
$(parent.document).ready(function(){//wait for parent to make sure it has jQuery ready
var parent$ = parent.jQuery;
parent$(iframe).trigger("iframeloading");
$(function(){
parent$(iframe).trigger("iframeready");
});
$(window).load(function(){//kind of unnecessary, but here for completion
parent$(iframe).trigger("iframeloaded");
});
$(window).unload(function(e){//not possible to prevent default
parent$(iframe).trigger("iframeunloaded");
});
$(window).on("beforeunload",function(){
parent$(iframe).trigger("iframebeforeunload");
});
});
}
parent test code:
$(function(){
$("iframe").on("iframeloading iframeready iframeloaded iframebeforeunload iframeunloaded", function(e){
console.log(e.type);
});
});
git config --global diff.tool vimdiff
git config --global difftool.prompt false
Typing git difftool
yields the expected behavior.
:qa
in vim cycles to the next file in the changeset without saving anything.git config --global alias.d difftool
.. will let you type git d
to invoke vimdiff.
:wq
in vim cycles to the next file in the changeset with changes saved.There are two steps you need to take.
First, you need to put the PDF in an iframe.
<iframe id="pdf" name="pdf" src="document.pdf"></iframe>
To print the iframe you can look at the answers here:
Javascript Print iframe contents only
If you want to print the iframe automatically after the PDF has loaded, you can add an onload handler to the <iframe>
:
<iframe onload="isLoaded()" id="pdf" name="pdf" src="document.pdf"></iframe>
the loader can look like this:
function isLoaded()
{
var pdfFrame = window.frames["pdf"];
pdfFrame.focus();
pdfFrame.print();
}
This will display the browser's print dialog, and then print just the PDF document itself. (I personally use the onload handler to enable a "print" button so the user can decide to print the document, or not).
I'm using this code pretty much verbatim in Safari and Chrome, but am yet to try it on IE or Firefox.
<div id="lightbox">
is inside the <body>
element, thus when you scroll the lightbox you also scroll the body. The solution is to not extend the <body>
element over 100%, to place the long content inside another div
element and to add a scrollbar if needed to this div
element with overflow: auto
.
html {_x000D_
height: 100%_x000D_
}_x000D_
body {_x000D_
margin: 0;_x000D_
height: 100%_x000D_
}_x000D_
#content {_x000D_
height: 100%;_x000D_
overflow: auto;_x000D_
}_x000D_
#lightbox {_x000D_
position: fixed;_x000D_
top: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
bottom: 0;_x000D_
}
_x000D_
<html>_x000D_
<body>_x000D_
<div id="content">much content</div>_x000D_
<div id="lightbox">lightbox<div>_x000D_
</body>_x000D_
</html>
_x000D_
Now, scrolling over the lightbox (and the body
as well) has no effect, because the body is no longer than 100% of the screen height.
Use the this.ngOnInit(); to reload the same component instead reloading the entire page!!
DeleteEmployee(id:number)
{
this.employeeService.deleteEmployee(id)
.subscribe(
(data) =>{
console.log(data);
this.ngOnInit();
}),
err => {
console.log("Error");
}
}
var StopWatch = function (performance) {
this.startTime = 0;
this.stopTime = 0;
this.running = false;
this.performance = performance === false ? false : !!window.performance;
};
StopWatch.prototype.currentTime = function () {
return this.performance ? window.performance.now() : new Date().getTime();
};
StopWatch.prototype.start = function () {
this.startTime = this.currentTime();
this.running = true;
};
StopWatch.prototype.stop = function () {
this.stopTime = this.currentTime();
this.running = false;
};
StopWatch.prototype.getElapsedMilliseconds = function () {
if (this.running) {
this.stopTime = this.currentTime();
}
return this.stopTime - this.startTime;
};
StopWatch.prototype.getElapsedSeconds = function () {
return this.getElapsedMilliseconds() / 1000;
};
StopWatch.prototype.printElapsed = function (name) {
var currentName = name || 'Elapsed:';
console.log(currentName, '[' + this.getElapsedMilliseconds() + 'ms]', '[' + this.getElapsedSeconds() + 's]');
};
Benchmark
var stopwatch = new StopWatch();
stopwatch.start();
for (var index = 0; index < 100; index++) {
stopwatch.printElapsed('Instance[' + index + ']');
}
stopwatch.stop();
stopwatch.printElapsed();
Output
Instance[0] [0ms] [0s]
Instance[1] [2.999999967869371ms] [0.002999999967869371s]
Instance[2] [2.999999967869371ms] [0.002999999967869371s]
/* ... */
Instance[99] [10.999999998603016ms] [0.010999999998603016s]
Elapsed: [10.999999998603016ms] [0.010999999998603016s]
performance.now() is optional - just pass false into StopWatch constructor function.
Just try this line:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
after:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
You have to specify the path that you are working on:
source = '/home/test/py_test/'
for root, dirs, filenames in os.walk(source):
for f in filenames:
print f
fullpath = os.path.join(source, f)
log = open(fullpath, 'r')
How are you loading this page? Is it getting anything on POST to load? If it's not, then the $name = $_POST['Name']; assignation doesn't have any 'Name' on POST.
It's (Get-NetTCPConnection -LocalPort "port no.").OwningProcess
if (list.Count > desiredIndex && list[desiredIndex] != null)
{
// logic
}
This is speed-optimized solution for converting int (signed 16-bit integer) into string.
This implementation avoids using division since 8-bit AVR used for Arduino has no hardware DIV instruction, the compiler translate division into time-consuming repetitive subtractions. Thus the fastest solution is using conditional branches to build the string.
A fixed 7 bytes buffer prepared from beginning in RAM to avoid dynamic allocation. Since it's only 7 bytes, the cost of fixed RAM usage is considered minimum. To assist compiler, we add register modifier into variable declaration to speed-up execution.
char _int2str[7];
char* int2str( register int i ) {
register unsigned char L = 1;
register char c;
register boolean m = false;
register char b; // lower-byte of i
// negative
if ( i < 0 ) {
_int2str[ 0 ] = '-';
i = -i;
}
else L = 0;
// ten-thousands
if( i > 9999 ) {
c = i < 20000 ? 1
: i < 30000 ? 2
: 3;
_int2str[ L++ ] = c + 48;
i -= c * 10000;
m = true;
}
// thousands
if( i > 999 ) {
c = i < 5000
? ( i < 3000
? ( i < 2000 ? 1 : 2 )
: i < 4000 ? 3 : 4
)
: i < 8000
? ( i < 6000
? 5
: i < 7000 ? 6 : 7
)
: i < 9000 ? 8 : 9;
_int2str[ L++ ] = c + 48;
i -= c * 1000;
m = true;
}
else if( m ) _int2str[ L++ ] = '0';
// hundreds
if( i > 99 ) {
c = i < 500
? ( i < 300
? ( i < 200 ? 1 : 2 )
: i < 400 ? 3 : 4
)
: i < 800
? ( i < 600
? 5
: i < 700 ? 6 : 7
)
: i < 900 ? 8 : 9;
_int2str[ L++ ] = c + 48;
i -= c * 100;
m = true;
}
else if( m ) _int2str[ L++ ] = '0';
// decades (check on lower byte to optimize code)
b = char( i );
if( b > 9 ) {
c = b < 50
? ( b < 30
? ( b < 20 ? 1 : 2 )
: b < 40 ? 3 : 4
)
: b < 80
? ( i < 60
? 5
: i < 70 ? 6 : 7
)
: i < 90 ? 8 : 9;
_int2str[ L++ ] = c + 48;
b -= c * 10;
m = true;
}
else if( m ) _int2str[ L++ ] = '0';
// last digit
_int2str[ L++ ] = b + 48;
// null terminator
_int2str[ L ] = 0;
return _int2str;
}
// Usage example:
int i = -12345;
char* s;
void setup() {
s = int2str( i );
}
void loop() {}
This sketch is compiled to 1,082 bytes of code using avr-gcc which bundled with Arduino v1.0.5 (size of int2str function itself is 594 bytes). Compared with solution using String object which compiled into 2,398 bytes, this implementation can reduce your code size by 1.2 Kb (assumed that you need no other String's object method, and your number is strict to signed int type).
This function can be optimized further by writing it in proper assembler code.
The guide linked here will probably answer the original question without the need for programming a custom SSL connector.
Found a very detailed how-to guide on importing root certificates that actually steps you through installing trusted CA certificates on different versions of Android devices (among other devices).
Basically you'll need to:
Download: the cacerts.bks file from your phone.
adb pull /system/etc/security/cacerts.bks cacerts.bks
Download the .crt file from the certifying authority you want to allow.
Modify the cacerts.bks file on your computer using the BouncyCastle Provider
Upload the cacerts.bks file back to your phone and reboot.
Here is a more detailed step by step to update earlier android phones: How to update HTTPS security certificate authority keystore on pre-android-4.0 device
I done it, below code is working for me....
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.hello_world, container, false);
Button newPage = (Button)v.findViewById(R.id.click);
newPage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), HomeActivity.class);
startActivity(intent);
}
});
return v;
}
and Please make sure that your destination activity should be register in Manifest.xml file,
but in my case all tabs are not shown in HomeActivity, is any solution for that ?
In my circumstance I also had a hidden element stopping me from getting the height value, but it wasn't the element itself but rather one of it's parents... so I just put in a check for one of my plugins to see if it's hidden, else find the closest hidden element. Here's an example:
var $content = $('.content'),
contentHeight = $content.height(),
contentWidth = $content.width(),
$closestHidden,
styleAttrValue,
limit = 20; //failsafe
if (!contentHeight) {
$closestHidden = $content;
//if the main element itself isn't hidden then roll through the parents
if ($closestHidden.css('display') !== 'none') {
while ($closestHidden.css('display') !== 'none' && $closestHidden.size() && limit) {
$closestHidden = $closestHidden.parent().closest(':hidden');
limit--;
}
}
styleAttrValue = $closestHidden.attr('style');
$closestHidden.css({
position: 'absolute',
visibility: 'hidden',
display: 'block'
});
contentHeight = $content.height();
contentWidth = $content.width();
if (styleAttrValue) {
$closestHidden.attr('style',styleAttrValue);
} else {
$closestHidden.removeAttr('style');
}
}
In fact, this is an amalgamation of Nick, Gregory and Eyelidlessness's responses to give you the use of Gregory's improved method, but utilises both methods in case there is supposed to be something in the style attribute that you want to put back, and looks for a parent element.
My only gripe with my solution is that the loop through the parents isn't entirely efficient.
Just use percentage widths and fixed table layout:
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</table>
with
table { table-layout: fixed; }
td { width: 33%; }
Fixed table layout is important as otherwise the browser will adjust the widths as it sees fit if the contents don't fit ie the widths are otherwise a suggestion not a rule without fixed table layout.
Obviously, adjust the CSS to fit your circumstances, which usually means applying the styling only to a tables with a given class or possibly with a given ID.
As others answer 0
meaning success, otherwise.
If you using bat file (window) System.exit(x)
will effect.
Code java (myapp):
if (error < 2){
help();
System.exit(-1);
}
else{
doSomthing();
System.exit(0);
}
}
bat file:
java -jar myapp.jar
if %errorlevel% neq 0 exit /b %errorlevel%
rem -- next command if myapp is success --
You could just add a toString()
method to MyClass, per http://developer.android.com/reference/android/widget/ArrayAdapter.html:
However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list.
class MyClass {
@Override
public String toString() {
return "Hello, world.";
}
}
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.
That seems a rather weird design for your code - it generally makes more sense to have your functions called directly from a .js file, and then only retrieve data with the Ajax call.
However, I believe it should work by calling eval() on the response - provided it is syntactically correct JavaScript code.